auth

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 6 Imported by: 0

README

gas/auth

Test Go Reference Go Version License

Part of the Gas monorepo · Documentation · All modules

Authentication, authorization, and credential management for the Gas framework: JWT, server-side sessions, API keys, and single-use tokens.

Defines auth.Authenticator, auth.Authorizer, and auth.PrincipalRevoker, and implements them. The gas.Principal they produce, and the helpers that store it on a request, stay in core.

go get github.com/gasmod/gas/auth
gas.WithSingletonService[*jwt.Service](jwt.New()),
gas.WithSingletonService[*session.Service](session.New()),

jwt.New() needs gas.ConfigProvider and gas.Logger. session.New(), apikey.New() and token.New() also need gas.DatabaseProvider and gas.MigrationManager, since they persist credentials and own migrations.

Package Provides
auth BasePrincipal, Chain, authentication and authorization middleware, sentinel errors
auth/jwt Stateless JWT, HS256 or RS256
auth/session Server-side sessions with cookie management
auth/apikey Hashed API keys with scopes
auth/token Single-use tokens: magic links, verification, password reset
auth/authtest Mocks for the three auth interfaces

Documentation

The full documentation is on the docs site. This README is deliberately a signpost: keeping a second copy here is how the docs drifted before.

License

MIT

Documentation

Overview

Package auth defines how a Gas app authenticates and authorizes HTTP requests: the Authenticator, Authorizer and PrincipalRevoker interfaces, the error contract they share, Chain to try several authenticators, and the middleware that runs them.

Packages jwt, session, apikey and token implement the credentials. The gas.Principal they produce, and gas.WithPrincipal and gas.PrincipalFromContext, live in core.

Usage

Authenticate every request with a JWT or a session cookie, then require a permission on one route:

authn := auth.Middleware(
	auth.Chain{jwtService, sessionService},
	auth.WithChallenge(`Bearer realm="api"`),
)
reports := auth.RequireAuthorization(authorizer, "read", "reports")

mux.Handle("/reports", authn(reports(reportsHandler)))

With this setup:

  • A request with a valid token or session reaches reportsHandler with its principal on the context, if authorizer allows it to read reports.
  • A request with neither gets a 401 with the header `WWW-Authenticate: Bearer realm="api"`.
  • A request the authorizer denies gets a 403.

Authenticators

An Authenticator looks at a request and returns the principal it identifies, or nil and an error that says why not:

  • ErrNoCredentials when the request carries no credentials for it, such as no Authorization header for a JWT authenticator.
  • An error matching ErrUnauthenticated when it carries credentials that are not valid. ErrCredentialsExpired and ErrCredentialRevoked are the specific cases, and both wrap ErrUnauthenticated.
  • Any other error when it could not decide, such as a database that is down. This is an infrastructure error.

An authenticator may wrap these sentinels; they are matched with errors.Is. A nil principal with a nil error, including a nil pointer of a type that implements gas.Principal, counts as ErrUnauthenticated everywhere in this package, never as a success.

Principals

BasePrincipal is a gas.Principal holding fixed values, which authenticators return. NewPrincipal builds one:

  • A nil metadata becomes an empty gas.BasePrincipalMetadata.
  • A non-nil metadata is kept, not copied, so later changes to the map show through.

SchemeJWT, SchemeSession and SchemeAPIKey are the schemes of this module's authenticators.

Chains

A Chain is an Authenticator that tries its members in order and returns the principal of the first one that succeeds. The members after it are not called, and a member that returns ErrNoCredentials is skipped. When no member succeeds:

  1. If every member returned ErrNoCredentials, or the chain is empty, the chain returns ErrNoCredentials.
  2. Otherwise, if any member returned an infrastructure error, the chain returns those errors joined with errors.Join, in member order, so an outage is never hidden by another member's denial.
  3. Otherwise the chain returns the error of the first member that denied the credentials it saw, so an expired token stays ErrCredentialsExpired even when a later member finds nothing.

Errors are returned as the members returned them, not wrapped. A nil member panics when the chain reaches it.

Middleware

Middleware runs an Authenticator on each request. On success it stores the principal on the request's context with gas.WithPrincipal, where handlers read it with gas.PrincipalFromContext or gas.Context.Principal, and calls the next handler.

Otherwise it does not call the next handler, and answers:

  • 401 for ErrNoCredentials or an error matching ErrUnauthenticated, with the code `unauthorized`.
  • 500 for any other error, with the code `internal_error`. When the request's context carries a gas.Logger, as gas.RequestLogger arranges, the error is logged with it at error level, with the message `authentication failed` and the error under `error`. Once the request's context has ended, such as when the client went away, the 500 is still written but nothing is logged.

