basesession

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 15 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 basesession implements the session management for the application.

Index

Constants

This section is empty.

Variables

View Source
var DefaultImpersonationTimeout = time.Hour

DefaultImpersonationTimeout is the hard cap on an impersonated session's lifetime when BaseSession.ImpersonationTimeout is zero.

View Source
var ErrImpersonationNotConfigured = errors.New("impersonation is not configured on the storage: attach sessionstorage.WithImpersonation")

ErrImpersonationNotConfigured is returned by every impersonation API when the storage has no impersonation record table.

Functions

This section is empty.

Types

type BaseSession

type BaseSession struct {
	SessionTimeout time.Duration
	// ImpersonationTimeout is the hard cap on an impersonated session's lifetime,
	// fixed when the session is established; zero selects the library default.
	ImpersonationTimeout time.Duration
	// ImpersonationAudit, when set, receives every lifecycle event of an impersonated
	// session (see sessioninfo.ImpersonationEvent).
	ImpersonationAudit func(ctx context.Context, event sessioninfo.ImpersonationEvent) error
	// PrincipalResolver, when set, chooses the request's authorization subject at
	// validation (see session.WithPrincipalResolver). It runs with the validated
	// session in ctx for ordinary sessions and user-principal impersonations; a
	// role-principal impersonation already names its subject and skips it.
	PrincipalResolver func(ctx context.Context) (accesstypes.Principal, error)
	Handle            LogHandler
	Storage           sessionstorage.BaseStore
	CookieHandler     internalcookie.Handler
	// TableNames are the table names the session options set, in order. The
	// constructor hands each to its store setter, which validates it, and reports a
	// refusal under the option's name.
	TableNames []TableName
}

BaseSession implements the shared features for all session implementations

func (*BaseSession) ActiveImpersonations

ActiveImpersonations lists the impersonated sessions that are live right now, newest first: their record has not ended, their hard cap has not passed, their session row is not expired, and the session has seen activity within the idle session timeout. q narrows the listing; nil lists every active impersonation. It errors when the storage has no impersonation table.

func (*BaseSession) Authenticated

func (s *BaseSession) Authenticated() http.HandlerFunc

Authenticated is the handler reports if the session is authenticated

func (*BaseSession) DestroyImpersonatedSession

func (s *BaseSession) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error

DestroyImpersonatedSession ends one live impersonated session: the session row is expired and the record ended with reason Revoked, in one transaction — the single-session form of DestroyImpersonatedSessions. The next request on that session is refused as expired. A session that is not impersonated, or whose record has already ended, is left untouched. It errors when the storage has no impersonation table.

func (*BaseSession) DestroyImpersonatedSessions

func (s *BaseSession) DestroyImpersonatedSessions(ctx context.Context, actor string) error

DestroyImpersonatedSessions expires every live impersonated session established by actor and ends their records with reason Revoked. It errors when the storage has no impersonation table.

func (*BaseSession) EmitImpersonationEvent

func (s *BaseSession) EmitImpersonationEvent(ctx context.Context, kind sessioninfo.ImpersonationEventKind, imp *sessioninfo.Impersonation, operation string) error

EmitImpersonationEvent logs a lifecycle event of an impersonated session with the record's evidence attributes, records it as an event on the current trace span, and delivers it to the audit hook when one is configured. It returns the hook's error, if any; the log line and span event are written regardless.

func (*BaseSession) EndImpersonation

func (s *BaseSession) EndImpersonation() http.HandlerFunc

EndImpersonation ends the impersonated session and, when it can, returns the actor to their own session; see EndImpersonationAPI. The body says which happened.

func (*BaseSession) EndImpersonationAPI

func (s *BaseSession) EndImpersonationAPI(ctx context.Context, w http.ResponseWriter) (restored bool, err error)

EndImpersonationAPI ends the impersonated session in ctx: the session row is expired and the record ends with reason Released, in one storage transaction, and the end is announced as an Ended event. For a local actor whose source session is still live, not itself impersonated, and still theirs, the response is given that session's cookies, so the actor is back in their own session without logging in; restored reports whether that happened. A context whose session is not impersonated is refused.

func (*BaseSession) EnforceReadOnlyMask

func (s *BaseSession) EnforceReadOnlyMask(next http.Handler) http.Handler

EnforceReadOnlyMask refuses non-safe requests (anything but GET, HEAD, OPTIONS and TRACE) from an impersonated session whose mask is read-only — a mask allowing nothing beyond List and Read — with 403 Forbidden, evidenced as a WriteBlocked event. Every other request, including every request of a session that is not impersonated or not masked, passes through. It runs after ValidateSession; without a validated session in the context it passes the request through.

The middleware is a coarse, opt-in backstop: it stops a read-only session from reaching any mutating handler regardless of whether that handler consults the mask. It is not a substitute for honoring the mask in permission checks (Execute reaches handlers by POST, and a session masked to Execute is not read-only).

func (*BaseSession) Establish

func (s *BaseSession) Establish(ctx context.Context, evidence trace.Span, sessData *sessioninfo.SessionData) (context.Context, error)

