authbase

package
v0.59.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package authbase holds authentication primitives shared between authkit's issuing core and its verification layer: plain data types, opaque-credential parsing, and sentinel errors that carry NO dependency on Postgres or the rest of core (stdlib only). It exists so the verification path — and, later, a standalone verify module (agents #110/#107) — can depend on these without pulling in the storage layer. The core package re-exports every symbol here as an alias, so existing callers using core.X are unaffected.

Index

Constants

View Source
const (
	ErrorTypeInvalidRequest = "invalid_request_error"
	ErrorTypeAuthentication = "authentication_error"
	ErrorTypeAuthorization  = "authorization_error"
	ErrorTypeRateLimit      = "rate_limit_error"
	ErrorTypeAPI            = "api_error"
)

Error type categories, aligned with openrails' / Stripe's taxonomy strings.

View Source
const (
	RemoteAppModeJWKS   = "jwks"
	RemoteAppModeStatic = "static"
)

Remote-application trust modes (#74). A remote_application is a federation PRINCIPAL whose credential is a key, with exactly one trust source:

jwks   — keys fetched + refreshed from JWKSURI; rotation is publishing a new
         kid at the same URL.
static — authorized_keys-style human-managed PEM list for principals without
         a JWKS endpoint; manual rotation by design.
View Source
const (
	// ServiceJWTTokenUse is the required `token_use` claim for service JWTs.
	ServiceJWTTokenUse = "service"
	// DefaultServiceJWTLifetime is the recommended lifetime for first-party
	// machine-to-machine service JWTs.
	DefaultServiceJWTLifetime = 15 * time.Minute
)
View Source
const PermWildcard = "*"

PermWildcard is the wildcard CHARACTER used inside namespace-anchored globs (`org:*`, `org:members:*`, `org:*:read`, `root:*`). A bare standalone `*` is NOT a valid grant — it is rejected everywhere.

Variables

View Source
var (
	// ErrInvalidAccessToken indicates an API key that does not exist, has a bad
	// secret, or whose owning permission group is gone. Deliberately indistinguishable from
	// a malformed token so callers learn nothing from the error.
	ErrInvalidAccessToken = errors.New("invalid_token")
	// ErrAccessTokenRevoked indicates the API key was explicitly revoked.
	ErrAccessTokenRevoked = errors.New("token_revoked")
	// ErrAccessTokenExpired indicates the API key is past its expires_at.
	ErrAccessTokenExpired = errors.New("token_expired")
)
View Source
var ErrAttributeDefNotFound = errors.New("attribute_def_not_found")

ErrAttributeDefNotFound indicates no registered remote-application attribute definition matched.

View Source
var ErrInvalidRemoteApplication = errors.New("invalid_remote_application")

ErrInvalidRemoteApplication indicates a malformed remote_application registration payload (including invalid allowed-origin values).

View Source
var ErrInvalidServiceJWT = errors.New("invalid_service_jwt")

ErrInvalidServiceJWT indicates a presented service JWT failed verification.

Functions

func APIKeyMarker

func APIKeyMarker(prefix string) string

APIKeyMarker returns the leading marker that identifies an API key for the given application prefix: "<prefix>_st_" when prefix is non-empty, else "st_".

func ErrorMessage added in v0.52.0

func ErrorMessage(code string) string

ErrorMessage returns a human-readable English message for a wire error code: a curated message for common codes, otherwise a humanized form of the code so the message is never empty. Localized catalogs are a future extension.

func ErrorTypeForStatus added in v0.52.0

func ErrorTypeForStatus(status int) string

ErrorTypeForStatus maps an HTTP status to its error-type category (the same inference openrails performs).

func FormatAPIKey

func FormatAPIKey(prefix, keyID, secret string) string

FormatAPIKey assembles the full presented token: <marker><key_id>_<secret>.

func HasAPIKeyPrefix

func HasAPIKeyPrefix(prefix, token string) bool

HasAPIKeyPrefix reports whether token carries the API-key marker for prefix. Used by middleware to route to the API-key path before attempting JWT verification.

func NormalizeAllowedOrigin

func NormalizeAllowedOrigin(origin string) (string, error)

NormalizeAllowedOrigin validates one browser Origin value and returns its canonical exact-match form. It accepts only scheme+host(+port), never paths, queries, fragments, userinfo, wildcards, or the special "null" origin.

func NormalizeAllowedOrigins

func NormalizeAllowedOrigins(origins []string) ([]string, error)

NormalizeAllowedOrigins validates, trims, normalizes, and de-duplicates exact browser origins for a remote_application.

func OriginAllowed

func OriginAllowed(origin string, allowedOrigins []string) bool

OriginAllowed reports whether origin exactly matches one of allowedOrigins.

func ParseAPIKey

func ParseAPIKey(prefix, token string) (keyID, secret string, ok bool)

ParseAPIKey splits a presented token into its key_id and secret. key_id and secret are base62 (no underscores), so the first "_" after the marker is the unambiguous delimiter. ok is false if the token lacks the marker or either part is empty.

func PermMatches

func PermMatches(grant, concrete string) bool

PermMatches reports whether a GRANT token authorizes a CONCRETE permission. The grant may be a literal (`org:members:read`) or a namespace-anchored glob where `*` wildcards a whole segment (`org:members:*`, `org:*:read`, `org:*`). The namespace (segment 0) must be a literal — a bare `*` (or a `*` namespace) never matches. A two-segment glob `ns:*` matches every concrete `ns:…` perm.

This is the shared, authz-critical matcher used by both core's RBAC checks and the verification layer's permission-coverage checks.

func PermissionTokenCovers

func PermissionTokenCovers(grant, requested string) bool

PermissionTokenCovers reports whether a stored grant token covers a requested permission token using AuthKit's namespace-anchored glob semantics.

Types

type APIKeyResource

type APIKeyResource struct {
	Persona string `json:"persona"`
	ID      string `json:"id"`
}

APIKeyResource is one opaque, host-defined resource scope carried by an API key: a {Persona, ID} reference to a permission-group instance. AuthKit stores and returns the exact pair but does not interpret it — hosts own resource semantics, including any wildcard-looking IDs such as "*".

type ErrorEnvelope added in v0.52.0

type ErrorEnvelope struct {
	Error ErrorObject `json:"error"`
}

ErrorEnvelope is the top-level error response: {"error": {...}}.

func NewErrorEnvelope added in v0.52.0

func NewErrorEnvelope(status int, code string, param *string, metadata map[string]any) ErrorEnvelope

NewErrorEnvelope builds the canonical nested error envelope for an HTTP status + machine code: the type is derived from the status and the message from the code catalog. param and metadata are optional (omitted when nil/empty).

type ErrorObject added in v0.52.0

type ErrorObject struct {
	Type     string         `json:"type"`
	Code     string         `json:"code"`
	Message  string         `json:"message"`
	Param    *string        `json:"param,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

ErrorObject is the nested error detail carried under the top-level "error" key.

type RemoteAppAttributeDef

type RemoteAppAttributeDef struct {
	RemoteApplicationID string
	Key                 string
	Version             int32
	Definition          json.RawMessage
}

RemoteAppAttributeDef is a remote_application's registered attribute definition: the full inline value a REFERENCE-mode delegated-token attribute resolves to (#75). Definition is opaque JSON the consuming app interprets.

type RemoteAppKey

type RemoteAppKey struct {
	KID          string `json:"kid,omitempty" yaml:"kid,omitempty"`
	PublicKeyPEM string `json:"public_key_pem" yaml:"public_key_pem"`
}

RemoteAppKey is one entry of a static-mode principal's human-managed key list (stored as jsonb; edited like an authorized_keys file).

type RemoteApplication

type RemoteApplication struct {
	ID                string
	Slug              string
	PermissionGroupID string // controlling permission-group id
	Issuer            string // OIDC iss
	JWKSURI           string // OIDC jwks_uri (jwks mode only)
	// Mode is the trust source: RemoteAppModeJWKS (fetch from JWKSURI) XOR
	// RemoteAppModeStatic (human-managed PublicKeys list). Never both.
	Mode string
	// PublicKeys is the static-mode key list (empty in jwks mode).
	PublicKeys     []RemoteAppKey
	Audiences      []string
	AllowedOrigins []string
	Enabled        bool
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

RemoteApplication is a registered federation principal: an external issuer authkit trusts to mint delegated/remote-application tokens. It is a plain data view; persistence and lifecycle live in core.

type ResolvedAPIKey

type ResolvedAPIKey struct {
	APIKeyID string
	KeyID    string
	// PermissionGroupID is the controlling permission-group id.
	PermissionGroupID string
	Role              string
	Permissions       []string
	Resources         []APIKeyResource
}

ResolvedAPIKey is the resource-aware API-key resolution result. Permissions is the key's role resolved to its effective permission set AT VERIFY TIME (so a role edit is reflected immediately — perms are never frozen into the key).

type ServiceJWTClaims

type ServiceJWTClaims struct {
	Issuer      string
	Subject     string
	Audiences   []string
	IssuedAt    time.Time
	NotBefore   time.Time
	ExpiresAt   time.Time
	JTI         string
	TokenUse    string
	Permissions []string
	Resources   []APIKeyResource
	Scope       []string
}

ServiceJWTClaims is the canonical AuthKit claim shape for caller-minted machine-to-machine JWTs. Permissions are requested capabilities; receiving services must still intersect them with server-side grants.

Jump to

Keyboard shortcuts

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