session

package
v0.0.0-...-292d0d8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session models the authenticated caller (Principal) and the store that keeps browser sessions.

Index

Constants

View Source
const CookieName = "othra_sid"

CookieName is the browser session cookie; its value is Sign(stateSecret, sid).

Variables

This section is empty.

Functions

func ClearCookie

func ClearCookie(w http.ResponseWriter, c CookieOptions)

ClearCookie tells the browser to drop the session cookie.

func EndUserInto

func EndUserInto(ctx context.Context, eu EndUser) context.Context

EndUserInto returns ctx carrying eu.

func HasCookie

func HasCookie(h http.Header) bool

HasCookie reports whether h carries a session cookie, valid or not.

func IsBadCookieError

func IsBadCookieError(err error) bool

IsBadCookieError reports whether err's tree contains a *BadCookieError.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError reports whether err's tree contains a *NotFoundError.

func NewID

func NewID() (string, error)

NewID returns a fresh session id: 32 random bytes, base64url without padding.

func PrincipalInto

func PrincipalInto(ctx context.Context, p Principal) context.Context

PrincipalInto returns ctx carrying p.

func ReadCookie

func ReadCookie(h http.Header, secret []byte) (string, bool)

ReadCookie returns the session id of the first session cookie in h whose signature verifies.

func SIDFrom

func SIDFrom(ctx context.Context) (string, bool)

SIDFrom returns the request's session id, if it came with one.

func SIDInto

func SIDInto(ctx context.Context, sid string) context.Context

SIDInto returns ctx carrying the id of the session the request came with.

func Sign

func Sign(secret []byte, value string) string

Sign returns "value|mac" where mac is base64url HMAC-SHA256(value) keyed on secret.

func Verify

func Verify(secret []byte, raw string) (string, error)

Verify checks a signed cookie in constant time and returns its value.

func WriteCookie

func WriteCookie(w http.ResponseWriter, c CookieOptions, signed string, expires time.Time)

WriteCookie sets the session cookie to signed until expires; it is always HttpOnly and SameSite=Lax.

Types

type BadCookieError

type BadCookieError struct{}

BadCookieError reports a session cookie that fails its HMAC check.

func (*BadCookieError) Error

func (*BadCookieError) Error() string

type CookieOptions

type CookieOptions struct {
	Path   string
	Secure bool
}

CookieOptions are the deployment-wide attributes of the session cookie.

type EndUser

type EndUser struct {
	OrgID           uuid.UUID
	ProjectID       uuid.UUID
	ProjectPublicID string
	ProjectName     string
	EndUserID       uuid.UUID
	Subject         string
	UserSession     string
	AuthTime        time.Time
	// SignOutToken and LinkToken are this browser's CSRF tokens for the hosted sign-out and connect-an-upstream forms the portal posts.
	SignOutToken string
	LinkToken    string
}

EndUser is the end user an account.v1 call runs for: the browser's active account in one project.

func EndUserFrom

func EndUserFrom(ctx context.Context) (eu EndUser, ok bool)

EndUserFrom returns the EndUser in ctx; ok is false outside the account plane.

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

MemoryStore keeps sessions in process memory; sessions are lost on restart.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty MemoryStore.

func (*MemoryStore) Delete

func (s *MemoryStore) Delete(_ context.Context, sid string) error

Delete removes the session for sid.

func (*MemoryStore) DeleteByUser

func (s *MemoryStore) DeleteByUser(_ context.Context, userID uuid.UUID) error

DeleteByUser removes every session of userID.

func (*MemoryStore) DeleteByUserExcept

func (s *MemoryStore) DeleteByUserExcept(_ context.Context, userID uuid.UUID, keepSID string) error

DeleteByUserExcept removes every session of userID but keepSID.

func (*MemoryStore) DeleteExpired

func (s *MemoryStore) DeleteExpired(_ context.Context) (int, error)

DeleteExpired removes expired sessions and reports how many went.

func (*MemoryStore) Load

func (s *MemoryStore) Load(_ context.Context, sid string) (Principal, bool, error)

Load returns the live session for sid; ok is false when it is missing or expired.

func (*MemoryStore) Save

func (s *MemoryStore) Save(_ context.Context, sid string, p Principal, expiresAt time.Time) error

Save stores p under sid until expiresAt, replacing any existing row.

func (*MemoryStore) Update

func (s *MemoryStore) Update(_ context.Context, sid string, p Principal) error

Update replaces the Principal of the live session sid and keeps its expiry.

type NotFoundError

type NotFoundError struct{}

NotFoundError reports a session that is missing or expired.

func (*NotFoundError) Error

func (*NotFoundError) Error() string

type PostgresStore

type PostgresStore struct {
	// contains filtered or unexported fields
}

PostgresStore keeps sealed sessions in the sessions table, always on the primary.

func NewPostgresStore

func NewPostgresStore(conn *sql.DB, schema, tablePrefix string, s sealer.Sealer, unexpected apperror.UnexpectedFunc) *PostgresStore

NewPostgresStore builds a PostgresStore; conn must be the writer pool so a fresh sign-in is never missed on a lagging replica.

func (*PostgresStore) Delete

func (s *PostgresStore) Delete(ctx context.Context, sid string) error

Delete removes the session for sid.

func (*PostgresStore) DeleteByUser

func (s *PostgresStore) DeleteByUser(ctx context.Context, userID uuid.UUID) error