The errors are told apart with errors.Is, so an error that joins a denial with another error counts as a denial; Chain never returns one.

Each response is the core's error response, written with gas.WriteError as a handler's error is: an RFC 9457 problem details document with the code above, or plain text for a client whose Accept header asks for HTML and not JSON. It says nothing about the cause. A 500 means the check itself failed, such as the database being down, not that the credentials were refused, so a client should not discard its credentials on one.

An authenticator that returns ErrForbidden, which is not a denial of credentials, gets a 500 like any other infrastructure error.

Middleware takes these options:

  • WithOnError replaces both responses with a function of the authenticator's error, which then owns the response and its logging.
  • WithChallenge sets a `WWW-Authenticate` value that Middleware puts on the response to a 401-class error, before calling the error function, which may change it. By default no such header is sent.

Middleware panics at construction when the Authenticator is nil or a nil pointer.

Schemes

RequireScheme lets a request through only when Middleware stored a principal with the given scheme, compared exactly. Otherwise:

  • A request without a principal gets a 401 with the code `unauthorized`.
  • A request with another scheme gets a 403 with the code `forbidden`.

Both are written as Middleware writes its responses, and neither says which scheme was wanted.

Authorization

An Authorizer decides whether a principal may perform an action on a resource. It returns:

  • nil to allow.
  • An error matching ErrForbidden to deny.
  • Any other error when it could not decide.

RequireAuthorization runs one with a fixed action and resource on the principal Middleware stored, and lets the request through when it allows. Otherwise:

  • A request without a principal gets a 401 with the code `unauthorized`.
  • A denial gets a 403 with the code `forbidden`.
  • Any other error gets a 500 with the code `internal_error`. It is logged as Middleware logs one, with the message `authorization failed`, and likewise not logged once the request's context has ended.

All three are written as Middleware writes its responses.

RequireAuthorization panics at construction when the Authorizer is nil or a nil pointer.

Revocation

A PrincipalRevoker invalidates credentials so that they no longer authenticate. It revokes one of:

  • The credential a principal used.
  • Every credential of a subject.
  • Every credential of a subject with a given scheme.

Issuing and revoking

The module's services share these rules, and the sentinels for them:

  • A credential is never issued for an empty subject: ErrEmptySubject from jwt's Sign and SignWithExpiry, session's Create, apikey's Generate and token's Issue.
  • A subject, an API key name and a token purpose hold at most MaxValueLength (255) bytes, checked before anything is stored, so every database behaves the same: ErrValueTooLong from session's Create, apikey's Generate and token's Issue. CheckLength makes the check; its error names the field, never the value.
  • A method that acts on the credential of a principal, such as session's Revoke or apikey's Revoke and Delete, returns ErrNilPrincipal for a nil principal, a nil pointer included, and ErrSchemeMismatch for a principal of another scheme, rather than doing nothing. RevokeAllByScheme with another scheme stays a no-op.

Concurrency

Chain, BasePrincipal and the middleware keep no mutable state. They are safe for concurrent use, as long as the authenticators and authorizers they call are.

A BasePrincipal's metadata map is shared with the caller of NewPrincipal, so changing it while requests read it is a data race.

Errors

The sentinel errors, to be tested with errors.Is:

The sentinels of the rules in Issuing and revoking follow. This package never returns them except from CheckLength, and the services return them wrapped after their name:

Their messages, then CheckLength's error for a subject:

no credentials
unauthenticated
unauthenticated: credentials expired
unauthenticated: credential revoked
forbidden
empty subject
value too long
principal scheme mismatch
nil principal
value too long: subject is longer than 255 bytes

The module's authenticators never put a credential, such as a token, a key or a session ID, into an error, and neither does this package.

Index

Constants

View Source
const (
	// SchemeJWT is the scheme of principals authenticated by a JWT.
	SchemeJWT = "jwt"
	// SchemeSession is the scheme of principals authenticated by a
	// server-side session.
	SchemeSession = "session"
	// SchemeAPIKey is the scheme of principals authenticated by an API
	// key.
	SchemeAPIKey = "apikey"
)

Scheme constants name the authentication method a principal came from, as gas.Principal.Scheme returns it.

View Source
const MaxValueLength = 255

MaxValueLength is the most bytes a subject, an API key name or a token purpose may hold, as described in the package documentation.

Variables

