authhttp

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// 2FA-specific rate limit buckets
	RL2FAStartPhone      = "auth_2fa_start_phone"
	RL2FAEnable          = "auth_2fa_enable"
	RL2FADisable         = "auth_2fa_disable"
	RL2FARegenerateCodes = "auth_2fa_regenerate_codes"
	RL2FAVerify          = "auth_2fa_verify"

	RLAuthToken               = "auth_token"
	RLAuthRegister            = "auth_register"
	RLAuthRegisterResendEmail = "auth_register_resend_email"
	RLAuthRegisterResendPhone = "auth_register_resend_phone"
	RLPasswordLogin           = "auth_password_login"
	RLAuthLogout              = "auth_logout"
	RLAuthSessionsCurrent     = "auth_sessions_current"
	RLAuthSessionsList        = "auth_sessions_list"
	RLAuthSessionsRevoke      = "auth_sessions_revoke"
	RLAuthSessionsRevokeAll   = "auth_sessions_revoke_all"

	RLPasswordResetRequest = "auth_pwd_reset_request"
	RLPasswordResetConfirm = "auth_pwd_reset_confirm"
	RLEmailVerifyRequest   = "auth_email_verify_request"
	RLEmailVerifyConfirm   = "auth_email_verify_confirm"
	RLPhoneVerifyRequest   = "auth_phone_verify_request"
	RLPhoneVerifyConfirm   = "auth_phone_verify_confirm"

	RLOIDCStart    = "auth_oidc_start"
	RLOIDCCallback = "auth_oidc_callback"

	RLUserPasswordChange = "auth_user_password_change"
	RLUserMe             = "auth_user_me"
	RLUserUpdateUsername = "auth_user_update_username"
	RLUserUpdateEmail    = "auth_user_update_email"

	RLUserEmailChangeRequest = "auth_user_email_change_request"
	RLUserEmailChangeConfirm = "auth_user_email_change_confirm"
	RLUserEmailChangeResend  = "auth_user_email_change_resend"

	RLUserPhoneChangeRequest = "auth_user_phone_change_request"
	RLUserPhoneChangeConfirm = "auth_user_phone_change_confirm"
	RLUserPhoneChangeResend  = "auth_user_phone_change_resend"

	RLUserDelete         = "auth_user_delete"
	RLUserUnlinkProvider = "auth_user_unlink_provider"

	RLAdminRolesGrant            = "auth_admin_roles_grant"
	RLAdminRolesRevoke           = "auth_admin_roles_revoke"
	RLAdminUserSessionsList      = "auth_admin_user_sessions_list"
	RLAdminUserSessionsRevoke    = "auth_admin_user_sessions_revoke"
	RLAdminUserSessionsRevokeAll = "auth_admin_user_sessions_revoke_all"

	// Solana SIWS authentication
	RLSolanaChallenge = "auth_solana_challenge"
	RLSolanaLogin     = "auth_solana_login"
	RLSolanaLink      = "auth_solana_link"
)

Bucket names used by authkit endpoints.

Variables

This section is empty.

Functions

func AllowNamed

func AllowNamed(r *http.Request, rl RateLimiter, bucket string) bool

AllowNamed applies a per-IP limit using the provided bucket name. It fails open on limiter error.

func CheckOrgAccess added in v0.4.4

func CheckOrgAccess(ctx context.Context, svc *core.Service, userID, orgSlug string) (canonicalOrg string, memberRoles []string, isMember bool, err error)

CheckOrgAccess resolves orgSlug (slug or alias) to its canonical slug, verifies membership, and returns the member's org-scoped roles.

func DefaultRateLimits

func DefaultRateLimits() map[string]Limit

DefaultRateLimits returns AuthKit's built-in per-endpoint rate limits.

