auth

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth authenticates requests to the query endpoint with OIDC JWT bearer tokens and authorises them by role, as decided in docs/content/docs/decisions/0006-authentication.md.

A Guard verifies a token against the configured issuers, which turns it into a Principal, checks the principal's role on a database against the configured rules, and wraps an http.Handler to do both for each request. Verification failures are *Error values with a stable Code; neither errors nor log lines contain a token or any part of one.

Index

Constants

View Source
const (
	// MaxTokenSize is the largest token accepted, in bytes.
	MaxTokenSize = 16 << 10
	// ClockSkew is the allowance applied to exp, nbf and iat.
	ClockSkew = time.Minute
)

Verification policy, fixed by decision record 0006.

Variables

This section is empty.

Functions

func BearerToken

func BearerToken(h http.Header) (string, error)

BearerToken returns the token of the request's single Authorization header with the Bearer scheme, or an *Error with CodeMissingToken or CodeMalformed.

func RefusalAttrs

func RefusalAttrs(e *Error, token string) []slog.Attr

RefusalAttrs are the log attributes of a refusal of ADR 0006, each value cut to 200 bytes. The token itself is represented only by a prefix of its SHA-256 hash.

Types

type Code

type Code string

Code is a stable identifier for why a request was refused.

const (
	CodeMissingToken         Code = "missing_token"
	CodeTokenTooLarge        Code = "token_too_large"
	CodeMalformed            Code = "malformed_token"
	CodeUnsupportedAlgorithm Code = "unsupported_algorithm"
	CodeUntrustedIssuer      Code = "untrusted_issuer"
	CodeUnknownKey           Code = "unknown_key"
	CodeKeysUnavailable      Code = "keys_unavailable"
	CodeInvalidSignature     Code = "invalid_signature"
	CodeMissingClaim         Code = "missing_claim"
	CodeInvalidAudience      Code = "invalid_audience"
	CodeExpired              Code = "token_expired"
	CodeNotYetValid          Code = "token_not_yet_valid"
	CodeIssuedInFuture       Code = "issued_in_future"
	CodeForbidden            Code = "forbidden"
)

The codes. Clients only ever see whether a token was missing, invalid or insufficient; the specific code is for server logs.

type Config

type Config struct {
	// Issuers are the token issuers the server trusts. At least one is required.
	Issuers []Issuer `json:"issuers"`
	// Rules grant roles. A principal no rule matches is denied everything.
	Rules []Rule `json:"rules"`
}

Config is the authentication and authorisation configuration of a server.

func (Config) Validate

func (c Config) Validate() error

Validate reports the first problem with the configuration, if any.

type Error

type Error struct {
	Code    Code
	Issuer  string
	Subject string
	KeyID   string
}

Error is a refused token or request. Its fields are safe to log: Issuer is set only when it equals a configured issuer, Subject only when the token's signature verified and then cut to 200 bytes, and KeyID only when it is at most 64 bytes long.

func (*Error) Error

func (e *Error) Error() string

type Guard

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

Guard verifies bearer tokens and authorises principals.

func New

func New(cfg Config, client *http.Client, now func() time.Time, log *slog.Logger) (*Guard, error)

New validates cfg and returns a Guard. client fetches discovery documents and key sets; each fetch is bounded by its own timeout, so client needs none, and a copy of it that follows no redirect is used. now is the clock and log receives refusals and key refresh failures. A nil client, now or log means http.DefaultClient, time.Now or no logging. New makes no network request.

func (*Guard) Authorize

func (g *Guard) Authorize(p *Principal, database string, need Role) bool

Authorize reports whether p holds at least role need on database. It is deny by default: without a matching rule the answer is false, and a name that is not a valid database name is denied before any rule is read. Subjects, claim values and names are compared exactly, byte for byte.

func (*Guard) LoadKeyFiles

func (g *Guard) LoadKeyFiles() error

LoadKeyFiles reads the key set of every issuer configured with a JWKS file, as a first refresh, and fails if one cannot be read or holds no usable key. Later refreshes follow the cache policy.

func (*Guard) Require

func (g *Guard) Require(need Role, database func(*http.Request) string, next http.Handler) http.Handler

Require returns a handler that serves next only if the request carries an "Authorization: Bearer" token that verifies, and its principal holds at least role need on the database that database returns for the request. next finds the principal with PrincipalFromContext.

A request without a bearer token gets 401 with "WWW-Authenticate: Bearer"; one whose token does not verify gets 401 with error="invalid_token"; an authenticated principal without the role gets 403. The response names no more than that; the specific Code is logged.

func (*Guard) Verify

func (g *Guard) Verify(ctx context.Context, token string) (*Principal, error)

Verify checks token and returns its principal, or an *Error.

type Issuer

type Issuer struct {
	// Issuer is the exact value tokens carry in their iss claim. Unless
	// JWKSFile is set, it must be an https URL without query, fragment, user
	// info or white space, and the issuer's discovery
	// document is fetched from Issuer + "/.well-known/openid-configuration".
	Issuer string `json:"issuer"`
	// Audience is the value a token's aud claim must contain.
	Audience string `json:"audience"`
	// JWKSFile, if set, is the path of a JSON Web Key Set file holding the
	// issuer's public keys. No network request is then made for this issuer.
	JWKSFile string `json:"jwks_file"`
}

Issuer is one trusted token issuer.

type Principal

type Principal struct {
	Issuer  string
	Subject string
	Claims  map[string]any
	// Expires is the token's exp plus ClockSkew: the time from which Verify
	// refuses the token. The principal must not be used after it, for example
	// on a long-lived connection.
	Expires time.Time
}

Principal is an authenticated caller: the pair (Issuer, Subject), with the claims of the token that authenticated it.

func PrincipalFromContext

func PrincipalFromContext(ctx context.Context) (*Principal, bool)

PrincipalFromContext returns the principal Require stored in ctx.

func (*Principal) LogAttrs

func (p *Principal) LogAttrs() []slog.Attr

LogAttrs are the log attributes naming p: its issuer and subject, each cut to 200 bytes.

type Role

type Role string

Role is a level of access to a database. Each role includes the ones before it: read, then write, then admin.

const (
	RoleRead  Role = "read"
	RoleWrite Role = "write"
	RoleAdmin Role = "admin"
)

The roles, in increasing order of access.

type Rule

type Rule struct {
	Issuer string `json:"issuer"`
	// Subject matches the sub claim exactly. Exactly one of Subject and
	// Claim must be set.
	Subject string `json:"subject"`
	// Claim names a top-level claim, for example "groups" or "roles".
	Claim string `json:"claim"`
	// Value is the string the claim must equal or contain.
	Value string `json:"value"`
	// Database is a database name, which is 1 to 63 bytes of lower-case ASCII
	// letters, digits and '-', starting with a letter or a digit, or a pattern.
	// A pattern may also hold '*', which matches any run of characters, and
	// '?', which matches one character. It is 1 to 63 bytes long and starts
	// with a letter, a digit, '*' or '?'.
	Database string `json:"database"`
	Role     Role   `json:"role"`
}

Rule grants Role on the databases matching Database to the principals of Issuer that have the given Subject, or, if Claim is set instead, whose token has the claim Claim equal to Value or, for an array claim, containing it.

Jump to

Keyboard shortcuts

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