auth

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 5 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, middleware, scheme constants, 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 guide, with configuration, testing, and worked examples, 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 provides authentication and authorization for the Gas ecosystem: JWT, server-side sessions, API keys, and single-use tokens. Sub-packages live under jwt, session, apikey, and token, and authtest provides recording mocks for tests.

Interfaces

The package defines the interfaces its services implement and its middleware consumes:

  • Authenticator turns an HTTP request into a gas.Principal. The jwt, session, and apikey services implement it, and Chain composes several.
  • Authorizer decides whether a principal may perform an action on a resource. The module ships no implementation; an app provides one.
  • PrincipalRevoker invalidates credentials. The session and apikey services implement it; JWTs are stateless and cannot be revoked.

gas.Principal, its metadata types, and the helpers that carry it on a context (gas.WithPrincipal, gas.PrincipalFromContext) live in core, so a handler can read the principal with gas.Context.Principal without importing this module. BasePrincipal is the implementation this module's services return.

Wiring

Middleware runs an Authenticator on each request. On success it stores the principal with gas.WithPrincipal and calls the next handler; on failure it calls the WithOnError handler, which by default writes a plain 401. An Authenticator that returns a nil principal with a nil error has failed: Middleware and Chain treat it as ErrUnauthenticated. RequireScheme answers 403 when the principal is missing or of another scheme. The services are registered with the DI container by the app; see each sub-package for its constructor and configuration.

See the module README for usage examples and design rationale.

SPDX-License-Identifier: MIT

Index

Constants

View Source
const (
	// SchemeJWT is the scheme for JWT-authenticated principals.
	SchemeJWT = "jwt"
	// SchemeSession is the scheme for session-authenticated principals.
	SchemeSession = "session"
	// SchemeAPIKey is the scheme for API-key-authenticated principals.
	SchemeAPIKey = "apikey"
)

Scheme constants identify the authentication method used by a principal.

Variables

View Source
var (
	// ErrUnauthenticated indicates that no valid credentials were provided.
	ErrUnauthenticated = errors.New("unauthenticated")
	// ErrForbidden indicates that the principal lacks permission for the action.
	ErrForbidden = errors.New("forbidden")
	// ErrCredentialsExpired indicates that the presented credentials have expired.
	ErrCredentialsExpired = errors.New("credentials expired")
	// ErrCredentialRevoked indicates that the presented credentials have been revoked.
	ErrCredentialRevoked = errors.New("credential revoked")
)

Sentinel errors returned by authenticators and middleware.

Functions

func Middleware

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

Middleware extracts and validates credentials from the request using the given authenticator. On success it sets the principal in the request context via gas.WithPrincipal and calls the next handler. On failure it invokes the OnError handler or writes a 401 Unauthorized response. A nil principal with a nil error is a failure with ErrUnauthenticated.

Panics if provider is nil, since that is a wiring mistake caught at startup.

func RequireScheme

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

RequireScheme enforces that the authenticated principal uses a specific authentication scheme (e.g. "jwt", "session", "apikey"). It reads the principal from context. If absent or the scheme doesn't match, it writes a 403 Forbidden response.

Types

type Authenticator added in v0.5.5

type Authenticator interface {
	Authenticate(ctx context.Context, r *http.Request) (gas.Principal, error)
}

Authenticator extracts a gas.Principal from an HTTP request. Implementations may use JWTs, server-side sessions, API keys, or any other credential scheme. Middleware runs an Authenticator and stores the principal it returns on the request context, where handlers read it with gas.Context.Principal.

An implementation returns a non-nil principal on success and an error, such as ErrUnauthenticated, otherwise. Middleware and Chain treat a nil principal with a nil error as ErrUnauthenticated, never as a success.

type Authorizer added in v0.5.5

type Authorizer interface {
	Authorize(ctx context.Context, principal gas.Principal, action, resource string) error
}

Authorizer decides whether a gas.Principal is allowed to perform an action on a resource. It is a separate concern from authentication: an Authenticator identifies who the caller is, while an Authorizer enforces what they can do.

type BasePrincipal

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

BasePrincipal is a concrete implementation of gas.Principal.

func NewPrincipal

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

NewPrincipal creates a new BasePrincipal. If meta is nil, an empty gas.BasePrincipalMetadata is used to avoid nil dereferences on Metadata().Value().

func (*BasePrincipal) CredentialID

func (p *BasePrincipal) CredentialID() string

CredentialID returns the identifier for the specific credential used.

func (*BasePrincipal) Metadata

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

Metadata returns the principal's metadata.

func (*BasePrincipal) Scheme

func (p *BasePrincipal) Scheme() string

Scheme returns the authentication method (e.g. "jwt", "session", "apikey").

func (*BasePrincipal) Subject

func (p *BasePrincipal) Subject() string

Subject returns the stable user identifier.

type Chain

type Chain []Authenticator

Chain is a composite authenticator that tries each authenticator in order. It satisfies Authenticator.

func (Chain) Authenticate

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

Authenticate tries each authenticator in order. It returns the first successful principal. If all fail, it returns the last error. If the chain is empty, it returns ErrUnauthenticated. A member that returns a nil principal with a nil error has failed with ErrUnauthenticated.

type MiddlewareOption

type MiddlewareOption func(*middlewareOptions)

MiddlewareOption configures the behavior of Middleware.

func WithOnError

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

WithOnError sets a custom error handler that is called when authentication fails. The handler receives the original error and is responsible for writing the HTTP response. When not set, the middleware writes a plain 401 Unauthorized response.

type PrincipalRevoker added in v0.5.5

type PrincipalRevoker interface {
	Revoke(ctx context.Context, principal gas.Principal) error
	RevokeAll(ctx context.Context, subject string) error
	RevokeAllByScheme(ctx context.Context, subject, scheme string) error
}

PrincipalRevoker invalidates credentials associated with a gas.Principal. Use Revoke to invalidate a single credential, RevokeAll to invalidate every credential for a subject, or RevokeAllByScheme to invalidate all credentials of a specific scheme (e.g. all sessions, all API keys) for a subject.

Directories

Path Synopsis
Package apikey provides API key authentication for the Gas ecosystem.
Package apikey provides API key authentication for the Gas ecosystem.
db
Package db provides the database-backed API key store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.
Package db provides the database-backed API key store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.
Package authtest provides mock implementations of the authentication, authorization, and revocation interfaces in package auth for use in tests.
Package authtest provides mock implementations of the authentication, authorization, and revocation interfaces in package auth for use in tests.
internal
cryptoutil
Package cryptoutil provides shared cryptographic helpers used across gas/auth sub-packages.
Package cryptoutil provides shared cryptographic helpers used across gas/auth sub-packages.
testutil
Package testutil provides shared test helpers and mock implementations for gas/auth integration and unit tests.
Package testutil provides shared test helpers and mock implementations for gas/auth integration and unit tests.
Package jwt provides a stateless JWT authenticator for the Gas ecosystem.
Package jwt provides a stateless JWT authenticator for the Gas ecosystem.
Package session provides server-side session authentication for the Gas ecosystem.
Package session provides server-side session authentication for the Gas ecosystem.
db
Package db provides the database-backed session store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.
Package db provides the database-backed session store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.
Package token provides single-use, time-limited tokens for the Gas ecosystem.
Package token provides single-use, time-limited tokens for the Gas ecosystem.
db
Package db provides the database-backed single-use token store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.
Package db provides the database-backed single-use token store with PostgreSQL, MySQL, and SQLite adapters over sqlc-generated queries.

Jump to

Keyboard shortcuts

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