Establish puts the validated session in ctx, resolves its principal, and stamps the request's evidence on the evidence span and on the request's log entry and every line logged within it: the end user, an impersonation's attributes, a token's attributes, and the principal a resolver changed. ValidateSession calls it once the cookie's session row has been checked; a machine outlet's token validation calls it with the session its token stands in for.

func (*BaseSession) ImpersonationTTL

func (s *BaseSession) ImpersonationTTL(maxDuration time.Duration) time.Duration

ImpersonationTTL returns the hard cap for a new impersonated session: the configured impersonation timeout (or the default), shortened by a positive maxDuration.

func (*BaseSession) Logout

func (s *BaseSession) Logout() http.HandlerFunc

Logout destroys the current session

func (*BaseSession) LogoutAPI

func (s *BaseSession) LogoutAPI(ctx context.Context) error

LogoutAPI destroys the session in ctx. For an impersonated session that this request validated, the record's end (written by DestroySession as Logout) is announced as an Ended event.

func (*BaseSession) SetXSRFToken

func (s *BaseSession) SetXSRFToken(next http.Handler) http.Handler

SetXSRFToken sets the XSRF Token

func (*BaseSession) StartImpersonatedSession

StartImpersonatedSession is the establishing step shared by every session type once the effective identity is resolved: it binds the actor to the validated session the call arrived on, if any, verifies a local actor's source session, writes the session row and its record atomically, delivers the Started event (a failing audit hook destroys the session and fails the call, so no unevidenced impersonated session ever lives), writes the auth and XSRF cookies, and stamps the evidence on the establishing request's log entry. req.Username is the session's effective identity; imp.SessionID is set on return.

func (*BaseSession) StartSession

func (s *BaseSession) StartSession(next http.Handler) http.Handler

StartSession initializes a session by restoring it from a cookie, or if that fails, initializing a new session. The session cookie is then updated and the sessionID is inserted into the context.

func (*BaseSession) StartSessionAPI

func (s *BaseSession) StartSessionAPI(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)

StartSessionAPI exposes the internals of the StartSession Handler for use with the API interface

func (*BaseSession) ValidateSession

func (s *BaseSession) ValidateSession(next http.Handler) http.Handler

ValidateSession checks the sessionID in the database to validate that it has not expired and updates the last activity timestamp if it is still valid. StartSession handler must be called before calling ValidateSession

The request's evidence — enduser.id, and the impersonation.* and principal.* attributes when they apply — is stamped on the span current in r.Context(): the server span, which is what trace-list filters match on.

func (*BaseSession) ValidateSessionAPI

func (s *BaseSession) ValidateSessionAPI(ctx context.Context) (context.Context, error)

ValidateSessionAPI checks the session cookie and if it is valid, stores the session data into the context. The request's evidence (see ValidateSession) is stamped on the span current in ctx — the caller's span.

func (*BaseSession) ValidateXSRFToken

func (s *BaseSession) ValidateXSRFToken(next http.Handler) http.Handler

ValidateXSRFToken validates the XSRF Token

type EndImpersonationResponse

type EndImpersonationResponse struct {
	// Restored reports that the browser's cookies name the actor's own session again;
	// false means the actor must log in.
	Restored bool `json:"restored"`
}

EndImpersonationResponse is the body of the EndImpersonation handler.

type Handlers

type Handlers interface {
	Authenticated() http.HandlerFunc
	Logout() http.HandlerFunc
	StartSession(next http.Handler) http.Handler
	ValidateSession(next http.Handler) http.Handler
	SetXSRFToken(next http.Handler) http.Handler
	ValidateXSRFToken(next http.Handler) http.Handler
	EnforceReadOnlyMask(next http.Handler) http.Handler
	EndImpersonation() http.HandlerFunc
}

Handlers defines the interface for session handlers used by all session implementations

type ImpersonationResponse

type ImpersonationResponse struct {
	Actor         string    `json:"actor"`
	ActorRealm    string    `json:"actorRealm,omitempty"`
	PrincipalKind string    `json:"principalKind"`
	Principal     string    `json:"principal"`
	Mask          []string  `json:"mask,omitempty"`
	Reason        string    `json:"reason,omitempty"`
	ExpiresAt     time.Time `json:"expiresAt"`
}

ImpersonationResponse is the impersonation portion of the Authenticated response, present only for an impersonated session so a frontend can banner it and render read-only affordances.

func NewImpersonationResponse

func NewImpersonationResponse(imp *sessioninfo.Impersonation) *ImpersonationResponse

NewImpersonationResponse renders the record for the Authenticated response; nil in, nil out. Mask is omitted for an unrestricted session.

type LogHandler

type LogHandler func(handler func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc

LogHandler defines the handler signature required for handling logs.

type TableName

type TableName struct {
	Option string
	Name   string
	Set    func(name string) error
}

TableName is a table name a session option set: the option's name for the error, the name, and the store setter that takes and validates it.

Jump to

Keyboard shortcuts

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