These limits are enforced per client IP (as determined by the Service's ClientIPFunc). Hosts can override by supplying their own limiter via WithRateLimiter(...).

func HasAnyOrgRole added in v0.4.4

func HasAnyOrgRole(roles []string, want ...string) bool

HasAnyOrgRole returns true if roles contains any of want (case-insensitive).

func HasRoleDBCheck added in v0.4.4

func HasRoleDBCheck(ctx context.Context, pg *pgxpool.Pool, userID, role string) (bool, error)

HasRoleDBCheck checks whether the given user has the provided role slug in Postgres. It also verifies the user is not deleted or banned.

func IsAdmin added in v0.4.3

func IsAdmin(ctx context.Context, pg *pgxpool.Pool, userID string) (bool, error)

IsAdmin checks whether the given user has the admin role in Postgres.

func JWKSHandler

func JWKSHandler(jwks jwtkit.JWKS) http.Handler

JWKSHandler serves the public JWKS document for the given key set.

func LanguageMiddleware

func LanguageMiddleware(cfg *LanguageConfig) func(http.Handler) http.Handler

LanguageMiddleware infers request language and attaches it to the request context.

func Optional

func Optional(v *Verifier) func(http.Handler) http.Handler

Optional validates when Authorization is present; otherwise passes through.

func RequireAdmin

func RequireAdmin(pg *pgxpool.Pool) func(http.Handler) http.Handler

RequireAdmin verifies admin role directly in Postgres.

func Required

func Required(v *Verifier) func(http.Handler) http.Handler

Required validates the Bearer token (JWT), enforces iss/aud/exp, and stores claims in request context.

func ToMemoryLimits

func ToMemoryLimits(in map[string]Limit) map[string]memorylimiter.Limit

func ToRedisLimits

func ToRedisLimits(in map[string]Limit) map[string]redislimiter.Limit

Types

type Claims

type Claims struct {
	UserID          string
	Email           string
	EmailVerified   bool
	Username        string
	DiscordUsername string
	SessionID       string
	Roles           []string
	Org             string
	OrgRoles        []string
	Entitlements    []string
	Issuer          string
	UserTier        string
	JTI             string
}

Claims is a typed view of authenticated user information attached by middleware.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) (Claims, bool)

func (Claims) HasEntitlement

func (c Claims) HasEntitlement(ent string) bool

func (Claims) HasRole

func (c Claims) HasRole(role string) bool

type ClientIPFunc

type ClientIPFunc func(r *http.Request) string

ClientIPFunc determines the client IP used for rate limiting and auditing.

Returning an empty string means "unknown" and causes rate limiting to fail open.

func ClientIPFromForwardedHeaders

func ClientIPFromForwardedHeaders(trustedProxies []netip.Prefix) ClientIPFunc

ClientIPFromForwardedHeaders trusts CF-Connecting-IP and X-Forwarded-For only when the immediate peer (RemoteAddr) is in trustedProxies. Otherwise it falls back to DefaultClientIP behavior.

func DefaultClientIP

func DefaultClientIP() ClientIPFunc

DefaultClientIP returns a conservative client IP strategy:

  • If RemoteAddr is a public IP, use it.
  • If RemoteAddr is private/loopback/etc, return "" (fail open) so we don't accidentally rate-limit a reverse proxy/ingress as a single client.

Hosts behind proxies should configure a forwarded-header strategy with a trusted proxy list.

type IssuerKey added in v0.6.0

type IssuerKey struct {
	KID          string
	PublicKeyPEM string
}

IssuerKey is a public key for an issuer, identified by key ID.

type IssuerOptions added in v0.6.0

type IssuerOptions struct {
	// JWKSURL is the URL to fetch JWKS from. If set, keys are fetched
	// automatically and refreshed when they expire or an unknown kid appears.
	JWKSURL string

	// Keys are pre-provided public keys as PEM. The caller is responsible for
	// refreshing by calling AddIssuer again with updated keys.
	Keys []IssuerKey

	// RawKeys are pre-provided public keys. Useful when the caller already
	// has parsed *rsa.PublicKey values (e.g., from a co-located core.Service).
	RawKeys map[string]*rsa.PublicKey

	// CacheTTL controls how long fetched JWKS keys are considered fresh.
	// Default: 5 minutes.
	CacheTTL time.Duration

	// MaxStale controls how long stale keys may be used as fallback after
	// a failed JWKS refresh. Default: 1 hour.
	MaxStale time.Duration
}

IssuerOptions configures how keys are obtained for an issuer. Provide one of JWKSURL, Keys, or RawKeys.

type LanguageConfig

type LanguageConfig struct {
	Supported  []string
	Default    string
	QueryParam string
	CookieName string
}

type Limit

type Limit struct {
	Limit  int
	Window time.Duration
}

Limit configures a named rate limit bucket.

type RateLimiter

type RateLimiter interface {
	AllowNamed(bucket string, key string) (bool, error)
}

RateLimiter is a minimal interface used by adapters.

type Service

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

Service wraps core.Service with net/http mounting helpers.

func NewService

func NewService(cfg core.Config) (*Service, error)

NewService constructs a core.Service and wraps it for net/http mounting. Returns an error if the core service fails to initialize (e.g., missing keys in production).

func (*Service) APIHandler

func (s *Service) APIHandler() http.Handler

APIHandler returns a handler that serves the JSON API routes under /auth/*. It is intended to be mounted under the host's mux/router at any prefix.

func (*Service) Core

func (s *Service) Core() *core.Service

func (*Service) DisableRateLimiter

func (s *Service) DisableRateLimiter() *Service

func (*Service) JWKSHandler

func (s *Service) JWKSHandler() http.Handler

JWKSHandler returns a handler for GET /.well-known/jwks.json.

func (*Service) OIDCHandler

func (s *Service) OIDCHandler() http.Handler

OIDCHandler returns a handler that serves browser redirect flows: - GET /oidc/{provider}/login - GET /oidc/{provider}/callback - GET /oidc/discord/login (if configured) - GET /oidc/discord/callback (if configured)

func (*Service) Verifier added in v0.6.0

func (s *Service) Verifier() *Verifier

func (*Service) WithAuthLogReader added in v0.4.2

func (s *Service) WithAuthLogReader(r core.AuthEventLogReader) *Service

func (*Service) WithAuthLogger

func (s *Service) WithAuthLogger(l core.AuthEventLogger) *Service

func (*Service) WithClientIPFunc

func (s *Service) WithClientIPFunc(fn ClientIPFunc) *Service

func (*Service) WithEmailSender

func (s *Service) WithEmailSender(es core.EmailSender) *Service

func (*Service) WithEntitlements

func (s *Service) WithEntitlements(p core.EntitlementsProvider) *Service

func (*Service) WithEphemeralStore

func (s *Service) WithEphemeralStore(store core.EphemeralStore, mode core.EphemeralMode) *Service

func (*Service) WithLanguageConfig

func (s *Service) WithLanguageConfig(cfg LanguageConfig) *Service

func (*Service) WithPostgres

func (s *Service) WithPostgres(pg *pgxpool.Pool) *Service

func (*Service) WithRateLimiter

func (s *Service) WithRateLimiter(rl RateLimiter) *Service

func (*Service) WithRedis

func (s *Service) WithRedis(rd *redis.Client) *Service

func (*Service) WithSMSSender

func (s *Service) WithSMSSender(sender core.SMSSender) *Service

func (*Service) WithSolanaDomain

func (s *Service) WithSolanaDomain(domain string) *Service

WithSolanaDomain sets the domain used in SIWS sign-in messages. If not set, the domain is derived from the request Origin or Host header.

type Verifier

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

Verifier validates JWTs from one or more issuers.

For verify-only mode, create with NewVerifier and add issuers via AddIssuer. For issuing mode, authhttp.Service creates a Verifier internally.

func NewVerifier

func NewVerifier(opts ...VerifierOption) *Verifier

NewVerifier creates a new Verifier. Add trusted issuers via AddIssuer.

func (*Verifier) AddIssuer added in v0.6.0

func (v *Verifier) AddIssuer(issuerID string, audiences []string, opts IssuerOptions) error

AddIssuer registers (or updates) a trusted issuer. This is the single method for adding any issuer — whether at startup or at runtime, whether keys come from a JWKS URL or are pre-provided.

func (*Verifier) RemoveIssuer added in v0.6.0

func (v *Verifier) RemoveIssuer(issuerID string)

RemoveIssuer removes a previously added issuer.

func (*Verifier) Verify

func (v *Verifier) Verify(tokenStr string) (Claims, error)

Verify parses + verifies a token and returns typed Claims. It enforces issuer/audience/expiry with the configured skew.

func (*Verifier) WithService

func (v *Verifier) WithService(svc *core.Service) *Verifier

WithService enables best-effort enrichment hooks (roles/provider usernames) from Postgres.

type VerifierOption added in v0.6.0

type VerifierOption func(*Verifier)

VerifierOption configures a Verifier.

func WithAlgorithms added in v0.6.0

func WithAlgorithms(algs ...string) VerifierOption

WithAlgorithms sets the allowed JWS algorithms. Default: ["RS256"].

func WithHTTPClient added in v0.6.0

func WithHTTPClient(c *http.Client) VerifierOption

WithHTTPClient sets the HTTP client used for JWKS fetching.

func WithOrgMode added in v0.6.0

func WithOrgMode(mode string) VerifierOption

WithOrgMode sets the organization mode ("single" or "multi") for claim extraction. When "multi" and an org claim is present, roles are treated as org-scoped roles.

func WithSkew added in v0.6.0

func WithSkew(d time.Duration) VerifierOption

WithSkew sets the clock skew tolerance for exp/nbf/iat checks. Default: 60s.

Jump to

Keyboard shortcuts

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