## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# 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.

The Markdown of https://gasmod.dev/reference/auth/session/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
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](#Service) is an
auth.Authenticator, an auth.PrincipalRevoker and a gas.Service.

## Usage

Register [New](#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:

```go
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-42` and whose scheme is auth.SchemeSession.
- A request without it gets a 401.
- A POST from another site's page gets a 403.

## Sessions

[Service.Create](#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

A session ID is 32 random bytes from crypto/rand, 43 characters of
unpadded URL-safe base64. The ID is in the returned [Session](#Session), and the
service sends it nowhere itself: [Service.SetCookie](#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

A session has two expiries:

- Its idle expiry, [Session](#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

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

[Session](#Session).LastActive, and an [Info](#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

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 deleted` at debug level,
with the number deleted under `count`, zero included.
- On failure, the message `background task failed` at warn level,
with `session cleanup` under `task` and the error under `error`. 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

[Service.SetCookie](#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](#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 Secure`
- `session cookie is not HttpOnly`
- `session cookie is not SameSite Lax or Strict`

## Authentication

[Service.Authenticate](#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 `Bearer` in 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](#ServiceName), such as
`gas/auth/session: no credentials`, so [errors.Is](https://pkg.go.dev/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

[Service.Rotate](#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](#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

[Service.List](#Service.List) returns a subject's live sessions as [Info](#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

Revoking deletes sessions:

- [Service.Revoke](#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](#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](#ErrInvalidSession).
- [Service.RevokeByID](#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](#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](#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](#Service.RevokeAll) deletes every session of a subject.
- [Service.RevokeAllByScheme](#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

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](#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-Site` header is present with a value other than
`same-origin` or `none`, compared exactly; or
- an `Origin` header is present and is not `scheme://host[:port]`
whose host and port equal the request's Host, ignoring case. The
scheme is not compared, and `Origin: null` never 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

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:

1. At sign-in, Create the session and return its [Session](#Session).ID to the
client in the response body, rather than calling SetCookie.
2. The client keeps the ID in its secure storage and sends it on every
request as `Authorization: Bearer <id>`.
3. 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.
4. 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:

```go
authn := auth.Chain{sessions, jwtService}
mux.Handle("/api/", auth.Middleware(authn)(apiHandler))
```

## Configuration

[Config](#Config) holds the [Settings](#Settings) in the `session` section of the
configuration. Init binds them from the gas.ConfigProvider over
[DefaultConfig](#DefaultConfig), or, with [WithConfig](#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](#DefaultConfig) to
keep the defaults.

The defaults:

- CookieName: [DefaultCookieName](#DefaultCookieName).
- CookiePath: [DefaultCookiePath](#DefaultCookiePath).
- CookieDomain: none.
- CookieSameSite: Lax.
- CookieSecure and CookieHTTPOnly: true.
- SessionTTL: [DefaultSessionTTL](#DefaultSessionTTL) (24 hours).
- MaxLifetime: [DefaultMaxLifetime](#DefaultMaxLifetime) (30 days).
- ExtendOnAccess: true.
- CleanupInterval: [DefaultCleanupInterval](#DefaultCleanupInterval) (1 hour).
- CleanupTimeout: [DefaultCleanupTimeout](#DefaultCleanupTimeout) (30 seconds).
- ActivityInterval: 0, off.
- AcceptBearer: false, the cookie only.

[Service.Config](#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

[New](#New) returns the constructor the dependency injection container calls,
with a gas.DatabaseProvider, gas.Logger, gas.MigrationManager and
gas.ConfigProvider. It fails with [ErrNilLogger](#ErrNilLogger) for a nil logger.

[Service.Init](#Service.Init) runs these steps, in order:

1. It resolves the configuration.
2. It picks the SQL dialect from the database driver.
3. It registers the migrations with the migration manager, which
creates and updates the `__gas_auth_sessions` table.
4. It starts the cleanup.
5. It logs `service initialized` at info level.

[Service.Close](#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](#ErrNotInitialized).

Every event the service logs carries [ServiceName](#ServiceName) under `service`.

## Storage

The database dialects are picked by the name the database provider's
Driver method reports:

- Postgres: `postgres` and `pgx`.
- MySQL: `mysql`. It needs `parseTime=true` in the DSN, as
gas/database sets it, and MySQL 8.0.13 or later, since the migration
that hashes session IDs gives the `metadata` and `user_agent`
columns expression defaults.
- SQLite: `sqlite` and `sqlite3`.

## Concurrency

A Service is safe for concurrent use, Init and Close included.
[Provider](#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

Authentication denials are the auth sentinels, wrapped, as listed under
Authentication. The other sentinels, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrNotInitialized](#ErrNotInitialized): a method ran before Init, after a failed Init,
or after Close.
- [ErrNilLogger](#ErrNilLogger): New's constructor was given a nil logger.
- [ErrNilConfig](#ErrNilConfig): WithConfig was given nil.
- [ErrNoConfigProvider](#ErrNoConfigProvider): there is neither a WithConfig configuration
nor a ConfigProvider.
- [ErrInvalidConfig](#ErrInvalidConfig): the configuration failed to bind, its tags or a
rule.
- [ErrNilRequest](#ErrNilRequest): Create or Rotate was given a nil request.
- [ErrEmptySubject](#ErrEmptySubject): Create was given an empty subject.
- auth.ErrValueTooLong: Create was given a subject longer than
auth.MaxValueLength bytes.
- [ErrInvalidSession](#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](#ErrNilConfig), [ErrNoConfigProvider](#ErrNoConfigProvider), [ErrInvalidConfig](#ErrInvalidConfig),
[ErrNotInitialized](#ErrNotInitialized) and [ErrNilLogger](#ErrNilLogger) are not defined by this package
but shared by the module's services, and [ErrEmptySubject](#ErrEmptySubject) is
auth.ErrEmptySubject.

Every error starts with [ServiceName](#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](https://pkg.go.dev/errors#As) reaches the driver's error.
No error includes a session ID, a cookie value or a configuration
value:

```go
gas/auth/session: service not initialized
gas/auth/session: logger is nil
gas/auth/session: no credentials
gas/auth/session: unauthenticated
gas/auth/session: unauthenticated: credentials expired
gas/auth/session: create: empty subject
gas/auth/session: create: value too long: subject is longer than 255 bytes
gas/auth/session: rotate: request is nil
gas/auth/session: set cookie: invalid session
gas/auth/session: revoke: nil principal
gas/auth/session: revoke: principal scheme mismatch
gas/auth/session: revoke session: invalid session
gas/auth/session: revoke by id: invalid session
gas/auth/session: invalid config: session TTL must not exceed the max lifetime
gas/auth/session: invalid config: cleanup interval must not be negative
gas/auth/session: authenticate: gas/auth/session-store: get session: sql: database is closed
```


## API reference

### Constants

<a id="DefaultCookieName"></a><a id="DefaultCookiePath"></a><a id="DefaultSessionTTL"></a><a id="DefaultMaxLifetime"></a><a id="DefaultCleanupInterval"></a><a id="DefaultCleanupTimeout"></a>

```go
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
)
```

<a id="ServiceName"></a>

```go
const ServiceName = "gas/auth/session"
```

ServiceName is the session service's name, which prefixes its errors.

### Variables

<a id="ErrNilConfig"></a><a id="ErrNoConfigProvider"></a><a id="ErrInvalidConfig"></a><a id="ErrNotInitialized"></a><a id="ErrNilLogger"></a><a id="ErrEmptySubject"></a><a id="ErrNilRequest"></a><a id="ErrInvalidSession"></a>

```go
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")
)
```

<a id="New"></a>

#### func New

```go
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.

<a id="RequireSameOrigin"></a>

#### func RequireSameOrigin

```go
func RequireSameOrigin() func(http.Handler) http.Handler
```

RequireSameOrigin 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.

<a id="Config"></a>

### type Config

```go
type Config struct {
	// Session holds the settings.
	Session Settings
}
```

Config is the session service's configuration, in the `session`
section.

<a id="DefaultConfig"></a>

#### func DefaultConfig

```go
func DefaultConfig() *Config
```

DefaultConfig returns a new Config holding the defaults.

<a id="Info"></a>

### type Info

```go
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.

<a id="Option"></a>

### type Option

```go
type Option func(*Service)
```

Option configures a Service. Options only record what they are given;
Init checks it.

<a id="WithConfig"></a>

#### func WithConfig

```go
func WithConfig(cfg *Config) Option
```

WithConfig 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.

<a id="Provider"></a><a id="Provider.Create"></a><a id="Provider.Rotate"></a><a id="Provider.SetCookie"></a><a id="Provider.ClearCookie"></a><a id="Provider.List"></a><a id="Provider.RevokeByID"></a><a id="Provider.RevokeOthers"></a>

### type Provider

```go
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.

<a id="Service"></a>

### type Service

```go
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.

<a id="Service.Authenticate"></a>

#### func (*Service) Authenticate

```go
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.

<a id="Service.ClearCookie"></a>

#### func (*Service) ClearCookie

```go
func (s *Service) ClearCookie(w http.ResponseWriter) error
```

ClearCookie 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.

<a id="Service.Close"></a>

#### func (*Service) Close

```go
func (s *Service) Close(context.Context) error
```

Close 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.

<a id="Service.Config"></a>

#### func (*Service) Config

```go
func (s *Service) Config() Config
```

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. Config holds no slice, map or
pointer, so the copy shares nothing with the service.

<a id="Service.Create"></a>

#### func (*Service) Create

```go
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.

<a id="Service.Init"></a>

#### func (*Service) Init

```go
func (s *Service) Init(context.Context) error
```

Init 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.

<a id="Service.List"></a>

#### func (*Service) List

```go
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.

<a id="Service.Name"></a>

#### func (*Service) Name

```go
func (s *Service) Name() string
```

Name returns ServiceName.

<a id="Service.Revoke"></a>

#### func (*Service) Revoke

```go
func (s *Service) Revoke(ctx context.Context, principal gas.Principal) error
```

Revoke 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.

<a id="Service.RevokeAll"></a>

#### func (*Service) RevokeAll

```go
func (s *Service) RevokeAll(ctx context.Context, subject string) error
```

RevokeAll deletes every session of subject. A subject with no sessions
is not an error.

<a id="Service.RevokeAllByScheme"></a>

#### func (*Service) RevokeAllByScheme

```go
func (s *Service) RevokeAllByScheme(ctx context.Context, subject, scheme string) error
```

RevokeAllByScheme is RevokeAll when scheme is auth.SchemeSession, and
does nothing for any other scheme. Either way it first checks that the
service is initialized.

<a id="Service.RevokeByID"></a>

#### func (*Service) RevokeByID

```go
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.

<a id="Service.RevokeOthers"></a>

#### func (*Service) RevokeOthers

```go
func (s *Service) RevokeOthers(ctx context.Context, principal gas.Principal) error
```

RevokeOthers 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.

<a id="Service.RevokeSession"></a>

#### func (*Service) RevokeSession

```go
func (s *Service) RevokeSession(ctx context.Context, sess *Session) error
```

RevokeSession 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.

<a id="Service.Rotate"></a>

#### func (*Service) Rotate

```go
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.

<a id="Service.SetCookie"></a>

#### func (*Service) SetCookie

```go
func (s *Service) SetCookie(w http.ResponseWriter, sess *Session) error
```

SetCookie 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.

<a id="Session"></a>

### type Session

```go
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.

<a id="Settings"></a>

### type Settings

```go
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.