View Source
var (
	// ErrUnauthenticated indicates that a request presented credentials
	// that are not valid. ErrCredentialsExpired and ErrCredentialRevoked
	// wrap it, so it matches every way credentials can be denied.
	ErrUnauthenticated = errors.New("unauthenticated")
	// ErrNoCredentials indicates that a request carries no credentials for
	// an authenticator, such as a missing header or cookie. It does not
	// wrap ErrUnauthenticated.
	ErrNoCredentials = errors.New("no credentials")
	// ErrCredentialsExpired indicates that a request presented credentials
	// that were valid once and have expired. It wraps ErrUnauthenticated.
	ErrCredentialsExpired = fmt.Errorf("%w: credentials expired", ErrUnauthenticated)
	// ErrCredentialRevoked indicates that a request presented a credential
	// that has been revoked. It wraps ErrUnauthenticated.
	ErrCredentialRevoked = fmt.Errorf("%w: credential revoked", ErrUnauthenticated)
	// ErrForbidden indicates that an Authorizer denied a principal an
	// action on a resource.
	ErrForbidden = errors.New("forbidden")
	// ErrNilPrincipal indicates that a method that acts on a principal,
	// such as Revoke, got a nil one or a nil pointer.
	ErrNilPrincipal = errors.New("nil principal")
	// ErrSchemeMismatch indicates that a method that acts on a principal,
	// such as Revoke, got one whose scheme is not the service's.
	ErrSchemeMismatch = errors.New("principal scheme mismatch")
	// ErrEmptySubject indicates that a credential was to be issued for an
	// empty subject.
	ErrEmptySubject = errors.New("empty subject")
	// ErrValueTooLong indicates that a value, such as a subject, holds
	// more than MaxValueLength bytes.
	ErrValueTooLong = errors.New("value too long")
)

Functions

func CheckLength added in v0.6.0

func CheckLength(field, value string) error

CheckLength returns nil when value holds at most MaxValueLength bytes, and otherwise an error wrapping ErrValueTooLong that names field, never the value.

func Middleware

func Middleware(a Authenticator, opts ...MiddlewareOption) func(http.Handler) http.Handler

Middleware returns middleware that authenticates each request with a, as described in the package documentation. On success it stores the principal with gas.WithPrincipal and calls the next handler; otherwise it answers the request itself.

Middleware panics when a is nil or a nil pointer, since that is a wiring mistake best caught at startup.

func RequireAuthorization added in v0.6.0

func RequireAuthorization(a Authorizer, action, resource string) func(http.Handler) http.Handler

RequireAuthorization returns middleware that lets a request through only when a allows its principal the action on the resource, as described in the package documentation: 401 without a principal, 403 when a denies, 500 when a fails.

RequireAuthorization panics when a is nil or a nil pointer, since that is a wiring mistake best caught at startup.

func RequireScheme

func RequireScheme(scheme string) func(http.Handler) http.Handler

RequireScheme returns middleware that lets a request through only when Middleware has authenticated it with the given scheme, as described in the package documentation: 401 without a principal, 403 for another scheme.

Types

type Authenticator added in v0.5.5

type Authenticator interface {
	// Authenticate returns the request's principal, or nil and an error:
	// ErrNoCredentials when the request carries no credentials for it, an
	// error matching ErrUnauthenticated when they are not valid, and any
	// other error when it could not decide.
	Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)
}

Authenticator identifies the caller of an HTTP request, following the error contract in the package documentation.

type Authorizer added in v0.5.5

type Authorizer interface {
	// Authorize returns nil to allow, an error matching ErrForbidden to
	// deny, and any other error when it could not decide.
	Authorize(ctx context.Context, principal gas.Principal, action, resource string) error
}

Authorizer decides whether a principal may perform an action on a resource. Authentication tells who the caller is; an Authorizer decides what the caller may do.

type BasePrincipal

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

BasePrincipal is a gas.Principal holding fixed values, as described in the package documentation.

func NewPrincipal

func NewPrincipal(subject, scheme, credentialID string, meta gas.PrincipalMetadata) *BasePrincipal

NewPrincipal returns a BasePrincipal with the given values. A nil meta becomes an empty gas.BasePrincipalMetadata, so Metadata().Value never dereferences nil. A non-nil meta is kept as given, not copied.

func (*BasePrincipal) CredentialID

func (p *BasePrincipal) CredentialID() string

CredentialID returns the identifier of the credential used, such as a session's or an API key's ID.

func (*BasePrincipal) Metadata

func (p *BasePrincipal) Metadata() gas.PrincipalMetadata

Metadata returns the principal's metadata. It is never nil.

func (*BasePrincipal) Scheme

func (p *BasePrincipal) Scheme() string

Scheme returns the authentication method, such as SchemeJWT.

func (*BasePrincipal) Subject

func (p *BasePrincipal) Subject() string

Subject returns the stable identifier of the user or client.

type Chain

type Chain []Authenticator

Chain is an Authenticator that tries its members in order, as described in the package documentation.

func (Chain) Authenticate

func (c Chain) Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)

Authenticate returns the principal of the first member that succeeds. When none does, it returns ErrNoCredentials if no member saw credentials, the members' infrastructure errors joined in order if there are any, and otherwise the error of the first member that denied the credentials.

