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

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

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

```go
import "github.com/gasmod/gas/auth"
```

Package auth defines how a Gas app authenticates and authorizes HTTP
requests: the [Authenticator](#Authenticator), [Authorizer](#Authorizer) and [PrincipalRevoker](#PrincipalRevoker)
interfaces, the error contract they share, [Chain](#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:

```go
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](#Authenticator) looks at a request and returns the principal it
identifies, or nil and an error that says why not:

- [ErrNoCredentials](#ErrNoCredentials) when the request carries no credentials for it,
such as no Authorization header for a JWT authenticator.
- An error matching [ErrUnauthenticated](#ErrUnauthenticated) when it carries credentials
that are not valid. [ErrCredentialsExpired](#ErrCredentialsExpired) and
[ErrCredentialRevoked](#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](https://pkg.go.dev/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](#BasePrincipal) is a gas.Principal holding fixed values, which
authenticators return. [NewPrincipal](#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](#SchemeJWT), [SchemeSession](#SchemeSession) and [SchemeAPIKey](#SchemeAPIKey) are the schemes of this
module's authenticators.

## Chains

A [Chain](#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](https://pkg.go.dev/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](#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](https://pkg.go.dev/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](#WithOnError) replaces both responses with a function of the
authenticator's error, which then owns the response and its logging.
- [WithChallenge](#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](#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](#Authorizer) decides whether a principal may perform an action on a
resource. It returns:

- nil to allow.
- An error matching [ErrForbidden](#ErrForbidden) to deny.
- Any other error when it could not decide.

[RequireAuthorization](#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](#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](#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](#MaxValueLength) (255) bytes, checked before anything is stored, so
every database behaves the same: [ErrValueTooLong](#ErrValueTooLong) from session's
Create, apikey's Generate and token's Issue. [CheckLength](#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](#ErrNilPrincipal) for a nil principal, a nil pointer included, and
[ErrSchemeMismatch](#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](https://pkg.go.dev/errors#Is):

- [ErrNoCredentials](#ErrNoCredentials): the request carries no credentials for the
authenticator. It does not wrap ErrUnauthenticated.
- [ErrUnauthenticated](#ErrUnauthenticated): the credentials are not valid. Every denial of
credentials matches it.
- [ErrCredentialsExpired](#ErrCredentialsExpired): the credentials have expired. It wraps
ErrUnauthenticated.
- [ErrCredentialRevoked](#ErrCredentialRevoked): the credential has been revoked. It wraps
ErrUnauthenticated.
- [ErrForbidden](#ErrForbidden): an Authorizer denied the action.

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:

- [ErrEmptySubject](#ErrEmptySubject): a credential was to be issued for an empty
subject.
- [ErrValueTooLong](#ErrValueTooLong): a subject, API key name or token purpose holds
more than MaxValueLength bytes.
- [ErrSchemeMismatch](#ErrSchemeMismatch): a method that acts on a principal got one of
another scheme.
- [ErrNilPrincipal](#ErrNilPrincipal): a method that acts on a principal got nil.

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

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


## API reference

### Constants

<a id="SchemeJWT"></a><a id="SchemeSession"></a><a id="SchemeAPIKey"></a>

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

<a id="MaxValueLength"></a>

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

<a id="ErrUnauthenticated"></a><a id="ErrNoCredentials"></a><a id="ErrCredentialsExpired"></a><a id="ErrCredentialRevoked"></a><a id="ErrForbidden"></a><a id="ErrNilPrincipal"></a><a id="ErrSchemeMismatch"></a><a id="ErrEmptySubject"></a><a id="ErrValueTooLong"></a>

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

<a id="CheckLength"></a>

#### func CheckLength

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

<a id="Middleware"></a>

#### func Middleware

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

<a id="RequireAuthorization"></a>

#### func RequireAuthorization

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

<a id="RequireScheme"></a>

#### func RequireScheme

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

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

### type Authenticator

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

<a id="Authorizer"></a><a id="Authorizer.Authorize"></a>

### type Authorizer

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

<a id="BasePrincipal"></a>

### type BasePrincipal

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

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

<a id="NewPrincipal"></a>

#### func NewPrincipal

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

<a id="BasePrincipal.CredentialID"></a>

#### func (*BasePrincipal) CredentialID

```go
func (p *BasePrincipal) CredentialID() string
```

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

<a id="BasePrincipal.Metadata"></a>

#### func (*BasePrincipal) Metadata

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

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

<a id="BasePrincipal.Scheme"></a>

#### func (*BasePrincipal) Scheme

```go
func (p *BasePrincipal) Scheme() string
```

Scheme returns the authentication method, such as SchemeJWT.

<a id="BasePrincipal.Subject"></a>

#### func (*BasePrincipal) Subject

```go
func (p *BasePrincipal) Subject() string
```

Subject returns the stable identifier of the user or client.

<a id="Chain"></a>

### type Chain

```go
type Chain []Authenticator
```

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

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

#### func (Chain) Authenticate

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

<a id="MiddlewareOption"></a>

### type MiddlewareOption

```go
type MiddlewareOption func(*middlewareOptions)
```

MiddlewareOption configures Middleware.

<a id="WithChallenge"></a>

#### func WithChallenge

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

<a id="WithOnError"></a>

#### func WithOnError

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

<a id="PrincipalRevoker"></a><a id="PrincipalRevoker.Revoke"></a><a id="PrincipalRevoker.RevokeAll"></a><a id="PrincipalRevoker.RevokeAllByScheme"></a>

### type PrincipalRevoker

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