Documentation
¶
Overview ¶
Package auth provides request authentication primitives for gofly services, including bearer-token extraction, static validation and RBAC helpers on a Principal type.
Package auth provides request authentication primitives for gofly services, including JWT signing/verification, OAuth2, RBAC and API key management.
Package auth provides request authentication primitives for gofly services, including bearer-token extraction, static validation and RBAC helpers on a Principal type.
Package auth provides request authentication primitives for gofly services, including JWT signing/verification, OAuth2, RBAC and API key management.
Package auth provides request authentication primitives for gofly services, including bearer-token extraction, static validation and RBAC helpers on a Principal type.
Package auth provides request authentication primitives for gofly services, including bearer-token extraction, static validation and RBAC helpers on a Principal type.
Index ¶
- Constants
- Variables
- func Authorize(ctx context.Context, req Requirement) error
- func BearerValue(token string) string
- func ExtractBearer(header string) (string, bool)
- func NewContext(ctx context.Context, principal Principal) context.Context
- func SignJWT(claims JWTClaims, secret []byte) (string, error)
- func SignJWTWithKID(claims JWTClaims, kid string, secret []byte) (string, error)
- func SignRequest(method string, path string, body []byte, timestamp int64, secret []byte) string
- func SubjectFromContext(ctx context.Context) string
- func VerifyRequestSignature(r *http.Request, body []byte, opts SignatureOptions) error
- type JWTClaims
- type JWTKeyring
- func (kr *JWTKeyring) ActiveKID() string
- func (kr *JWTKeyring) Add(key SigningKey) error
- func (kr *JWTKeyring) KIDs() []string
- func (kr *JWTKeyring) Remove(kid string) error
- func (kr *JWTKeyring) Rotate(key SigningKey) error
- func (kr *JWTKeyring) SetClock(now func() time.Time)
- func (kr *JWTKeyring) Sign(claims JWTClaims) (string, error)
- func (kr *JWTKeyring) Validator(opts JWTOptions) Validator
- func (kr *JWTKeyring) Verify(token string, opts JWTOptions) (JWTClaims, error)
- type JWTOptions
- type OAuth2Client
- type OAuth2Config
- type OAuth2Error
- type OAuth2Server
- type OAuth2Token
- type Principal
- func (p Principal) HasAllPermissions(permissions ...string) bool
- func (p Principal) HasAllRoles(roles ...string) bool
- func (p Principal) HasAnyPermission(permissions ...string) bool
- func (p Principal) HasAnyRole(roles ...string) bool
- func (p Principal) HasPermission(permission string) bool
- func (p Principal) HasRole(role string) bool
- type Requirement
- type SignatureOptions
- type SigningKey
- type Validator
Constants ¶
const ( GrantClientCredentials = "client_credentials" GrantRefreshToken = "refresh_token" )
OAuth2 grant types supported by the token endpoint.
const ( // SignatureHeader is the HMAC request signature header. SignatureHeader = "X-Gofly-Signature" // TimestampHeader is the request timestamp header used with signatures. TimestampHeader = "X-Gofly-Timestamp" )
const ( // AuthorizationHeader is the HTTP header carrying bearer tokens. AuthorizationHeader = "Authorization" // BearerPrefix is the literal prefix expected before the token value. BearerPrefix = "Bearer " // MetadataKey is the metadata map key used for authorization tokens. MetadataKey = "authorization" )
Variables ¶
var ( // ErrMissingCredentials is returned when no token is present. ErrMissingCredentials = errors.New("missing credentials") // ErrInvalidCredentials is returned when a token fails validation. ErrInvalidCredentials = errors.New("invalid credentials") // ErrPermissionDenied is returned when an authenticated principal lacks the // role or permission required to perform an action. ErrPermissionDenied = errors.New("permission denied") )
var ErrExpiredToken = errors.New("expired token")
ErrExpiredToken is returned when a JWT has passed its expiration time.
var ErrNoActiveKey = errors.New("auth: no active signing key")
ErrNoActiveKey is returned when a JWTKeyring has no key available for signing.
Functions ¶
func Authorize ¶
func Authorize(ctx context.Context, req Requirement) error
Authorize checks the principal in ctx against the requirement. It returns ErrMissingCredentials when no principal is present and ErrPermissionDenied when the principal does not satisfy the requirement.
func BearerValue ¶
BearerValue returns the full header value for a raw token string.
func ExtractBearer ¶
ExtractBearer parses a Bearer token from an Authorization header value.
func NewContext ¶
NewContext returns a context carrying principal.
func SignJWTWithKID ¶
SignJWTWithKID signs the claims and, when kid is non-empty, embeds it in the token header so verifiers can select the matching key during rotation.
func SignRequest ¶
SignRequest computes an HMAC-SHA256 signature for the given request parts.
func SubjectFromContext ¶
SubjectFromContext returns the principal's Subject or "" if absent.
func VerifyRequestSignature ¶
func VerifyRequestSignature(r *http.Request, body []byte, opts SignatureOptions) error
Types ¶
type JWTClaims ¶
type JWTClaims struct {
Subject string `json:"sub,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Extra map[string]any `json:"-"`
}
JWTClaims holds the standard JWT claim set used by gofly.
type JWTKeyring ¶
type JWTKeyring struct {
// contains filtered or unexported fields
}
JWTKeyring holds the active signing key plus any older keys still trusted for verification, enabling zero-downtime secret rotation. It is safe for concurrent use.
func NewJWTKeyring ¶
func NewJWTKeyring(active SigningKey) (*JWTKeyring, error)
NewJWTKeyring creates a keyring with the given active key. Additional trusted (verification-only) keys can be added with Add.
func (*JWTKeyring) ActiveKID ¶
func (kr *JWTKeyring) ActiveKID() string
ActiveKID returns the KID of the current signing key.
func (*JWTKeyring) Add ¶
func (kr *JWTKeyring) Add(key SigningKey) error
Add registers a key for verification without making it active.
func (*JWTKeyring) KIDs ¶
func (kr *JWTKeyring) KIDs() []string
KIDs returns all trusted key identifiers, sorted.
func (*JWTKeyring) Remove ¶
func (kr *JWTKeyring) Remove(kid string) error
Remove drops a key from the keyring. Removing the active key is rejected.
func (*JWTKeyring) Rotate ¶
func (kr *JWTKeyring) Rotate(key SigningKey) error
Rotate installs a new active signing key while keeping the previous keys available for verification.
func (*JWTKeyring) SetClock ¶
func (kr *JWTKeyring) SetClock(now func() time.Time)
SetClock overrides the time source (used for tests).
func (*JWTKeyring) Sign ¶
func (kr *JWTKeyring) Sign(claims JWTClaims) (string, error)
Sign signs the claims with the active key, embedding its KID in the header.
func (*JWTKeyring) Validator ¶
func (kr *JWTKeyring) Validator(opts JWTOptions) Validator
Validator returns a Validator backed by the keyring, suitable for the REST and gRPC auth middleware.
func (*JWTKeyring) Verify ¶
func (kr *JWTKeyring) Verify(token string, opts JWTOptions) (JWTClaims, error)
Verify validates a token by selecting the key referenced in its "kid" header. Tokens without a kid are rejected to avoid ambiguity during rotation.
type JWTOptions ¶
JWTOptions customises JWT signing and verification.
type OAuth2Client ¶
type OAuth2Client struct {
ID string
Secret string
// Scopes the client is permitted to request. An empty slice grants no
// scopes; use {"*"} to allow any requested scope.
Scopes []string
// Audience embedded in issued tokens (optional).
Audience string
}
OAuth2Client is a registered confidential client allowed to obtain tokens via the client_credentials grant.
type OAuth2Config ¶
type OAuth2Config struct {
// Keyring signs the issued JWT access tokens, enabling key rotation.
Keyring *JWTKeyring
// Issuer placed in the "iss" claim.
Issuer string
// TTL is the access-token lifetime; defaults to one hour.
TTL time.Duration
// Clients is the registry of confidential clients keyed by client id.
Clients map[string]OAuth2Client
// Now overrides the clock (tests).
Now func() time.Time
}
OAuth2Config configures the token endpoint.
type OAuth2Error ¶
type OAuth2Error struct {
Code string `json:"error"`
Description string `json:"error_description,omitempty"`
// contains filtered or unexported fields
}
OAuth2Error is the RFC 6749 section 5.2 error response.
func (*OAuth2Error) Error ¶
func (e *OAuth2Error) Error() string
type OAuth2Server ¶
type OAuth2Server struct {
// contains filtered or unexported fields
}
OAuth2Server issues JWT access tokens via the OAuth2 client_credentials grant.
func NewOAuth2Server ¶
func NewOAuth2Server(conf OAuth2Config) (*OAuth2Server, error)
NewOAuth2Server builds a token server. A keyring is required for signing.
func (*OAuth2Server) Issue ¶
func (s *OAuth2Server) Issue(clientID, clientSecret string, scopes []string) (OAuth2Token, error)
Issue authenticates a client and returns a signed access token covering the requested scopes. Requested scopes must all be permitted by the client.
func (*OAuth2Server) TokenHandler ¶
func (s *OAuth2Server) TokenHandler() http.Handler
TokenHandler exposes the token endpoint as an http.Handler. It accepts application/x-www-form-urlencoded POST requests carrying grant_type, scope and either form-encoded or Basic-auth client credentials.
type OAuth2Token ¶
type OAuth2Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
Scope string `json:"scope,omitempty"`
}
OAuth2Token is the response body of a successful token request, matching RFC 6749 section 5.1.
type Principal ¶
Principal is the authenticated identity attached to a request context. Beyond the Subject it carries RBAC material (Roles and Permissions) and arbitrary claim metadata.
func FromContext ¶
FromContext extracts the Principal from ctx.
func (Principal) HasAllPermissions ¶
HasAllPermissions reports whether the principal holds every permission.
func (Principal) HasAllRoles ¶
HasAllRoles reports whether the principal owns every listed role.
func (Principal) HasAnyPermission ¶
HasAnyPermission reports whether the principal holds at least one permission.
func (Principal) HasAnyRole ¶
HasAnyRole reports whether the principal owns at least one of the roles.
func (Principal) HasPermission ¶
HasPermission reports whether the principal holds the given permission. A permission ending in ":*" (or "*") acts as a wildcard prefix grant, so a principal holding "orders:*" satisfies a required "orders:read".
type Requirement ¶
type Requirement struct {
// Roles that the principal must all possess.
Roles []string
// AnyRole is satisfied when the principal holds at least one of these roles.
AnyRole []string
// Permissions that the principal must all hold.
Permissions []string
// AnyPermission is satisfied when the principal holds at least one.
AnyPermission []string
}
Requirement expresses an authorization rule against a Principal. All listed roles/permissions are required unless the AnyOf variants are used. An empty Requirement authorizes any authenticated principal.
func RequireAnyPermission ¶
func RequireAnyPermission(perms ...string) Requirement
RequireAnyPermission builds a requirement satisfied by any one permission.
func RequireAnyRole ¶
func RequireAnyRole(roles ...string) Requirement
RequireAnyRole builds a requirement satisfied by any one of the roles.
func RequirePermissions ¶
func RequirePermissions(perms ...string) Requirement
RequirePermissions builds a requirement demanding every listed permission.
func RequireRoles ¶
func RequireRoles(roles ...string) Requirement
RequireRoles builds a requirement demanding every listed role.
func (Requirement) Satisfied ¶
func (r Requirement) Satisfied(p Principal) bool
Satisfied reports whether the principal meets the requirement.
type SignatureOptions ¶
SignatureOptions configures HMAC request signature verification.
type SigningKey ¶
type SigningKey struct {
KID string
Secret []byte
// NotAfter, when set, marks the key as retired for signing after the given
// time. Retired keys remain valid for verification until removed.
NotAfter time.Time
}
SigningKey is a versioned HMAC secret used to sign and verify JWTs. The KID is embedded in the token header so verifiers can pick the right secret during rotation windows.
type Validator ¶
Validator validates a token and returns an enriched context carrying the authenticated Principal.
func JWTValidator ¶
func JWTValidator(secret []byte, opts JWTOptions) Validator
func OAuth2Validator ¶
func OAuth2Validator(keyring *JWTKeyring, opts JWTOptions, requiredScopes ...string) Validator
OAuth2Validator returns a Validator that verifies bearer access tokens issued by this server's keyring and enforces that the token carries every required scope.
func StaticTokenValidator ¶
StaticTokenValidator returns a Validator that compares the presented token with expected using constant-time comparison.