type MiddlewareOption

type MiddlewareOption func(*middlewareOptions)

MiddlewareOption configures Middleware.

func WithChallenge added in v0.6.0

func WithChallenge(value string) MiddlewareOption

WithChallenge sets the `WWW-Authenticate` header value Middleware sends when it denies a request for its credentials, such as `Bearer realm="api"`. An empty value sends no header.

Default: no header.

func WithOnError

func WithOnError(fn func(w http.ResponseWriter, r *http.Request, err error)) MiddlewareOption

WithOnError sets the function that writes the response when authentication fails, in place of the default 401 or 500. It gets the authenticator's error and owns the whole response. A nil fn keeps the default.

Default: the core's error response, written with gas.WriteError: a 401 with code `unauthorized`, or a 500 with code `internal_error`, as described in the package documentation.

type PrincipalRevoker added in v0.5.5

type PrincipalRevoker interface {
	// Revoke invalidates the credential the principal was authenticated
	// with.
	Revoke(ctx context.Context, principal gas.Principal) error
	// RevokeAll invalidates every credential of a subject.
	RevokeAll(ctx context.Context, subject string) error
	// RevokeAllByScheme invalidates every credential of a subject that has
	// the given scheme, such as all its sessions.
	RevokeAllByScheme(ctx context.Context, subject, scheme string) error
}

PrincipalRevoker invalidates credentials, so that they no longer authenticate.

Directories

Path Synopsis
Package apikey authenticates HTTP requests by API key: a Service generates random keys, stores only their SHA-256 hashes in a SQL database, and turns a key presented in a request header into a gas.Principal with the key's subject, scopes and metadata.
Package apikey authenticates HTTP requests by API key: a Service generates random keys, stores only their SHA-256 hashes in a SQL database, and turns a key presented in a request header into a gas.Principal with the key's subject, scopes and metadata.
Package authtest holds mocks of the interfaces in package auth, for tests of code that authenticates, authorizes or revokes: MockAuthenticator, MockAuthorizer and MockRevoker.
Package authtest holds mocks of the interfaces in package auth, for tests of code that authenticates, authorizes or revokes: MockAuthenticator, MockAuthorizer and MockRevoker.
internal
apikeystore
Package apikeystore keeps the API key service's keys in a SQL database, over queries sqlc generates for each dialect.
Package apikeystore keeps the API key service's keys in a SQL database, over queries sqlc generates for each dialect.
cryptoutil
Package cryptoutil holds the cryptographic helpers the auth module's services share: random secrets, their hashes, and comparing secrets in constant time.
Package cryptoutil holds the cryptographic helpers the auth module's services share: random secrets, their hashes, and comparing secrets in constant time.
sessionstore
Package sessionstore keeps the session service's sessions in a SQL database, over queries sqlc generates for each dialect.
Package sessionstore keeps the session service's sessions in a SQL database, over queries sqlc generates for each dialect.
sqlutil
Package sqlutil holds what the auth module's stores share about SQL databases: which dialect a driver speaks, how SQLite and MySQL store a time, and how a nullable time maps to a pointer.
Package sqlutil holds what the auth module's stores share about SQL databases: which dialect a driver speaks, how SQLite and MySQL store a time, and how a nullable time maps to a pointer.
svcutil
Package svcutil holds the plumbing the auth module's services share: resolving and checking a service's configuration in Init, and running a background task, such as expiry cleanup, between Init and Close.
Package svcutil holds the plumbing the auth module's services share: resolving and checking a service's configuration in Init, and running a background task, such as expiry cleanup, between Init and Close.
testutil
Package testutil is the auth module's test harness: real database and migration services on an in-memory SQLite database or on a PostgreSQL or MySQL container, and small fakes for the services the stores need.
Package testutil is the auth module's test harness: real database and migration services on an in-memory SQLite database or on a PostgreSQL or MySQL container, and small fakes for the services the stores need.
tokenstore
Package tokenstore keeps the token service's single-use tokens in a SQL database, over queries sqlc generates for each dialect.
Package tokenstore keeps the token service's single-use tokens in a SQL database, over queries sqlc generates for each dialect.
Package jwt signs and verifies JSON Web Tokens with HS256 or RS256, and authenticates requests that carry one as a bearer token.
Package jwt signs and verifies JSON Web Tokens with HS256 or RS256, and authenticates requests that carry one as a bearer token.
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.
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.
Package token issues single-use, time-limited tokens, for links such as a password reset, an email verification, a magic login link or an invite.
Package token issues single-use, time-limited tokens, for links such as a password reset, an email verification, a magic login link or an invite.

Jump to

Keyboard shortcuts

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