gas/auth
auth/session
import "github.com/gasmod/gas/auth/session"Package session authenticates HTTP requests by a session cookie, or by
an Authorization: Bearer header for clients that are not browsers,
with the sessions kept server-side in a SQL database. Its Service is an
auth.Authenticator, an auth.PrincipalRevoker and a gas.Service.
Register New as a singleton service, next to the database, migrate and config services, so that sessions, the *Service, is built and initialized. Then issue a session at login, and authenticate the routes behind it, rejecting cross-site writes:
login := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // ... check the user's password ... sess, err := sessions.Create(r.Context(), "user-42", nil, r) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } if err := sessions.SetCookie(w, sess); err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return }})
sameOrigin := session.RequireSameOrigin()mux.Handle("POST /login", sameOrigin(login))mux.Handle("/", sameOrigin(auth.Middleware(sessions)(appHandler)))With this setup:
- A login sets the cookie
session_id. - A later request that carries it reaches appHandler with a principal
whose subject is
user-42and whose scheme is auth.SchemeSession. - A request without it gets a 401.
- A POST from another site’s page gets a 403.
Sessions
Section titled “Sessions”Service.Create issues a session for a subject, with metadata that the session’s principal will carry, and stores it.
The subject must not be empty and holds at most auth.MaxValueLength (255) bytes, checked before anything is stored, so every dialect rejects the same subjects.
The metadata follows these rules:
- A nil metadata is an empty one; the session keeps a copy.
- Metadata is stored as JSON, so its values read back as JSON decodes them: numbers as float64, objects as map[string]any.
- Metadata that cannot be encoded as JSON fails Create.
The session records the request’s remote address and User-Agent, as the request gives them, so behind a proxy the address is the proxy’s. Both are cleaned before they are stored:
- Invalid UTF-8 becomes U+FFFD.
- Control characters are dropped.
- The address is cut to 255 bytes, and the User-Agent to 512.
Session IDs
Section titled “Session IDs”A session ID is 32 random bytes from crypto/rand, 43 characters of unpadded URL-safe base64. The ID is in the returned Session, and the service sends it nowhere itself: Service.SetCookie puts it in the cookie, or the app returns it in a response body to a client that is not a browser, as described under Clients that are not browsers. The database keys a session by the SHA-256 of its ID, so reading the database, or a backup of it, gives no ID that authenticates.
Upgrading from a version that stored the raw ID runs a migration that deletes every stored session, which signs every user out once.
Expiry
Section titled “Expiry”A session has two expiries:
- Its idle expiry, Session.ExpiresAt, is SessionTTL after it was created.
- Its absolute expiry is MaxLifetime after it was created, and nothing moves it.
A session is expired from the first of the two on, however it is used. SessionTTL must not exceed MaxLifetime.
The expiries are compared with the time in Go, as the database returns them. MySQL and SQLite keep times in whole seconds, and the auth stores truncate every time to the second before writing it, so a stored time is up to a second earlier than the one written. On those databases a session may so expire up to a second before its ExpiresAt, never after. Postgres keeps microseconds.
Extending on access
Section titled “Extending on access”With ExtendOnAccess on, Authenticate moves the idle expiry of a session it accepts to SessionTTL from now. It never moves it past the absolute expiry, and only does so when less than half of SessionTTL remains, so a session in steady use costs one write per half TTL rather than one per request. With ExtendOnAccess off, a session lasts SessionTTL from its creation.
The write is best-effort: when it fails, Authenticate still succeeds.
The error is logged at warn level with the message
session extend failed and the error under error, unless the
request’s context has ended, as when the client went away.
Last activity
Section titled “Last activity”Session.LastActive, and an Info’s, is when the session was last used, as last recorded. Create and Rotate record it, and so does every extension on access. Without more, a session in steady use is recorded about once per half SessionTTL, every 12 hours with the defaults.
ActivityInterval makes it finer: when Authenticate accepts a session whose last activity was recorded at least ActivityInterval ago, and does not extend it, it records now as its last activity, with an UPDATE of that column alone, so that it never undoes a concurrent extension. LastActive is then less than ActivityInterval behind the last request Authenticate accepted for the session, unless a write failed, enough for “active 5 minutes ago” on a page of the user’s sessions. A session in steady use costs one write per interval: a shorter one is more accurate and writes more. Zero, the default, turns it off; a negative interval is a configuration error.
The write is best-effort, as the extension’s is: when it fails,
Authenticate still succeeds, and the error is logged at warn level with
the message session touch failed and the error under error, unless
the request’s context has ended. On MySQL and SQLite, which keep whole
seconds, the last activity may be recorded up to a second early.
Cleanup
Section titled “Cleanup”Expired sessions are deleted by a cleanup that runs every CleanupInterval, each run bounded by CleanupTimeout, from Init to Close. Its first run is one CleanupInterval after Init.
Each run logs, with gas/auth/session under service:
- On success, the message
expired sessions deletedat debug level, with the number deleted undercount, zero included. - On failure, the message
background task failedat warn level, withsession cleanupundertaskand the error undererror. The cleanup goes on.
A zero CleanupInterval turns the cleanup off, and expired sessions then stay in the table, still rejected. A negative one is a configuration error.
Cookies
Section titled “Cookies”Service.SetCookie writes the cookie for a session that Create or Rotate returned, with:
- The configured name.
- The session ID as its value.
- The configured Path, Domain, Secure, HttpOnly and SameSite attributes.
- An Expires of the session’s absolute expiry.
The browser so keeps the cookie for as long as the session can live, while the server enforces the idle expiry, and an extended session needs no new cookie.
Service.ClearCookie writes a cookie of the same name and attributes
with an empty value and Max-Age=0, which makes the browser delete it.
It leaves the session in the database.
Init checks that the name, path and domain make a valid cookie, which net/http would otherwise drop or alter with only a log line. It also logs a warning, once per Init, for each insecure attribute:
session cookie is not Securesession cookie is not HttpOnlysession cookie is not SameSite Lax or Strict
Authentication
Section titled “Authentication”Service.Authenticate reads the session ID from the configured cookie
and, with AcceptBearer on, from the Authorization header:
- A request with the cookie, its value not empty, is authenticated by the cookie alone, and its Authorization headers are not read, even when the cookie’s value is not a session ID.
- Otherwise, with AcceptBearer on, an Authorization header whose
value, trimmed, starts with
Bearerin any case, then one or more spaces, carries the ID when its token has the form of a session ID. A Bearer token of another form, such as a JWT, is not a session credential and is left for other authenticators.
It returns:
- auth.ErrNoCredentials when the request is nil, or carries no ID: no such cookie, an empty value or one net/http cannot parse, and, with AcceptBearer on, no Bearer header whose token has the form of a session ID. An auth.Chain so moves on to its next member, such as a jwt.Service reading the same header.
- auth.ErrUnauthenticated when the cookie’s value is not a session ID, when more than one Bearer header carries a token of that form, or when no stored session has the ID. A value that does not have the form of a session ID is rejected without reading the database.
- auth.ErrCredentialsExpired when the session is past its idle or its absolute expiry.
- Otherwise an auth.BasePrincipal with the session’s subject and metadata, the scheme auth.SchemeSession, and as its credential ID the SHA-256 hex of the session ID, which identifies the session without being the secret.
Each denial is the auth sentinel prefixed with ServiceName, such as
gas/auth/session: no credentials, so errors.Is matches it and the
text names the service. A database failure is an infrastructure error,
which auth.Middleware answers with a 500.
Rotation
Section titled “Rotation”Service.Rotate moves the session whose ID the request carries, read as Authenticate reads it, to a new ID, and returns it for SetCookie or for the response to a client that is not a browser; the old ID no longer authenticates. It fails as Authenticate does when the request carries no ID or the session is missing or expired, and with ErrNilRequest when the request is nil.
The rotated session has:
- A new ID.
- The old one’s subject, metadata and creation time, so rotating never extends the absolute expiry.
- The address and User-Agent of the request.
- An idle expiry SessionTTL from now, capped by the absolute one.
The session is rotated in place, with one UPDATE of its stored row that changes its ID hash. Under concurrency:
- Of two concurrent rotations of one session, one succeeds and the other returns auth.ErrUnauthenticated.
- A RevokeAll of the subject that runs concurrently with a rotation leaves no session of the subject behind, the rotated one included, on every dialect.
Rotate after a change of the session’s privileges, such as a role change or a step-up authentication, and after a login that keeps an existing session, so that an ID captured before, such as one planted in the victim’s browser (session fixation), is worthless afterwards. A login that issues a session with Create needs no rotation, though the app should Revoke the session the request had, if any.
Listing
Section titled “Listing”Service.List returns a subject’s live sessions as Info values, newest first, for a page where a user sees where they are signed in and signs out one device. Sessions created at the same stored time are ordered by ID, descending. Sessions past their idle or absolute expiry are left out, as Authenticate would reject them, even before the cleanup deletes them.
An Info holds the session’s subject, metadata, address, User-Agent and times, and as its ID the SHA-256 hex of the session ID, never the session ID. Its ID is so safe to show to the user and to send back from a form, and it equals the credential ID of the principal Authenticate returns for the session, which tells the request’s own session apart in the list. Rotate changes it.
Revocation
Section titled “Revocation”Revoking deletes sessions:
- Service.Revoke deletes the session a principal from Authenticate stands for. A nil principal, a nil pointer included, is auth.ErrNilPrincipal, and one of another scheme auth.ErrSchemeMismatch. The principal’s credential ID is the hash of the session ID, so a principal built from Session.ID deletes nothing.
- Service.RevokeSession deletes a Session from Create or Rotate, without a request. A nil session, or one whose ID is not a session ID, is ErrInvalidSession.
- Service.RevokeByID deletes the session an Info.ID names, only if it belongs to the subject given, so that a user who sends back another user’s ID deletes nothing. An ID that is not 64 lowercase hex digits, such as a Session.ID, is ErrInvalidSession. An ID from before the session was rotated matches nothing. It reports whether it deleted a session, false when the ID matched none of the subject’s, whether the session is gone or another subject’s, so an API can answer “not found” without listing the sessions first.
- Service.RevokeOthers deletes every session of a principal’s subject but the principal’s own, for “sign out other devices”, in one DELETE. It rejects a principal as Revoke does. If the principal’s session is rotated before the DELETE runs, its ID hash no longer matches and it is deleted too.
- Service.RevokeAll deletes every session of a subject.
- Service.RevokeAllByScheme does the same for auth.SchemeSession, and nothing for any other scheme.
Revoking what is already gone, or was never there, is not an error. Revoking does not clear the cookie; ClearCookie does.
Cross-site requests
Section titled “Cross-site requests”A browser sends the session cookie with every request to the site, including one that another site’s page makes. So a cookie session needs protection against cross-site request forgery (CSRF), which the app owns.
SameSite=Lax, the default, keeps the cookie off cross-site POSTs from other sites. It does not keep it off POSTs from other subdomains of the same site, nor off GETs, so state-changing GETs stay unsafe.
RequireSameOrigin is middleware that adds a check based on headers
browsers set. It lets GET, HEAD, OPTIONS and TRACE through. Any other
method is rejected with a plain-text 403 Forbidden when:
- a
Sec-Fetch-Siteheader is present with a value other thansame-originornone, compared exactly; or - an
Originheader is present and is notscheme://host[:port]whose host and port equal the request’s Host, ignoring case. The scheme is not compared, andOrigin: nullnever matches.
Every value of a repeated header must pass. A request with neither header, as from a client that is not a browser or an old browser, is let through. RequireSameOrigin does not need the Service.
Behind a proxy that rewrites the Host header, the Origin check rejects every cross-origin-looking request, so forward the original Host.
RequireSameOrigin decides by those headers alone. It does not know how the request will be authenticated, and treats one with a Bearer header as any other, since a request that also carries the cookie is authenticated by the cookie. A session ID in a header needs no such check: a browser never adds the header on its own, so another site’s page cannot make a request that carries it. A client that is not a browser sends neither Sec-Fetch-Site nor Origin, and is let through. Script in a page of another origin that sends the header is rejected for unsafe methods; leave a route out of RequireSameOrigin for it only when no browser reaches that route with the cookie.
Clients that are not browsers
Section titled “Clients that are not browsers”A client that holds the session itself, such as a mobile app calling a
JSON API or native code opening a WebSocket, sends the session ID in an
Authorization: Bearer header instead of a cookie. Turn AcceptBearer
on; with it off, the default, the header is never read and the cookie
is the only carrier. Then:
- At sign-in, Create the session and return its Session.ID to the client in the response body, rather than calling SetCookie.
- The client keeps the ID in its secure storage and sends it on every
request as
Authorization: Bearer <id>. - Rotate returns a session with a new ID, and the old one stops authenticating at once: return the new ID in the response, and the client replaces the one it keeps.
- A WebSocket opens with an HTTP GET upgrade request, which authenticates like any other request, so put the header on it. The connection is not authenticated again after the upgrade.
The session’s expiry, extension, listing and revocation are the same as for a cookie session. Revoke the session at sign-out; there is no cookie to clear.
The header is read only when the request has no session cookie. A Bearer token that does not have the form of a session ID is auth.ErrNoCredentials for this service, so in an auth.Chain of this service and a jwt.Service the JWTs still reach the jwt.Service:
authn := auth.Chain{sessions, jwtService}mux.Handle("/api/", auth.Middleware(authn)(apiHandler))Configuration
Section titled “Configuration”Config holds the Settings in the session section of the
configuration. Init binds them from the gas.ConfigProvider over
DefaultConfig, or, with WithConfig, uses a copy of the given
configuration. Either way it checks the validate tags and these rules:
- CookieName is required and a valid cookie name.
- CookiePath and CookieDomain are valid for a cookie.
- CookieSameSite is 0 or an http.SameSite constant.
- SessionTTL and MaxLifetime are positive, and SessionTTL is at most MaxLifetime.
- CleanupInterval is not negative.
- CleanupTimeout is positive when CleanupInterval is.
- ActivityInterval is not negative.
A configuration given to WithConfig is checked as given: no zero setting in it is replaced by its default, so a Config literal that leaves MaxLifetime out fails Init. Build one from DefaultConfig to keep the defaults.
The defaults:
- CookieName: DefaultCookieName.
- CookiePath: DefaultCookiePath.
- CookieDomain: none.
- CookieSameSite: Lax.
- CookieSecure and CookieHTTPOnly: true.
- SessionTTL: DefaultSessionTTL (24 hours).
- MaxLifetime: DefaultMaxLifetime (30 days).
- ExtendOnAccess: true.
- CleanupInterval: DefaultCleanupInterval (1 hour).
- CleanupTimeout: DefaultCleanupTimeout (30 seconds).
- ActivityInterval: 0, off.
- AcceptBearer: false, the cookie only.
Service.Config returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was.
Lifecycle
Section titled “Lifecycle”New returns the constructor the dependency injection container calls, with a gas.DatabaseProvider, gas.Logger, gas.MigrationManager and gas.ConfigProvider. It fails with ErrNilLogger for a nil logger.
Service.Init runs these steps, in order:
- It resolves the configuration.
- It picks the SQL dialect from the database driver.
- It registers the migrations with the migration manager, which
creates and updates the
__gas_auth_sessionstable. - It starts the cleanup.
- It logs
service initializedat info level.
Service.Close stops the cleanup and waits for a run in progress.
Init may run again after Close, or again without it, and picks up a changed configuration. A failed Init stops the cleanup and leaves the service uninitialized. Before Init, after a failed Init and after Close, every method but Name, Init, Close and Config returns ErrNotInitialized.
Every event the service logs carries ServiceName under service.
Storage
Section titled “Storage”The database dialects are picked by the name the database provider’s Driver method reports:
- Postgres:
postgresandpgx. - MySQL:
mysql. It needsparseTime=truein the DSN, as gas/database sets it, and MySQL 8.0.13 or later, since the migration that hashes session IDs gives themetadataanduser_agentcolumns expression defaults. - SQLite:
sqliteandsqlite3.
Concurrency
Section titled “Concurrency”A Service is safe for concurrent use, Init and Close included. Provider is the interface the Service implements, for a mock seam.
Each Init builds its own store and publishes it with the configuration in one atomic step, so a method runs entirely with the configuration and store of one Init. Init and Close may run while other methods run:
- Each method running finishes with what it started with.
- The methods that start after Close return ErrNotInitialized.
Init and Close run one at a time, so the published state and the running cleanup always belong to the same call: once Close returns, no cleanup runs until the next Init.
Errors
Section titled “Errors”Authentication denials are the auth sentinels, wrapped, as listed under Authentication. The other sentinels, to be tested with errors.Is:
- ErrNotInitialized: a method ran before Init, after a failed Init, or after Close.
- ErrNilLogger: New’s constructor was given a nil logger.
- ErrNilConfig: WithConfig was given nil.
- ErrNoConfigProvider: there is neither a WithConfig configuration nor a ConfigProvider.
- ErrInvalidConfig: the configuration failed to bind, its tags or a rule.
- ErrNilRequest: Create or Rotate was given a nil request.
- ErrEmptySubject: Create was given an empty subject.
- auth.ErrValueTooLong: Create was given a subject longer than auth.MaxValueLength bytes.
- ErrInvalidSession: SetCookie or RevokeSession was given a nil session or one that Create or Rotate did not return, or RevokeByID an ID that is not an Info.ID.
- auth.ErrNilPrincipal: Revoke or RevokeOthers was given a nil principal.
- auth.ErrSchemeMismatch: Revoke or RevokeOthers was given a principal of another scheme.
ErrNilConfig, ErrNoConfigProvider, ErrInvalidConfig, ErrNotInitialized and ErrNilLogger are not defined by this package but shared by the module’s services, and ErrEmptySubject is auth.ErrEmptySubject.
Every error starts with ServiceName. Some errors then name the
operation, such as create: or revoke all::
- These do: the errors of Create, Rotate, SetCookie, List, Revoke, RevokeSession, RevokeByID, RevokeOthers, RevokeAll and RevokeAllByScheme, other than a denial or ErrNotInitialized, and a database error from Authenticate.
- These do not: a denial, ErrNotInitialized, and the errors of the constructor and Init.
A database error is wrapped, so errors.As reaches the driver’s error. No error includes a session ID, a cookie value or a configuration value:
gas/auth/session: service not initializedgas/auth/session: logger is nilgas/auth/session: no credentialsgas/auth/session: unauthenticatedgas/auth/session: unauthenticated: credentials expiredgas/auth/session: create: empty subjectgas/auth/session: create: value too long: subject is longer than 255 bytesgas/auth/session: rotate: request is nilgas/auth/session: set cookie: invalid sessiongas/auth/session: revoke: nil principalgas/auth/session: revoke: principal scheme mismatchgas/auth/session: revoke session: invalid sessiongas/auth/session: revoke by id: invalid sessiongas/auth/session: invalid config: session TTL must not exceed the max lifetimegas/auth/session: invalid config: cleanup interval must not be negativegas/auth/session: authenticate: gas/auth/session-store: get session: sql: database is closedAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultCookieName is the default name of the session cookie. DefaultCookieName = "session_id" // DefaultCookiePath is the default path of the session cookie. DefaultCookiePath = "/" // DefaultSessionTTL is the default idle lifetime of a session. DefaultSessionTTL = 24 * time.Hour // DefaultMaxLifetime is the default absolute lifetime of a session, // counted from its creation: 30 days. DefaultMaxLifetime = 30 * 24 * time.Hour // DefaultCleanupInterval is the default time between two deletions of // expired sessions. DefaultCleanupInterval = time.Hour // DefaultCleanupTimeout is the default bound on one deletion of expired // sessions. DefaultCleanupTimeout = 30 * time.Second)const ServiceName = "gas/auth/session"ServiceName is the session service’s name, which prefixes its errors.
Variables
Section titled “Variables”var ( // ErrNilConfig indicates that WithConfig was given nil. It is // svcutil.ErrNilConfig. ErrNilConfig = svcutil.ErrNilConfig // ErrNoConfigProvider indicates that there is neither a configuration // given to WithConfig nor a ConfigProvider to bind one from. It is // svcutil.ErrNoConfigProvider. ErrNoConfigProvider = svcutil.ErrNoConfigProvider // ErrInvalidConfig indicates that the configuration failed to bind, // failed its validate tags, or broke a rule. It is // svcutil.ErrInvalidConfig. ErrInvalidConfig = svcutil.ErrInvalidConfig // ErrNotInitialized indicates that a method was called before Init // succeeded, after a failed Init, or after Close. It is // svcutil.ErrNotInitialized. ErrNotInitialized = svcutil.ErrNotInitialized // ErrNilLogger indicates that the constructor was given a nil logger. // It is svcutil.ErrNilLogger. ErrNilLogger = svcutil.ErrNilLogger // ErrEmptySubject indicates that Create was given an empty subject. It // is auth.ErrEmptySubject. ErrEmptySubject = auth.ErrEmptySubject // ErrNilRequest indicates that Create or Rotate was given a nil // request. ErrNilRequest = errors.New("request is nil") // ErrInvalidSession indicates that SetCookie or RevokeSession was // given a nil session, or one that Create or Rotate did not issue: its // ID is not a session ID or, for SetCookie, it has no creation time. // RevokeByID returns it for an ID that is not an Info.ID. ErrInvalidSession = errors.New("invalid session"))func New
Section titled “func New”func New( opts ...Option,) func(gas.DatabaseProvider, gas.Logger, gas.MigrationManager, gas.ConfigProvider) (*Service, error)New returns a constructor for a Service, in the shape the dependency injection container calls. The constructor fails only for a nil logger, with ErrNilLogger; Init checks the configuration.
func RequireSameOrigin
Section titled “func RequireSameOrigin”func RequireSameOrigin() func(http.Handler) http.HandlerRequireSameOrigin returns middleware that rejects a cross-site request
with an unsafe method, as described in the package documentation, with
a plain-text 403 Forbidden. Requests it lets through reach the next
handler unchanged.
type Config
Section titled “type Config”type Config struct { // Session holds the settings. Session Settings}Config is the session service’s configuration, in the session
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns a new Config holding the defaults.
type Info
Section titled “type Info”type Info struct { // CreatedAt is when the session was created. CreatedAt time.Time // ExpiresAt is when the session expires unless it is used and // extended. ExpiresAt time.Time // LastActive is when the session was last used, as last recorded, as // Session.LastActive describes. LastActive time.Time // Metadata holds the values stored with the session. It is never nil. Metadata gas.BasePrincipalMetadata // ID identifies the session: the SHA-256 hex of its session ID, which // is also the CredentialID of the principal Authenticate returns for // it. It is not the session ID, and Rotate changes it. ID string // Subject is the user or client the session belongs to. Subject string // IPAddress is the remote address of the request that issued or last // rotated the session. IPAddress string // UserAgent is the User-Agent of the request that issued or last // rotated the session. UserAgent string}Info describes a live session, as List returns it. It holds the hash of the session ID, never the ID, so it is safe to show to the session’s user and to send back to revoke it with RevokeByID.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; Init checks it.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. It only records cfg: Init copies *cfg each time it runs, never changes it, and checks the copy as it checks a bound configuration. A nil cfg makes Init fail with ErrNilConfig.
Default: bind the session section from the ConfigProvider over
DefaultConfig.
type Provider
Section titled “type Provider”type Provider interface { auth.Authenticator auth.PrincipalRevoker
// Create issues a new session for subject, as Service.Create does. Create( ctx context.Context, subject string, meta gas.BasePrincipalMetadata, r *http.Request, ) (*Session, error) // Rotate replaces the request's session with a new one, as // Service.Rotate does. Rotate(ctx context.Context, r *http.Request) (*Session, error) // SetCookie writes the session's cookie, as Service.SetCookie does. SetCookie(w http.ResponseWriter, sess *Session) error // ClearCookie writes a cookie that removes the session cookie, as // Service.ClearCookie does. ClearCookie(w http.ResponseWriter) error // List returns the live sessions of subject, newest first, as // Service.List does. List(ctx context.Context, subject string) ([]Info, error) // RevokeByID deletes the session of subject that an Info.ID // names and reports whether it did, as Service.RevokeByID does. RevokeByID(ctx context.Context, subject, id string) (bool, error) // RevokeOthers deletes every session of the principal's subject but // the principal's own, as Service.RevokeOthers does. RevokeOthers(ctx context.Context, principal gas.Principal) error}Provider is what Service offers, for code that wants to depend on an interface, such as to swap in a mock in its tests.
type Service
Section titled “type Service”type Service struct { // contains filtered or unexported fields}Service authenticates requests by a session cookie, or with AcceptBearer an Authorization header, and manages the sessions, as described in the package documentation. It is safe for concurrent use, Init and Close included.
func (*Service) Authenticate
Section titled “func (*Service) Authenticate”func (s *Service) Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)Authenticate returns the principal of the session whose ID the request carries, in its cookie or, with AcceptBearer, in a Bearer header, as described in the package documentation.
func (*Service) ClearCookie
Section titled “func (*Service) ClearCookie”func (s *Service) ClearCookie(w http.ResponseWriter) errorClearCookie writes a cookie that makes the browser delete the session
cookie: the same name and attributes, an empty value and Max-Age=0.
It does not delete the session; Revoke does.
func (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose stops the cleanup, waiting for a run in progress, after which the service’s methods return ErrNotInitialized until Init runs again. It never fails, and the context is unused.
func (*Service) Config
Section titled “func (*Service) Config”func (s *Service) Config() ConfigConfig returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Config holds no slice, map or pointer, so the copy shares nothing with the service.
func (*Service) Create
Section titled “func (*Service) Create”func (s *Service) Create( ctx context.Context, subject string, meta gas.BasePrincipalMetadata, r *http.Request,) (*Session, error)Create issues a new session for subject with meta, from the request r, and stores it, as described in the package documentation. The caller sends it with SetCookie, or in the response to a client that sends it back in a Bearer header. meta may be nil; the session holds a copy.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(context.Context) errorInit resolves and checks the configuration, builds a store and registers its migrations, and starts the cleanup, as described in the package documentation. A failed Init stops the cleanup and leaves the service uninitialized. The context is unused: the cleanup runs until Close.
func (*Service) List
Section titled “func (*Service) List”func (s *Service) List(ctx context.Context, subject string) ([]Info, error)List returns the live sessions of subject, newest first; sessions created at the same stored time are ordered by ID, descending. Expired sessions the cleanup has not deleted yet are left out. A subject without live sessions gets an empty slice.
func (*Service) Name
Section titled “func (*Service) Name”func (s *Service) Name() stringName returns ServiceName.
func (*Service) Revoke
Section titled “func (*Service) Revoke”func (s *Service) Revoke(ctx context.Context, principal gas.Principal) errorRevoke deletes the session a principal from Authenticate stands for. A session that is already gone is not an error. A nil principal is auth.ErrNilPrincipal, and one of another scheme auth.ErrSchemeMismatch.
The principal’s credential ID is the hash of the session ID, so a principal built from Session.ID matches no session and deletes nothing; RevokeSession deletes a Session.
func (*Service) RevokeAll
Section titled “func (*Service) RevokeAll”func (s *Service) RevokeAll(ctx context.Context, subject string) errorRevokeAll deletes every session of subject. A subject with no sessions is not an error.
func (*Service) RevokeAllByScheme
Section titled “func (*Service) RevokeAllByScheme”func (s *Service) RevokeAllByScheme(ctx context.Context, subject, scheme string) errorRevokeAllByScheme is RevokeAll when scheme is auth.SchemeSession, and does nothing for any other scheme. Either way it first checks that the service is initialized.
func (*Service) RevokeByID
Section titled “func (*Service) RevokeByID”func (s *Service) RevokeByID(ctx context.Context, subject, id string) (bool, error)RevokeByID deletes the session whose Info.ID is id, only if it belongs to subject, so that a user given the IDs of their own sessions cannot revoke another user’s, and reports whether this call deleted one. A session that is gone, one that belongs to another subject, an ID from before the session was rotated and an ID that never named a session all answer false and no error, alike, so the answer says nothing about other subjects’ sessions. An id that is not an Info.ID, such as a Session.ID, is ErrInvalidSession and deletes nothing.
func (*Service) RevokeOthers
Section titled “func (*Service) RevokeOthers”func (s *Service) RevokeOthers(ctx context.Context, principal gas.Principal) errorRevokeOthers deletes every session of the subject of a principal from Authenticate except the session the principal stands for, as a “sign out other devices” action does, in one DELETE. The principal’s own session need not still exist, and a subject with no other sessions is not an error. A nil principal is auth.ErrNilPrincipal, and one of another scheme auth.ErrSchemeMismatch.
The session kept is the one whose ID hash is the principal’s credential ID, so if that session is rotated before the DELETE runs, its new ID hash no longer matches and it is deleted too.
func (*Service) RevokeSession
Section titled “func (*Service) RevokeSession”func (s *Service) RevokeSession(ctx context.Context, sess *Session) errorRevokeSession deletes the session sess, as returned by Create or Rotate. A session that is already gone is not an error. A nil session, or one whose ID is not a session ID, is ErrInvalidSession and deletes nothing.
func (*Service) Rotate
Section titled “func (*Service) Rotate”func (s *Service) Rotate(ctx context.Context, r *http.Request) (*Session, error)Rotate moves the session whose ID the request carries, as Authenticate reads it, to a new ID, as described in the package documentation, and returns it. The caller sends it with SetCookie, or in the response to a client that sends it back in a Bearer header.
func (*Service) SetCookie
Section titled “func (*Service) SetCookie”func (s *Service) SetCookie(w http.ResponseWriter, sess *Session) errorSetCookie writes the session cookie for sess, as described in the package documentation: its value is sess.ID and it expires at sess.CreatedAt plus MaxLifetime. sess must come from Create or Rotate; a nil session, or one without a valid ID or creation time, is ErrInvalidSession and writes nothing.
type Session
Section titled “type Session”type Session struct { // CreatedAt is when the session was created. The session expires at // CreatedAt plus the MaxLifetime setting at the latest. CreatedAt time.Time // ExpiresAt is when the session expires unless it is used and // extended. ExpiresAt time.Time // LastActive is when the session was last used, as last recorded: // when it was created or rotated, when Authenticate extended it, and, // with ActivityInterval set, when Authenticate found the last record // at least that old. See the package documentation. LastActive time.Time // Metadata holds the values stored with the session, which its // principal carries. Metadata gas.BasePrincipalMetadata // ID is the session ID, the secret the client sends back in the // cookie or, with AcceptBearer, in a Bearer header. The service // stores only its hash. ID string // Subject is the user or client the session belongs to. Subject string // IPAddress is the remote address of the request that issued the // session. IPAddress string // UserAgent is the User-Agent of the request that issued the session. UserAgent string}Session is a session that Create or Rotate issued, as described in the package documentation. Its ID is the secret the client sends back.
type Settings
Section titled “type Settings”type Settings struct { // CookieName is the name of the session cookie. It must be a valid // cookie name. // // Default: DefaultCookieName. CookieName string `validate:"required"` // CookiePath is the cookie's Path attribute. Empty sends none. // // Default: DefaultCookiePath. CookiePath string // CookieDomain is the cookie's Domain attribute. Empty sends none, so // the cookie goes only to the host that set it. // // Default: empty. CookieDomain string // CookieSameSite is the cookie's SameSite attribute, one of the // http.SameSite constants or 0 for none. // // Default: http.SameSiteLaxMode. CookieSameSite http.SameSite // SessionTTL is how long a session lasts without being used: its idle // lifetime. It must be positive and at most MaxLifetime. // // Default: DefaultSessionTTL. SessionTTL time.Duration `validate:"gt=0s"` // MaxLifetime is how long a session lasts at most from its creation, // however much it is used. It must be positive. // // Default: DefaultMaxLifetime. MaxLifetime time.Duration `validate:"gt=0s"` // CleanupInterval is the time between two deletions of expired // sessions. Zero turns the cleanup off; a negative interval is a // configuration error. // // Default: DefaultCleanupInterval. CleanupInterval time.Duration // CleanupTimeout bounds one deletion of expired sessions. It must be // positive when the cleanup is on. // // Default: DefaultCleanupTimeout. CleanupTimeout time.Duration // ActivityInterval makes authentication record a session's last active // time once at least this long has passed since it was last recorded, // as described in the package documentation, so that LastActive is // accurate to within it. Zero records it only when the expiry is set; // a negative interval is a configuration error. // // Default: 0. ActivityInterval time.Duration // CookieSecure sets the cookie's Secure attribute. // // Default: true. CookieSecure bool // CookieHTTPOnly sets the cookie's HttpOnly attribute. // // Default: true. CookieHTTPOnly bool // ExtendOnAccess makes authentication move a session's idle expiry // forward, as described in the package documentation. // // Default: true. ExtendOnAccess bool // AcceptBearer makes Authenticate and Rotate also read the session ID // from an `Authorization: Bearer` header, for clients that are not // browsers, as described in the package documentation. The cookie // takes precedence when a request carries both. // // Default: false. AcceptBearer bool}Settings are the session service’s settings, as described in the package documentation.