Documentation
¶
Index ¶
- Constants
- Variables
- func AccessRequestFromContext(ctx context.Context) fosite.AccessRequester
- func AuthorizeIntrospectionCaller(r *http.Request, clientPublic func(clientID string) (known, public bool), ...) bool
- func ContextWithOwnerID(ctx context.Context, ownerID uuid.UUID) context.Context
- func KeyThumbprint(key *rsa.PrivateKey) (string, error)
- func LoggerFromContext(ctx context.Context) *slog.Logger
- func ParseSigningKey(pemData []byte) (*rsa.PrivateKey, error)
- func SaveConfig(cfg *Config, path string) error
- func TrustAllRequests(*http.Request) bool
- func UserInfoClaims(subject string, claims map[string]any, granted []string) map[string]any
- func ValidateBackchannelLogoutURI(raw string) error
- func WithAccessRequest(ctx context.Context, ar fosite.AccessRequester) context.Context
- type AccessChangeLister
- type AccessChangeResponse
- type AccessChangesResponse
- type AppRoleResolver
- type AuthCodeData
- type AuthMethod
- type AuthSession
- type AuthenticateRequest
- type AuthenticationProvider
- type AuthorizationSession
- type AuthorizeInput
- type AuthorizeOutput
- type Backchannel
- type BackchannelOption
- type Client
- func (c *Client) GetAudience() fosite.Arguments
- func (c *Client) GetGrantTypes() fosite.Arguments
- func (c *Client) GetHashedSecret() []byte
- func (c *Client) GetID() string
- func (c *Client) GetRedirectURIs() []string
- func (c *Client) GetResponseTypes() fosite.Arguments
- func (c *Client) GetRotatedHashes() [][]byte
- func (c *Client) GetScopes() fosite.Arguments
- func (c *Client) IsPublic() bool
- func (c *Client) ValidateSecret(secret string) bool
- type ClientConfig
- type ClientManager
- type ClientType
- type Config
- type ConfigFormat
- type ConsentSession
- type ConsentStore
- type CredentialType
- type DatabaseConfig
- type DefaultIdentitySyncHandler
- type DefaultSessionProvider
- func (p *DefaultSessionProvider) GetAuthenticatedUser(r *http.Request) string
- func (p *DefaultSessionProvider) GetUserClaims(_ context.Context, userID string, _ []string) map[string]interface{}
- func (p *DefaultSessionProvider) HasConsent(_ context.Context, _, _ string, _ []string) bool
- func (p *DefaultSessionProvider) RedirectToConsent(returnURL string) string
- func (p *DefaultSessionProvider) RedirectToLogin(returnURL string) string
- func (p *DefaultSessionProvider) SaveConsent(_ context.Context, _, _ string, _ []string) error
- type DefaultSessionProviderOption
- type DeviceInfo
- type Duration
- func (d Duration) Duration() time.Duration
- func (Duration) JSONSchema() *jsonschema.Schema
- func (d Duration) MarshalJSON() ([]byte, error)
- func (d Duration) MarshalYAML() (interface{}, error)
- func (d *Duration) UnmarshalJSON(b []byte) error
- func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error
- type EmbeddedAuthProvider
- func (p *EmbeddedAuthProvider) Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
- func (p *EmbeddedAuthProvider) ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
- func (p *EmbeddedAuthProvider) RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
- func (p *EmbeddedAuthProvider) RevokeSession(ctx context.Context, sessionToken string) error
- func (p *EmbeddedAuthProvider) RevokeSessions(ctx context.Context, identityID uuid.UUID) error
- func (p *EmbeddedAuthProvider) ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
- type EmbeddedAuthProviderOption
- type EmbeddedIdentityProvider
- func (p *EmbeddedIdentityProvider) CreateIdentity(ctx context.Context, identity *Identity) error
- func (p *EmbeddedIdentityProvider) DeleteIdentity(ctx context.Context, id uuid.UUID) error
- func (p *EmbeddedIdentityProvider) GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
- func (p *EmbeddedIdentityProvider) GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
- func (p *EmbeddedIdentityProvider) ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
- func (p *EmbeddedIdentityProvider) UpdateIdentity(ctx context.Context, identity *Identity) error
- type EmbeddedOAuthClientStore
- func (s *EmbeddedOAuthClientStore) CreateClient(ctx context.Context, client *OAuthClient) error
- func (s *EmbeddedOAuthClientStore) DeleteClient(ctx context.Context, clientID string) error
- func (s *EmbeddedOAuthClientStore) GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
- func (s *EmbeddedOAuthClientStore) ListClients(ctx context.Context) ([]*OAuthClient, error)
- func (s *EmbeddedOAuthClientStore) UpdateClient(ctx context.Context, client *OAuthClient) error
- type EmbeddedOAuthProvider
- func (p *EmbeddedOAuthProvider) AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
- func (p *EmbeddedOAuthProvider) AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
- func (p *EmbeddedOAuthProvider) Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
- func (p *EmbeddedOAuthProvider) GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
- func (p *EmbeddedOAuthProvider) GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
- func (p *EmbeddedOAuthProvider) Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
- func (p *EmbeddedOAuthProvider) RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
- func (p *EmbeddedOAuthProvider) RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
- func (p *EmbeddedOAuthProvider) Revoke(ctx context.Context, token string, tokenTypeHint string) error
- func (p *EmbeddedOAuthProvider) Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
- func (p *EmbeddedOAuthProvider) UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
- type EntConsentStore
- func (s *EntConsentStore) HasConsent(ctx context.Context, principalID, clientID string, scopes []string) (bool, error)
- func (s *EntConsentStore) RevokeConsent(ctx context.Context, principalID, clientID string) error
- func (s *EntConsentStore) SaveConsent(ctx context.Context, principalID, clientID string, scopes []string) error
- type EntLoginSessionStore
- func (s *EntLoginSessionStore) Create(ctx context.Context, token string, session LoginSession) error
- func (s *EntLoginSessionStore) Delete(ctx context.Context, token string) error
- func (s *EntLoginSessionStore) DeleteExpired(ctx context.Context) (int, error)
- func (s *EntLoginSessionStore) Get(ctx context.Context, token string) (LoginSession, error)
- type EntLoginStateStore
- type EntOrgsSource
- type EntPrincipalDirectory
- func (d *EntPrincipalDirectory) CreateFromExternal(ctx context.Context, login ExternalLogin) (*HumanPrincipal, error)
- func (d *EntPrincipalDirectory) EnsurePersonalOrg(ctx context.Context, p *HumanPrincipal, login ExternalLogin) error
- func (d *EntPrincipalDirectory) FindByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
- func (d *EntPrincipalDirectory) FindByVerifiedEmail(ctx context.Context, email string) (*HumanPrincipal, error)
- func (d *EntPrincipalDirectory) GetPrincipal(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
- func (d *EntPrincipalDirectory) LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, login ExternalLogin) error
- func (d *EntPrincipalDirectory) RecordLogin(ctx context.Context, principalID uuid.UUID, login ExternalLogin, at time.Time) error
- type EntPrincipalDirectoryOption
- type EntStorage
- func (s *EntStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
- func (s *EntStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
- func (s *EntStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
- func (s *EntStorage) CreateClient(ctx context.Context, client *Client) error
- func (s *EntStorage) CreateHuman(ctx context.Context, h *HumanPrincipal) error
- func (s *EntStorage) CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) error
- func (s *EntStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
- func (s *EntStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, ...) error
- func (s *EntStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
- func (s *EntStorage) DeleteClient(ctx context.Context, id string) error
- func (s *EntStorage) DeleteHuman(ctx context.Context, id uuid.UUID) error
- func (s *EntStorage) DeleteOpenIDConnectSession(ctx context.Context, authorizeCode string) error
- func (s *EntStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
- func (s *EntStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
- func (s *EntStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetClient(ctx context.Context, clientID string) (fosite.Client, error)
- func (s *EntStorage) GetClientByID(ctx context.Context, id string) (*Client, error)
- func (s *EntStorage) GetHuman(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
- func (s *EntStorage) GetHumanByEmail(ctx context.Context, email string) (*HumanPrincipal, error)
- func (s *EntStorage) GetHumanByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
- func (s *EntStorage) GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error)
- func (s *EntStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *EntStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
- func (s *EntStorage) LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, provider, subject string) error
- func (s *EntStorage) ListClients(ctx context.Context) ([]*Client, error)
- func (s *EntStorage) PrincipalActive(ctx context.Context, subject string) (bool, error)
- func (s *EntStorage) RevokeAccessToken(ctx context.Context, requestID string) error
- func (s *EntStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
- func (s *EntStorage) RevokeSubjectTokens(ctx context.Context, subject string) error
- func (s *EntStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
- func (s *EntStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
- func (s *EntStorage) UpdateClient(ctx context.Context, client *Client) error
- func (s *EntStorage) UpdateHuman(ctx context.Context, h *HumanPrincipal) error
- type EntStorageOption
- type EntStoreOption
- type ExternalLogin
- type FeatureConfig
- type FederationAuthenticator
- type FederationClient
- func (c *FederationClient) Config() *FederationConfig
- func (c *FederationClient) Discovery() *SystemAuthDiscovery
- func (c *FederationClient) ExchangeCode(ctx context.Context, code, redirectURI string) (*SSOTokenResponse, error)
- func (c *FederationClient) GetGlobalIdentity(ctx context.Context, globalID uuid.UUID) (*GlobalIdentity, error)
- func (c *FederationClient) GetIdentityMapping(ctx context.Context, globalID uuid.UUID) (*IdentityMapping, error)
- func (c *FederationClient) GetSSOAuthorizationURL(ctx context.Context, state, redirectURI string) (string, error)
- func (c *FederationClient) Initialize(ctx context.Context) error
- func (c *FederationClient) NotifyAppAccess(ctx context.Context, sessionID uuid.UUID) error
- func (c *FederationClient) RegisterWithSystemAuth(ctx context.Context, federationID uuid.UUID, displayName, baseURL string, ...) error
- func (c *FederationClient) ValidateSSOSession(ctx context.Context, sessionID uuid.UUID) (*SSOSession, error)
- type FederationConfig
- type FederationEndpoints
- type FederationHealthResponse
- type FederationOption
- type GlobalIdentity
- type HumanPrincipal
- type Identity
- type IdentityCredential
- type IdentityFilter
- type IdentityMapping
- type IdentityProvider
- type IdentityState
- type IdentitySyncHandler
- type IdentitySyncRequest
- type IdentitySyncResponse
- type IdentityTraits
- type IntrospectInput
- type IntrospectOutput
- type IntrospectResponse
- type JWKSInput
- type JWKSOutput
- type KeyConfig
- type LoginSession
- type LoginSessionStore
- type ManagedPrincipalsConfig
- type MembershipsInput
- type MembershipsOutput
- type MembershipsResponse
- type MemoryConsentStore
- func (s *MemoryConsentStore) HasConsent(_ context.Context, principalID, clientID string, scopes []string) (bool, error)
- func (s *MemoryConsentStore) RevokeConsent(_ context.Context, principalID, clientID string) error
- func (s *MemoryConsentStore) SaveConsent(_ context.Context, principalID, clientID string, scopes []string) error
- type MemoryLoginSessionStore
- type MemoryPrincipalDirectory
- func (d *MemoryPrincipalDirectory) AddPrincipal(p HumanPrincipal) error
- func (d *MemoryPrincipalDirectory) CreateFromExternal(_ context.Context, login ExternalLogin) (*HumanPrincipal, error)
- func (d *MemoryPrincipalDirectory) FindByExternalIdentity(_ context.Context, provider, subject string) (*HumanPrincipal, error)
- func (d *MemoryPrincipalDirectory) FindByVerifiedEmail(_ context.Context, email string) (*HumanPrincipal, error)
- func (d *MemoryPrincipalDirectory) GetPrincipal(_ context.Context, id uuid.UUID) (*HumanPrincipal, error)
- func (d *MemoryPrincipalDirectory) LastLogin(id uuid.UUID) (time.Time, bool)
- func (d *MemoryPrincipalDirectory) LinkExternalIdentity(_ context.Context, principalID uuid.UUID, login ExternalLogin) error
- func (d *MemoryPrincipalDirectory) RecordLogin(_ context.Context, principalID uuid.UUID, _ ExternalLogin, at time.Time) error
- type MemoryStorage
- func (s *MemoryStorage) CleanupExpired(ctx context.Context) error
- func (s *MemoryStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error
- func (s *MemoryStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error
- func (s *MemoryStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error
- func (s *MemoryStorage) CreateClient(ctx context.Context, client *Client) error
- func (s *MemoryStorage) CreateHuman(_ context.Context, h *HumanPrincipal) error
- func (s *MemoryStorage) CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) error
- func (s *MemoryStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
- func (s *MemoryStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, ...) error
- func (s *MemoryStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) DeleteClient(ctx context.Context, id string) error
- func (s *MemoryStorage) DeleteHuman(_ context.Context, id uuid.UUID) error
- func (s *MemoryStorage) DeleteOpenIDConnectSession(ctx context.Context, authorizeCode string) error
- func (s *MemoryStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
- func (s *MemoryStorage) GetAccessTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetAuthorizeCodeSession(ctx context.Context, code string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetClient(ctx context.Context, id string) (fosite.Client, error)
- func (s *MemoryStorage) GetClientByID(ctx context.Context, id string) (*Client, error)
- func (s *MemoryStorage) GetHuman(_ context.Context, id uuid.UUID) (*HumanPrincipal, error)
- func (s *MemoryStorage) GetHumanByEmail(_ context.Context, email string) (*HumanPrincipal, error)
- func (s *MemoryStorage) GetHumanByExternalIdentity(_ context.Context, provider, subject string) (*HumanPrincipal, error)
- func (s *MemoryStorage) GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error)
- func (s *MemoryStorage) GetPKCERequestSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
- func (s *MemoryStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
- func (s *MemoryStorage) LinkExternalIdentity(_ context.Context, principalID uuid.UUID, provider, subject string) error
- func (s *MemoryStorage) ListClients(ctx context.Context) ([]*Client, error)
- func (s *MemoryStorage) PrincipalActive(_ context.Context, subject string) (bool, error)
- func (s *MemoryStorage) RevokeAccessToken(ctx context.Context, requestID string) error
- func (s *MemoryStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
- func (s *MemoryStorage) RevokeSubjectTokens(ctx context.Context, subject string) error
- func (s *MemoryStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
- func (s *MemoryStorage) SetClientAssertionJWT(ctx context.Context, jti string, exp time.Time) error
- func (s *MemoryStorage) UpdateClient(ctx context.Context, client *Client) error
- func (s *MemoryStorage) UpdateHuman(_ context.Context, h *HumanPrincipal) error
- type OAuthAuthorizeRequest
- type OAuthAuthorizeResponse
- type OAuthClient
- type OAuthClientStore
- type OAuthConsentAccept
- type OAuthConsentReject
- type OAuthConsentRequest
- type OAuthConsentResponse
- type OAuthError
- type OAuthIntrospection
- type OAuthLoginAccept
- type OAuthLoginReject
- type OAuthLoginRequest
- type OAuthLoginResponse
- type OAuthProvider
- type OAuthTokenRequest
- type OAuthTokenResponse
- type OAuthUserInfo
- type OpenIDConfigInput
- type OpenIDConfigOutput
- type OpenIDConfiguration
- type Option
- func WithAccessChanges(lister AccessChangeLister) Option
- func WithConsentStore(store ConsentStore) Option
- func WithCredentialService(svc credential.Service) Option
- func WithLogger(logger *slog.Logger) Option
- func WithLoginSessionStore(store LoginSessionStore) Option
- func WithLoginStateStore(store oauthclient.StateStore) Option
- func WithLoginTokenClientIP(clientIP func(r *http.Request) string) Option
- func WithLoginTokenRateLimit(storage ratelimit.Storage, perAddress, perClient ratelimit.Limit) Option
- func WithObservability(obs *observability.Observability) Option
- func WithOrgsSource(src OrgsSource) Option
- func WithPrincipalDirectory(dir PrincipalDirectory) Option
- func WithReadinessCheck(name string, check func(context.Context) error) Option
- func WithSessionProvider(provider SessionProvider) Option
- func WithSocialAuthzSyncer(syncer authz.RelationshipSyncer, mode authz.SyncMode) Option
- func WithSocialConnector(c *oauthclient.Connector) Option
- func WithStorage(storage Storage) Option
- type OrgClaim
- type OrgsResult
- type OrgsSource
- type PersonalOrgEnsurer
- type PrincipalDirectory
- type PrincipalStatus
- type Providers
- type ProvidersOption
- type RequestGate
- type RevokeInput
- type RevokeOutput
- type SSOSession
- type SSOTokenResponse
- type Server
- func (s *Server) CurrentLoginSession(r *http.Request) (*LoginSession, error)
- func (s *Server) GetClient(id string) (*Client, error)
- func (s *Server) Huma() huma.API
- func (s *Server) KeyID() string
- func (s *Server) Logger() *slog.Logger
- func (s *Server) LoginTokenPolicy(ctx context.Context, clientID string) (credential.LoginTokenPolicy, error)
- func (s *Server) ManagedPrincipalsAllowed(ctx context.Context, clientID string) (bool, error)
- func (s *Server) Middleware() func(http.Handler) http.Handler
- func (s *Server) NewBackchannel(opts ...BackchannelOption) *Backchannel
- func (s *Server) OAuth2Provider() fosite.OAuth2Provider
- func (s *Server) OIDCSession(subject string, claims map[string]interface{}) *Session
- func (s *Server) Observability() *observability.Observability
- func (s *Server) OpenIDConfiguration() OpenIDConfiguration
- func (s *Server) OrgsClaim(ctx context.Context, principalID uuid.UUID, compact bool) (OrgsResult, error)
- func (s *Server) PublicKey() *rsa.PublicKey
- func (s *Server) Ready(ctx context.Context) error
- func (s *Server) RegisterClient(client *Client) error
- func (s *Server) RequireScopes(scopes ...string) func(http.Handler) http.Handler
- func (s *Server) Router() chi.Router
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Session(subject string) *Session
- func (s *Server) SessionProvider() SessionProvider
- func (s *Server) Storage() Storage
- func (s *Server) TokenAuthenticator(scope string) FederationAuthenticator
- type Session
- type SessionProvider
- type SocialLoginConfig
- type SocialProviderConfig
- type Storage
- type StoredRequest
- type StoredSession
- type SubjectTokenRevoker
- type SystemAuthDiscovery
- type TokenConfig
- type TokenData
- type TokenInput
- type TokenOutput
- type TokenResponse
- type UserInfoInput
- type UserInfoOutput
Constants ¶
const ( // EventBackchannelLogout is the OpenID Connect Back-Channel Logout 1.0 // event: the relying party ends the sessions of the token's sub (or // sid). EventBackchannelLogout = "http://schemas.openid.net/event/backchannel-logout" // EventAccessChange announces a reduction of the sub's access (ADR-010). // Its value holds organization_id (absent for every organization), // changed_at (RFC 3339) and reason. EventAccessChange = "urn:systemforge:event:access_change" )
Event identifiers carried in the "events" claim of a logout token.
const ( // HealthzPath reports liveness: the process is serving HTTP. HealthzPath = "/healthz" // ReadyzPath reports readiness: every registered check (e.g. the // database ping) passes. ReadyzPath = "/readyz" )
Health endpoints for process supervisors and load balancers.
const ( // OrgsClaim is the claim listing the organizations a principal belongs // to, with the principal's role and application roles in each. OrgsClaim = "orgs" // OrgsTruncatedClaim is true when OrgsClaim omits organizations // because the principal belongs to more than MaxOrgsInToken. OrgsTruncatedClaim = "orgs_truncated" // MaxOrgsInToken is the most organizations a token or the userinfo // claim carries. GET /oauth/userinfo/memberships returns them all. MaxOrgsInToken = 50 // MembershipsPath is the paginated memberships endpoint. MembershipsPath = UserInfoPath + "/memberships" // DefaultMembershipsPageSize and MaxMembershipsPageSize bound the // memberships endpoint's page. DefaultMembershipsPageSize = 50 MaxMembershipsPageSize = 100 )
The organization claims of ADR-007.
const AccessChangesPath = "/access-changes"
AccessChangesPath is the path of the replay endpoint (ADR-010 decision 6).
const AccessChangesScope = "access_changes:read"
AccessChangesScope is the scope a client-credentials token needs to read the replay endpoint.
const ConsentPath = "/consent"
ConsentPath is the consent page. /oauth/authorize sends a signed-in user here (with the authorization URL as return_to) when the client has not been granted the requested scopes and social_login.skip_consent is off.
const DefaultStoreCleanupInterval = 5 * time.Minute
DefaultStoreCleanupInterval is how often the Ent-backed social login stores opportunistically delete expired rows while handling writes.
const FederationProvider = "systemauth-federation"
FederationProvider is the ExternalIdentity provider name recorded for identities synced from a federation hub; the federation's identity ID is the subject.
const IDPHintParam = "idp_hint"
IDPHintParam is an optional /oauth/authorize parameter naming the upstream provider (github, google) to sign in with, skipping the chooser.
const IntrospectionScope = "introspect"
IntrospectionScope is the scope an access token must carry to be used as the credential for calling the introspection endpoint.
const ( // LoginCookieName is the SystemAuth login session cookie. The __Host- // prefix makes browsers enforce Secure, Path=/ and no Domain attribute, // so the cookie cannot be set or read by sibling subdomains. LoginCookieName = "__Host-sf_login" )
const ( // LoginPath renders the provider chooser (or redirects when only one // provider is configured). It accepts a return_to query parameter. LoginPath = "/login" )
Social login routes mounted on the SystemAuth router when Config.SocialLogin is set.
const LoginTokenPath = "/login-token"
LoginTokenPath exchanges a managed principal's login token for a SystemAuth login session (ADR-005).
const LogoutPath = "/logout"
LogoutPath ends the SystemAuth login session. GET renders a confirmation form; POST (same-origin or from an allowed relying-party origin) deletes the __Host-sf_login session, revokes the principal's OAuth tokens and redirects to the validated return_to (default: social_login.default_redirect).
const LogoutTokenType = "logout+jwt" //nolint:gosec // G101: a JOSE typ value, not a credential
LogoutTokenType is the JOSE typ header of a logout token.
const ManagedClaim = "managed"
ManagedClaim is the ID token and userinfo claim, true for managed principals: humans with at least one active manager (ADR-009), with or without an email. It is absent for everyone else.
const UserInfoPath = "/oauth/userinfo"
UserInfoPath is the OpenID Connect UserInfo endpoint (OIDC Core §5.3).
Variables ¶
var ( // ErrMissingIssuer is returned when the issuer is not configured. ErrMissingIssuer = errors.New("systemauth: issuer is required") // ErrKeyGenerationFailed is returned when key generation fails. ErrKeyGenerationFailed = errors.New("systemauth: failed to generate signing key") // ErrStorageInitFailed is returned when storage initialization fails. ErrStorageInitFailed = errors.New("systemauth: failed to initialize storage") // ErrInvalidSocialLoginConfig is returned when social login is misconfigured. ErrInvalidSocialLoginConfig = errors.New("systemauth: invalid social login configuration") // ErrInvalidConfig is returned when a configuration value is invalid. ErrInvalidConfig = errors.New("systemauth: invalid configuration") )
Configuration errors.
var ( // ErrClientNotFound is returned when a client is not found. ErrClientNotFound = errors.New("systemauth: client not found") // ErrClientExists is returned when trying to create a client that already exists. ErrClientExists = errors.New("systemauth: client already exists") // ErrInvalidClientType is returned when the client type is invalid. ErrInvalidClientType = errors.New("systemauth: invalid client type") )
Client errors.
var ( // ErrTokenNotFound is returned when a token is not found. ErrTokenNotFound = errors.New("systemauth: token not found") // ErrTokenExpired is returned when a token has expired. ErrTokenExpired = errors.New("systemauth: token expired") // ErrTokenRevoked is returned when a token has been revoked. ErrTokenRevoked = errors.New("systemauth: token revoked") // ErrInvalidToken is returned when a token is invalid. ErrInvalidToken = errors.New("systemauth: invalid token") )
Token errors.
var ( // ErrAuthCodeNotFound is returned when an authorization code is not found. ErrAuthCodeNotFound = errors.New("systemauth: authorization code not found") // ErrAuthCodeExpired is returned when an authorization code has expired. ErrAuthCodeExpired = errors.New("systemauth: authorization code expired") // ErrAuthCodeUsed is returned when an authorization code has already been used. ErrAuthCodeUsed = errors.New("systemauth: authorization code already used") // ErrPKCEVerificationFailed is returned when PKCE verification fails. ErrPKCEVerificationFailed = errors.New("systemauth: PKCE verification failed") )
Authorization errors.
var ( // ErrFederationNotConfigured is returned when federation is not configured. ErrFederationNotConfigured = errors.New("systemauth: federation not configured") // ErrFederationConnectionFailed is returned when connection to SystemAuth fails. ErrFederationConnectionFailed = errors.New("systemauth: failed to connect to SystemAuth") // ErrInvalidGlobalToken is returned when a global identity token is invalid. ErrInvalidGlobalToken = errors.New("systemauth: invalid global identity token") )
Federation errors.
var ( // ErrPrincipalExists is returned when creating a human principal whose ID // or email is already taken. ErrPrincipalExists = errors.New("systemauth: principal already exists") // ErrEmailRequired is returned when creating or updating a human // without an email. Only managed principals may omit one (ADR-005). ErrEmailRequired = errors.New("systemauth: email is required") )
Human principal errors.
var ( // ErrPrincipalNotFound is returned when no principal matches a lookup. ErrPrincipalNotFound = errors.New("systemauth: principal not found") // ErrPrincipalInactive is returned when the resolved principal is deactivated. ErrPrincipalInactive = errors.New("systemauth: principal is inactive") // ErrEmailNotVerified is returned when an upstream login carries no // verified email and cannot be matched by its provider identity. ErrEmailNotVerified = errors.New("systemauth: upstream email is not verified") // ErrEmailConflict is returned when the upstream email belongs to an // account that cannot be safely linked automatically. ErrEmailConflict = errors.New("systemauth: email already belongs to an account that cannot be linked") // ErrRedirectNotAllowed is returned when a post-login redirect target is // not on the allowlist. ErrRedirectNotAllowed = errors.New("systemauth: redirect target not allowed") // ErrLoginSessionNotFound is returned when a login session is unknown or expired. ErrLoginSessionNotFound = errors.New("systemauth: login session not found") )
Social login errors.
var ( DefaultLoginTokenAddressLimit = ratelimit.PerMinute(60) DefaultLoginTokenClientLimit = ratelimit.PerMinute(600) )
Default login token exchange rate limits. A classroom signs in at once from one address, so the per-address limit allows a class-sized burst; the per-client limit bounds every address together.
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrSessionNotFound = errors.New("session not found") ErrSessionExpired = errors.New("session expired") ErrSessionRevoked = errors.New("session revoked") )
Common authentication errors.
var ErrExternalIdentityExists = errors.New("systemauth: external identity already linked")
ErrExternalIdentityExists is returned by PrincipalDirectory implementations when the (provider, subject) pair is already linked to a principal. The resolver treats it as a lost race and re-reads the existing link.
ErrFederationUnauthorized is returned by authenticators for a request that does not prove it comes from the federation hub.
var ErrInvalidBackchannelURI = errors.New("systemauth: invalid backchannel_logout_uri")
ErrInvalidBackchannelURI is returned for a back-channel logout URI that is not an acceptable delivery target.
var ErrInvalidCursor = errors.New("systemauth: invalid memberships cursor")
ErrInvalidCursor means a memberships cursor does not name a membership of the principal.
var ErrInvalidSigningKey = errors.New("systemauth: invalid signing key")
ErrInvalidSigningKey is returned when a configured signing key cannot be loaded.
Functions ¶
func AccessRequestFromContext ¶
func AccessRequestFromContext(ctx context.Context) fosite.AccessRequester
AccessRequestFromContext retrieves the access request from context.
func AuthorizeIntrospectionCaller ¶ added in v0.14.0
func AuthorizeIntrospectionCaller(r *http.Request, clientPublic func(clientID string) (known, public bool), bearerScopes func(token string) []string) bool
AuthorizeIntrospectionCaller reports whether the caller of a token introspection request (RFC 7662 section 2.1) may introspect tokens. Fosite accepts any valid access token, or any client's Basic credentials, public clients included, so a token or a public client_id obtained anywhere would let its holder test other parties' tokens and read their subject, scopes, client, and audience. A caller must be:
- a confidential client, authenticating with HTTP Basic or a client assertion (Fosite verifies the secret or signature afterwards), or
- the bearer of an access token carrying IntrospectionScope.
clientPublic reports whether a client ID is registered and public. bearerScopes returns the scopes of an active access token, or nil.
func ContextWithOwnerID ¶
ContextWithOwnerID adds an owner ID to the context.
func KeyThumbprint ¶ added in v0.12.0
func KeyThumbprint(key *rsa.PrivateKey) (string, error)
KeyThumbprint returns the RFC 7638 SHA-256 thumbprint of the key's public part, base64url-encoded. SystemAuth uses it as the default key ID, so a new key automatically gets a new "kid".
func LoggerFromContext ¶
LoggerFromContext returns the logger from context, or slog.Default() if not set.
func ParseSigningKey ¶ added in v0.12.0
func ParseSigningKey(pemData []byte) (*rsa.PrivateKey, error)
ParseSigningKey parses a PEM-encoded RSA private key (PKCS#1 "RSA PRIVATE KEY" or PKCS#8 "PRIVATE KEY") of at least 2048 bits.
func SaveConfig ¶
SaveConfig saves configuration to a file. The format is determined by the file extension.
func TrustAllRequests ¶ added in v0.14.0
TrustAllRequests is a RequestGate that admits every request. Use it only when the server cannot be reached except through a proxy that removes the identity header from client requests and sets it itself; otherwise any client can sign in as anyone by sending the header.
func UserInfoClaims ¶ added in v0.12.0
UserInfoClaims filters claims to those releasable under granted: "sub" is always subject; a standard claim is kept only when its scope was granted; other (non-standard) claims returned by the SessionProvider are passed through, since the provider already chose them by scope.
func ValidateBackchannelLogoutURI ¶ added in v0.14.0
ValidateBackchannelLogoutURI checks a client's back-channel endpoint. The empty string is valid and means none. SystemAuth POSTs to this address, so it must be an absolute https URL without credentials or a fragment; http is accepted only for loopback hosts, for development.
func WithAccessRequest ¶
WithAccessRequest adds the access request to the context.
Types ¶
type AccessChangeLister ¶ added in v0.14.0
type AccessChangeLister interface {
List(ctx context.Context, since time.Time, limit int) ([]accesschange.Change, error)
}
AccessChangeLister lists recorded access changes. *accesschange.Source implements it.
type AccessChangeResponse ¶ added in v0.14.0
type AccessChangeResponse struct {
PrincipalID string `json:"principal_id"`
OrganizationID string `json:"organization_id,omitempty"`
ChangedAt time.Time `json:"changed_at"`
Reason string `json:"reason"`
}
AccessChangeResponse is one change in the replay response.
type AccessChangesResponse ¶ added in v0.14.0
type AccessChangesResponse struct {
Changes []AccessChangeResponse `json:"changes"`
NextSince *time.Time `json:"next_since,omitempty"`
}
AccessChangesResponse is the replay response. NextSince is set when more changes follow; pass it as since to read them.
type AppRoleResolver ¶ added in v0.14.0
type AppRoleResolver interface {
EffectiveRoles(ctx context.Context, principalID, organizationID uuid.UUID) (map[string]string, error)
}
AppRoleResolver reports a principal's application roles in an organization. identity/approle.Service implements it.
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 AuthMethod ¶
type AuthMethod string
AuthMethod is the authentication method.
const ( AuthMethodPassword AuthMethod = "password" AuthMethodOIDC AuthMethod = "oidc" AuthMethodWebAuthn AuthMethod = "webauthn" AuthMethodTOTP AuthMethod = "totp" )
type AuthSession ¶
type AuthSession struct {
// ID is the session ID.
ID string `json:"id"`
// Token is the session token (cookie value).
Token string `json:"token"`
// IdentityID is the authenticated identity.
IdentityID uuid.UUID `json:"identity_id"`
// Identity contains identity details (optional, may be nil).
Identity *Identity `json:"identity,omitempty"`
// AuthenticatedAt is when authentication occurred.
AuthenticatedAt time.Time `json:"authenticated_at"`
// ExpiresAt is when the session expires.
ExpiresAt time.Time `json:"expires_at"`
// AuthenticationMethods used in this session.
AuthenticationMethods []AuthMethod `json:"authentication_methods,omitempty"`
// Active indicates if the session is still valid.
Active bool `json:"active"`
// DeviceInfo about the session.
DeviceInfo *DeviceInfo `json:"device_info,omitempty"`
}
AuthSession represents an authentication session.
type AuthenticateRequest ¶
type AuthenticateRequest struct {
// Method is the authentication method.
Method AuthMethod `json:"method"`
// Identifier is the user identifier (email, username, etc.).
Identifier string `json:"identifier"`
// Password is used for password authentication.
Password string `json:"password,omitempty"`
// OIDCToken is used for OIDC authentication.
OIDCToken string `json:"oidc_token,omitempty"`
// OIDCProvider is the OIDC provider name.
OIDCProvider string `json:"oidc_provider,omitempty"`
// DeviceInfo contains device/client information.
DeviceInfo *DeviceInfo `json:"device_info,omitempty"`
}
AuthenticateRequest contains authentication credentials.
type AuthenticationProvider ¶
type AuthenticationProvider interface {
// Authenticate validates credentials and creates a session.
Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
// ValidateSession validates a session token and returns session info.
ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
// RefreshSession extends a session's lifetime.
RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
// RevokeSession invalidates a session.
RevokeSession(ctx context.Context, sessionToken string) error
// RevokeSessions invalidates all sessions for an identity.
RevokeSessions(ctx context.Context, identityID uuid.UUID) error
// ListSessions lists active sessions for an identity.
ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
}
AuthenticationProvider manages user authentication sessions. In Ory Kratos, this maps to the session management API.
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 Backchannel ¶ added in v0.14.0
type Backchannel struct {
// contains filtered or unexported fields
}
Backchannel delivers access changes, and the logouts they imply, to the clients that registered a backchannel_logout_uri (ADR-010 decision 4, separate deployments). It is an accesschange.Sink: pass it to the WithAccessChangeSink option of the services that record changes, and run it with Run.
Each change becomes one OpenID Connect Back-Channel Logout token per client, signed with the issuer key, typ logout+jwt, with sub, jti, iat and exp, aud set to the client ID and an "events" claim. The access_change event is always present; the back-channel logout event is added when the change ends the principal's sessions (deactivation, session revocation). It is POSTed as logout_token=<jwt>. A delivery that fails is retried with exponential backoff until one maximum access-token lifetime after the change, since after that no token issued before it can still be valid, and each failure is logged against the client ID. A response of 4xx other than 408 and 429 is permanent and not retried.
Every registered client receives every change: the token carries only opaque principal and organization identifiers, but an operator who does not want a client to see other tenants' changes should not register an endpoint for it.
func (*Backchannel) AccessChange ¶ added in v0.14.0
func (b *Backchannel) AccessChange(c accesschange.Change)
AccessChange implements accesschange.Sink. It queues the change without blocking; a full queue drops it with a log line, which leaves the token lifetime as the bound for the affected clients.
type BackchannelOption ¶ added in v0.14.0
type BackchannelOption func(*Backchannel)
BackchannelOption configures a Backchannel.
func WithBackchannelBackoff ¶ added in v0.14.0
func WithBackchannelBackoff(base, maxWait time.Duration) BackchannelOption
WithBackchannelBackoff sets the first and the longest wait between attempts (1 second and 5 minutes by default).
func WithBackchannelClock ¶ added in v0.14.0
func WithBackchannelClock(now func() time.Time) BackchannelOption
WithBackchannelClock sets the clock that stamps tokens and bounds retries. For tests.
func WithBackchannelHTTPClient ¶ added in v0.14.0
func WithBackchannelHTTPClient(c *http.Client) BackchannelOption
WithBackchannelHTTPClient sets the HTTP client used for delivery. Its redirect policy is replaced so that a redirect is never followed.
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"`
// RotatedSecretHashes are the bcrypt hashes of other secrets that are
// still active, accepted during a secret rotation.
RotatedSecretHashes []string `json:"-"`
// 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"`
// ManagedPrincipalsEnabled allows this client to create and sign in
// managed principals. It takes effect only when the deployment also
// enables managed principals (see Server.ManagedPrincipalsAllowed).
ManagedPrincipalsEnabled bool `json:"managed_principals_enabled,omitempty"`
// LoginTokenTTL overrides the deployment's default lifetime of reusable
// login tokens for this client's managed principals; nil uses it.
LoginTokenTTL *time.Duration `json:"login_token_ttl,omitempty"`
// BackchannelLogoutURI is the client's endpoint for OIDC Back-Channel
// Logout tokens, which also carry access-change events (ADR-010). It
// must be an https URL (http is allowed for loopback hosts); empty means
// the client receives none.
BackchannelLogoutURI string `json:"backchannel_logout_uri,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 ¶
GetAudience returns the allowed audiences.
func (*Client) GetGrantTypes ¶
GetGrantTypes returns the allowed grant types.
func (*Client) GetHashedSecret ¶
GetHashedSecret returns the hashed client secret.
func (*Client) GetRedirectURIs ¶
GetRedirectURIs returns the allowed redirect URIs.
func (*Client) GetResponseTypes ¶
GetResponseTypes returns the allowed response types.
func (*Client) GetRotatedHashes ¶ added in v0.14.0
GetRotatedHashes returns the hashes of the other active secrets (fosite.ClientWithSecretRotation), accepted alongside SecretHash.
func (*Client) ValidateSecret ¶
ValidateSecret checks if the provided secret matches the stored hash or, during a rotation, one of the other active secrets.
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 `` /* 155-byte string literal not displayed */
// RefreshTokenLifetime overrides the default for this client.
RefreshTokenLifetime *Duration `` /* 143-byte string literal not displayed */
// ManagedPrincipals allows this client to create and sign in managed
// principals (humans without an email, ADR-005). It takes effect only
// when the deployment's managed_principals.enabled is also set.
ManagedPrincipals bool `` /* 155-byte string literal not displayed */
// BackchannelLogoutURI is where SystemAuth sends this client OIDC
// Back-Channel Logout tokens, which also carry access-change events
// (ADR-010). An https URL; http only for loopback hosts.
BackchannelLogoutURI string `` /* 162-byte string literal not displayed */
// LoginTokenTTL overrides the deployment's default lifetime of reusable
// login tokens issued for this client's managed principals, for example
// a school year. It never exceeds managed_principals.login_token_max_ttl.
LoginTokenTTL *Duration `` /* 161-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 SystemAuth integration.
Federation *FederationConfig `json:"federation,omitempty" yaml:"federation,omitempty" jsonschema:"description=SystemAuth federation configuration"`
// Features enables/disables optional features.
Features FeatureConfig `json:"features,omitempty" yaml:"features,omitempty" jsonschema:"description=Feature flags"`
// SocialLogin enables "log in with GitHub/Google" on this server.
// If nil, no social login routes are mounted.
SocialLogin *SocialLoginConfig `` /* 134-byte string literal not displayed */
// Authz selects the authorization mode (ADR-008): "rbac" (the default)
// or "rebac" with an engine. SystemAuth does not build the provider
// from it: the application passes it to authz/mode.New, so the
// configuration file stays one document.
Authz authz.ModeConfig `json:"authz,omitempty" yaml:"authz,omitempty" jsonschema:"description=Authorization mode and relationship engine"`
// ManagedPrincipals configures managed principals; nil disables them.
ManagedPrincipals *ManagedPrincipalsConfig `` /* 154-byte string literal not displayed */
}
Config holds SystemAuth server configuration. This is the root configuration object for both embedded and standalone modes.
func DecodeConfig ¶ added in v0.13.0
func DecodeConfig(data []byte, format ConfigFormat) (*Config, error)
DecodeConfig decodes configuration from bytes in the specified format and expands environment variables in it, without applying defaults or validating. Callers that adjust the configuration afterwards (e.g. to supply a missing issuer) then call ApplyDefaults and Validate.
func DecodeConfigFile ¶ added in v0.13.0
DecodeConfigFile reads and decodes the configuration file at path like LoadConfig, expanding environment variables, but without applying defaults or validating, so a caller can adjust the result first (then call ApplyDefaults and Validate).
func DefaultConfig ¶
DefaultConfig returns a Config with sensible defaults for embedded mode.
func LoadConfig ¶
LoadConfig loads configuration from a file, applies defaults and validates it. 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, expands environment variables, applies defaults and validates it.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults fills in missing values with defaults.
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 ConsentSession ¶
type ConsentSession struct {
AccessToken map[string]any `json:"access_token,omitempty"`
IDToken map[string]any `json:"id_token,omitempty"`
}
ConsentSession holds session data for consent.
type ConsentStore ¶ added in v0.12.0
type ConsentStore interface {
// HasConsent reports whether principalID has granted clientID every
// scope in scopes.
HasConsent(ctx context.Context, principalID, clientID string, scopes []string) (bool, error)
// SaveConsent records that principalID granted clientID scopes, adding
// to any scopes granted before.
SaveConsent(ctx context.Context, principalID, clientID string, scopes []string) error
// RevokeConsent removes every scope principalID granted clientID.
RevokeConsent(ctx context.Context, principalID, clientID string) error
}
ConsentStore records which scopes a principal has granted to a client. SystemAuth consults it on /oauth/authorize when social login is enabled and skip_consent is off.
type CredentialType ¶
type CredentialType string
CredentialType is the type of credential.
const ( CredentialTypePassword CredentialType = "password" CredentialTypeOIDC CredentialType = "oidc" CredentialTypeWebAuthn CredentialType = "webauthn" CredentialTypeTOTP CredentialType = "totp" )
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 ¶
func (h *DefaultIdentitySyncHandler) SyncIdentity(ctx context.Context, req *IdentitySyncRequest) (*IdentitySyncResponse, error)
SyncIdentity implements IdentitySyncHandler.
type DefaultSessionProvider ¶
type DefaultSessionProvider struct {
// contains filtered or unexported fields
}
DefaultSessionProvider is a minimal session provider. It authenticates nobody unless configured with WithTrustedUserIDHeader, so by default every authorization request is sent to the login URL. For a real deployment configure social login, supply your own SessionProvider, or trust a header written by your gateway.
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 trusted header when one is configured and the request passes the gate, and "" otherwise.
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 ¶
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 the return URL as a query-escaped redirect parameter.
func (*DefaultSessionProvider) SaveConsent ¶
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 WithTrustedUserIDHeader ¶ added in v0.14.0
func WithTrustedUserIDHeader(header string, gate RequestGate) DefaultSessionProviderOption
WithTrustedUserIDHeader makes the provider authenticate requests as the user named in header, for a gateway that authenticates users and forwards the result (a backend-for-frontend). Only requests the gate admits are believed: pass TrustedProxyNetworks for the gateway's addresses, or TrustAllRequests when the server is reachable only through a gateway that overwrites the header. A nil gate or an empty header trusts nothing.
type DeviceInfo ¶
type DeviceInfo struct {
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
DeviceID string `json:"device_id,omitempty"`
}
DeviceInfo contains information about the authenticating device.
type Duration ¶
Duration is a wrapper around time.Duration that supports human-readable string serialization (e.g., "15m", "1h", "7d").
func (Duration) JSONSchema ¶
func (Duration) JSONSchema() *jsonschema.Schema
JSONSchema implements jsonschema.JSONSchemaer for Duration.
func (Duration) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (Duration) MarshalYAML ¶
MarshalYAML implements yaml.Marshaler.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Duration) UnmarshalYAML ¶
UnmarshalYAML implements yaml.Unmarshaler.
type EmbeddedAuthProvider ¶
type EmbeddedAuthProvider struct {
// contains filtered or unexported fields
}
EmbeddedAuthProvider implements AuthenticationProvider with in-memory session storage. For production, use a persistent session store (Redis, database, etc.).
func NewEmbeddedAuthProvider ¶
func NewEmbeddedAuthProvider(identityProvider IdentityProvider, opts ...EmbeddedAuthProviderOption) *EmbeddedAuthProvider
NewEmbeddedAuthProvider creates an AuthenticationProvider with in-memory sessions.
func (*EmbeddedAuthProvider) Authenticate ¶
func (p *EmbeddedAuthProvider) Authenticate(ctx context.Context, req *AuthenticateRequest) (*AuthSession, error)
Authenticate implements AuthenticationProvider.
func (*EmbeddedAuthProvider) ListSessions ¶
func (p *EmbeddedAuthProvider) ListSessions(ctx context.Context, identityID uuid.UUID) ([]*AuthSession, error)
ListSessions implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RefreshSession ¶
func (p *EmbeddedAuthProvider) RefreshSession(ctx context.Context, sessionToken string) (*AuthSession, error)
RefreshSession implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RevokeSession ¶
func (p *EmbeddedAuthProvider) RevokeSession(ctx context.Context, sessionToken string) error
RevokeSession implements AuthenticationProvider.
func (*EmbeddedAuthProvider) RevokeSessions ¶
RevokeSessions implements AuthenticationProvider.
func (*EmbeddedAuthProvider) ValidateSession ¶
func (p *EmbeddedAuthProvider) ValidateSession(ctx context.Context, sessionToken string) (*AuthSession, error)
ValidateSession implements AuthenticationProvider.
type EmbeddedAuthProviderOption ¶
type EmbeddedAuthProviderOption func(*EmbeddedAuthProvider)
EmbeddedAuthProviderOption configures an EmbeddedAuthProvider.
func WithPasswordVerifier ¶
func WithPasswordVerifier(verifier func(ctx context.Context, identityID uuid.UUID, password string) (bool, error)) EmbeddedAuthProviderOption
WithPasswordVerifier sets the password verification function.
func WithSessionDuration ¶
func WithSessionDuration(d time.Duration) EmbeddedAuthProviderOption
WithSessionDuration sets the session duration.
type EmbeddedIdentityProvider ¶
type EmbeddedIdentityProvider struct {
// contains filtered or unexported fields
}
EmbeddedIdentityProvider implements IdentityProvider using the embedded storage.
func NewEmbeddedIdentityProvider ¶
func NewEmbeddedIdentityProvider(storage Storage) *EmbeddedIdentityProvider
NewEmbeddedIdentityProvider creates an IdentityProvider backed by SystemAuth storage.
func (*EmbeddedIdentityProvider) CreateIdentity ¶
func (p *EmbeddedIdentityProvider) CreateIdentity(ctx context.Context, identity *Identity) error
CreateIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) DeleteIdentity ¶
DeleteIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) GetIdentity ¶
func (p *EmbeddedIdentityProvider) GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
GetIdentity implements IdentityProvider.
func (*EmbeddedIdentityProvider) GetIdentityByEmail ¶
func (p *EmbeddedIdentityProvider) GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
GetIdentityByEmail implements IdentityProvider.
func (*EmbeddedIdentityProvider) ListIdentities ¶
func (p *EmbeddedIdentityProvider) ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
ListIdentities implements IdentityProvider. Note: The embedded storage doesn't support listing, so this returns an error.
func (*EmbeddedIdentityProvider) UpdateIdentity ¶
func (p *EmbeddedIdentityProvider) UpdateIdentity(ctx context.Context, identity *Identity) error
UpdateIdentity implements IdentityProvider.
type EmbeddedOAuthClientStore ¶
type EmbeddedOAuthClientStore struct {
// contains filtered or unexported fields
}
EmbeddedOAuthClientStore implements OAuthClientStore using SystemAuth storage.
func NewEmbeddedOAuthClientStore ¶
func NewEmbeddedOAuthClientStore(storage Storage) *EmbeddedOAuthClientStore
NewEmbeddedOAuthClientStore creates an OAuthClientStore backed by SystemAuth storage.
func (*EmbeddedOAuthClientStore) CreateClient ¶
func (s *EmbeddedOAuthClientStore) CreateClient(ctx context.Context, client *OAuthClient) error
CreateClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) DeleteClient ¶
func (s *EmbeddedOAuthClientStore) DeleteClient(ctx context.Context, clientID string) error
DeleteClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) GetClient ¶
func (s *EmbeddedOAuthClientStore) GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
GetClient implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) ListClients ¶
func (s *EmbeddedOAuthClientStore) ListClients(ctx context.Context) ([]*OAuthClient, error)
ListClients implements OAuthClientStore.
func (*EmbeddedOAuthClientStore) UpdateClient ¶
func (s *EmbeddedOAuthClientStore) UpdateClient(ctx context.Context, client *OAuthClient) error
UpdateClient implements OAuthClientStore.
type EmbeddedOAuthProvider ¶
type EmbeddedOAuthProvider struct {
// contains filtered or unexported fields
}
EmbeddedOAuthProvider implements OAuthProvider using Fosite.
func NewEmbeddedOAuthProvider ¶
func NewEmbeddedOAuthProvider(server *Server) *EmbeddedOAuthProvider
NewEmbeddedOAuthProvider creates an OAuthProvider backed by a SystemAuth Server.
func (*EmbeddedOAuthProvider) AcceptConsent ¶
func (p *EmbeddedOAuthProvider) AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
AcceptConsent implements OAuthProvider.
func (*EmbeddedOAuthProvider) AcceptLogin ¶
func (p *EmbeddedOAuthProvider) AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
AcceptLogin implements OAuthProvider.
func (*EmbeddedOAuthProvider) Authorize ¶
func (p *EmbeddedOAuthProvider) Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
Authorize implements OAuthProvider. Note: This is typically handled by the HTTP handler; this method is for programmatic access.
func (*EmbeddedOAuthProvider) GetConsentRequest ¶
func (p *EmbeddedOAuthProvider) GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
GetConsentRequest implements OAuthProvider. This is used for the consent flow when separating login/consent UI.
func (*EmbeddedOAuthProvider) GetLoginRequest ¶
func (p *EmbeddedOAuthProvider) GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
GetLoginRequest implements OAuthProvider.
func (*EmbeddedOAuthProvider) Introspect ¶
func (p *EmbeddedOAuthProvider) Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
Introspect implements OAuthProvider.
func (*EmbeddedOAuthProvider) RejectConsent ¶
func (p *EmbeddedOAuthProvider) RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
RejectConsent implements OAuthProvider.
func (*EmbeddedOAuthProvider) RejectLogin ¶
func (p *EmbeddedOAuthProvider) RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
RejectLogin implements OAuthProvider.
func (*EmbeddedOAuthProvider) Revoke ¶
func (p *EmbeddedOAuthProvider) Revoke(ctx context.Context, token string, tokenTypeHint string) error
Revoke implements OAuthProvider.
func (*EmbeddedOAuthProvider) Token ¶
func (p *EmbeddedOAuthProvider) Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
Token implements OAuthProvider. Note: This is typically handled by the HTTP handler; this method is for programmatic access.
func (*EmbeddedOAuthProvider) UserInfo ¶
func (p *EmbeddedOAuthProvider) UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
UserInfo implements OAuthProvider.
type EntConsentStore ¶ added in v0.12.0
type EntConsentStore struct {
// contains filtered or unexported fields
}
EntConsentStore is a ConsentStore backed by the sf_consent_grants table, one row per granted scope.
func NewEntConsentStore ¶ added in v0.12.0
func NewEntConsentStore(client *ent.Client) *EntConsentStore
NewEntConsentStore creates a consent store on client.
func (*EntConsentStore) HasConsent ¶ added in v0.12.0
func (s *EntConsentStore) HasConsent(ctx context.Context, principalID, clientID string, scopes []string) (bool, error)
HasConsent implements ConsentStore. With no scopes it reports whether any grant exists for the pair.
func (*EntConsentStore) RevokeConsent ¶ added in v0.12.0
func (s *EntConsentStore) RevokeConsent(ctx context.Context, principalID, clientID string) error
RevokeConsent implements ConsentStore.
func (*EntConsentStore) SaveConsent ¶ added in v0.12.0
func (s *EntConsentStore) SaveConsent(ctx context.Context, principalID, clientID string, scopes []string) error
SaveConsent implements ConsentStore. Already granted scopes are kept.
type EntLoginSessionStore ¶ added in v0.12.0
type EntLoginSessionStore struct {
// contains filtered or unexported fields
}
EntLoginSessionStore is a LoginSessionStore backed by the sf_login_sessions table. Only token hashes are stored. It is safe for concurrent use and shared by every SystemAuth instance using the same database.
func NewEntLoginSessionStore ¶ added in v0.12.0
func NewEntLoginSessionStore(client *ent.Client, opts ...EntStoreOption) *EntLoginSessionStore
NewEntLoginSessionStore creates a login session store on client.
func (*EntLoginSessionStore) Create ¶ added in v0.12.0
func (s *EntLoginSessionStore) Create(ctx context.Context, token string, session LoginSession) error
Create implements LoginSessionStore.
func (*EntLoginSessionStore) Delete ¶ added in v0.12.0
func (s *EntLoginSessionStore) Delete(ctx context.Context, token string) error
Delete implements LoginSessionStore.
func (*EntLoginSessionStore) DeleteExpired ¶ added in v0.12.0
func (s *EntLoginSessionStore) DeleteExpired(ctx context.Context) (int, error)
DeleteExpired removes expired sessions and returns how many were removed.
func (*EntLoginSessionStore) Get ¶ added in v0.12.0
func (s *EntLoginSessionStore) Get(ctx context.Context, token string) (LoginSession, error)
Get implements LoginSessionStore.
type EntLoginStateStore ¶ added in v0.12.0
type EntLoginStateStore struct {
// contains filtered or unexported fields
}
EntLoginStateStore is an oauthclient.StateStore backed by the sf_login_states table. Only a hash of the state value is stored. Take is single-use across instances: a row is returned only to the caller whose delete removed it.
func NewEntLoginStateStore ¶ added in v0.12.0
func NewEntLoginStateStore(client *ent.Client, opts ...EntStoreOption) *EntLoginStateStore
NewEntLoginStateStore creates a login state store on client.
func (*EntLoginStateStore) DeleteExpired ¶ added in v0.12.0
func (s *EntLoginStateStore) DeleteExpired(ctx context.Context) (int, error)
DeleteExpired removes expired login states and returns how many were removed.
func (*EntLoginStateStore) Put ¶ added in v0.12.0
func (s *EntLoginStateStore) Put(ctx context.Context, state string, data oauthclient.StateData, ttl time.Duration) error
Put implements oauthclient.StateStore.
func (*EntLoginStateStore) Take ¶ added in v0.12.0
func (s *EntLoginStateStore) Take(ctx context.Context, state string) (oauthclient.StateData, error)
Take implements oauthclient.StateStore.
type EntOrgsSource ¶ added in v0.14.0
type EntOrgsSource struct {
// contains filtered or unexported fields
}
EntOrgsSource builds the orgs claim from memberships stored through Ent and application roles from an AppRoleResolver.
func NewEntOrgsSource ¶ added in v0.14.0
func NewEntOrgsSource(client *ent.Client, roles AppRoleResolver) *EntOrgsSource
NewEntOrgsSource returns an OrgsSource over client. roles supplies the apps of each organization; with nil every organization carries an empty apps map.
func (*EntOrgsSource) Memberships ¶ added in v0.14.0
func (s *EntOrgsSource) Memberships(ctx context.Context, principalID uuid.UUID, limit int, cursor string) ([]OrgClaim, string, error)
Memberships implements OrgsSource. The cursor is an organization ID.
func (*EntOrgsSource) OrgsClaim ¶ added in v0.14.0
func (s *EntOrgsSource) OrgsClaim(ctx context.Context, principalID uuid.UUID, compact bool) (OrgsResult, error)
OrgsClaim implements OrgsSource.
type EntPrincipalDirectory ¶ added in v0.12.0
type EntPrincipalDirectory struct {
// contains filtered or unexported fields
}
EntPrincipalDirectory implements PrincipalDirectory on the Ent identity schema: Principal (type=human) + Human extension + ExternalIdentity link.
func NewEntPrincipalDirectory ¶ added in v0.12.0
func NewEntPrincipalDirectory(db *ent.Client, opts ...EntPrincipalDirectoryOption) *EntPrincipalDirectory
NewEntPrincipalDirectory creates an Ent-backed PrincipalDirectory. Without a syncer option, nothing is registered with an authorization backend.
func (*EntPrincipalDirectory) CreateFromExternal ¶ added in v0.12.0
func (d *EntPrincipalDirectory) CreateFromExternal(ctx context.Context, login ExternalLogin) (*HumanPrincipal, error)
CreateFromExternal implements PrincipalDirectory. The principal, its human row, the external identity, the personal organization and the owner membership are written in one transaction: a failure at any step leaves nothing behind.
func (*EntPrincipalDirectory) EnsurePersonalOrg ¶ added in v0.14.0
func (d *EntPrincipalDirectory) EnsurePersonalOrg(ctx context.Context, p *HumanPrincipal, login ExternalLogin) error
EnsurePersonalOrg implements PersonalOrgEnsurer. It runs in its own transaction and is a no-op for a principal that already has a personal organization.
func (*EntPrincipalDirectory) FindByExternalIdentity ¶ added in v0.12.0
func (d *EntPrincipalDirectory) FindByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
FindByExternalIdentity implements PrincipalDirectory.
func (*EntPrincipalDirectory) FindByVerifiedEmail ¶ added in v0.12.0
func (d *EntPrincipalDirectory) FindByVerifiedEmail(ctx context.Context, email string) (*HumanPrincipal, error)
FindByVerifiedEmail implements PrincipalDirectory.
func (*EntPrincipalDirectory) GetPrincipal ¶ added in v0.12.0
func (d *EntPrincipalDirectory) GetPrincipal(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
GetPrincipal implements PrincipalDirectory.
func (*EntPrincipalDirectory) LinkExternalIdentity ¶ added in v0.12.0
func (d *EntPrincipalDirectory) LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, login ExternalLogin) error
LinkExternalIdentity implements PrincipalDirectory.
func (*EntPrincipalDirectory) RecordLogin ¶ added in v0.12.0
func (d *EntPrincipalDirectory) RecordLogin(ctx context.Context, principalID uuid.UUID, login ExternalLogin, at time.Time) error
RecordLogin implements PrincipalDirectory.
type EntPrincipalDirectoryOption ¶ added in v0.14.0
type EntPrincipalDirectoryOption func(*EntPrincipalDirectory)
EntPrincipalDirectoryOption configures an EntPrincipalDirectory.
func WithDirectoryAuthzSyncer ¶ added in v0.14.0
func WithDirectoryAuthzSyncer(syncer authz.RelationshipSyncer) EntPrincipalDirectoryOption
WithDirectoryAuthzSyncer sets the authorization syncer that registers the principals and personal organizations the directory creates, so they exist in relationship-based authorization. Registration runs after the creating transaction commits.
func WithDirectoryLogger ¶ added in v0.14.0
func WithDirectoryLogger(logger *slog.Logger) EntPrincipalDirectoryOption
WithDirectoryLogger sets the logger used for tolerated sync failures.
func WithDirectorySyncMode ¶ added in v0.14.0
func WithDirectorySyncMode(mode authz.SyncMode) EntPrincipalDirectoryOption
WithDirectorySyncMode sets the sync mode: in strict mode a failed registration is returned (the rows stay committed), in eventual mode (the default) it is logged.
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 implements fosite.ClientManager: it reports fosite.ErrJTIKnown for a client-assertion JWT ID that is already 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) CreateHuman ¶ added in v0.14.0
func (s *EntStorage) CreateHuman(ctx context.Context, h *HumanPrincipal) error
CreateHuman implements Storage.
func (*EntStorage) CreateOpenIDConnectSession ¶ added in v0.12.0
func (s *EntStorage) CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) error
CreateOpenIDConnectSession stores the OIDC session for an authorization code.
func (*EntStorage) CreatePKCERequestSession ¶
func (s *EntStorage) CreatePKCERequestSession(ctx context.Context, signature string, requester fosite.Requester) error
CreatePKCERequestSession records the PKCE challenge on the authorization code row (Fosite stores the code first and strips the challenge from the request it hands to CreateAuthorizeCodeSession).
func (*EntStorage) CreateRefreshTokenSession ¶
func (s *EntStorage) CreateRefreshTokenSession(ctx context.Context, signature string, accessSignature string, request fosite.Requester) error
CreateRefreshTokenSession stores a refresh token session. Fosite creates the paired access token first; the refresh token is attached to that row so revoking either revokes both.
func (*EntStorage) DeleteAccessTokenSession ¶
func (s *EntStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error
DeleteAccessTokenSession removes an access token session. A row that also carries a refresh token is marked revoked instead, so the refresh token's reuse can still be detected.
func (*EntStorage) DeleteClient ¶
func (s *EntStorage) DeleteClient(ctx context.Context, id string) error
DeleteClient deletes a client.
func (*EntStorage) DeleteHuman ¶ added in v0.14.0
DeleteHuman implements Storage. It removes the principal together with its Human extension, external identities, and credentials. Other records that still reference the principal cause the delete to fail.
func (*EntStorage) DeleteOpenIDConnectSession ¶ added in v0.12.0
func (s *EntStorage) DeleteOpenIDConnectSession(ctx context.Context, authorizeCode string) error
DeleteOpenIDConnectSession removes the OIDC session for an authorization code.
func (*EntStorage) DeletePKCERequestSession ¶
func (s *EntStorage) DeletePKCERequestSession(ctx context.Context, signature string) error
DeletePKCERequestSession is a no-op: the PKCE data lives on the authorization code row, which the authorization code handler invalidates once the exchange completes. Invalidating it here would make the code look replayed to the authorization code handler.
func (*EntStorage) DeleteRefreshTokenSession ¶
func (s *EntStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error
DeleteRefreshTokenSession removes a refresh token session.
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. A code that was already exchanged returns the request together with fosite.ErrInvalidatedAuthorizeCode so Fosite can revoke the tokens issued from it (authorization code replay).
func (*EntStorage) GetClientByID ¶
GetClientByID retrieves a client by ID.
func (*EntStorage) GetHuman ¶ added in v0.14.0
func (s *EntStorage) GetHuman(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
GetHuman implements Storage.
func (*EntStorage) GetHumanByEmail ¶ added in v0.14.0
func (s *EntStorage) GetHumanByEmail(ctx context.Context, email string) (*HumanPrincipal, error)
GetHumanByEmail implements Storage. The match is case-insensitive.
func (*EntStorage) GetHumanByExternalIdentity ¶ added in v0.14.0
func (s *EntStorage) GetHumanByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
GetHumanByExternalIdentity implements Storage.
func (*EntStorage) GetOpenIDConnectSession ¶ added in v0.12.0
func (s *EntStorage) GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error)
GetOpenIDConnectSession returns the OIDC session for an authorization code.
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: the stored authorization request with the code challenge restored to its form.
func (*EntStorage) GetRefreshTokenSession ¶
func (s *EntStorage) GetRefreshTokenSession(ctx context.Context, signature string, session fosite.Session) (fosite.Requester, error)
GetRefreshTokenSession retrieves a refresh token session. A revoked (rotated) refresh token returns the request together with fosite.ErrInactiveToken so Fosite detects reuse and revokes the whole token family.
func (*EntStorage) InvalidateAuthorizeCodeSession ¶
func (s *EntStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
InvalidateAuthorizeCodeSession marks an authorization code as used.
func (*EntStorage) LinkExternalIdentity ¶ added in v0.14.0
func (s *EntStorage) LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, provider, subject string) error
LinkExternalIdentity implements Storage.
func (*EntStorage) ListClients ¶
func (s *EntStorage) ListClients(ctx context.Context) ([]*Client, error)
ListClients returns all clients.
func (*EntStorage) PrincipalActive ¶ added in v0.14.0
PrincipalActive implements PrincipalStatus for the principals in the identity database.
func (*EntStorage) RevokeAccessToken ¶
func (s *EntStorage) RevokeAccessToken(ctx context.Context, requestID string) error
RevokeAccessToken revokes every token of the family identified by the Fosite request ID. Access and refresh tokens share rows, so this is the same operation as RevokeRefreshToken.
func (*EntStorage) RevokeRefreshToken ¶
func (s *EntStorage) RevokeRefreshToken(ctx context.Context, requestID string) error
RevokeRefreshToken revokes every token of the family identified by the Fosite request ID.
func (*EntStorage) RevokeSubjectTokens ¶ added in v0.12.0
func (s *EntStorage) RevokeSubjectTokens(ctx context.Context, subject string) error
RevokeSubjectTokens implements SubjectTokenRevoker.
func (*EntStorage) RotateRefreshToken ¶
func (s *EntStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
RotateRefreshToken retires the current tokens of the family before Fosite stores their replacements. Retired rows stay (revoked) so that reuse of an old refresh token is detected.
func (*EntStorage) SetClientAssertionJWT ¶
SetClientAssertionJWT implements fosite.ClientManager: it records a client-assertion JWT ID as used until exp.
func (*EntStorage) UpdateClient ¶
func (s *EntStorage) UpdateClient(ctx context.Context, client *Client) error
UpdateClient updates an existing client.
func (*EntStorage) UpdateHuman ¶ added in v0.14.0
func (s *EntStorage) UpdateHuman(ctx context.Context, h *HumanPrincipal) error
UpdateHuman implements Storage. It replaces the profile fields of an existing human principal with those in h.
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.
func WithEntAccessChangeSink ¶ added in v0.14.0
func WithEntAccessChangeSink(sink accesschange.Sink) EntStorageOption
WithEntAccessChangeSink announces RevokeSubjectTokens to sink after it commits (ADR-010). The access-change record is written whether or not a sink is set.
type EntStoreOption ¶ added in v0.12.0
type EntStoreOption func(*entStoreConfig)
EntStoreOption configures the Ent-backed social login stores.
func WithCleanupInterval ¶ added in v0.12.0
func WithCleanupInterval(d time.Duration) EntStoreOption
WithCleanupInterval sets how often a store deletes expired rows while handling writes. Zero or negative disables opportunistic cleanup; call DeleteExpired from a scheduled job instead.
type ExternalLogin ¶ added in v0.12.0
type ExternalLogin struct {
// Provider is the upstream provider name (github, google).
Provider string
// Subject is the provider's stable user ID.
Subject string
// Email is the provider-reported email.
Email string
// EmailVerified reports whether the provider asserts Email is verified.
EmailVerified bool
// Name is the display name.
Name string
// Username is the provider's handle for the person (the GitHub login),
// when it has one. It seeds the personal organization's slug.
Username string
// AvatarURL is the profile picture URL.
AvatarURL string
}
ExternalLogin is a normalized, upstream-authenticated identity.
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 FederationAuthenticator ¶ added in v0.14.0
FederationAuthenticator decides whether a request to a federation endpoint comes from the federation hub. It returns nil to admit the request.
func SharedSecretAuthenticator ¶ added in v0.14.0
func SharedSecretAuthenticator(secret string) FederationAuthenticator
SharedSecretAuthenticator admits requests carrying the shared secret as a bearer token, compared in constant time. The secret should be long and random, and distinct per federated application.
type FederationClient ¶
type FederationClient struct {
// contains filtered or unexported fields
}
FederationClient connects a SystemAuth app to SystemAuth 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() *SystemAuthDiscovery
Discovery returns the SystemAuth discovery document.
func (*FederationClient) ExchangeCode ¶
func (c *FederationClient) ExchangeCode(ctx context.Context, code, redirectURI string) (*SSOTokenResponse, error)
ExchangeCode exchanges an authorization code from SystemAuth for tokens.
func (*FederationClient) GetGlobalIdentity ¶
func (c *FederationClient) GetGlobalIdentity(ctx context.Context, globalID uuid.UUID) (*GlobalIdentity, error)
GetGlobalIdentity retrieves a global identity from SystemAuth.
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 SystemAuth for SSO.
func (*FederationClient) Initialize ¶
func (c *FederationClient) Initialize(ctx context.Context) error
Initialize fetches the SystemAuth discovery document.
func (*FederationClient) NotifyAppAccess ¶
NotifyAppAccess records that a user accessed this app via SSO.
func (*FederationClient) RegisterWithSystemAuth ¶
func (c *FederationClient) RegisterWithSystemAuth(ctx context.Context, federationID uuid.UUID, displayName, baseURL string, capabilities []string) error
RegisterWithSystemAuth 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 SystemAuth.
type FederationConfig ¶
type FederationConfig struct {
// Enabled enables federation mode.
Enabled bool `json:"enabled" yaml:"enabled" jsonschema:"description=Enable SystemAuth federation"`
// SystemAuthURL is the SystemAuth server URL.
SystemAuthURL string `json:"systemauth_url" yaml:"systemauth_url" jsonschema:"format=uri,description=SystemAuth 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 SystemAuth.
ClientID string `json:"client_id" yaml:"client_id" jsonschema:"description=OAuth client ID for SystemAuth"`
// ClientSecret is the OAuth client secret for SystemAuth.
// Supports environment variable expansion: ${SYSTEMAUTH_SECRET}
ClientSecret string `json:"client_secret" yaml:"client_secret" jsonschema:"description=OAuth client secret (supports env var expansion)"`
}
FederationConfig configures SystemAuth integration.
type FederationEndpoints ¶
type FederationEndpoints struct {
// contains filtered or unexported fields
}
FederationEndpoints provides SystemForge federation contract endpoints.
func NewFederationEndpoints ¶
func NewFederationEndpoints(server *Server, syncHandler IdentitySyncHandler, opts ...FederationOption) *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. The identity sync and lookup endpoints are registered only when an authenticator was configured (WithFederationAuthenticator).
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 FederationOption ¶ added in v0.14.0
type FederationOption func(*FederationEndpoints)
FederationOption configures FederationEndpoints.
func WithFederationAuthenticator ¶ added in v0.14.0
func WithFederationAuthenticator(auth FederationAuthenticator) FederationOption
WithFederationAuthenticator sets how requests to the identity sync and lookup endpoints are authenticated. Without it those endpoints are not registered: they act on the request body as truth, so they must never be reachable unauthenticated.
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 SystemAuth.
type HumanPrincipal ¶ added in v0.14.0
type HumanPrincipal struct {
ID uuid.UUID
Email string
EmailVerified bool
DisplayName string
GivenName string
FamilyName string
AvatarURL string
Locale string
Active bool
// Managed is true while the principal has an active manager
// relationship (ADR-009), whether or not it has an email.
Managed bool
Metadata map[string]any
CreatedAt time.Time
UpdatedAt time.Time
}
HumanPrincipal is a human Principal joined with its Human extension. It is the single view of a person used by password login, social login, and federation sync.
func ResolveExternalLogin ¶ added in v0.12.0
func ResolveExternalLogin(ctx context.Context, dir PrincipalDirectory, login ExternalLogin, now time.Time) (*HumanPrincipal, error)
ResolveExternalLogin finds or creates the principal for an upstream login using the canonical account-linking model:
- The (provider, subject) link is the primary key: if it exists, that principal signs in, regardless of the current email.
- Otherwise a verified upstream email may link to an existing principal whose own email is verified.
- Otherwise a new principal is created, which requires a verified email.
An unverified email never links to or creates an account.
type Identity ¶
type Identity struct {
// ID is the unique identifier.
ID uuid.UUID `json:"id"`
// State is the identity state (active, inactive, etc.).
State IdentityState `json:"state"`
// Traits holds identity attributes (email, name, etc.).
// In Kratos, this maps to the identity traits.
Traits IdentityTraits `json:"traits"`
// Metadata holds administrative metadata.
Metadata map[string]any `json:"metadata,omitempty"`
// Credentials holds credential information (password hash, etc.).
// Note: Sensitive data should not be returned in queries.
Credentials []IdentityCredential `json:"credentials,omitempty"`
// CreatedAt is when the identity was created.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is when the identity was last updated.
UpdatedAt time.Time `json:"updated_at"`
}
Identity represents a user identity. This is a clean abstraction that can map to Kratos identity schema.
type IdentityCredential ¶
type IdentityCredential struct {
Type CredentialType `json:"type"`
Identifiers []string `json:"identifiers,omitempty"`
}
IdentityCredential represents a credential type.
type IdentityFilter ¶
type IdentityFilter struct {
Email string
State IdentityState
PageSize int
Page int
}
IdentityFilter for listing identities.
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 IdentityProvider ¶
type IdentityProvider interface {
// CreateIdentity creates a new identity.
CreateIdentity(ctx context.Context, identity *Identity) error
// GetIdentity retrieves an identity by ID.
GetIdentity(ctx context.Context, id uuid.UUID) (*Identity, error)
// GetIdentityByEmail retrieves an identity by email address.
GetIdentityByEmail(ctx context.Context, email string) (*Identity, error)
// UpdateIdentity updates an existing identity.
UpdateIdentity(ctx context.Context, identity *Identity) error
// DeleteIdentity deletes an identity.
DeleteIdentity(ctx context.Context, id uuid.UUID) error
// ListIdentities lists identities with optional filtering.
ListIdentities(ctx context.Context, filter *IdentityFilter) ([]*Identity, error)
}
IdentityProvider manages user identities (CRUD operations). In Ory Kratos, this maps to the identity management API.
type IdentityState ¶
type IdentityState string
IdentityState represents the state of an identity.
const ( IdentityStateActive IdentityState = "active" IdentityStateInactive IdentityState = "inactive" )
type IdentitySyncHandler ¶
type IdentitySyncHandler interface {
// SyncIdentity is called when SystemAuth 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 SystemAuth. 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 SystemAuth 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 SystemAuth after syncing.
type IdentityTraits ¶
type IdentityTraits struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified,omitempty"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
}
IdentityTraits holds identity attributes.
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 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 */
// KeyID is the "kid" published in the JWKS and set on every JWT.
// Default: the RFC 7638 thumbprint of the key.
KeyID string `` /* 126-byte string literal not displayed */
// PrivateKeyFile is the path of a PEM-encoded RSA private key (PKCS#1
// or PKCS#8, at least 2048 bits). Supports environment variable
// expansion: ${SYSTEMAUTH_SIGNING_KEY_FILE}
PrivateKeyFile string `` /* 153-byte string literal not displayed */
// PrivateKeyPEM is a PEM-encoded RSA private key, normally injected from
// a secret: ${SYSTEMAUTH_SIGNING_KEY}. Mutually exclusive with
// PrivateKeyFile.
PrivateKeyPEM string `` /* 174-byte string literal not displayed */
// PrivateKey is an optional pre-configured RSA private key. When nil,
// PrivateKeyPEM or PrivateKeyFile is loaded; when none is set an
// ephemeral key is generated (development only).
// This field is not serialized - for programmatic use only.
PrivateKey *rsa.PrivateKey `json:"-" yaml:"-" jsonschema:"-"`
}
KeyConfig configures signing key management.
func (*KeyConfig) HasSigningKey ¶ added in v0.12.0
HasSigningKey reports whether the configuration supplies a signing key (programmatically, as PEM, or as a file).
func (*KeyConfig) LoadSigningKey ¶ added in v0.12.0
LoadSigningKey resolves PrivateKeyPEM or PrivateKeyFile into PrivateKey. It is a no-op when PrivateKey is already set or no key is configured.
type LoginSession ¶ added in v0.12.0
type LoginSession struct {
// PrincipalID is the authenticated principal.
PrincipalID uuid.UUID
// Provider is the upstream provider used to sign in.
Provider string
// CreatedAt is when the session was established.
CreatedAt time.Time
// ExpiresAt is the absolute session expiry.
ExpiresAt time.Time
}
LoginSession is an authenticated browser session on SystemAuth.
type LoginSessionStore ¶ added in v0.12.0
type LoginSessionStore interface {
// Create stores session under token.
Create(ctx context.Context, token string, session LoginSession) error
// Get returns the session for token, or ErrLoginSessionNotFound when it
// is unknown or expired.
Get(ctx context.Context, token string) (LoginSession, error)
// Delete removes the session for token. Deleting an unknown token is not
// an error.
Delete(ctx context.Context, token string) error
}
LoginSessionStore persists login sessions keyed by an opaque session token. Implementations should store only a hash of the token.
type ManagedPrincipalsConfig ¶ added in v0.14.0
type ManagedPrincipalsConfig struct {
// Enabled allows managed principals in this deployment.
Enabled bool `json:"enabled" yaml:"enabled" jsonschema:"description=Allow managed principals in this deployment"`
// LoginTokenTTL is the default lifetime of a reusable login token when
// neither the request nor the client sets one.
LoginTokenTTL Duration `` /* 145-byte string literal not displayed */
// LoginTokenMaxTTL caps the lifetime of every login token; longer
// requests are clamped.
LoginTokenMaxTTL Duration `` /* 148-byte string literal not displayed */
// SingleUseTokenTTL is the default lifetime of a single-use login token.
SingleUseTokenTTL Duration `` /* 156-byte string literal not displayed */
}
ManagedPrincipalsConfig configures managed principals: humans without an email who always have a manager with one (ADR-005). They are disabled unless Enabled is set here and on the requesting client.
type MembershipsInput ¶ added in v0.14.0
type MembershipsInput struct {
Authorization string `header:"Authorization" doc:"Bearer access token granted the openid scope"`
Limit int `query:"limit" minimum:"1" maximum:"100" doc:"Page size (default 50)"`
Cursor string `query:"cursor" doc:"next_cursor of the previous page"`
}
MembershipsInput documents the memberships request for OpenAPI.
type MembershipsOutput ¶ added in v0.14.0
type MembershipsOutput struct {
Body MembershipsResponse
}
MembershipsOutput documents the memberships response for OpenAPI.
type MembershipsResponse ¶ added in v0.14.0
type MembershipsResponse struct {
Orgs []OrgClaim `json:"orgs"`
NextCursor string `json:"next_cursor,omitempty"`
}
MembershipsResponse is the body of GET /oauth/userinfo/memberships.
type MemoryConsentStore ¶ added in v0.12.0
type MemoryConsentStore struct {
// contains filtered or unexported fields
}
MemoryConsentStore is an in-memory ConsentStore. Consents are lost on restart (users are asked again); use a shared store for multiple replicas.
func NewMemoryConsentStore ¶ added in v0.12.0
func NewMemoryConsentStore() *MemoryConsentStore
NewMemoryConsentStore creates an empty in-memory consent store.
func (*MemoryConsentStore) HasConsent ¶ added in v0.12.0
func (s *MemoryConsentStore) HasConsent(_ context.Context, principalID, clientID string, scopes []string) (bool, error)
HasConsent implements ConsentStore.
func (*MemoryConsentStore) RevokeConsent ¶ added in v0.12.0
func (s *MemoryConsentStore) RevokeConsent(_ context.Context, principalID, clientID string) error
RevokeConsent implements ConsentStore.
func (*MemoryConsentStore) SaveConsent ¶ added in v0.12.0
func (s *MemoryConsentStore) SaveConsent(_ context.Context, principalID, clientID string, scopes []string) error
SaveConsent implements ConsentStore.
type MemoryLoginSessionStore ¶ added in v0.12.0
type MemoryLoginSessionStore struct {
// contains filtered or unexported fields
}
MemoryLoginSessionStore is an in-memory LoginSessionStore. It is suitable for a single SystemAuth instance; use a shared store for multiple replicas.
func NewMemoryLoginSessionStore ¶ added in v0.12.0
func NewMemoryLoginSessionStore() *MemoryLoginSessionStore
NewMemoryLoginSessionStore creates an empty in-memory session store.
func (*MemoryLoginSessionStore) Create ¶ added in v0.12.0
func (s *MemoryLoginSessionStore) Create(_ context.Context, token string, session LoginSession) error
Create implements LoginSessionStore. Expired sessions are pruned.
func (*MemoryLoginSessionStore) Delete ¶ added in v0.12.0
func (s *MemoryLoginSessionStore) Delete(_ context.Context, token string) error
Delete implements LoginSessionStore.
func (*MemoryLoginSessionStore) Get ¶ added in v0.12.0
func (s *MemoryLoginSessionStore) Get(_ context.Context, token string) (LoginSession, error)
Get implements LoginSessionStore.
type MemoryPrincipalDirectory ¶ added in v0.12.0
type MemoryPrincipalDirectory struct {
// contains filtered or unexported fields
}
MemoryPrincipalDirectory is an in-memory PrincipalDirectory for development and tests.
func NewMemoryPrincipalDirectory ¶ added in v0.12.0
func NewMemoryPrincipalDirectory() *MemoryPrincipalDirectory
NewMemoryPrincipalDirectory creates an empty in-memory directory.
func (*MemoryPrincipalDirectory) AddPrincipal ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) AddPrincipal(p HumanPrincipal) error
AddPrincipal seeds a principal (e.g. one created by password signup).
func (*MemoryPrincipalDirectory) CreateFromExternal ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) CreateFromExternal(_ context.Context, login ExternalLogin) (*HumanPrincipal, error)
CreateFromExternal implements PrincipalDirectory.
func (*MemoryPrincipalDirectory) FindByExternalIdentity ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) FindByExternalIdentity(_ context.Context, provider, subject string) (*HumanPrincipal, error)
FindByExternalIdentity implements PrincipalDirectory.
func (*MemoryPrincipalDirectory) FindByVerifiedEmail ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) FindByVerifiedEmail(_ context.Context, email string) (*HumanPrincipal, error)
FindByVerifiedEmail implements PrincipalDirectory.
func (*MemoryPrincipalDirectory) GetPrincipal ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) GetPrincipal(_ context.Context, id uuid.UUID) (*HumanPrincipal, error)
GetPrincipal implements PrincipalDirectory.
func (*MemoryPrincipalDirectory) LastLogin ¶ added in v0.12.0
LastLogin returns the last recorded login time for a principal.
func (*MemoryPrincipalDirectory) LinkExternalIdentity ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) LinkExternalIdentity(_ context.Context, principalID uuid.UUID, login ExternalLogin) error
LinkExternalIdentity implements PrincipalDirectory.
func (*MemoryPrincipalDirectory) RecordLogin ¶ added in v0.12.0
func (d *MemoryPrincipalDirectory) RecordLogin(_ context.Context, principalID uuid.UUID, _ ExternalLogin, at time.Time) error
RecordLogin implements PrincipalDirectory.
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 fosite.ErrJTIKnown if the JTI was used and has not expired, so a captured client assertion cannot be replayed.
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) CreateHuman ¶ added in v0.14.0
func (s *MemoryStorage) CreateHuman(_ context.Context, h *HumanPrincipal) error
CreateHuman implements Storage.
func (*MemoryStorage) CreateOpenIDConnectSession ¶ added in v0.12.0
func (s *MemoryStorage) CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) error
CreateOpenIDConnectSession stores the OIDC session for an authorization code.
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) 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) DeleteHuman ¶ added in v0.14.0
DeleteHuman implements Storage. It also removes the human's external identities.
func (*MemoryStorage) DeleteOpenIDConnectSession ¶ added in v0.12.0
func (s *MemoryStorage) DeleteOpenIDConnectSession(ctx context.Context, authorizeCode string) error
DeleteOpenIDConnectSession removes the OIDC session for an authorization code.
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) 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 ¶
GetClient retrieves a client by ID (implements fosite.ClientManager).
func (*MemoryStorage) GetClientByID ¶
GetClientByID retrieves a client by ID.
func (*MemoryStorage) GetHuman ¶ added in v0.14.0
func (s *MemoryStorage) GetHuman(_ context.Context, id uuid.UUID) (*HumanPrincipal, error)
GetHuman implements Storage.
func (*MemoryStorage) GetHumanByEmail ¶ added in v0.14.0
func (s *MemoryStorage) GetHumanByEmail(_ context.Context, email string) (*HumanPrincipal, error)
GetHumanByEmail implements Storage. The match is case-insensitive.
func (*MemoryStorage) GetHumanByExternalIdentity ¶ added in v0.14.0
func (s *MemoryStorage) GetHumanByExternalIdentity(_ context.Context, provider, subject string) (*HumanPrincipal, error)
GetHumanByExternalIdentity implements Storage.
func (*MemoryStorage) GetOpenIDConnectSession ¶ added in v0.12.0
func (s *MemoryStorage) GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error)
GetOpenIDConnectSession returns the OIDC session for an authorization code.
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) InvalidateAuthorizeCodeSession ¶
func (s *MemoryStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error
InvalidateAuthorizeCodeSession marks an authorization code as used.
func (*MemoryStorage) LinkExternalIdentity ¶ added in v0.14.0
func (s *MemoryStorage) LinkExternalIdentity(_ context.Context, principalID uuid.UUID, provider, subject string) error
LinkExternalIdentity implements Storage.
func (*MemoryStorage) ListClients ¶
func (s *MemoryStorage) ListClients(ctx context.Context) ([]*Client, error)
ListClients returns all clients.
func (*MemoryStorage) PrincipalActive ¶ added in v0.14.0
PrincipalActive implements PrincipalStatus for the humans the memory storage holds; other subjects are not judged.
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) RevokeSubjectTokens ¶ added in v0.12.0
func (s *MemoryStorage) RevokeSubjectTokens(ctx context.Context, subject string) error
RevokeSubjectTokens implements SubjectTokenRevoker.
func (*MemoryStorage) RotateRefreshToken ¶
func (s *MemoryStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error
RotateRefreshToken retires the refresh and access tokens of a token family before Fosite issues their replacements. Retired refresh tokens stay stored (inactive) so that a later reuse is detected.
func (*MemoryStorage) SetClientAssertionJWT ¶
SetClientAssertionJWT marks a JTI as used until exp.
func (*MemoryStorage) UpdateClient ¶
func (s *MemoryStorage) UpdateClient(ctx context.Context, client *Client) error
UpdateClient updates an existing client.
func (*MemoryStorage) UpdateHuman ¶ added in v0.14.0
func (s *MemoryStorage) UpdateHuman(_ context.Context, h *HumanPrincipal) error
UpdateHuman implements Storage.
type OAuthAuthorizeRequest ¶
type OAuthAuthorizeRequest struct {
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
ResponseType string `json:"response_type"`
Scope string `json:"scope"`
State string `json:"state"`
Nonce string `json:"nonce,omitempty"`
CodeChallenge string `json:"code_challenge,omitempty"`
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
Prompt string `json:"prompt,omitempty"`
MaxAge int `json:"max_age,omitempty"`
UILocales string `json:"ui_locales,omitempty"`
ACRValues string `json:"acr_values,omitempty"`
}
OAuthAuthorizeRequest represents an authorization request.
type OAuthAuthorizeResponse ¶
type OAuthAuthorizeResponse struct {
// Code is the authorization code (for code flow).
Code string `json:"code,omitempty"`
// RedirectTo is the URL to redirect the user to.
RedirectTo string `json:"redirect_to"`
// Error information if authorization failed.
Error string `json:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthAuthorizeResponse is the authorization response.
type OAuthClient ¶
type OAuthClient struct {
// ClientID is the unique client identifier.
ClientID string `json:"client_id"`
// ClientSecret is the client secret (hashed in storage).
ClientSecret string `json:"client_secret,omitempty"`
// ClientName is the human-readable client name.
ClientName string `json:"client_name,omitempty"`
// RedirectURIs are the allowed redirect URIs.
RedirectURIs []string `json:"redirect_uris"`
// GrantTypes are the allowed grant types.
GrantTypes []string `json:"grant_types"`
// ResponseTypes are the allowed response types.
ResponseTypes []string `json:"response_types"`
// Scope is the allowed scope.
Scope string `json:"scope"`
// Audience are the allowed audiences.
Audience []string `json:"audience,omitempty"`
// TokenEndpointAuthMethod is the authentication method for the token endpoint.
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
// Public indicates if this is a public client (no secret).
Public bool `json:"public"`
// Metadata holds custom client metadata.
Metadata map[string]any `json:"metadata,omitempty"`
// CreatedAt is when the client was created.
CreatedAt time.Time `json:"created_at,omitzero"`
// UpdatedAt is when the client was last updated.
UpdatedAt time.Time `json:"updated_at,omitzero"`
}
OAuthClient represents an OAuth 2.0 client.
type OAuthClientStore ¶
type OAuthClientStore interface {
// CreateClient creates a new OAuth client.
CreateClient(ctx context.Context, client *OAuthClient) error
// GetClient retrieves a client by ID.
GetClient(ctx context.Context, clientID string) (*OAuthClient, error)
// UpdateClient updates an existing client.
UpdateClient(ctx context.Context, client *OAuthClient) error
// DeleteClient deletes a client.
DeleteClient(ctx context.Context, clientID string) error
// ListClients lists all clients.
ListClients(ctx context.Context) ([]*OAuthClient, error)
}
OAuthClientStore manages OAuth 2.0 clients. In Ory Hydra, this maps to the admin client API.
type OAuthConsentAccept ¶
type OAuthConsentAccept struct {
GrantScopes []string `json:"grant_scopes"`
Remember bool `json:"remember"`
RememberFor int `json:"remember_for,omitempty"`
Session *ConsentSession `json:"session,omitempty"`
}
OAuthConsentAccept accepts a consent request.
type OAuthConsentReject ¶
type OAuthConsentReject struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthConsentReject rejects a consent request.
type OAuthConsentRequest ¶
type OAuthConsentRequest struct {
Challenge string `json:"challenge"`
ClientID string `json:"client_id"`
RequestedScopes []string `json:"requested_scopes"`
Subject string `json:"subject"`
Skip bool `json:"skip"`
}
OAuthConsentRequest is a pending consent request.
type OAuthConsentResponse ¶
type OAuthConsentResponse struct {
RedirectTo string `json:"redirect_to"`
}
OAuthConsentResponse is the consent response.
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 OAuthIntrospection ¶
type OAuthIntrospection struct {
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
Username string `json:"username,omitempty"`
TokenType string `json:"token_type,omitempty"`
Exp int64 `json:"exp,omitempty"`
Iat int64 `json:"iat,omitempty"`
Nbf int64 `json:"nbf,omitempty"`
Sub string `json:"sub,omitempty"`
Aud []string `json:"aud,omitempty"`
Iss string `json:"iss,omitempty"`
Jti string `json:"jti,omitempty"`
}
OAuthIntrospection is the token introspection response.
type OAuthLoginAccept ¶
type OAuthLoginAccept struct {
Subject string `json:"subject"`
Remember bool `json:"remember"`
RememberFor int `json:"remember_for,omitempty"`
ACR string `json:"acr,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
OAuthLoginAccept accepts a login request.
type OAuthLoginReject ¶
type OAuthLoginReject struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthLoginReject rejects a login request.
type OAuthLoginRequest ¶
type OAuthLoginRequest struct {
Challenge string `json:"challenge"`
ClientID string `json:"client_id"`
RequestedScopes []string `json:"requested_scopes"`
Skip bool `json:"skip"`
Subject string `json:"subject,omitempty"`
}
OAuthLoginRequest is a pending login request.
type OAuthLoginResponse ¶
type OAuthLoginResponse struct {
RedirectTo string `json:"redirect_to"`
}
OAuthLoginResponse is the login response.
type OAuthProvider ¶
type OAuthProvider interface {
// Authorize handles the authorization request.
// Returns an authorization code or error.
Authorize(ctx context.Context, req *OAuthAuthorizeRequest) (*OAuthAuthorizeResponse, error)
// Token handles token requests (authorization code, refresh, client credentials).
Token(ctx context.Context, req *OAuthTokenRequest) (*OAuthTokenResponse, error)
// Introspect validates and returns information about a token.
Introspect(ctx context.Context, token string, tokenTypeHint string) (*OAuthIntrospection, error)
// Revoke revokes an access or refresh token.
Revoke(ctx context.Context, token string, tokenTypeHint string) error
// UserInfo returns claims about the authenticated user (OIDC).
UserInfo(ctx context.Context, accessToken string) (*OAuthUserInfo, error)
// GetConsentRequest retrieves a pending consent request.
GetConsentRequest(ctx context.Context, challenge string) (*OAuthConsentRequest, error)
// AcceptConsent accepts a consent request.
AcceptConsent(ctx context.Context, challenge string, accept *OAuthConsentAccept) (*OAuthConsentResponse, error)
// RejectConsent rejects a consent request.
RejectConsent(ctx context.Context, challenge string, reject *OAuthConsentReject) (*OAuthConsentResponse, error)
// GetLoginRequest retrieves a pending login request.
GetLoginRequest(ctx context.Context, challenge string) (*OAuthLoginRequest, error)
// AcceptLogin accepts a login request.
AcceptLogin(ctx context.Context, challenge string, accept *OAuthLoginAccept) (*OAuthLoginResponse, error)
// RejectLogin rejects a login request.
RejectLogin(ctx context.Context, challenge string, reject *OAuthLoginReject) (*OAuthLoginResponse, error)
}
OAuthProvider handles OAuth 2.0 / OpenID Connect operations. In Ory Hydra, this maps to the public and admin APIs.
type OAuthTokenRequest ¶
type OAuthTokenRequest struct {
GrantType string `json:"grant_type"`
Code string `json:"code,omitempty"`
RedirectURI string `json:"redirect_uri,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
ClientID string `json:"client_id,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
CodeVerifier string `json:"code_verifier,omitempty"`
Scope string `json:"scope,omitempty"`
}
OAuthTokenRequest represents a token request.
type OAuthTokenResponse ¶
type OAuthTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
IDToken string `json:"id_token,omitempty"`
Scope string `json:"scope,omitempty"`
}
OAuthTokenResponse is the token response.
type OAuthUserInfo ¶
type OAuthUserInfo struct {
Sub string `json:"sub"`
Name string `json:"name,omitempty"`
GivenName string `json:"given_name,omitempty"`
FamilyName string `json:"family_name,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified bool `json:"email_verified,omitempty"`
Picture string `json:"picture,omitempty"`
Locale string `json:"locale,omitempty"`
Zoneinfo string `json:"zoneinfo,omitempty"`
}
OAuthUserInfo is the OIDC userinfo 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 WithAccessChanges ¶ added in v0.14.0
func WithAccessChanges(lister AccessChangeLister) Option
WithAccessChanges serves GET /access-changes?since=<RFC 3339> from lister to clients holding a token with the access_changes:read scope. A relying party that restarted calls it to rebuild its revocation cache before serving. Without it the endpoint answers 501.
func WithConsentStore ¶ added in v0.12.0
func WithConsentStore(store ConsentStore) Option
WithConsentStore sets the store for user consent decisions made on the /consent page. Defaults to an EntConsentStore when the server uses EntStorage, otherwise an in-memory (single-instance) store.
func WithCredentialService ¶ added in v0.14.0
func WithCredentialService(svc credential.Service) Option
WithCredentialService sets the credential service that verifies login tokens. Defaults to one over the Ent database when the server uses EntStorage; without either, the login token endpoint is not mounted.
func WithLogger ¶
WithLogger sets the logger for the server.
func WithLoginSessionStore ¶ added in v0.12.0
func WithLoginSessionStore(store LoginSessionStore) Option
WithLoginSessionStore sets the store for __Host-sf_login sessions. Defaults to an EntLoginSessionStore when the server uses EntStorage, otherwise an in-memory (single-instance) store.
func WithLoginStateStore ¶ added in v0.12.0
func WithLoginStateStore(store oauthclient.StateStore) Option
WithLoginStateStore sets the store for in-flight upstream OAuth state. Defaults to an EntLoginStateStore when the server uses EntStorage, otherwise an in-memory (single-instance) store.
func WithLoginTokenClientIP ¶ added in v0.14.0
WithLoginTokenClientIP sets how the login token endpoint finds the client's address, for its per-address rate limit and the last-used address recorded on the token. The default is the direct peer, which behind a reverse proxy is the proxy: pass ratelimit.ForwardedClientIP(proxyNetworks...) there. Never read forwarding headers without naming the proxies that set them.
func WithLoginTokenRateLimit ¶ added in v0.14.0
func WithLoginTokenRateLimit(storage ratelimit.Storage, perAddress, perClient ratelimit.Limit) Option
WithLoginTokenRateLimit sets the rate limit storage and the limits per source address and per client for the login token endpoint. Defaults to in-memory storage with DefaultLoginTokenAddressLimit and DefaultLoginTokenClientLimit; use shared storage, such as Redis, when several instances serve the endpoint.
func WithObservability ¶
func WithObservability(obs *observability.Observability) Option
WithObservability sets the observability provider for metrics and tracing.
func WithOrgsSource ¶ added in v0.14.0
func WithOrgsSource(src OrgsSource) Option
WithOrgsSource makes the server emit the orgs claim (ADR-007) in ID tokens, at the userinfo endpoint and, in compact form, in JWT access tokens, and serve GET /oauth/userinfo/memberships. Without it no organization claim is emitted.
func WithPrincipalDirectory ¶ added in v0.12.0
func WithPrincipalDirectory(dir PrincipalDirectory) Option
WithPrincipalDirectory sets the principal store used by social login. Defaults to an Ent directory when the server uses EntStorage, otherwise an in-memory directory.
func WithReadinessCheck ¶ added in v0.12.0
WithReadinessCheck adds a dependency check to GET /readyz, e.g. a database ping. All checks must pass for the server to report ready.
func WithSessionProvider ¶
func WithSessionProvider(provider SessionProvider) Option
WithSessionProvider sets a custom session provider for authentication.
func WithSocialAuthzSyncer ¶ added in v0.14.0
func WithSocialAuthzSyncer(syncer authz.RelationshipSyncer, mode authz.SyncMode) Option
WithSocialAuthzSyncer sets the authorization syncer that registers principals and personal organizations created by social login, so they exist in relationship-based authorization (rebac) mode. It applies to the default Ent-backed directory; a directory supplied with WithPrincipalDirectory is responsible for its own registration. mode selects strict (a failed registration fails the login, rows stay committed) or eventual (logged).
func WithSocialConnector ¶ added in v0.12.0
func WithSocialConnector(c *oauthclient.Connector) Option
WithSocialConnector adds or replaces the upstream connector for c.Provider. Use it to point a provider at alternate endpoints (tests, GitHub Enterprise); credentials normally come from Config.SocialLogin.
func WithStorage ¶
WithStorage sets a custom storage implementation.
type OrgClaim ¶ added in v0.14.0
type OrgClaim struct {
ID string `json:"id"`
Slug string `json:"slug,omitempty"`
Name string `json:"name,omitempty"`
// Type is personal, team or enterprise.
Type string `json:"type,omitempty"`
// Role is the principal's organization role: owner, admin, member or
// collaborator.
Role string `json:"role"`
// Apps maps each application the principal may open in this
// organization to the principal's role in it. An application absent
// from the map is one the principal may not open.
Apps map[string]string `json:"apps"`
}
OrgClaim is one organization in the orgs claim. The compact form, used in JWT access tokens, leaves Slug, Name and Type empty so they are omitted.
type OrgsResult ¶ added in v0.14.0
OrgsResult is the orgs claim of one principal.
type OrgsSource ¶ added in v0.14.0
type OrgsSource interface {
// OrgsClaim returns the principal's organizations, personal first and
// then by most recent membership, at most MaxOrgsInToken of them. The
// compact form omits slug, name and type.
OrgsClaim(ctx context.Context, principalID uuid.UUID, compact bool) (OrgsResult, error)
// Memberships returns one page of the principal's organizations in
// the full form and the same order, limit at most, starting after the
// organization cursor names ("" for the first page). next is empty on
// the last page.
Memberships(ctx context.Context, principalID uuid.UUID, limit int, cursor string) (page []OrgClaim, next string, err error)
}
OrgsSource supplies the orgs claim. EntOrgsSource is the standard implementation.
type PersonalOrgEnsurer ¶ added in v0.14.0
type PersonalOrgEnsurer interface {
// EnsurePersonalOrg creates the principal's personal organization when
// it has none and does nothing otherwise.
EnsurePersonalOrg(ctx context.Context, p *HumanPrincipal, login ExternalLogin) error
}
PersonalOrgEnsurer is implemented by directories that keep personal organizations. ResolveExternalLogin calls it on every successful login.
type PrincipalDirectory ¶ added in v0.12.0
type PrincipalDirectory interface {
// FindByExternalIdentity returns the principal linked to (provider,
// subject), or ErrPrincipalNotFound.
FindByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
// FindByVerifiedEmail returns the human principal whose email matches
// (case-insensitively) and is itself verified, or ErrPrincipalNotFound.
FindByVerifiedEmail(ctx context.Context, email string) (*HumanPrincipal, error)
// CreateFromExternal creates a human principal from login, with the
// email marked verified, and links the external identity. An
// implementation backed by an organization store also creates the
// person's personal organization in the same transaction (ADR-006
// decision 1), so a first login yields both or nothing. It returns
// ErrEmailConflict if the email is already taken, and
// ErrExternalIdentityExists if the identity was linked concurrently.
CreateFromExternal(ctx context.Context, login ExternalLogin) (*HumanPrincipal, error)
// LinkExternalIdentity links login's identity to an existing principal.
// It returns ErrExternalIdentityExists if already linked.
LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, login ExternalLogin) error
// RecordLogin updates last-login bookkeeping and the provider-reported
// email on the external identity.
RecordLogin(ctx context.Context, principalID uuid.UUID, login ExternalLogin, at time.Time) error
// GetPrincipal returns a principal by ID, or ErrPrincipalNotFound.
GetPrincipal(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
}
PrincipalDirectory is the persistence port for social login. It works on Principal records (and their Human extension), never on legacy User rows.
type PrincipalStatus ¶ added in v0.14.0
type PrincipalStatus interface {
// PrincipalActive reports whether the principal named by subject is
// active. Subjects that are not principals this storage holds, such as
// users an application's session provider names, are not judged and
// report true.
PrincipalActive(ctx context.Context, subject string) (bool, error)
}
PrincipalStatus is implemented by storage that can tell whether a token's subject may still use it. SystemAuth checks it whenever a token is used or refreshed, so deactivating or deleting a principal takes effect immediately, however it was deactivated.
type Providers ¶
type Providers struct {
Identity IdentityProvider
Authentication AuthenticationProvider
OAuth OAuthProvider
OAuthClients OAuthClientStore
}
Providers holds all provider implementations for SystemAuth. This provides a unified way to access identity, authentication, and OAuth services.
func NewProviders ¶
func NewProviders(server *Server, opts ...ProvidersOption) *Providers
NewProviders creates all embedded providers from a SystemAuth Server. This is the simplest way to get all provider implementations.
Example:
server, _ := systemauth.NewEmbedded(cfg) providers := systemauth.NewProviders(server) // Use providers identity, _ := providers.Identity.GetIdentity(ctx, userID) session, _ := providers.Authentication.ValidateSession(ctx, token) userInfo, _ := providers.OAuth.UserInfo(ctx, accessToken)
func NewProvidersFromStorage ¶
func NewProvidersFromStorage(storage Storage, opts ...ProvidersOption) *Providers
NewProvidersFromStorage creates providers directly from storage. Use this when you don't need the full OAuth server functionality.
Example:
storage := systemauth.NewMemoryStorage() providers := systemauth.NewProvidersFromStorage(storage)
type ProvidersOption ¶
type ProvidersOption func(*providersConfig)
ProvidersOption configures the embedded providers.
func WithProviderPasswordVerifier ¶
func WithProviderPasswordVerifier(verifier func(ctx context.Context, identityID uuid.UUID, password string) (bool, error)) ProvidersOption
WithProviderPasswordVerifier sets the password verification function.
func WithProviderSessionDuration ¶
func WithProviderSessionDuration(d time.Duration) ProvidersOption
WithProviderSessionDuration sets the session duration for the auth provider.
type RequestGate ¶ added in v0.14.0
RequestGate decides whether a request may be believed when it carries identity in a header. Headers are written by the client unless a proxy in front of the server overwrites them, so identity read from one is only as trustworthy as the gate that admits the request.
func TrustedProxyNetworks ¶ added in v0.14.0
func TrustedProxyNetworks(cidrs ...string) (RequestGate, error)
TrustedProxyNetworks returns a RequestGate that admits requests whose direct peer address (r.RemoteAddr, never a forwarded-for header) is in one of the CIDR ranges, such as the load balancer's.
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 SystemAuth.
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 SystemAuth SSO.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the SystemAuth OAuth 2.0 / OpenID Connect server.
func NewEmbedded ¶
NewEmbedded creates a SystemAuth server for embedding in applications. This is the simplest way to add OAuth to a SystemForge application.
Example:
auth, err := systemauth.NewEmbedded(systemauth.Config{
Issuer: "https://myapp.example.com",
})
router.Mount("/oauth", auth.Router())
func (*Server) CurrentLoginSession ¶ added in v0.12.0
func (s *Server) CurrentLoginSession(r *http.Request) (*LoginSession, error)
CurrentLoginSession returns the SystemAuth login session carried by r's __Host-sf_login cookie. It returns ErrLoginSessionNotFound when there is none or social login is not enabled.
func (*Server) KeyID ¶ added in v0.12.0
KeyID returns the key ID ("kid") of the signing key, published in the JWKS and set in the header of every JWT the server signs. It is keys.key_id when configured, otherwise the key's RFC 7638 thumbprint.
func (*Server) LoginTokenPolicy ¶ added in v0.14.0
func (s *Server) LoginTokenPolicy(ctx context.Context, clientID string) (credential.LoginTokenPolicy, error)
LoginTokenPolicy returns the lifetime policy for login tokens issued for clientID's managed principals: the deployment's settings, with the client's own default lifetime when it sets one. Callers check ManagedPrincipalsAllowed first.
func (*Server) ManagedPrincipalsAllowed ¶ added in v0.14.0
ManagedPrincipalsAllowed reports whether clientID may create and sign in managed principals: the deployment must enable managed principals and the client must opt in. It is the single check every managed-principal path uses, so neither switch can be enforced without the other (ADR-005).
func (*Server) Middleware ¶
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) NewBackchannel ¶ added in v0.14.0
func (s *Server) NewBackchannel(opts ...BackchannelOption) *Backchannel
NewBackchannel returns a sender for s's clients and signing key.
func (*Server) OAuth2Provider ¶
func (s *Server) OAuth2Provider() fosite.OAuth2Provider
OAuth2Provider returns the underlying Fosite provider.
func (*Server) OIDCSession ¶
OIDCSession creates an OpenID Connect session for Fosite.
func (*Server) Observability ¶
func (s *Server) Observability() *observability.Observability
Observability returns the observability provider, or nil if not configured.
func (*Server) OpenIDConfiguration ¶ added in v0.13.0
func (s *Server) OpenIDConfiguration() OpenIDConfiguration
OpenIDConfiguration returns the OpenID Provider configuration served at /.well-known/openid-configuration. A relying party in the same process can use it instead of fetching the discovery document over the network.
func (*Server) OrgsClaim ¶ added in v0.14.0
func (s *Server) OrgsClaim(ctx context.Context, principalID uuid.UUID, compact bool) (OrgsResult, error)
OrgsClaim returns the principal's orgs claim, compact for access tokens. It returns an empty result when no OrgsSource is configured.
func (*Server) Ready ¶ added in v0.13.0
Ready runs every readiness check registered with WithReadinessCheck and returns the joined failures, or nil when the server is ready. It is the programmatic form of GET /readyz.
func (*Server) RegisterClient ¶
RegisterClient registers a new OAuth client.
func (*Server) RequireScopes ¶
RequireScopes returns middleware that requires specific scopes.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*Server) Session ¶
Session creates a new, empty OAuth session for subject. Storage implementations hydrate it when loading codes and tokens.
func (*Server) SessionProvider ¶
func (s *Server) SessionProvider() SessionProvider
SessionProvider returns the session provider.
func (*Server) TokenAuthenticator ¶ added in v0.14.0
func (s *Server) TokenAuthenticator(scope string) FederationAuthenticator
TokenAuthenticator admits requests whose bearer token is a valid access token of this server carrying scope.
type Session ¶ added in v0.12.0
type Session struct {
*openid.DefaultSession `json:"oidc"`
// FamilyIssuedAt is when the grant that started this token family was
// first exchanged for tokens. Refresh rotation never extends past
// FamilyIssuedAt + Tokens.RefreshTokenAbsoluteLifetime.
FamilyIssuedAt time.Time `json:"family_issued_at,omitzero"`
// AccessClaims are the claims of JWT access tokens.
AccessClaims *jwt.JWTClaims `json:"access_claims,omitempty"`
// AccessHeader is the JOSE header of JWT access tokens.
AccessHeader *jwt.Headers `json:"access_header,omitempty"`
}
Session is the Fosite session SystemAuth stores with every authorization code and token. It carries the OpenID Connect ID-token claims, the claims of JWT access tokens (when features.enable_jwt_access_tokens is on) and the start of the refresh-token family, which bounds refresh rotation with an absolute lifetime.
Session is JSON-serializable so persistent storage can round-trip it.
func (*Session) GetJWTClaims ¶ added in v0.12.0
func (s *Session) GetJWTClaims() jwt.JWTClaimsContainer
GetJWTClaims implements oauth2.JWTSessionContainer. The subject defaults to the session subject.
func (*Session) GetJWTHeader ¶ added in v0.12.0
GetJWTHeader implements oauth2.JWTSessionContainer.
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 SocialLoginConfig ¶ added in v0.12.0
type SocialLoginConfig struct {
// GitHub configures login with GitHub. Nil disables it.
GitHub *SocialProviderConfig `json:"github,omitempty" yaml:"github,omitempty" jsonschema:"description=GitHub OAuth app credentials"`
// Google configures login with Google. Nil disables it.
Google *SocialProviderConfig `json:"google,omitempty" yaml:"google,omitempty" jsonschema:"description=Google OAuth client credentials"`
// AllowedRedirectOrigins lists absolute origins (scheme://host[:port])
// that a post-login return_to URL may point at, in addition to the
// issuer's own origin. Relative same-origin paths are always allowed.
AllowedRedirectOrigins []string `` /* 164-byte string literal not displayed */
// DefaultRedirect is where users land after login when no return_to is
// given. Default: "/".
DefaultRedirect string `` /* 145-byte string literal not displayed */
// SessionLifetime is the absolute lifetime of the login session cookie.
// Default: 12h.
SessionLifetime Duration `` /* 136-byte string literal not displayed */
// SkipConsent auto-grants consent for authorization requests from users
// signed in through social login. Use only when every registered client
// is first-party.
SkipConsent bool `` /* 141-byte string literal not displayed */
// InsecureCookies drops the __Host- prefix and the Secure flag so the
// login works over plain HTTP. Local development only.
InsecureCookies bool `` /* 160-byte string literal not displayed */
}
SocialLoginConfig configures upstream social login (GitHub, Google). Upstream client credentials live only in the SystemAuth deployment.
type SocialProviderConfig ¶ added in v0.12.0
type SocialProviderConfig struct {
// ClientID is the upstream OAuth client ID.
// Supports environment variable expansion: ${GITHUB_CLIENT_ID}
ClientID string `json:"client_id" yaml:"client_id" jsonschema:"required,description=Upstream OAuth client ID (supports env var expansion)"`
// ClientSecret is the upstream OAuth client secret.
// Supports environment variable expansion: ${GITHUB_CLIENT_SECRET}
ClientSecret string `` /* 133-byte string literal not displayed */
// RedirectURL overrides the callback URL registered with the provider.
// Default: {issuer}/login/{provider}/callback
RedirectURL string `` /* 137-byte string literal not displayed */
// Scopes overrides the default scopes.
Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty" jsonschema:"description=Upstream OAuth scopes"`
}
SocialProviderConfig holds upstream OAuth client credentials.
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
// OpenID Connect sessions for the authorization code flow
// (openid.OpenIDConnectRequestStorage), keyed by the raw code.
CreateOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) error
GetOpenIDConnectSession(ctx context.Context, authorizeCode string, requester fosite.Requester) (fosite.Requester, error)
DeleteOpenIDConnectSession(ctx context.Context, authorizeCode 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)
// Human principals, used by password login and federation sync.
// CreateHuman assigns an ID when h.ID is uuid.Nil and writes it back.
CreateHuman(ctx context.Context, h *HumanPrincipal) error
GetHuman(ctx context.Context, id uuid.UUID) (*HumanPrincipal, error)
GetHumanByEmail(ctx context.Context, email string) (*HumanPrincipal, error)
GetHumanByExternalIdentity(ctx context.Context, provider, subject string) (*HumanPrincipal, error)
// LinkExternalIdentity records an upstream identity for a human. Linking
// the same identity to the same principal again is a no-op; linking it
// to a different principal returns ErrExternalIdentityExists.
LinkExternalIdentity(ctx context.Context, principalID uuid.UUID, provider, subject string) error
UpdateHuman(ctx context.Context, h *HumanPrincipal) error
DeleteHuman(ctx context.Context, id uuid.UUID) error
}
Storage defines the persistence interface for SystemAuth. 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 SubjectTokenRevoker ¶ added in v0.12.0
type SubjectTokenRevoker interface {
// RevokeSubjectTokens marks all of subject's access and refresh tokens
// revoked. Revoking a subject without tokens is not an error.
RevokeSubjectTokens(ctx context.Context, subject string) error
}
SubjectTokenRevoker is implemented by storage that can revoke every access and refresh token issued to a subject (principal). SystemAuth uses it on logout to end the principal's delegated access along with the login session. MemoryStorage and EntStorage implement it.
type SystemAuthDiscovery ¶
type SystemAuthDiscovery 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"`
}
SystemAuthDiscovery holds the OIDC discovery configuration from SystemAuth.
type TokenConfig ¶
type TokenConfig struct {
// AccessTokenLifetime is how long access tokens are valid. It is the
// fallback bound on how long an access change can go unseen by a
// relying party (ADR-010), so it may not exceed
// accesschange.MaxAccessTokenLifetime (15 minutes).
// Default: 10 minutes
AccessTokenLifetime Duration `` /* 160-byte string literal not displayed */
// RefreshTokenLifetime is how long refresh tokens are valid.
// Default: 7 days
RefreshTokenLifetime Duration `` /* 158-byte string literal not displayed */
// RefreshTokenAbsoluteLifetime bounds a refresh-token family: rotation
// issues a new refresh token on every use, but never past this long
// after the original grant. After it the user must sign in again.
// Default: 30 days. Must be at least RefreshTokenLifetime.
RefreshTokenAbsoluteLifetime Duration `` /* 208-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 UserInfoInput ¶ added in v0.12.0
type UserInfoInput struct {
Authorization string `header:"Authorization" doc:"Bearer access token granted the openid scope"`
}
UserInfoInput documents the UserInfo request for OpenAPI.
type UserInfoOutput ¶ added in v0.12.0
UserInfoOutput documents the UserInfo response for OpenAPI.
Source Files
¶
- backchannel.go
- client.go
- config.go
- config_loader.go
- consent_store.go
- cookie_session.go
- errors.go
- federation.go
- federation_handlers.go
- fosite_session.go
- handler_access_changes.go
- handler_discovery.go
- handler_fosite.go
- handler_health.go
- handler_userinfo.go
- human_principal.go
- introspection_auth.go
- login_token_exchange.go
- orgs_claim.go
- principal_status.go
- provider.go
- provider_auth.go
- provider_identity.go
- provider_oauth.go
- providers.go
- server.go
- session.go
- signing_key.go
- social_consent.go
- social_directory.go
- social_directory_ent.go
- social_login.go
- social_logout.go
- social_redirect.go
- social_store_ent.go
- storage.go
- storage_ent.go
- storage_ent_human.go
- storage_memory.go
- types_oauth.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package schema provides the embedded JSON Schema for SystemAuth configuration.
|
Package schema provides the embedded JSON Schema for SystemAuth configuration. |
|
Package storetest is a conformance suite for SystemAuth social login stores.
|
Package storetest is a conformance suite for SystemAuth social login stores. |