DeleteByUser removes every session of userID; it joins the transaction on ctx when there is one.

func (*PostgresStore) DeleteByUserExcept

func (s *PostgresStore) DeleteByUserExcept(ctx context.Context, userID uuid.UUID, keepSID string) error

DeleteByUserExcept removes every session of userID but keepSID; it joins the transaction on ctx when there is one.

func (*PostgresStore) DeleteExpired

func (s *PostgresStore) DeleteExpired(ctx context.Context) (int, error)

DeleteExpired removes expired sessions in batches and reports how many went.

func (*PostgresStore) Load

func (s *PostgresStore) Load(ctx context.Context, sid string) (Principal, bool, error)

Load returns the live session for sid; an expired, missing or unopenable row reads as signed out.

func (*PostgresStore) Save

func (s *PostgresStore) Save(ctx context.Context, sid string, p Principal, expiresAt time.Time) error

Save upserts the sealed principal under sid.

func (*PostgresStore) Update

func (s *PostgresStore) Update(ctx context.Context, sid string, p Principal) error

Update replaces the sealed Principal of the live session sid and keeps its expiry.

type Principal

type Principal struct {
	UserID          uuid.UUID
	KeyID           uuid.UUID
	KeyHint         string
	OwnerID         uuid.UUID
	Email           string
	Name            string
	AvatarURL       string
	Source          Source
	IDPIssuer       string
	IDPSubject      string
	IDToken         string
	Scopes          []string `json:"-"`
	TokenScopes     []string `json:"-"`
	Operator        bool     `json:"-"`
	ActiveOrgID     uuid.UUID
	ActiveProjectID uuid.UUID
	ProjectIDs      []uuid.UUID `json:"-"`
	AllProjects     bool        `json:"-"`
	ResourceIDs     []uuid.UUID `json:"-"`
	Locale          string
	TermsAcceptedAt time.Time
	IssuedAt        time.Time
}

Principal is the authenticated caller. SECURITY: Scopes, Operator and reach fields are rebuilt per request, never persisted.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) Principal

PrincipalFrom returns the Principal in ctx, or the zero Principal when there is none.

func System

func System() Principal

System is the Principal of a trusted local process: `othra mcp` over stdio, run by whoever holds the DB DSN.

func (Principal) IsPerson

func (p Principal) IsPerson() bool

IsPerson reports whether p is a signed-in person rather than a key or the shared basic credential.

func (Principal) ReachesProject

func (p Principal) ReachesProject(orgID, projectID uuid.UUID) bool

ReachesProject reports whether p may act in projectID of orgID. SECURITY: never across orgs; a key only reaches granted projects.

func (Principal) ReachesResource

func (p Principal) ReachesResource(orgID, projectID, resourceID uuid.UUID) bool

ReachesResource reports whether p may act on resourceID inside projectID of orgID.

func (Principal) ReachesWholeProject

func (p Principal) ReachesWholeProject(orgID, projectID uuid.UUID) bool

ReachesWholeProject reports whether p may act across every resource of projectID, as a list or a create does.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler adapts a Store to scheduler.Provider.

func NewScheduler

func NewScheduler(store Store, log *slog.Logger) *Scheduler

NewScheduler binds store to the expired-session sweep job.

func (*Scheduler) SchedulerJobs

func (a *Scheduler) SchedulerJobs() []scheduler.Job

SchedulerJobs implements scheduler.Provider.

type SignedCookie

type SignedCookie struct {
	Name   string
	Path   string
	Secret []byte
	Secure bool
	Now    func() time.Time
}

SignedCookie is an HttpOnly, SameSite=Lax cookie whose value is signed with Secret and bound to its Name.

func (SignedCookie) Clear

func (c SignedCookie) Clear(w http.ResponseWriter)

Clear tells the browser to drop the cookie.

func (SignedCookie) Get

func (c SignedCookie) Get(r *http.Request) (string, bool)

Get returns the cookie's value when its signature verifies for this cookie's name.

func (SignedCookie) Set

func (c SignedCookie) Set(w http.ResponseWriter, value string, expires time.Time)

Set writes value, signed, until expires (at least one second).

type Source

type Source string

Source names the credential a Principal came from.

const (
	SourceLocal  Source = "local"
	SourceBasic  Source = "basic"
	SourceAPIKey Source = "apikey"
	SourceOIDC   Source = "oidc"
	SourceToken  Source = "token"
	SourceSystem Source = "system"
)

The credential sources.

type Store

type Store interface {
	Save(ctx context.Context, sid string, p Principal, expiresAt time.Time) error
	Load(ctx context.Context, sid string) (Principal, bool, error)
	// Update replaces the Principal of the live session sid and keeps its expiry; a missing or expired one is a *NotFoundError.
	Update(ctx context.Context, sid string, p Principal) error
	Delete(ctx context.Context, sid string) error
	DeleteByUser(ctx context.Context, userID uuid.UUID) error
	// DeleteByUserExcept removes every session of userID but keepSID.
	DeleteByUserExcept(ctx context.Context, userID uuid.UUID, keepSID string) error
	DeleteExpired(ctx context.Context) (int, error)
}

Store keeps browser sessions by opaque id.

Directories

Path Synopsis
Package sessiontest holds the behavior every session.Store must share.
Package sessiontest holds the behavior every session.Store must share.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL