coreauth

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingIssuer is returned when the issuer is not configured.
	ErrMissingIssuer = errors.New("coreauth: issuer is required")

	// ErrKeyGenerationFailed is returned when key generation fails.
	ErrKeyGenerationFailed = errors.New("coreauth: failed to generate signing key")

	// ErrStorageInitFailed is returned when storage initialization fails.
	ErrStorageInitFailed = errors.New("coreauth: failed to initialize storage")
)

Configuration errors.

View Source
var (
	// ErrClientNotFound is returned when a client is not found.
	ErrClientNotFound = errors.New("coreauth: client not found")

	// ErrClientExists is returned when trying to create a client that already exists.
	ErrClientExists = errors.New("coreauth: client already exists")

	// ErrInvalidClientType is returned when the client type is invalid.
	ErrInvalidClientType = errors.New("coreauth: invalid client type")
)

Client errors.

View Source
var (
	// ErrTokenNotFound is returned when a token is not found.
	ErrTokenNotFound = errors.New("coreauth: token not found")

	// ErrTokenExpired is returned when a token has expired.
	ErrTokenExpired = errors.New("coreauth: token expired")

	// ErrTokenRevoked is returned when a token has been revoked.
	ErrTokenRevoked = errors.New("coreauth: token revoked")

	// ErrInvalidToken is returned when a token is invalid.
	ErrInvalidToken = errors.New("coreauth: invalid token")
)

Token errors.

View Source
var (
	// ErrAuthCodeNotFound is returned when an authorization code is not found.
	ErrAuthCodeNotFound = errors.New("coreauth: authorization code not found")

	// ErrAuthCodeExpired is returned when an authorization code has expired.
	ErrAuthCodeExpired = errors.New("coreauth: authorization code expired")

	// ErrAuthCodeUsed is returned when an authorization code has already been used.
	ErrAuthCodeUsed = errors.New("coreauth: authorization code already used")

	// ErrPKCEVerificationFailed is returned when PKCE verification fails.
	ErrPKCEVerificationFailed = errors.New("coreauth: PKCE verification failed")
)

Authorization errors.

View Source
var (
	// ErrFederationNotConfigured is returned when federation is not configured.
	ErrFederationNotConfigured = errors.New("coreauth: federation not configured")

	// ErrFederationConnectionFailed is returned when connection to CoreControl fails.
	ErrFederationConnectionFailed = errors.New("coreauth: failed to connect to CoreControl")

	// ErrInvalidGlobalToken is returned when a global identity token is invalid.
	ErrInvalidGlobalToken = errors.New("coreauth: invalid global identity token")
)

Federation errors.

View Source
var (
	// ErrUserNotFound is returned when a user is not found.
	ErrUserNotFound = errors.New("coreauth: user not found")

	// ErrUserExists is returned when trying to create a user that already exists.
	ErrUserExists = errors.New("coreauth: user already exists")
)

User errors.

Functions

func AccessRequestFromContext

func AccessRequestFromContext(ctx context.Context) fosite.AccessRequester

AccessRequestFromContext retrieves the access request from context.

func ContextWithOwnerID

func ContextWithOwnerID(ctx context.Context, ownerID uuid.UUID) context.Context

ContextWithOwnerID adds an owner ID to the context.

func LoggerFromContext

func LoggerFromContext(ctx context.Context) *slog.Logger

LoggerFromContext returns the logger from context, or slog.Default() if not set.

func SaveConfig

func SaveConfig(cfg *Config, path string) error

SaveConfig saves configuration to a file. The format is determined by the file extension.

func WithAccessRequest

func WithAccessRequest(ctx context.Context, ar fosite.AccessRequester) context.Context

WithAccessRequest adds the access request to the context.

Types

type AuthCodeData

type AuthCodeData struct {
	// Signature is the hashed authorization code.
	Signature string

	// ClientID is the client that requested the code.
	ClientID string

	// Subject is the user ID.
	Subject string

	// RedirectURI is the callback URI.
	RedirectURI string

	// Scopes are the requested scopes.
	Scopes []string

	// GrantedScopes are the granted scopes.
	GrantedScopes []string

	// State is the CSRF state parameter.
	State string

	// CodeChallenge is the PKCE code challenge.
	CodeChallenge string

	// CodeChallengeMethod is the PKCE method (S256 or plain).
	CodeChallengeMethod string

	// Nonce is the OpenID Connect nonce.
	Nonce string

	// Session holds the session data.
	Session *StoredSession

	// ExpiresAt is when the code expires.
	ExpiresAt int64

	// Used indicates the code has been exchanged.
	Used bool
}

AuthCodeData holds authorization code storage data.

type AuthorizationSession

type AuthorizationSession struct {
	// RequestID uniquely identifies this authorization request.
	RequestID string `json:"request_id"`

	// ClientID is the OAuth client requesting authorization.
	ClientID string `json:"client_id"`

	// RedirectURI is the client's callback URL.
	RedirectURI string `json:"redirect_uri"`

	// Scopes requested by the client.
	Scopes []string `json:"scopes"`

	// State is the client's CSRF token.
	State string `json:"state"`

	// Nonce is the OpenID Connect nonce for replay protection.
	Nonce string `json:"nonce,omitempty"`

	// CodeChallenge is the PKCE code challenge.
	CodeChallenge string `json:"code_challenge,omitempty"`

	// CodeChallengeMethod is the PKCE challenge method.
	CodeChallengeMethod string `json:"code_challenge_method,omitempty"`

	// UserID is set after authentication.
	UserID string `json:"user_id,omitempty"`

	// ConsentGranted is set after user consents to scopes.
	ConsentGranted bool `json:"consent_granted"`

	// GrantedScopes are the scopes the user consented to.
	GrantedScopes []string `json:"granted_scopes,omitempty"`

	// CreatedAt is when this session was created.
	CreatedAt time.Time `json:"created_at"`

	// ExpiresAt is when this session expires.
	ExpiresAt time.Time `json:"expires_at"`
}

AuthorizationSession holds the session data for an authorization request. This can be stored in a session store to persist across redirects.

func NewAuthorizationSession

func NewAuthorizationSession(ar fosite.AuthorizeRequester) *AuthorizationSession

NewAuthorizationSession creates a new authorization session from a Fosite request.

func (*AuthorizationSession) IsExpired

func (s *AuthorizationSession) IsExpired() bool

IsExpired returns true if the session has expired.

type AuthorizeInput

type AuthorizeInput struct {
	ResponseType        string `query:"response_type" required:"true" enum:"code,token" doc:"OAuth 2.0 response type"`
	ClientID            string `query:"client_id" required:"true" doc:"Client identifier"`
	RedirectURI         string `query:"redirect_uri" doc:"URI to redirect after authorization"`
	Scope               string `query:"scope" doc:"Space-separated list of requested scopes"`
	State               string `query:"state" doc:"Opaque value for CSRF protection"`
	CodeChallenge       string `query:"code_challenge" doc:"PKCE code challenge"`
	CodeChallengeMethod string `query:"code_challenge_method" enum:"S256,plain" doc:"PKCE code challenge method"`
	Nonce               string `query:"nonce" doc:"OpenID Connect nonce for replay protection"`
}

AuthorizeInput represents the OAuth 2.0 authorization request parameters.

type AuthorizeOutput

type AuthorizeOutput struct {
	Location string `header:"Location" doc:"Redirect URI with authorization code or token"`
}

AuthorizeOutput represents the authorization response (redirect).

type Client

type Client struct {
	// ID is the client identifier.
	ID string `json:"id"`

	// Secret is the client secret (never serialized).
	Secret string `json:"-"`

	// SecretHash is the bcrypt hash of the secret.
	SecretHash string `json:"secret_hash,omitempty"`

	// Type is "public" or "confidential".
	Type ClientType `json:"type"`

	// Name is a human-readable name.
	Name string `json:"name"`

	// Description is an optional description.
	Description string `json:"description,omitempty"`

	// RedirectURIs are allowed redirect URIs.
	RedirectURIs []string `json:"redirect_uris"`

	// GrantTypes are allowed grant types.
	GrantTypes []string `json:"grant_types"`

	// ResponseTypes are allowed response types.
	ResponseTypes []string `json:"response_types"`

	// Scopes are allowed scopes.
	Scopes []string `json:"scopes"`

	// Audience restricts the token audience.
	Audience []string `json:"audience,omitempty"`

	// AccessTokenLifetime overrides the default for this client.
	AccessTokenLifetime *time.Duration `json:"access_token_lifetime,omitempty"`

	// RefreshTokenLifetime overrides the default for this client.
	RefreshTokenLifetime *time.Duration `json:"refresh_token_lifetime,omitempty"`

	// Metadata holds arbitrary client metadata.
	Metadata map[string]any `json:"metadata,omitempty"`

	// CreatedAt is when the client was created.
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is when the client was last updated.
	UpdatedAt time.Time `json:"updated_at"`
}

Client represents an OAuth 2.0 client.

func NewClientFromConfig

func NewClientFromConfig(cfg ClientConfig) (*Client, error)

NewClientFromConfig creates a Client from a ClientConfig.

func (*Client) GetAudience

func (c *Client) GetAudience() fosite.Arguments

GetAudience returns the allowed audiences.

func (*Client) GetGrantTypes

func (c *Client) GetGrantTypes() fosite.Arguments

GetGrantTypes returns the allowed grant types.

func (*Client) GetHashedSecret

func (c *Client) GetHashedSecret() []byte

GetHashedSecret returns the hashed client secret.

func (*Client) GetID

func (c *Client) GetID() string

GetID returns the client ID.

func (*Client) GetRedirectURIs

func (c *Client) GetRedirectURIs() []string

GetRedirectURIs returns the allowed redirect URIs.

func (*Client) GetResponseTypes

func (c *Client) GetResponseTypes() fosite.Arguments

GetResponseTypes returns the allowed response types.

func (*Client) GetScopes

func (c *Client) GetScopes() fosite.Arguments

GetScopes returns the allowed scopes.

func (*Client) IsPublic

func (c *Client) IsPublic() bool

IsPublic returns true if the client is public (no secret).

func (*Client) ValidateSecret

func (c *Client) ValidateSecret(secret string) bool

ValidateSecret checks if the provided secret matches the stored hash.

type ClientConfig

type ClientConfig struct {
	// ID is the client identifier.
	ID string `json:"id" yaml:"id" jsonschema:"required,description=Unique client identifier"`

	// Secret is the client secret (for confidential clients).
	// Supports environment variable expansion: ${CLIENT_SECRET}
	Secret string `json:"secret,omitempty" yaml:"secret,omitempty" jsonschema:"description=Client secret (supports env var expansion)"`

	// Type is "public" or "confidential".
	Type string `json:"type" yaml:"type" jsonschema:"required,enum=public,enum=confidential,description=Client type"`

	// Name is a human-readable name.
	Name string `json:"name" yaml:"name" jsonschema:"required,description=Human-readable client name"`

	// Description is an optional description.
	Description string `json:"description,omitempty" yaml:"description,omitempty" jsonschema:"description=Client description"`

	// RedirectURIs are allowed redirect URIs.
	RedirectURIs []string `json:"redirect_uris,omitempty" yaml:"redirect_uris,omitempty" jsonschema:"description=Allowed redirect URIs"`

	// GrantTypes are allowed grant types.
	// Options: "authorization_code", "refresh_token", "client_credentials"
	GrantTypes []string `json:"grant_types,omitempty" yaml:"grant_types,omitempty" jsonschema:"description=Allowed OAuth grant types"`

	// ResponseTypes are allowed response types.
	// Options: "code", "token"
	ResponseTypes []string `json:"response_types,omitempty" yaml:"response_types,omitempty" jsonschema:"description=Allowed OAuth response types"`

	// Scopes are allowed scopes.
	Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty" jsonschema:"description=Allowed OAuth scopes"`

	// Audience restricts the token audience.
	Audience []string `json:"audience,omitempty" yaml:"audience,omitempty" jsonschema:"description=Allowed token audiences"`

	// AccessTokenLifetime overrides the default for this client.
	AccessTokenLifetime *Duration `` /* 140-byte string literal not displayed */

	// RefreshTokenLifetime overrides the default for this client.
	RefreshTokenLifetime *Duration `` /* 143-byte string literal not displayed */
}

ClientConfig defines a statically configured OAuth client.

type ClientManager

type ClientManager interface {
	// CreateClient creates a new OAuth client.
	CreateClient(ctx context.Context, client *Client) error

	// GetClientByID retrieves a client by ID.
	GetClientByID(ctx context.Context, id string) (*Client, error)

	// UpdateClient updates an existing client.
	UpdateClient(ctx context.Context, client *Client) error

	// DeleteClient deletes a client.
	DeleteClient(ctx context.Context, id string) error

	// ListClients returns all clients.
	ListClients(ctx context.Context) ([]*Client, error)
}

ClientManager provides CRUD operations for OAuth clients.

type ClientType

type ClientType string

ClientType defines whether a client is public or confidential.

const (
	// ClientTypePublic is for clients that cannot keep secrets (SPAs, mobile apps).
	ClientTypePublic ClientType = "public"

	// ClientTypeConfidential is for clients that can keep secrets (server apps).
	ClientTypeConfidential ClientType = "confidential"
)

type Config

type Config struct {
	// Issuer is the OAuth/OIDC issuer URL (required).
	// Example: "https://auth.example.com"
	Issuer string `json:"issuer" yaml:"issuer" jsonschema:"required,format=uri,description=OAuth/OIDC issuer URL"`

	// Database configures persistent storage.
	// If nil, in-memory storage is used (suitable for embedded mode).
	Database *DatabaseConfig `json:"database,omitempty" yaml:"database,omitempty" jsonschema:"description=Database configuration for persistent storage"`

	// Keys configures signing key management.
	Keys KeyConfig `json:"keys,omitempty" yaml:"keys,omitempty" jsonschema:"description=Signing key configuration"`

	// Tokens configures token lifetimes.
	Tokens TokenConfig `json:"tokens,omitempty" yaml:"tokens,omitempty" jsonschema:"description=Token lifetime configuration"`

	// Clients defines statically configured OAuth clients.
	Clients []ClientConfig `json:"clients,omitempty" yaml:"clients,omitempty" jsonschema:"description=Static OAuth client configurations"`

	// Federation configures CoreControl integration.
	Federation *FederationConfig `json:"federation,omitempty" yaml:"federation,omitempty" jsonschema:"description=CoreControl federation configuration"`

	// Features enables/disables optional features.
	Features FeatureConfig `json:"features,omitempty" yaml:"features,omitempty" jsonschema:"description=Feature flags"`
}

Config holds CoreAuth server configuration. This is the root configuration object for both embedded and standalone modes.

func DefaultConfig

func DefaultConfig(issuer string) *Config

DefaultConfig returns a Config with sensible defaults for embedded mode.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig loads configuration from a file. Supports both YAML (.yaml, .yml) and JSON (.json) formats. The format is detected by file extension.

func ParseConfig

func ParseConfig(data []byte, format ConfigFormat) (*Config, error)

ParseConfig parses configuration from bytes in the specified format.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults fills in missing values with defaults.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that the configuration is valid.

type ConfigFormat

type ConfigFormat string

ConfigFormat represents a configuration file format.

const (
	// FormatYAML indicates YAML format.
	FormatYAML ConfigFormat = "yaml"
	// FormatJSON indicates JSON format.
	FormatJSON ConfigFormat = "json"
)

type CoreControlDiscovery

type CoreControlDiscovery struct {
	Issuer                string   `json:"issuer"`
	AuthorizationEndpoint string   `json:"authorization_endpoint"`
	TokenEndpoint         string   `json:"token_endpoint"`
	UserinfoEndpoint      string   `json:"userinfo_endpoint"`
	JwksURI               string   `json:"jwks_uri"`
	IntrospectionEndpoint string   `json:"introspection_endpoint"`
	RevocationEndpoint    string   `json:"revocation_endpoint"`
	ScopesSupported       []string `json:"scopes_supported"`
}

CoreControlDiscovery holds the OIDC discovery configuration from CoreControl.

type DatabaseConfig

type DatabaseConfig struct {
	// Driver is the database driver: "postgres", "sqlite", "mysql"
	Driver string `json:"driver" yaml:"driver" jsonschema:"required,enum=postgres,enum=sqlite,enum=mysql,description=Database driver"`

	// DSN is the database connection string.
	// Supports environment variable expansion: ${DATABASE_URL}
	DSN string `json:"dsn" yaml:"dsn" jsonschema:"required,description=Database connection string (supports env var expansion)"`
}

DatabaseConfig configures persistent storage.

type DefaultIdentitySyncHandler

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

DefaultIdentitySyncHandler provides a basic implementation that creates local users.

func NewDefaultIdentitySyncHandler

func NewDefaultIdentitySyncHandler(storage Storage) *DefaultIdentitySyncHandler

NewDefaultIdentitySyncHandler creates a sync handler that uses the storage.

func (*DefaultIdentitySyncHandler) SyncIdentity

SyncIdentity implements IdentitySyncHandler.

type DefaultSessionProvider

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

DefaultSessionProvider provides a basic session provider for testing. In production, implement SessionProvider with your authentication system.

func NewDefaultSessionProvider

func NewDefaultSessionProvider(opts ...DefaultSessionProviderOption) *DefaultSessionProvider

NewDefaultSessionProvider creates a default session provider.

func (*DefaultSessionProvider) GetAuthenticatedUser

func (p *DefaultSessionProvider) GetAuthenticatedUser(r *http.Request) string

GetAuthenticatedUser returns the user ID from the configured header.

func (*DefaultSessionProvider) GetUserClaims

func (p *DefaultSessionProvider) GetUserClaims(_ context.Context, userID string, _ []string) map[string]interface{}

GetUserClaims returns an empty map. Override this in production to return actual user claims.

func (*DefaultSessionProvider) HasConsent

func (p *DefaultSessionProvider) HasConsent(_ context.Context, _, _ string, _ []string) bool

HasConsent always returns the value of skipConsent. Override this in production to check actual consent records.

func (*DefaultSessionProvider) RedirectToConsent

func (p *DefaultSessionProvider) RedirectToConsent(returnURL string) string

RedirectToConsent returns the consent URL with return URL parameter.

func (*DefaultSessionProvider) RedirectToLogin

func (p *DefaultSessionProvider) RedirectToLogin(returnURL string) string

RedirectToLogin returns the login URL with return URL parameter.

func (*DefaultSessionProvider) SaveConsent

func (p *DefaultSessionProvider) SaveConsent(_ context.Context, _, _ string, _ []string) error

SaveConsent is a no-op in the default provider. Override this in production to persist consent records.

type DefaultSessionProviderOption

type DefaultSessionProviderOption func(*DefaultSessionProvider)

DefaultSessionProviderOption configures a DefaultSessionProvider.

func WithConsentURL

func WithConsentURL(url string) DefaultSessionProviderOption

WithConsentURL sets the consent redirect URL.

func WithLoginURL

func WithLoginURL(url string) DefaultSessionProviderOption

WithLoginURL sets the login redirect URL.

func WithSkipConsent

func WithSkipConsent(skip bool) DefaultSessionProviderOption

WithSkipConsent enables automatic consent for all requests.

func WithUserIDHeader

func WithUserIDHeader(header string) DefaultSessionProviderOption

WithUserIDHeader sets the header to read user ID from. Default is "X-User-ID".

type Duration

type Duration time.Duration

Duration is a wrapper around time.Duration that supports human-readable string serialization (e.g., "15m", "1h", "7d").

func (Duration) Duration

func (d Duration) Duration() time.Duration

Duration returns the underlying time.Duration.

func (Duration) JSONSchema

func (Duration) JSONSchema() *jsonschema.Schema

JSONSchema implements jsonschema.JSONSchemaer for Duration.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (interface{}, error)

MarshalYAML implements yaml.Marshaler.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements yaml.Unmarshaler.

type EntStorage

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

EntStorage implements Storage using Ent ORM.

func NewEntStorage

func NewEntStorage(db *ent.Client, opts ...EntStorageOption) *EntStorage

NewEntStorage creates a new Ent-backed storage.

func (*EntStorage) ClientAssertionJWTValid

func (s *EntStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error

ClientAssertionJWTValid checks if a JWT ID has been used.

func (*EntStorage) CreateAccessTokenSession

func (s *EntStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error

CreateAccessTokenSession stores an access token session.

func (*EntStorage) CreateAuthorizeCodeSession

func (s *EntStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error

CreateAuthorizeCodeSession stores an authorization code session.

func (*EntStorage) CreateClient

func (s *EntStorage) CreateClient(ctx context.Context, client *Client) error

CreateClient creates a new OAuth client.

func (*EntStorage) CreatePKCERequestSession

func (s *EntStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error

CreatePKCERequestSession creates a PKCE session (stored with auth code).

func (*EntStorage) CreateRefreshTokenSession

func (s *EntStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error

CreateRefreshTokenSession stores a refresh token session.

func (*EntStorage) CreateUser

func (s *EntStorage) CreateUser(ctx context.Context, user *User) error

CreateUser creates a new user from federation sync.

func (*EntStorage) DeleteAccessTokenSession

func (s *EntStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error

DeleteAccessTokenSession removes an access token session.

func (*EntStorage) DeleteClient

func (s *EntStorage) DeleteClient(ctx context.Context, id string) error

DeleteClient deletes a client.

func (*EntStorage) DeletePKCERequestSession

func (s *EntStorage) DeletePKCERequestSession(ctx context.Context, signature string) error

DeletePKCERequestSession deletes a PKCE session.

func (*EntStorage) DeleteRefreshTokenSession

func (s *EntStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error

DeleteRefreshTokenSession removes a refresh token session.

func (*EntStorage) DeleteUser

func (s *EntStorage) DeleteUser(ctx context.Context, id uuid.UUID) error

DeleteUser deletes a user.

func (*EntStorage) GetAccessTokenSession

func (s *EntStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetAccessTokenSession retrieves an access token session.

func (*EntStorage) GetAuthorizeCodeSession

func (s *EntStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)

GetAuthorizeCodeSession retrieves an authorization code session.

func (*EntStorage) GetClient

func (s *EntStorage) GetClient(ctx context.Context, clientID string) (fosite.Client, error)

GetClient loads an OAuth client by its client_id.

func (*EntStorage) GetClientByID

func (s *EntStorage) GetClientByID(ctx context.Context, id string) (*Client, error)

GetClientByID retrieves a client by ID.

func (*EntStorage) GetPKCERequestSession

func (s *EntStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetPKCERequestSession gets the PKCE session for a code.

func (*EntStorage) GetRefreshTokenSession

func (s *EntStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetRefreshTokenSession retrieves a refresh token session.

func (*EntStorage) GetUserByEmail

func (s *EntStorage) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a user by email.

func (*EntStorage) GetUserByFederationID

func (s *EntStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)

GetUserByFederationID retrieves a user by their federation ID.

func (*EntStorage) GetUserByID

func (s *EntStorage) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)

GetUserByID retrieves a user by ID.

func (*EntStorage) InvalidateAuthorizeCodeSession

func (s *EntStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error

InvalidateAuthorizeCodeSession marks an authorization code as used.

func (*EntStorage) ListClients

func (s *EntStorage) ListClients(ctx context.Context) ([]*Client, error)

ListClients returns all clients.

func (*EntStorage) RevokeAccessToken

func (s *EntStorage) RevokeAccessToken(ctx context.Context, requestID string) error

RevokeAccessToken revokes an access token by request ID.

func (*EntStorage) RevokeRefreshToken

func (s *EntStorage) RevokeRefreshToken(ctx context.Context, requestID string) error

RevokeRefreshToken revokes a refresh token by request ID (family).

func (*EntStorage) RotateRefreshToken

func (s *EntStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error

RotateRefreshToken handles refresh token rotation.

func (*EntStorage) SetClientAssertionJWT

func (s *EntStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error

SetClientAssertionJWT marks a JWT ID as used.

func (*EntStorage) UpdateClient

func (s *EntStorage) UpdateClient(ctx context.Context, client *Client) error

UpdateClient updates an existing client.

func (*EntStorage) UpdateUser

func (s *EntStorage) UpdateUser(ctx context.Context, user *User) error

UpdateUser updates an existing user.

func (*EntStorage) ValidateSecretArgon2id

func (s *EntStorage) ValidateSecretArgon2id(ctx context.Context, clientID, secret string) error

ValidateSecretArgon2id validates a client secret using Argon2id.

type EntStorageOption

type EntStorageOption func(*EntStorage)

EntStorageOption configures EntStorage.

func WithDefaultOwner

func WithDefaultOwner(ownerID uuid.UUID) EntStorageOption

WithDefaultOwner sets the default owner ID for new clients. This is used when creating clients without an explicit owner context.

type FeatureConfig

type FeatureConfig struct {
	// RequirePKCE requires PKCE for all authorization code flows.
	// Default: true for public clients, configurable for confidential
	RequirePKCE bool `` /* 139-byte string literal not displayed */

	// AllowDynamicRegistration enables RFC 7591 dynamic client registration.
	AllowDynamicRegistration bool `` /* 172-byte string literal not displayed */

	// EnableDeviceFlow enables the device authorization grant (RFC 8628).
	EnableDeviceFlow bool `` /* 155-byte string literal not displayed */

	// EnableJWTAccessTokens issues JWT access tokens instead of opaque tokens.
	EnableJWTAccessTokens bool `` /* 171-byte string literal not displayed */
}

FeatureConfig enables/disables optional features.

type FederationClient

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

FederationClient connects a CoreAuth app to CoreControl for SSO.

func NewFederationClient

func NewFederationClient(config *FederationConfig) (*FederationClient, error)

NewFederationClient creates a new federation client.

func (*FederationClient) Config

func (c *FederationClient) Config() *FederationConfig

Config returns the federation configuration.

func (*FederationClient) Discovery

func (c *FederationClient) Discovery() *CoreControlDiscovery

Discovery returns the CoreControl discovery document.

func (*FederationClient) ExchangeCode

func (c *FederationClient) ExchangeCode(ctx context.Context, code, redirectURI string) (*SSOTokenResponse, error)

ExchangeCode exchanges an authorization code from CoreControl for tokens.

func (*FederationClient) GetGlobalIdentity

func (c *FederationClient) GetGlobalIdentity(ctx context.Context, globalID uuid.UUID) (*GlobalIdentity, error)

GetGlobalIdentity retrieves a global identity from CoreControl.

func (*FederationClient) GetIdentityMapping

func (c *FederationClient) GetIdentityMapping(ctx context.Context, globalID uuid.UUID) (*IdentityMapping, error)

GetIdentityMapping retrieves the mapping for a global identity in this app.

func (*FederationClient) GetSSOAuthorizationURL

func (c *FederationClient) GetSSOAuthorizationURL(ctx context.Context, state, redirectURI string) (string, error)

GetSSOAuthorizationURL generates the URL to redirect users to CoreControl for SSO.

func (*FederationClient) Initialize

func (c *FederationClient) Initialize(ctx context.Context) error

Initialize fetches the CoreControl discovery document.

func (*FederationClient) NotifyAppAccess

func (c *FederationClient) NotifyAppAccess(ctx context.Context, sessionID uuid.UUID) error

NotifyAppAccess records that a user accessed this app via SSO.

func (*FederationClient) RegisterWithCoreControl

func (c *FederationClient) RegisterWithCoreControl(ctx context.Context, federationID uuid.UUID, displayName, baseURL string, capabilities []string) error

RegisterWithCoreControl registers this app with a federation.

func (*FederationClient) ValidateSSOSession

func (c *FederationClient) ValidateSSOSession(ctx context.Context, sessionID uuid.UUID) (*SSOSession, error)

ValidateSSOSession validates an SSO session with CoreControl.

type FederationConfig

type FederationConfig struct {
	// Enabled enables federation mode.
	Enabled bool `json:"enabled" yaml:"enabled" jsonschema:"description=Enable CoreControl federation"`

	// CoreControlURL is the CoreControl server URL.
	CoreControlURL string `json:"corecontrol_url" yaml:"corecontrol_url" jsonschema:"format=uri,description=CoreControl server URL"`

	// AppID is this application's identifier in the federation.
	AppID string `json:"app_id" yaml:"app_id" jsonschema:"description=Application ID in the federation"`

	// ClientID is the OAuth client ID for CoreControl.
	ClientID string `json:"client_id" yaml:"client_id" jsonschema:"description=OAuth client ID for CoreControl"`

	// ClientSecret is the OAuth client secret for CoreControl.
	// Supports environment variable expansion: ${CORECONTROL_SECRET}
	ClientSecret string `json:"client_secret" yaml:"client_secret" jsonschema:"description=OAuth client secret (supports env var expansion)"`
}

FederationConfig configures CoreControl integration.

type FederationEndpoints

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

FederationEndpoints provides CoreForge federation contract endpoints.

func NewFederationEndpoints

func NewFederationEndpoints(server *Server, syncHandler IdentitySyncHandler) *FederationEndpoints

NewFederationEndpoints creates federation endpoints for the server.

func (*FederationEndpoints) RegisterRoutes

func (f *FederationEndpoints) RegisterRoutes()

RegisterRoutes registers the federation endpoints on the server's router.

type FederationHealthResponse

type FederationHealthResponse struct {
	Status       string            `json:"status"`
	AppID        string            `json:"app_id"`
	Version      string            `json:"version"`
	Capabilities []string          `json:"capabilities"`
	Details      map[string]string `json:"details,omitempty"`
}

FederationHealthResponse is returned by the health endpoint.

type GlobalIdentity

type GlobalIdentity struct {
	ID           uuid.UUID              `json:"id"`
	FederationID uuid.UUID              `json:"federation_id"`
	Email        string                 `json:"email"`
	DisplayName  string                 `json:"display_name"`
	Status       string                 `json:"status"`
	Attributes   map[string]interface{} `json:"attributes,omitempty"`
	CreatedAt    time.Time              `json:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at"`
}

GlobalIdentity represents a user's identity from CoreControl.

type IdentityMapping

type IdentityMapping struct {
	ID               uuid.UUID `json:"id"`
	GlobalIdentityID uuid.UUID `json:"global_identity_id"`
	AppID            string    `json:"app_id"`
	LocalPrincipalID uuid.UUID `json:"local_principal_id"`
	MappedAt         time.Time `json:"mapped_at"`
	SyncStatus       string    `json:"sync_status"`
}

IdentityMapping maps a global identity to a local principal.

type IdentitySyncHandler

type IdentitySyncHandler interface {
	// SyncIdentity is called when CoreControl wants to sync an identity to this app.
	// The handler should create/update/delete the local principal as appropriate.
	SyncIdentity(ctx context.Context, req *IdentitySyncRequest) (*IdentitySyncResponse, error)
}

IdentitySyncHandler handles identity sync requests from CoreControl. Apps must implement this interface to handle identity provisioning.

type IdentitySyncRequest

type IdentitySyncRequest struct {
	Action   string          `json:"action"` // create, update, delete
	Identity *GlobalIdentity `json:"identity"`
}

IdentitySyncRequest is received from CoreControl to sync an identity.

type IdentitySyncResponse

type IdentitySyncResponse struct {
	LocalPrincipalID uuid.UUID `json:"local_principal_id"`
	Status           string    `json:"status"` // synced, pending, failed
	Error            string    `json:"error,omitempty"`
}

IdentitySyncResponse is returned to CoreControl after syncing.

type IntrospectInput

type IntrospectInput struct {
	Token         string `form:"token" required:"true" doc:"The token to introspect"`
	TokenTypeHint string `form:"token_type_hint" enum:"access_token,refresh_token" doc:"Hint about the token type"`

	// Client authentication
	Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}

IntrospectInput represents the token introspection request.

type IntrospectOutput

type IntrospectOutput struct {
	Body IntrospectResponse
}

IntrospectOutput wraps the introspection response.

type IntrospectResponse

type IntrospectResponse struct {
	Active    bool   `json:"active" doc:"Whether the token is active"`
	Scope     string `json:"scope,omitempty" doc:"Scopes associated with the token"`
	ClientID  string `json:"client_id,omitempty" doc:"Client that requested the token"`
	Username  string `json:"username,omitempty" doc:"Resource owner username"`
	TokenType string `json:"token_type,omitempty" doc:"Token type"`
	Exp       int64  `json:"exp,omitempty" doc:"Token expiration timestamp"`
	Iat       int64  `json:"iat,omitempty" doc:"Token issue timestamp"`
	Nbf       int64  `json:"nbf,omitempty" doc:"Token not-before timestamp"`
	Sub       string `json:"sub,omitempty" doc:"Subject (user ID)"`
	Aud       string `json:"aud,omitempty" doc:"Intended audience"`
	Iss       string `json:"iss,omitempty" doc:"Token issuer"`
	Jti       string `json:"jti,omitempty" doc:"JWT ID"`
}

IntrospectResponse represents the token introspection response.

type JWKSInput

type JWKSInput struct{}

JWKSInput is the input for the JWKS endpoint (no params).

type JWKSOutput

type JWKSOutput struct {
	Body jose.JSONWebKeySet
}

JWKSOutput wraps the JWKS response.

type KeyConfig

type KeyConfig struct {
	// Algorithm is the signing algorithm: "RS256" (default), "ES256"
	Algorithm string `` /* 136-byte string literal not displayed */

	// RotationDays is how often to rotate keys (0 = never)
	RotationDays int `` /* 138-byte string literal not displayed */

	// PrivateKey is an optional pre-configured RSA private key.
	// If nil, a key will be generated automatically.
	// This field is not serialized - for programmatic use only.
	PrivateKey *rsa.PrivateKey `json:"-" yaml:"-" jsonschema:"-"`
}

KeyConfig configures signing key management.

type MemoryStorage

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

MemoryStorage implements the Storage interface using in-memory maps. This is suitable for embedded mode and testing.

func NewMemoryStorage

func NewMemoryStorage() *MemoryStorage

NewMemoryStorage creates a new in-memory storage.

func (*MemoryStorage) CleanupExpired

func (s *MemoryStorage) CleanupExpired(ctx context.Context) error

CleanupExpired removes all expired entries. Should be called periodically (e.g., every minute).

func (*MemoryStorage) ClientAssertionJWTValid

func (s *MemoryStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error

ClientAssertionJWTValid returns an error if the JTI is known or the DB check failed.

func (*MemoryStorage) CreateAccessTokenSession

func (s *MemoryStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error

CreateAccessTokenSession stores an access token session.

func (*MemoryStorage) CreateAuthorizeCodeSession

func (s *MemoryStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error

CreateAuthorizeCodeSession stores an authorization code session.

func (*MemoryStorage) CreateClient

func (s *MemoryStorage) CreateClient(ctx context.Context, client *Client) error

CreateClient creates a new OAuth client.

func (*MemoryStorage) CreatePKCERequestSession

func (s *MemoryStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error

CreatePKCERequestSession creates a PKCE session.

func (*MemoryStorage) CreateRefreshTokenSession

func (s *MemoryStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error

CreateRefreshTokenSession stores a refresh token session.

func (*MemoryStorage) CreateUser

func (s *MemoryStorage) CreateUser(ctx context.Context, user *User) error

CreateUser creates a new user.

func (*MemoryStorage) DeleteAccessTokenSession

func (s *MemoryStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error

DeleteAccessTokenSession removes an access token session.

func (*MemoryStorage) DeleteClient

func (s *MemoryStorage) DeleteClient(ctx context.Context, id string) error

DeleteClient deletes a client.

func (*MemoryStorage) DeletePKCERequestSession

func (s *MemoryStorage) DeletePKCERequestSession(ctx context.Context, signature string) error

DeletePKCERequestSession deletes a PKCE session.

func (*MemoryStorage) DeleteRefreshTokenSession

func (s *MemoryStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error

DeleteRefreshTokenSession removes a refresh token session.

func (*MemoryStorage) DeleteUser

func (s *MemoryStorage) DeleteUser(ctx context.Context, id uuid.UUID) error

DeleteUser deletes a user.

func (*MemoryStorage) GetAccessTokenSession

func (s *MemoryStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetAccessTokenSession retrieves an access token session.

func (*MemoryStorage) GetAuthorizeCodeSession

func (s *MemoryStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)

GetAuthorizeCodeSession retrieves an authorization code session.

func (*MemoryStorage) GetClient

func (s *MemoryStorage) GetClient(ctx context.Context, id string) (fosite.Client, error)

GetClient retrieves a client by ID (implements fosite.ClientManager).

func (*MemoryStorage) GetClientByID

func (s *MemoryStorage) GetClientByID(ctx context.Context, id string) (*Client, error)

GetClientByID retrieves a client by ID.

func (*MemoryStorage) GetPKCERequestSession

func (s *MemoryStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetPKCERequestSession retrieves a PKCE session.

func (*MemoryStorage) GetRefreshTokenSession

func (s *MemoryStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)

GetRefreshTokenSession retrieves a refresh token session.

func (*MemoryStorage) GetUserByEmail

func (s *MemoryStorage) GetUserByEmail(ctx context.Context, email string) (*User, error)

GetUserByEmail retrieves a user by email.

func (*MemoryStorage) GetUserByFederationID

func (s *MemoryStorage) GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)

GetUserByFederationID retrieves a user by their federation ID.

func (*MemoryStorage) GetUserByID

func (s *MemoryStorage) GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)

GetUserByID retrieves a user by ID.

func (*MemoryStorage) InvalidateAuthorizeCodeSession

func (s *MemoryStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error

InvalidateAuthorizeCodeSession marks an authorization code as used.

func (*MemoryStorage) ListClients

func (s *MemoryStorage) ListClients(ctx context.Context) ([]*Client, error)

ListClients returns all clients.

func (*MemoryStorage) RevokeAccessToken

func (s *MemoryStorage) RevokeAccessToken(ctx context.Context, requestID string) error

RevokeAccessToken revokes all access tokens for a request ID.

func (*MemoryStorage) RevokeRefreshToken

func (s *MemoryStorage) RevokeRefreshToken(ctx context.Context, requestID string) error

RevokeRefreshToken revokes all refresh tokens for a request ID.

func (*MemoryStorage) RotateRefreshToken

func (s *MemoryStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error

RotateRefreshToken rotates a refresh token.

func (*MemoryStorage) SetClientAssertionJWT

func (s *MemoryStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error

SetClientAssertionJWT marks a JTI as used.

func (*MemoryStorage) UpdateClient

func (s *MemoryStorage) UpdateClient(ctx context.Context, client *Client) error

UpdateClient updates an existing client.

func (*MemoryStorage) UpdateUser

func (s *MemoryStorage) UpdateUser(ctx context.Context, user *User) error

UpdateUser updates an existing user.

type OAuthError

type OAuthError struct {
	Error            string `json:"error" doc:"Error code"`
	ErrorDescription string `json:"error_description,omitempty" doc:"Human-readable error description"`
	ErrorURI         string `json:"error_uri,omitempty" doc:"URI with more information about the error"`
}

OAuthError represents an OAuth 2.0 error response.

type OpenIDConfigInput

type OpenIDConfigInput struct{}

OpenIDConfigInput is the input for the discovery endpoint (no params).

type OpenIDConfigOutput

type OpenIDConfigOutput struct {
	Body OpenIDConfiguration
}

OpenIDConfigOutput wraps the OpenID configuration response.

type OpenIDConfiguration

type OpenIDConfiguration struct {
	Issuer                            string   `json:"issuer"`
	AuthorizationEndpoint             string   `json:"authorization_endpoint"`
	TokenEndpoint                     string   `json:"token_endpoint"`
	UserinfoEndpoint                  string   `json:"userinfo_endpoint,omitempty"`
	JwksURI                           string   `json:"jwks_uri"`
	RegistrationEndpoint              string   `json:"registration_endpoint,omitempty"`
	IntrospectionEndpoint             string   `json:"introspection_endpoint,omitempty"`
	RevocationEndpoint                string   `json:"revocation_endpoint,omitempty"`
	ScopesSupported                   []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported            []string `json:"response_types_supported"`
	ResponseModesSupported            []string `json:"response_modes_supported,omitempty"`
	GrantTypesSupported               []string `json:"grant_types_supported,omitempty"`
	SubjectTypesSupported             []string `json:"subject_types_supported"`
	IDTokenSigningAlgValuesSupported  []string `json:"id_token_signing_alg_values_supported"`
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
	ClaimsSupported                   []string `json:"claims_supported,omitempty"`
	CodeChallengeMethodsSupported     []string `json:"code_challenge_methods_supported,omitempty"`
}

OpenIDConfiguration represents the OpenID Provider configuration.

type Option

type Option func(*Server)

Option configures a Server.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for the server.

func WithSessionProvider

func WithSessionProvider(provider SessionProvider) Option

WithSessionProvider sets a custom session provider for authentication.

func WithStorage

func WithStorage(storage Storage) Option

WithStorage sets a custom storage implementation.

type RevokeInput

type RevokeInput struct {
	Token         string `form:"token" required:"true" doc:"The token to revoke"`
	TokenTypeHint string `form:"token_type_hint" enum:"access_token,refresh_token" doc:"Hint about the token type"`

	// Client authentication
	Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}

RevokeInput represents the token revocation request.

type RevokeOutput

type RevokeOutput struct{}

RevokeOutput represents the token revocation response (empty on success).

type SSOSession

type SSOSession struct {
	ID               uuid.UUID `json:"id"`
	GlobalIdentityID uuid.UUID `json:"global_identity_id"`
	AuthTime         time.Time `json:"auth_time"`
	ExpiresAt        time.Time `json:"expires_at"`
	AppsAccessed     []string  `json:"apps_accessed"`
}

SSOSession represents an active SSO session from CoreControl.

type SSOTokenResponse

type SSOTokenResponse struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
	IDToken      string `json:"id_token,omitempty"`
	Scope        string `json:"scope,omitempty"`
}

SSOTokenResponse contains tokens from CoreControl SSO.

type Server

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

Server is the CoreAuth OAuth 2.0 / OpenID Connect server.

func NewEmbedded

func NewEmbedded(cfg Config, opts ...Option) (*Server, error)

NewEmbedded creates a CoreAuth server for embedding in applications. This is the simplest way to add OAuth to a CoreForge application.

Example:

auth, err := coreauth.NewEmbedded(coreauth.Config{
    Issuer: "https://myapp.example.com",
})
router.Mount("/oauth", auth.Router())

func (*Server) GetClient

func (s *Server) GetClient(id string) (*Client, error)

GetClient retrieves a client by ID.

func (*Server) Huma

func (s *Server) Huma() huma.API

Huma returns the Huma API for advanced configuration.

func (*Server) Logger

func (s *Server) Logger() *slog.Logger

Logger returns the server's logger.

func (*Server) Middleware

func (s *Server) Middleware() func(http.Handler) http.Handler

Middleware returns HTTP middleware that validates access tokens. Use this to protect your API endpoints.

Example:

router.With(auth.Middleware()).Get("/api/me", meHandler)

func (*Server) OAuth2Provider

func (s *Server) OAuth2Provider() fosite.OAuth2Provider

OAuth2Provider returns the underlying Fosite provider.

func (*Server) OIDCSession

func (s *Server) OIDCSession(subject string, claims map[string]interface{}) *openid.DefaultSession

OIDCSession creates an OpenID Connect session for Fosite.

func (*Server) PublicKey

func (s *Server) PublicKey() *rsa.PublicKey

PublicKey returns the public RSA key for external verification.

func (*Server) RegisterClient

func (s *Server) RegisterClient(client *Client) error

RegisterClient registers a new OAuth client.

func (*Server) RequireScopes

func (s *Server) RequireScopes(scopes ...string) func(http.Handler) http.Handler

RequireScopes returns middleware that requires specific scopes.

func (*Server) Router

func (s *Server) Router() chi.Router

Router returns the Chi router for mounting.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*Server) Session

func (s *Server) Session(subject string) *openid.DefaultSession

Session creates a new OAuth session for a user.

func (*Server) SessionProvider

func (s *Server) SessionProvider() SessionProvider

SessionProvider returns the session provider.

func (*Server) Storage

func (s *Server) Storage() Storage

Storage returns the storage implementation.

type SessionProvider

type SessionProvider interface {
	// GetAuthenticatedUser returns the authenticated user ID from the request.
	// Returns empty string if the user is not authenticated.
	GetAuthenticatedUser(r *http.Request) string

	// RedirectToLogin returns the URL to redirect unauthenticated users to.
	// The returnURL is the original authorization request URL to return to after login.
	RedirectToLogin(returnURL string) string

	// HasConsent checks if the user has already granted consent for the client and scopes.
	// Returns true if consent exists and is still valid.
	HasConsent(ctx context.Context, userID, clientID string, scopes []string) bool

	// RedirectToConsent returns the URL to redirect users for consent approval.
	// The returnURL is the original authorization request URL to return to after consent.
	RedirectToConsent(returnURL string) string

	// SaveConsent records that the user has granted consent for the client and scopes.
	SaveConsent(ctx context.Context, userID, clientID string, scopes []string) error

	// GetUserClaims returns additional claims to include in the ID token.
	// Common claims: name, email, picture, etc.
	GetUserClaims(ctx context.Context, userID string, scopes []string) map[string]interface{}
}

SessionProvider handles user authentication and consent for the authorization flow. Implement this interface to integrate with your authentication system.

type Storage

type Storage interface {
	// Fosite storage interfaces
	fosite.ClientManager

	// Authorization code operations
	CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
	GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
	InvalidateAuthorizeCodeSession(ctx context.Context, code string) error

	// Access token operations
	CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
	GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
	DeleteAccessTokenSession(ctx context.Context, signature string) error

	// Refresh token operations
	CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error
	GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
	DeleteRefreshTokenSession(ctx context.Context, signature string) error
	RevokeRefreshToken(ctx context.Context, requestID string) error
	RevokeAccessToken(ctx context.Context, requestID string) error
	RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error

	// PKCE operations
	CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
	GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
	DeletePKCERequestSession(ctx context.Context, signature string) error

	// Client assertion JWT tracking
	ClientAssertionJWTValid(ctx context.Context, jti string) error
	SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error

	// Client management operations (extended)
	CreateClient(ctx context.Context, client *Client) error
	GetClientByID(ctx context.Context, id string) (*Client, error)
	UpdateClient(ctx context.Context, client *Client) error
	DeleteClient(ctx context.Context, id string) error
	ListClients(ctx context.Context) ([]*Client, error)

	// User management for federation (optional - may return ErrNotImplemented)
	CreateUser(ctx context.Context, user *User) error
	GetUserByID(ctx context.Context, id uuid.UUID) (*User, error)
	GetUserByEmail(ctx context.Context, email string) (*User, error)
	GetUserByFederationID(ctx context.Context, federationID uuid.UUID) (*User, error)
	UpdateUser(ctx context.Context, user *User) error
	DeleteUser(ctx context.Context, id uuid.UUID) error
}

Storage defines the persistence interface for CoreAuth. It extends Fosite's storage requirements with client management.

type StoredRequest

type StoredRequest struct {
	ID            string
	ClientID      string
	Scopes        []string
	GrantedScopes []string
	Form          map[string][]string
	Session       *StoredSession
	RequestedAt   time.Time
}

StoredRequest holds the data needed to reconstruct a fosite.Requester.

type StoredSession

type StoredSession struct {
	// Subject is the user ID.
	Subject string `json:"sub"`

	// Username is the human-readable username.
	Username string `json:"username,omitempty"`

	// Email is the user's email.
	Email string `json:"email,omitempty"`

	// Claims are additional claims.
	Claims map[string]any `json:"claims,omitempty"`

	// ExpiresAt maps token types to expiration times (unix timestamps).
	ExpiresAt map[string]int64 `json:"expires_at"`

	// RequestedAt is when the session was created (unix timestamp).
	RequestedAt int64 `json:"requested_at"`
}

StoredSession holds serializable session information.

type TokenConfig

type TokenConfig struct {
	// AccessTokenLifetime is how long access tokens are valid.
	// Default: 15 minutes
	AccessTokenLifetime Duration `` /* 151-byte string literal not displayed */

	// RefreshTokenLifetime is how long refresh tokens are valid.
	// Default: 7 days
	RefreshTokenLifetime Duration `` /* 158-byte string literal not displayed */

	// IDTokenLifetime is how long ID tokens are valid.
	// Default: 1 hour
	IDTokenLifetime Duration `` /* 133-byte string literal not displayed */

	// AuthCodeLifetime is how long authorization codes are valid.
	// Default: 10 minutes
	AuthCodeLifetime Duration `` /* 147-byte string literal not displayed */
}

TokenConfig configures token lifetimes. Durations are specified as strings: "15m", "1h", "7d", etc.

type TokenData

type TokenData struct {
	// AccessTokenSignature is the hashed access token.
	AccessTokenSignature string

	// RefreshTokenSignature is the hashed refresh token.
	RefreshTokenSignature string

	// ClientID is the client that owns the token.
	ClientID string

	// Subject is the user ID.
	Subject string

	// Scopes are the granted scopes.
	Scopes []string

	// Session holds the session data.
	Session *StoredSession

	// AccessExpiresAt is when the access token expires.
	AccessExpiresAt int64

	// RefreshExpiresAt is when the refresh token expires.
	RefreshExpiresAt int64

	// Revoked indicates the token has been revoked.
	Revoked bool

	// RequestID is used for token family tracking.
	RequestID string
}

TokenData holds access/refresh token storage data.

type TokenInput

type TokenInput struct {
	GrantType    string `form:"grant_type" required:"true" enum:"authorization_code,refresh_token,client_credentials" doc:"OAuth 2.0 grant type"`
	Code         string `form:"code" doc:"Authorization code (for authorization_code grant)"`
	RedirectURI  string `form:"redirect_uri" doc:"Redirect URI (must match authorization request)"`
	ClientID     string `form:"client_id" doc:"Client identifier (if not using Basic auth)"`
	ClientSecret string `form:"client_secret" doc:"Client secret (if not using Basic auth)"`
	RefreshToken string `form:"refresh_token" doc:"Refresh token (for refresh_token grant)"`
	Scope        string `form:"scope" doc:"Requested scopes (for refresh_token or client_credentials)"`
	CodeVerifier string `form:"code_verifier" doc:"PKCE code verifier"`

	// Basic auth credentials (alternative to form-based client auth)
	Authorization string `header:"Authorization" doc:"Basic authentication header (client_id:client_secret)"`
}

TokenInput represents the OAuth 2.0 token request parameters. Field names follow OAuth 2.0 specification (RFC 6749).

type TokenOutput

type TokenOutput struct {
	Body TokenResponse
}

TokenOutput wraps the token response.

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token" doc:"The access token"`
	TokenType    string `json:"token_type" doc:"Token type (typically 'Bearer')"`
	ExpiresIn    int    `json:"expires_in,omitempty" doc:"Token lifetime in seconds"`
	RefreshToken string `json:"refresh_token,omitempty" doc:"Refresh token for obtaining new access tokens"`
	Scope        string `json:"scope,omitempty" doc:"Granted scopes (may differ from requested)"`
	IDToken      string `json:"id_token,omitempty" doc:"OpenID Connect ID token"`
}

TokenResponse represents the OAuth 2.0 token response. Field names follow OAuth 2.0 specification (RFC 6749).

type User

type User struct {
	ID           uuid.UUID  `json:"id"`
	Email        string     `json:"email"`
	Name         string     `json:"name"`
	Active       bool       `json:"active"`
	Federated    bool       `json:"federated"`
	FederationID *uuid.UUID `json:"federation_id,omitempty"`
}

User represents a local user for federation sync.

Directories

Path Synopsis
Package schema provides the embedded JSON Schema for CoreAuth configuration.
Package schema provides the embedded JSON Schema for CoreAuth configuration.

Jump to

Keyboard shortcuts

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