auth

package
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 73 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxOpenConns    = 5
	DefaultMaxIdleConns    = 3
	DefaultConnMaxLifetime = 15 * time.Minute
)

Database connection pool defaults.

View Source
const APIKeyPrefix = "tak_"

APIKeyPrefix marks turna auth api keys.

View Source
const DefaultPrefixPath = "/auth"

Variables

View Source
var DefaultCachePollInterval = 5 * time.Second
View Source
var DefaultLDAPSyncDuration = 10 * time.Minute
View Source
var ErrNotFound = errors.New("not found")

Functions

This section is empty.

Types

type APIKeyCreateRequest added in v0.9.0

type APIKeyCreateRequest struct {
	// UserID owns the key. Empty keeps the legacy X-User self-service behavior.
	UserID string `json:"user_id"`
	// Name is a user-facing label for the key.
	Name string `json:"name"`
	// ExpiresIn is a duration string (e.g. "720h", "30d"); empty means no expiry
	// unless the api_key setting enforces a max lifetime.
	ExpiresIn     string         `json:"expires_in"`
	RoleIDs       *[]string      `json:"role_ids"`
	PermissionIDs *[]string      `json:"permission_ids"`
	Details       map[string]any `json:"details"`
	Disabled      bool           `json:"disabled"`
}

type APIKeyCreateResponse added in v0.9.0

type APIKeyCreateResponse struct {
	ID string `json:"id"`
	// Key is shown exactly once; only its hash is stored.
	Key       string `json:"key"`
	ExpiresAt string `json:"expires_at,omitempty"`
}

type APIKeyMeta added in v0.9.0

type APIKeyMeta struct {
	ID            string         `json:"id"`
	UserID        string         `json:"user_id"`
	Name          string         `json:"name"`
	RoleIDs       []string       `json:"role_ids"`
	PermissionIDs []string       `json:"permission_ids"`
	Details       map[string]any `json:"details,omitempty"`
	Disabled      bool           `json:"disabled"`
	Revision      int64          `json:"revision"`
	ExpiresAt     string         `json:"expires_at,omitempty"`
	CreatedAt     string         `json:"created_at"`
	UpdatedAt     string         `json:"updated_at"`
	LastUsedAt    string         `json:"last_used_at,omitempty"`
}

APIKeyMeta is the listing shape for stored api keys; the key itself is only returned once at creation time.

type APIKeySettings added in v0.9.0

type APIKeySettings struct {
	// Disabled turns off api key creation and validation.
	Disabled bool `json:"disabled"`
	// MaxLifetime caps the expiry of newly created keys (duration string).
	// Empty means keys may live forever.
	MaxLifetime string `json:"max_lifetime"`
	// contains filtered or unexported fields
}

APIKeySettings is the decoded "api_key" setting namespace.

func (APIKeySettings) GetMaxLifetime added in v0.9.0

func (a APIKeySettings) GetMaxLifetime() time.Duration

type APIKeyUpdate added in v0.9.0

type APIKeyUpdate struct {
	Name          *string
	RoleIDs       *[]string
	PermissionIDs *[]string
	Details       *map[string]any
	Disabled      *bool
}

type APIKeyUpdateRequest added in v0.9.0

type APIKeyUpdateRequest struct {
	Name          *string         `json:"name"`
	RoleIDs       *[]string       `json:"role_ids"`
	PermissionIDs *[]string       `json:"permission_ids"`
	Details       *map[string]any `json:"details"`
	Disabled      *bool           `json:"disabled"`
}

type AccessClient added in v0.9.0

type AccessClient struct {
	ClientSecret  string   `json:"client_secret"`
	Scope         []string `json:"scope"`
	WhitelistURLs []string `json:"whitelist_urls"`
	// RolesClaim overrides the global token roles_claim dot path for tokens
	// issued to this client. Empty falls back to TokenSettings.GetRolesClaim().
	RolesClaim string `json:"roles_claim"`
}

AccessClient is the decoded OAuth client config stored in auth_oauth_clients.

type AccessTokenErrorResponse added in v0.9.0

type AccessTokenErrorResponse struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
	// contains filtered or unexported fields
}

func (AccessTokenErrorResponse) GetCode added in v0.9.0

func (e AccessTokenErrorResponse) GetCode() int

type AccessTokenRequest added in v0.9.0

type AccessTokenRequest struct {
	GrantType    string `form:"grant_type"    json:"grant_type"`
	Code         string `form:"code"          json:"code"`
	RedirectURI  string `form:"redirect_uri"  json:"redirect_uri"`
	ClientID     string `form:"client_id"     json:"client_id"`
	ClientSecret string `form:"client_secret" json:"client_secret"`
	RefreshToken string `form:"refresh_token" json:"refresh_token"`
	Username     string `form:"username"      json:"username"`
	Password     string `form:"password"      json:"password"`
	Scope        string `form:"scope"         json:"scope"`
	// TOTP second factor for the password grant.
	TOTP string `form:"totp" json:"totp"`
	// DeviceCode for the RFC 8628 device flow.
	DeviceCode string `form:"device_code" json:"device_code"`
	// SubjectToken/SubjectTokenType for RFC 8693 token exchange.
	SubjectToken     string `form:"subject_token"      json:"subject_token"`
	SubjectTokenType string `form:"subject_token_type" json:"subject_token_type"`
	// CodeVerifier for PKCE (RFC 7636) on the authorization_code grant.
	CodeVerifier string `form:"code_verifier" json:"code_verifier"`
}

type AccessTokenResponse added in v0.9.0

type AccessTokenResponse struct {
	TokenType             string `json:"token_type"`
	AccessToken           string `json:"access_token"`
	ExpiresIn             int64  `json:"expires_in"`
	RefreshToken          string `json:"refresh_token,omitempty"`
	RefreshTokenExpiresIn int64  `json:"refresh_expires_in,omitempty"`
	Scope                 string `json:"scope,omitempty"`
	// IDToken is issued when the granted scope contains "openid".
	IDToken string `json:"id_token,omitempty"`
	// IssuedTokenType is set for RFC 8693 token exchange responses.
	IssuedTokenType string `json:"issued_token_type,omitempty"`
}

type AdminSettings added in v0.9.0

type AdminSettings struct {
	// Permission is matched against permission id or name on the X-User.
	Permission string `json:"permission"`
	// AdminPermission is accepted as a legacy/explicit alias for Permission.
	AdminPermission string `json:"admin_permission,omitempty"`
	// AllowMissingXUser allows break-glass admin access when the session chain
	// is removed and no X-User header is present. Default true.
	AllowMissingXUser *bool `json:"allow_missing_x_user"`
}

AdminSettings controls access to auth management APIs/UI. Empty permission keeps bootstrap compatibility: authenticated users, and break-glass requests without X-User, are treated as admin.

func (AdminSettings) GetAllowMissingXUser added in v0.9.0

func (a AdminSettings) GetAllowMissingXUser() bool

func (AdminSettings) GetPermission added in v0.9.0

func (a AdminSettings) GetPermission() string

type Auth

type Auth struct {
	PrefixPath string     `cfg:"prefix_path"`
	Database   Database   `cfg:"database"`
	Encryption Encryption `cfg:"encryption"`
	// contains filtered or unexported fields
}

Auth is a self-contained identity provider with its own UI. All runtime settings (oauth2, check, cache, token, providers, clients, ldap) live in PostgreSQL and are managed through the API/UI. The static configuration is only what is needed to reach that database: encryption key, database connection and migration settings.

func (*Auth) APIAuth added in v0.9.0

func (m *Auth) APIAuth(w http.ResponseWriter, r *http.Request)

APIAuth starts the authorization code flow against an upstream provider.

func (*Auth) APICerts added in v0.9.0

func (m *Auth) APICerts(w http.ResponseWriter, r *http.Request)

APICerts returns the JWKS document.

func (*Auth) APICodeAuth added in v0.9.0

func (m *Auth) APICodeAuth(w http.ResponseWriter, r *http.Request)

APICodeAuth handles the upstream provider callback and issues a local code.

func (*Auth) APIDeviceAuthorization added in v0.9.0

func (m *Auth) APIDeviceAuthorization(w http.ResponseWriter, r *http.Request)

APIDeviceAuthorization implements the RFC 8628 device authorization endpoint.

func (*Auth) APIEmailCode added in v0.9.0

func (m *Auth) APIEmailCode(w http.ResponseWriter, r *http.Request)

APIEmailCode sends a one-time login code (and magic link) to the user's email. The response is always 200 to avoid account enumeration.

func (*Auth) APIKeyAuthAPI added in v0.9.0

func (m *Auth) APIKeyAuthAPI(w http.ResponseWriter, r *http.Request)

APIKeyAuthAPI validates a raw static api key and returns identity claims for its principal. The key comes from the X-API-Key header (or the api_key form/query value). This is the remote counterpart of session's in-process auth_middleware validation; no JWT is issued.

func (*Auth) APIKeyData added in v0.9.0

func (m *Auth) APIKeyData(ctx context.Context, key string) ([]byte, error)

APIKeyData validates a raw static api key against the database and returns claim-shaped identity JSON for the key principal. It implements session.InfAPIKey; the session middleware calls it on every request that carries the api key header, so revocation is immediate.

func (*Auth) APIPasskeyToken added in v0.9.0

func (m *Auth) APIPasskeyToken(w http.ResponseWriter, r *http.Request)

APIPasskeyToken begins/finishes passkey login and issues tokens. Finish responses use the same shape as the token endpoint.

func (*Auth) APIPasswordReset added in v0.9.0

func (m *Auth) APIPasswordReset(w http.ResponseWriter, r *http.Request)

APIPasswordReset sends a password reset code/magic link. The response is always 200 to avoid account enumeration.

func (*Auth) APIPasswordResetConfirm added in v0.9.0

func (m *Auth) APIPasswordResetConfirm(w http.ResponseWriter, r *http.Request)

APIPasswordResetConfirm sets a new password with a valid reset code.

func (*Auth) APISignup added in v0.9.0

func (m *Auth) APISignup(w http.ResponseWriter, r *http.Request)

APISignup registers a new local user. With email verification enabled the account is created only after /oauth2/signup/verify; the response is always generic to avoid account enumeration. Without verification the user is created immediately and duplicate addresses answer 409.

func (*Auth) APISignupVerify added in v0.9.0

func (m *Auth) APISignupVerify(w http.ResponseWriter, r *http.Request)

APISignupVerify finishes email verification and creates the account.

func (*Auth) APIToken added in v0.9.0

func (m *Auth) APIToken(w http.ResponseWriter, r *http.Request)

APIToken implements the token endpoint.

func (*Auth) APIUserInfo added in v0.9.0

func (m *Auth) APIUserInfo(w http.ResponseWriter, r *http.Request)

APIUserInfo returns claims for a bearer access token.

func (*Auth) APIWellKnown added in v0.9.0

func (m *Auth) APIWellKnown(w http.ResponseWriter, r *http.Request)

APIWellKnown returns the OpenID configuration for this issuer.

func (*Auth) AccessServiceAccountAPI added in v0.9.0

func (m *Auth) AccessServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) AccessUserAPI added in v0.9.0

func (m *Auth) AccessUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CapabilitiesAPI added in v0.9.0

func (m *Auth) CapabilitiesAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CheckAPI added in v0.9.0

func (m *Auth) CheckAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CheckUserAPI added in v0.9.0

func (m *Auth) CheckUserAPI(w http.ResponseWriter, r *http.Request)

CheckUserAPI checks the X-User header identity against the request body.

func (*Auth) CreateAPIKeyAPI added in v0.9.0

func (m *Auth) CreateAPIKeyAPI(w http.ResponseWriter, r *http.Request)

CreateAPIKeyAPI creates an api key for the authenticated X-User.

func (*Auth) CreateAPIKeyPrincipalAPI added in v0.9.0

func (m *Auth) CreateAPIKeyPrincipalAPI(w http.ResponseWriter, r *http.Request)

CreateAPIKeyPrincipalAPI creates an api key for the requested owner.

func (*Auth) CreateLMapAPI added in v0.9.0

func (m *Auth) CreateLMapAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CreatePermissionAPI added in v0.9.0

func (m *Auth) CreatePermissionAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CreatePermissionBulkAPI added in v0.9.0

func (m *Auth) CreatePermissionBulkAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CreateRoleAPI added in v0.9.0

func (m *Auth) CreateRoleAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CreateServiceAccountAPI added in v0.9.0

func (m *Auth) CreateServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CreateUserAPI added in v0.9.0

func (m *Auth) CreateUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) CustomInfoPreviewAPI added in v0.9.0

func (m *Auth) CustomInfoPreviewAPI(w http.ResponseWriter, r *http.Request)

CustomInfoPreviewAPI applies an inline custom_info set to sample claims and returns the resulting claims, mirroring the templating in APIUserInfo (add, overwrite, or remove on empty render).

func (*Auth) DashboardAPI added in v0.9.0

func (m *Auth) DashboardAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteAPIKeyAPI added in v0.9.0

func (m *Auth) DeleteAPIKeyAPI(w http.ResponseWriter, r *http.Request)

DeleteAPIKeyAPI deletes an api key owned by the authenticated X-User.

func (*Auth) DeleteAPIKeyPrincipalAPI added in v0.9.0

func (m *Auth) DeleteAPIKeyPrincipalAPI(w http.ResponseWriter, r *http.Request)

DeleteAPIKeyPrincipalAPI deletes an api key without X-User ownership scoping.

func (*Auth) DeleteLDAPConfig added in v0.9.0

func (m *Auth) DeleteLDAPConfig(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteLMapAPI added in v0.9.0

func (m *Auth) DeleteLMapAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteOAuthClient added in v0.9.0

func (m *Auth) DeleteOAuthClient(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteOAuthProvider added in v0.9.0

func (m *Auth) DeleteOAuthProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) DeletePermissionAPI added in v0.9.0

func (m *Auth) DeletePermissionAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteRoleAPI added in v0.9.0

func (m *Auth) DeleteRoleAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteSAMLProvider added in v0.9.0

func (m *Auth) DeleteSAMLProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteServiceAccountAPI added in v0.9.0

func (m *Auth) DeleteServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteSetting added in v0.9.0

func (m *Auth) DeleteSetting(w http.ResponseWriter, r *http.Request)

func (*Auth) DeleteUserAPI added in v0.9.0

func (m *Auth) DeleteUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) DeviceApproveAPI added in v0.9.0

func (m *Auth) DeviceApproveAPI(w http.ResponseWriter, r *http.Request)

DeviceApproveAPI approves or denies a device login as the X-User.

func (*Auth) DeviceInfoAPI added in v0.9.0

func (m *Auth) DeviceInfoAPI(w http.ResponseWriter, r *http.Request)

DeviceInfoAPI shows the pending device request for consent display.

func (*Auth) EmailPreviewAPI added in v0.9.0

func (m *Auth) EmailPreviewAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) ExportPermissionsAPI added in v0.9.0

func (m *Auth) ExportPermissionsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) ExportRolesAPI added in v0.9.0

func (m *Auth) ExportRolesAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) ExportServiceAccountsAPI added in v0.9.0

func (m *Auth) ExportServiceAccountsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) ExportUsersAPI added in v0.9.0

func (m *Auth) ExportUsersAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetAccessClient added in v0.9.0

func (m *Auth) GetAccessClient(clientID, clientSecret string) (*AccessClient, error)

GetAccessClient resolves the OAuth client; configured clients first, IAM service accounts as fallback.

func (*Auth) GetLDAPConfig added in v0.9.0

func (m *Auth) GetLDAPConfig(w http.ResponseWriter, r *http.Request)

func (*Auth) GetLMapAPI added in v0.9.0

func (m *Auth) GetLMapAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetLMapsAPI added in v0.9.0

func (m *Auth) GetLMapsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetOAuthClient added in v0.9.0

func (m *Auth) GetOAuthClient(w http.ResponseWriter, r *http.Request)

func (*Auth) GetOAuthProvider added in v0.9.0

func (m *Auth) GetOAuthProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) GetOrCreateUser added in v0.9.0

func (m *Auth) GetOrCreateUser(ctx context.Context, req data.GetUserRequest) (*data.UserExtended, error)

GetOrCreateUser returns the user, attempting an LDAP sync when missing.

func (*Auth) GetPermissionAPI added in v0.9.0

func (m *Auth) GetPermissionAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetPermissionsAPI added in v0.9.0

func (m *Auth) GetPermissionsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetRoleAPI added in v0.9.0

func (m *Auth) GetRoleAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetRoleRelationAPI added in v0.9.0

func (m *Auth) GetRoleRelationAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetRolesAPI added in v0.9.0

func (m *Auth) GetRolesAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetSAMLProvider added in v0.9.0

func (m *Auth) GetSAMLProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) GetServiceAccountAPI added in v0.9.0

func (m *Auth) GetServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetServiceAccountsAPI added in v0.9.0

func (m *Auth) GetServiceAccountsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetSetting added in v0.9.0

func (m *Auth) GetSetting(w http.ResponseWriter, r *http.Request)

func (*Auth) GetUserAPI added in v0.9.0

func (m *Auth) GetUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) GetUsersAPI added in v0.9.0

func (m *Auth) GetUsersAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) Info added in v0.9.0

func (m *Auth) Info(w http.ResponseWriter, r *http.Request)

func (*Auth) IssueToken added in v0.9.0

func (m *Auth) IssueToken(ctx context.Context, form url.Values) ([]byte, int, error)

IssueToken runs the OAuth2 token endpoint in-process and returns the raw JSON body with its status code. It implements session.InfIssuer.

func (*Auth) KeepPermissionBulkAPI added in v0.9.0

func (m *Auth) KeepPermissionBulkAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) Keyfunc added in v0.9.0

func (m *Auth) Keyfunc(token *jwt.Token) (any, error)

Keyfunc returns the public key for access tokens signed by this middleware. It implements session.InfIssuer so session providers can validate tokens in-process with `auth_middleware: <name>`.

func (*Auth) LdapCheckPassword added in v0.9.0

func (m *Auth) LdapCheckPassword(username, password string) (bool, error)

func (*Auth) LdapGetGroupsAPI added in v0.9.0

func (m *Auth) LdapGetGroupsAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) LdapGetUserAPI added in v0.9.0

func (m *Auth) LdapGetUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) LdapSync added in v0.9.0

func (m *Auth) LdapSync(ctx context.Context, force bool, uid string) error

LdapSync syncs LDAP groups and users into the store. When uid is set, only that user is synced.

func (*Auth) LdapSyncAPI added in v0.9.0

func (m *Auth) LdapSyncAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) LdapSyncUIDAPI added in v0.9.0

func (m *Auth) LdapSyncUIDAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) ListAPIKeyPrincipalsAPI added in v0.9.0

func (m *Auth) ListAPIKeyPrincipalsAPI(w http.ResponseWriter, r *http.Request)

ListAPIKeyPrincipalsAPI lists api key principals across owners.

func (*Auth) ListAPIKeysAPI added in v0.9.0

func (m *Auth) ListAPIKeysAPI(w http.ResponseWriter, r *http.Request)

ListAPIKeysAPI lists api keys of the authenticated X-User.

func (*Auth) ListLDAPConfigs added in v0.9.0

func (m *Auth) ListLDAPConfigs(w http.ResponseWriter, r *http.Request)

func (*Auth) ListOAuthClients added in v0.9.0

func (m *Auth) ListOAuthClients(w http.ResponseWriter, r *http.Request)

func (*Auth) ListOAuthProviders added in v0.9.0

func (m *Auth) ListOAuthProviders(w http.ResponseWriter, r *http.Request)

func (*Auth) ListSAMLProviders added in v0.9.0

func (m *Auth) ListSAMLProviders(w http.ResponseWriter, r *http.Request)

func (*Auth) ListSettings added in v0.9.0

func (m *Auth) ListSettings(w http.ResponseWriter, r *http.Request)

func (*Auth) MeAPI added in v0.9.0

func (m *Auth) MeAPI(w http.ResponseWriter, r *http.Request)

MeAPI returns the authenticated user's profile, roles, permissions and security material overview.

func (*Auth) MePasswordAPI added in v0.9.0

func (m *Auth) MePasswordAPI(w http.ResponseWriter, r *http.Request)

MePasswordAPI changes the password of the authenticated local user. The current password must be provided and verified.

func (*Auth) Middleware

func (m *Auth) Middleware(ctx context.Context, name string) (func(http.Handler) http.Handler, error)

func (*Auth) MuxSet added in v0.9.0

func (m *Auth) MuxSet(prefix string) *ada.Mux

func (*Auth) PasskeyCredentialDeleteAPI added in v0.9.0

func (m *Auth) PasskeyCredentialDeleteAPI(w http.ResponseWriter, r *http.Request)

PasskeyCredentialDeleteAPI removes a stored passkey credential.

func (*Auth) PasskeyCredentialsAPI added in v0.9.0

func (m *Auth) PasskeyCredentialsAPI(w http.ResponseWriter, r *http.Request)

PasskeyCredentialsAPI lists own passkeys. Querying another user_id requires admin capability.

func (*Auth) PasskeyRegisterAPI added in v0.9.0

func (m *Auth) PasskeyRegisterAPI(w http.ResponseWriter, r *http.Request)

PasskeyRegisterAPI begins/finishes passkey registration. Without user_id it targets the X-User identity (self-service); with user_id it registers for that user and requires admin capability.

func (*Auth) PasskeyToken added in v0.9.0

func (m *Auth) PasskeyToken(ctx context.Context, orig *http.Request, body []byte) ([]byte, int, error)

PasskeyToken runs the passkey login endpoint in-process. It implements session.InfPasskey so the login middleware can proxy WebAuthn ceremonies. The original request carries host/scheme used to derive the relying party.

func (*Auth) PatchPermissionAPI added in v0.9.0

func (m *Auth) PatchPermissionAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PatchRoleAPI added in v0.9.0

func (m *Auth) PatchRoleAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PatchServiceAccountAPI added in v0.9.0

func (m *Auth) PatchServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PatchUserAPI added in v0.9.0

func (m *Auth) PatchUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutLDAPConfig added in v0.9.0

func (m *Auth) PutLDAPConfig(w http.ResponseWriter, r *http.Request)

func (*Auth) PutLMapAPI added in v0.9.0

func (m *Auth) PutLMapAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutOAuthClient added in v0.9.0

func (m *Auth) PutOAuthClient(w http.ResponseWriter, r *http.Request)

func (*Auth) PutOAuthProvider added in v0.9.0

func (m *Auth) PutOAuthProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) PutPermissionAPI added in v0.9.0

func (m *Auth) PutPermissionAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutRoleAPI added in v0.9.0

func (m *Auth) PutRoleAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutRoleRelationAPI added in v0.9.0

func (m *Auth) PutRoleRelationAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutSAMLProvider added in v0.9.0

func (m *Auth) PutSAMLProvider(w http.ResponseWriter, r *http.Request)

func (*Auth) PutServiceAccountAPI added in v0.9.0

func (m *Auth) PutServiceAccountAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) PutSetting added in v0.9.0

func (m *Auth) PutSetting(w http.ResponseWriter, r *http.Request)

func (*Auth) PutUserAPI added in v0.9.0

func (m *Auth) PutUserAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) RotateEncryptionAPI added in v0.9.0

func (m *Auth) RotateEncryptionAPI(w http.ResponseWriter, r *http.Request)

RotateEncryptionAPI re-encrypts every encrypted column with a new key, swaps the live cipher, and refreshes the startup canary. The new key MUST be set in the static config (encryption.key) before the next restart, otherwise the startup canary check fails.

func (*Auth) RotateJWTAPI added in v0.9.0

func (m *Auth) RotateJWTAPI(w http.ResponseWriter, r *http.Request)

RotateJWTAPI generates a fresh RSA signing key and applies it immediately. Outstanding access and refresh tokens become invalid.

func (*Auth) SAMLACS added in v0.9.0

func (m *Auth) SAMLACS(w http.ResponseWriter, r *http.Request)

SAMLACS handles the IdP assertion callback and issues a local code.

func (*Auth) SAMLLogin added in v0.9.0

func (m *Auth) SAMLLogin(w http.ResponseWriter, r *http.Request)

SAMLLogin starts a SAML login against the IdP; on success the user is redirected back to redirect_uri with a local authorization code.

func (*Auth) SAMLMetadata added in v0.9.0

func (m *Auth) SAMLMetadata(w http.ResponseWriter, r *http.Request)

SAMLMetadata serves the SP metadata document for a provider.

func (*Auth) SignupAction added in v0.9.0

func (m *Auth) SignupAction(ctx context.Context, action string, body []byte) ([]byte, int, error)

SignupAction runs a signup/password-reset request in-process for login middlewares backed by auth_middleware; body is the JSON request payload.

func (*Auth) SignupFeatures added in v0.9.0

func (m *Auth) SignupFeatures() session.SignupFeatures

SignupFeatures reports which self-service flows are currently enabled so the login page can show/hide signup and forgot-password live.

func (*Auth) SwaggerDocAPI added in v0.9.0

func (m *Auth) SwaggerDocAPI(w http.ResponseWriter, _ *http.Request)

SwaggerDocAPI serves the embedded OpenAPI document with basePath set to the configured prefix path.

func (*Auth) SwaggerUIHandler added in v0.9.0

func (m *Auth) SwaggerUIHandler() http.HandlerFunc

SwaggerUIHandler returns the swagger UI page configured to load the embedded OpenAPI document.

func (*Auth) SyncAPI added in v0.9.0

func (m *Auth) SyncAPI(w http.ResponseWriter, r *http.Request)

func (*Auth) TOTPConfirmAPI added in v0.9.0

func (m *Auth) TOTPConfirmAPI(w http.ResponseWriter, r *http.Request)

TOTPConfirmAPI verifies a code and activates totp for the X-User.

func (*Auth) TOTPDeleteAPI added in v0.9.0

func (m *Auth) TOTPDeleteAPI(w http.ResponseWriter, r *http.Request)

TOTPDeleteAPI removes the X-User's totp secret.

func (*Auth) TOTPRecoveryAPI added in v0.9.0

func (m *Auth) TOTPRecoveryAPI(w http.ResponseWriter, r *http.Request)

TOTPRecoveryAPI regenerates recovery codes; the old set becomes invalid.

func (*Auth) TOTPRegisterAPI added in v0.9.0

func (m *Auth) TOTPRegisterAPI(w http.ResponseWriter, r *http.Request)

TOTPRegisterAPI generates a fresh (unconfirmed) totp secret for the X-User.

func (*Auth) TOTPStatusAPI added in v0.9.0

func (m *Auth) TOTPStatusAPI(w http.ResponseWriter, r *http.Request)

TOTPStatusAPI reports whether the X-User has a confirmed totp secret.

func (*Auth) UIMiddleware added in v0.9.0

func (m *Auth) UIMiddleware() (func(http.Handler) http.Handler, error)

func (*Auth) UpdateAPIKeyAPI added in v0.9.0

func (m *Auth) UpdateAPIKeyAPI(w http.ResponseWriter, r *http.Request)

UpdateAPIKeyAPI updates api key principal metadata and access.

func (*Auth) UpdateAPIKeyPrincipalAPI added in v0.9.0

func (m *Auth) UpdateAPIKeyPrincipalAPI(w http.ResponseWriter, r *http.Request)

UpdateAPIKeyPrincipalAPI updates api key metadata without X-User ownership scoping.

func (*Auth) UserInfoAPI added in v0.9.0

func (m *Auth) UserInfoAPI(w http.ResponseWriter, r *http.Request)

UserInfoAPI returns identity info for the X-User header.

func (*Auth) VersionAPI added in v0.9.0

func (m *Auth) VersionAPI(w http.ResponseWriter, r *http.Request)

type Cache added in v0.9.0

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

Cache keeps the snapshot up to date with polling and explicit reloads.

func NewCache added in v0.9.0

func NewCache(store *Store) *Cache

func (*Cache) Check added in v0.9.0

func (c *Cache) Check(req data.CheckRequest) (*data.CheckResponse, error)

func (*Cache) Dashboard added in v0.9.0

func (c *Cache) Dashboard() (*data.Dashboard, error)

func (*Cache) GetLMap added in v0.9.0

func (c *Cache) GetLMap(name string) (*data.LMap, error)

func (*Cache) GetLMaps added in v0.9.0

func (c *Cache) GetLMaps(req data.GetLMapRequest) (*data.Response[[]data.LMap], error)

func (*Cache) GetPermission added in v0.9.0

func (c *Cache) GetPermission(req data.GetPermissionRequest) (*data.PermissionExtended, error)

func (*Cache) GetPermissions added in v0.9.0

func (c *Cache) GetPermissions(req data.GetPermissionRequest) (*data.Response[[]data.PermissionExtended], error)

func (*Cache) GetRole added in v0.9.0

func (c *Cache) GetRole(req data.GetRoleRequest) (*data.RoleExtended, error)

func (*Cache) GetRoles added in v0.9.0

func (c *Cache) GetRoles(req data.GetRoleRequest) (*data.Response[[]data.RoleExtended], error)

func (*Cache) GetUser added in v0.9.0

func (c *Cache) GetUser(req data.GetUserRequest) (*data.UserExtended, error)

func (*Cache) GetUsers added in v0.9.0

func (c *Cache) GetUsers(req data.GetUserRequest) (*data.Response[[]data.UserExtended], error)

func (*Cache) Reload added in v0.9.0

func (c *Cache) Reload(ctx context.Context) error

func (*Cache) Snapshot added in v0.9.0

func (c *Cache) Snapshot() *Snapshot

func (*Cache) Watch added in v0.9.0

func (c *Cache) Watch(ctx context.Context)

Watch polls the auth version and reloads the snapshot when it changes. The poll interval comes from the "cache" setting namespace and is applied live.

type CacheSettings added in v0.9.0

type CacheSettings struct {
	// PollInterval for version polling between instances. Default 5s.
	PollInterval string `json:"poll_interval"`
	// CodeStore configures the temporary OAuth2 code/state cache. Default memory.
	CodeStore CodeStoreSettings `json:"code_store"`
	// contains filtered or unexported fields
}

CacheSettings is the decoded "cache" setting namespace.

func (CacheSettings) GetPollInterval added in v0.9.0

func (c CacheSettings) GetPollInterval() time.Duration

type CapabilitiesResponse added in v0.9.0

type CapabilitiesResponse struct {
	IsAdmin                   bool   `json:"is_admin"`
	AnonymousAdmin            bool   `json:"anonymous_admin"`
	BootstrapAdmin            bool   `json:"bootstrap_admin"`
	SelfService               bool   `json:"self_service"`
	AdminPermission           string `json:"admin_permission"`
	AdminPermissionConfigured bool   `json:"admin_permission_configured"`
	AllowMissingXUser         bool   `json:"allow_missing_x_user"`
	XUser                     string `json:"x_user,omitempty"`
	AuthorizationError        string `json:"authorization_error,omitempty"`
}

type CheckSettings added in v0.9.0

type CheckSettings struct {
	// DefaultHosts used when a permission resource has no hosts.
	DefaultHosts []string `json:"default_hosts"`
	// NoHostCheck disables host checking on permission resources.
	NoHostCheck bool `json:"no_host_check"`
}

CheckSettings is the decoded "check" setting namespace.

func (CheckSettings) Config added in v0.9.0

func (c CheckSettings) Config() data.CheckConfig

type Cipher added in v0.9.0

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

Cipher seals and opens values with AES-GCM. The active key can be swapped at runtime via Rekey; the *Cipher pointer stays stable so holders (Store, Auth) never need to be re-wired.

func NewCipher added in v0.9.0

func NewCipher(key string) (*Cipher, error)

func (*Cipher) DecryptString added in v0.9.0

func (c *Cipher) DecryptString(value string) (string, error)

func (*Cipher) EncryptString added in v0.9.0

func (c *Cipher) EncryptString(plain string) (string, error)

func (*Cipher) Rekey added in v0.9.0

func (c *Cipher) Rekey(key string) error

Rekey atomically swaps the active key. In-flight calls keep using the AEAD snapshot they already loaded; subsequent calls use the new key.

type ClaimMapping added in v0.9.0

type ClaimMapping struct {
	// RolesClaim is the claim/attribute holding group or role values.
	// OAuth2 supports dot paths into nested claims (e.g. "realm_access.roles",
	// "groups"); SAML matches the attribute name or friendly name.
	RolesClaim string `json:"roles_claim"`
	// UseLMap resolves claim values through the LDAP group maps (lmaps),
	// sharing one group->role model across LDAP, OAuth2 and SAML.
	UseLMap bool `json:"use_lmap"`
	// RoleMap maps a claim value directly to role names or role IDs.
	RoleMap map[string][]string `json:"role_map"`
	// Register creates unknown users on first login (non-local, like LDAP).
	Register bool `json:"register"`
}

ClaimMapping maps upstream identity claims (OAuth2/OIDC) or assertion attributes (SAML) onto local users, mirroring the LDAP sync model.

type CodeStoreRedisSettings added in v0.9.0

type CodeStoreRedisSettings struct {
	ClientName string                    `json:"client_name"`
	Address    []string                  `json:"address"`
	Username   string                    `json:"username"`
	Password   string                    `json:"password"`
	TLS        CodeStoreRedisTLSSettings `json:"tls"`
}

type CodeStoreRedisTLSSettings added in v0.9.0

type CodeStoreRedisTLSSettings struct {
	Enabled  bool   `json:"enabled"`
	CertFile string `json:"cert_file"`
	KeyFile  string `json:"key_file"`
	CAFile   string `json:"ca_file"`
}

type CodeStoreSettings added in v0.9.0

type CodeStoreSettings struct {
	// Active is "memory" or "redis". Empty keeps the in-process memory store.
	Active string                 `json:"active"`
	Redis  CodeStoreRedisSettings `json:"redis"`
}

CodeStoreSettings configures the temporary OAuth2 code/state cache.

type ConfigMeta added in v0.9.0

type ConfigMeta struct {
	ID        string     `json:"id"`
	Enabled   bool       `json:"enabled"`
	UpdatedAt types.Time `json:"updated_at"`
	UpdatedBy string     `json:"updated_by"`
}

type ConfigRequest added in v0.9.0

type ConfigRequest struct {
	Enabled *bool           `json:"enabled"`
	Config  json.RawMessage `json:"config"`
}

type ConfigResource added in v0.9.0

type ConfigResource struct {
	ID        string        `json:"id"`
	Enabled   bool          `json:"enabled"`
	Config    types.RawJSON `json:"config"`
	UpdatedAt types.Time    `json:"updated_at"`
	UpdatedBy string        `json:"updated_by"`
}

type CustomInfoSet added in v0.9.0

type CustomInfoSet struct {
	// Claims maps an output claim name to a mugo/Go template string. Templates
	// receive {"claims": <base claims>, "user": <full user record>} as data.
	Claims map[string]string `json:"claims"`
}

CustomInfoSet is a single named group of userinfo claim templates.

type CustomInfoSettings added in v0.9.0

type CustomInfoSettings struct {
	// Disabled turns off custom userinfo templating entirely.
	Disabled bool `json:"disabled"`
	// Sets maps a custom name (the {custom} path value) to its claim templates.
	Sets map[string]CustomInfoSet `json:"sets"`
}

CustomInfoSettings is the decoded "custom_info" setting namespace. Each named set maps an output claim name to a mugo/Go template rendered against the user's base claims and full profile. A template whose key is not already a claim ADDS a new claim; an existing key OVERWRITES it. The set is selected by the {custom} path segment of /oauth2/userinfo/{custom}.

type Database added in v0.9.0

type Database struct {
	DSN string `cfg:"dsn" log:"-"`

	// MaxOpenConns default 5; negative for unlimited.
	MaxOpenConns int `cfg:"max_open_conns"`
	// MaxIdleConns default 3; negative for none.
	MaxIdleConns int `cfg:"max_idle_conns"`
	// ConnMaxLifetime default 15m; negative for unlimited.
	ConnMaxLifetime time.Duration `cfg:"conn_max_lifetime"`
	ConnMaxIdleTime time.Duration `cfg:"conn_max_idle_time"`

	Migration Migration `cfg:"migration"`
}

type DeviceApproveRequest added in v0.9.0

type DeviceApproveRequest struct {
	UserCode string `json:"user_code"`
	// Action is "approve" (default) or "deny".
	Action string `json:"action"`
}

type DeviceAuthorizationResponse added in v0.9.0

type DeviceAuthorizationResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete"`
	ExpiresIn               int64  `json:"expires_in"`
	Interval                int    `json:"interval"`
}

type DeviceSettings added in v0.9.0

type DeviceSettings struct {
	// Disabled turns off the device authorization flow.
	Disabled bool `json:"disabled"`
	// CodeLifetime of device/user codes. Default 10m.
	CodeLifetime string `json:"code_lifetime"`
	// Interval minimum polling interval in seconds. Default 5.
	Interval int `json:"interval"`
	// VerificationURI shown to the user. Default <prefix>/ui/device.
	VerificationURI string `json:"verification_uri"`
	// contains filtered or unexported fields
}

DeviceSettings is the decoded "device" setting namespace (RFC 8628).

func (DeviceSettings) GetCodeLifetime added in v0.9.0

func (d DeviceSettings) GetCodeLifetime() time.Duration

func (DeviceSettings) GetInterval added in v0.9.0

func (d DeviceSettings) GetInterval() int

type EmailSettings added in v0.9.0

type EmailSettings struct {
	// Disabled turns off the one-time code email login even when smtp is
	// configured. The magic link is controlled separately by MagicLink.
	Disabled bool `json:"disabled"`
	// MagicLink enables the magic-link login mail when a redirect_uri is
	// provided and allowed by the client whitelist. Default true.
	MagicLink *bool `json:"magic_link"`
	// From address; defaults to the smtp username.
	From string `json:"from"`
	// Subject of the one-time code mail (Go text/template).
	// Default "Your login code".
	Subject string `json:"subject"`
	// BodyTemplate is the Go text/template body of the one-time code mail.
	// Empty uses the built-in code template.
	BodyTemplate string `json:"body_template"`
	// MagicLinkSubject is the subject of the magic-link mail (Go text/template).
	// Empty uses the built-in default.
	MagicLinkSubject string `json:"magic_link_subject"`
	// MagicLinkBodyTemplate is the Go text/template body of the magic-link
	// mail. Empty uses the built-in magic-link template.
	MagicLinkBodyTemplate string `json:"magic_link_body_template"`
	// CodeLifetime of login codes. Default 15m.
	CodeLifetime string       `json:"code_lifetime"`
	SMTP         SMTPSettings `json:"smtp"`
	// contains filtered or unexported fields
}

EmailSettings is the decoded "email" setting namespace. It controls two independent passwordless flows: the one-time code mail and the magic-link mail. Each has its own enable flag and Go text/template subject + body.

func (EmailSettings) GetCodeLifetime added in v0.9.0

func (e EmailSettings) GetCodeLifetime() time.Duration
func (e EmailSettings) GetMagicLink() bool

type EmailTemplateData added in v0.9.0

type EmailTemplateData struct {
	Email       string   `json:"email"`
	Name        string   `json:"name"`
	Code        string   `json:"code"`
	MagicLink   string   `json:"magic_link"`
	ExpiresIn   string   `json:"expires_in"`
	ClientID    string   `json:"client_id"`
	RedirectURI string   `json:"redirect_uri"`
	UserID      string   `json:"user_id"`
	UserAlias   []string `json:"user_alias"`
}

type Encryption added in v0.9.0

type Encryption struct {
	Key string `cfg:"key" log:"-"`
}

type JWK added in v0.9.0

type JWK struct {
	KID string   `json:"kid"`
	KTY string   `json:"kty"`
	ALG string   `json:"alg"`
	Use string   `json:"use"`
	N   string   `json:"n"`
	E   string   `json:"e"`
	X5C []string `json:"x5c,omitempty"`
}

type JWKSResponse added in v0.9.0

type JWKSResponse struct {
	Keys []JWK `json:"keys"`
}

type LDAPSettings added in v0.9.0

type LDAPSettings struct {
	Addr string `json:"addr"`
	Bind struct {
		Username string `json:"username"`
		Password string `json:"password"`
	} `json:"bind"`
	UserBaseDN string `json:"user_base_dn"`
	Groups     []struct {
		BaseDN     string   `json:"base_dn"`
		Filter     string   `json:"filter"`
		Attributes []string `json:"attributes"`
	} `json:"groups"`
	SyncDuration string `json:"sync_duration"`
	DisableSync  bool   `json:"disable_sync"`
}

LDAPSettings is the decoded LDAP config stored in auth_ldap_configs.

type LdapSyncRequest added in v0.9.0

type LdapSyncRequest struct {
	Force bool `json:"force"`
}

type MTLSSettings added in v0.9.0

type MTLSSettings struct {
	// Enabled allows certificate based client authentication.
	Enabled bool `json:"enabled"`
	// CertHeader is a trusted header carrying the client certificate set
	// by a TLS-terminating proxy (e.g. "ssl-client-cert" from nginx with
	// $ssl_client_escaped_cert). Only set this behind a trusted proxy.
	CertHeader string `json:"cert_header"`
}

MTLSSettings is the decoded "mtls" setting namespace (RFC 8705 style).

type MePasswordRequest added in v0.9.0

type MePasswordRequest struct {
	CurrentPassword string `json:"current_password"`
	NewPassword     string `json:"new_password"`
}

type MeResponse added in v0.9.0

type MeResponse struct {
	ID          string         `json:"id"`
	Alias       []string       `json:"alias"`
	Details     map[string]any `json:"details"`
	Roles       []string       `json:"roles"`
	Permissions []string       `json:"permissions"`
	IsActive    bool           `json:"is_active"`
	// Local users manage their password here; non-local users authenticate
	// against LDAP or an upstream provider.
	Local bool `json:"local"`

	// security material overview
	TOTPEnabled  bool `json:"totp_enabled"`
	PasskeyCount int  `json:"passkey_count"`
	APIKeyCount  int  `json:"api_key_count"`
}

MeResponse is the self-service account overview for the X-User identity.

type Meta added in v0.9.0

type Meta struct {
	TotalItemCount uint64 `json:"total_item_count,omitempty"`
	Version        uint64 `json:"version,omitempty"`
}

type Migration added in v0.9.0

type Migration struct {
	// DSN used only for running migrations; defaults to database.dsn.
	// Set it to a user with DDL privileges when the runtime user has none.
	DSN string `cfg:"dsn" log:"-"`

	Disabled bool `cfg:"disabled"`

	// Values for muz template substitution inside migration files.
	Values map[string]string `cfg:"values"`

	Table   string `cfg:"table"`
	LockKey string `cfg:"lock_key"`
}

Migration runs the embedded SQL migrations on startup.

type OAuth2Settings added in v0.9.0

type OAuth2Settings struct {
	// BaseURL for redirect URLs. Default is the request host.
	BaseURL string `json:"base_url"`
	// Schema for redirect URLs when base_url is empty. Default https.
	Schema string `json:"schema"`

	InsecureSkipVerify bool `json:"insecure_skip_verify"`
}

OAuth2Settings is the decoded "oauth2" setting namespace. It controls the code-flow redirect behavior for upstream providers.

type PasskeyBeginResponse added in v0.9.0

type PasskeyBeginResponse struct {
	SessionID string `json:"session_id"`
	Options   any    `json:"options"`
}

type PasskeyCredentialMeta added in v0.9.0

type PasskeyCredentialMeta struct {
	ID        string `json:"id"`
	UserID    string `json:"user_id"`
	Name      string `json:"name"`
	SignCount uint32 `json:"sign_count"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

PasskeyCredentialMeta is the listing shape for stored passkeys.

type PasskeyRegisterRequest added in v0.9.0

type PasskeyRegisterRequest struct {
	// UserID, when set, registers the passkey for that user instead of the
	// X-User identity. Targeting another user requires admin capability.
	UserID    string `json:"user_id"`
	SessionID string `json:"session_id"`
	// Name is a user-facing label for the credential.
	Name string `json:"name"`
	// Credential is the browser's RegistrationResponseJSON; nil means begin.
	Credential json.RawMessage `json:"credential"`
}

type PasskeySettings added in v0.9.0

type PasskeySettings struct {
	// Disabled turns off passkey registration and login endpoints.
	Disabled bool `json:"disabled"`
	// RPID is the WebAuthn relying party ID (bare host, e.g. "example.com").
	RPID string `json:"rp_id"`
	// RPDisplayName is shown by the platform passkey UI. Default "Turna Auth".
	RPDisplayName string `json:"rp_display_name"`
	// Origins allowed in WebAuthn client data (e.g. "https://example.com").
	Origins []string `json:"origins"`
	// UserVerification is required, preferred (default) or discouraged.
	UserVerification string `json:"user_verification"`
}

PasskeySettings is the decoded "passkey" setting namespace. Empty values are derived from the request: rp_id from the host and origins from the forwarded scheme/host.

type PasskeyTokenRequest added in v0.9.0

type PasskeyTokenRequest struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	// Username scopes allowCredentials to a known user; empty uses the
	// discoverable (passwordless) flow.
	Username  string `json:"username"`
	Scope     string `json:"scope"`
	SessionID string `json:"session_id"`
	// Assertion is the browser's AssertionResponseJSON; nil means begin.
	Assertion json.RawMessage `json:"assertion"`
}

type PasswordSettings added in v0.9.0

type PasswordSettings struct {
	// Disabled turns off the password grant entirely.
	Disabled bool `json:"disabled"`
	// LocalDisabled blocks password login for local users.
	LocalDisabled bool `json:"local_disabled"`
	// LdapDisabled blocks LDAP password checks for non-local users.
	LdapDisabled bool `json:"ldap_disabled"`
	// LdapRegisterDisabled stops creating unknown users from LDAP at login.
	LdapRegisterDisabled bool `json:"ldap_register_disabled"`
}

PasswordSettings is the decoded "password" setting namespace. It controls which credential sources the password grant accepts. All defaults keep the implicit behavior: local users check bcrypt, non-local users bind against LDAP, unknown aliases are created from LDAP.

type ProviderConfig added in v0.9.0

type ProviderConfig struct {
	ClientID      string   `json:"client_id"`
	ClientSecret  string   `json:"client_secret"`
	Scopes        []string `json:"scopes"`
	CertURL       string   `json:"cert_url"`
	IntrospectURL string   `json:"introspect_url"`
	UserInfoURL   string   `json:"userinfo_url"`
	RevocationURL string   `json:"revocation_url"`
	AuthURL       string   `json:"auth_url"`
	TokenURL      string   `json:"token_url"`
	LogoutURL     string   `json:"logout_url"`

	// ClaimMapping maps provider claims to local users and roles.
	ClaimMapping ClaimMapping `json:"claim_mapping"`
}

ProviderConfig is the decoded OAuth provider config stored in auth_oauth_providers.

func (ProviderConfig) Session added in v0.9.0

func (p ProviderConfig) Session() *session.Oauth2

type Response added in v0.9.0

type Response[T any] struct {
	Payload T     `json:"payload"`
	Meta    *Meta `json:"meta,omitempty"`
}

type SAMLProviderConfig added in v0.9.0

type SAMLProviderConfig struct {
	// MetadataURL of the IdP; fetched and cached.
	MetadataURL string `json:"metadata_url"`
	// MetadataXML inline IdP metadata; takes precedence over metadata_url.
	MetadataXML string `json:"metadata_xml"`
	// EntityID of this SP. Default is the metadata URL of the provider.
	EntityID string `json:"entity_id"`
	// AliasAttribute to read the user alias from; default tries
	// email-like attributes and falls back to the subject NameID.
	AliasAttribute string `json:"alias_attribute"`
	// SignRequests signs AuthnRequests with the SP key (RSA-SHA256).
	SignRequests bool `json:"sign_requests"`

	// ClaimMapping maps assertion attributes to local users and roles;
	// roles_claim matches the attribute name or friendly name.
	ClaimMapping ClaimMapping `json:"claim_mapping"`
}

SAMLProviderConfig is the decoded SAML provider config stored in auth_saml_providers.

type SMTPSettings added in v0.9.0

type SMTPSettings struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	// NoAuth skips SMTP AUTH even when username is set. Useful for trusted
	// relays where username is only used as the default From address.
	NoAuth bool `json:"no_auth"`
	// StartTLS upgrades a plain connection. Default port 587.
	StartTLS bool `json:"starttls"`
	// TLS uses an implicit TLS connection. Default port 465.
	TLS                bool `json:"tls"`
	InsecureSkipVerify bool `json:"insecure_skip_verify"`
}

SMTPSettings configures the mail relay for email login.

func (SMTPSettings) GetPort added in v0.9.0

func (s SMTPSettings) GetPort() int

type Setting added in v0.9.0

type Setting struct {
	Namespace string        `json:"namespace"`
	Value     types.RawJSON `json:"value"`
	UpdatedAt types.Time    `json:"updated_at"`
	UpdatedBy string        `json:"updated_by"`
}

type SettingMeta added in v0.9.0

type SettingMeta struct {
	Namespace string     `json:"namespace"`
	UpdatedAt types.Time `json:"updated_at"`
	UpdatedBy string     `json:"updated_by"`
}

type SettingRequest added in v0.9.0

type SettingRequest struct {
	Value json.RawMessage `json:"value"`
}

type SignupRequest added in v0.9.0

type SignupRequest struct {
	ClientID     string `form:"client_id"     json:"client_id"`
	ClientSecret string `form:"client_secret" json:"client_secret"`
	Email        string `form:"email"         json:"email"`
	Name         string `form:"name"          json:"name"`
	Password     string `form:"password"      json:"password"`
	// RedirectURI builds the magic link in the mail; it must match the
	// client whitelist. The verification code is appended as ?code=...
	RedirectURI string `form:"redirect_uri" json:"redirect_uri"`
	// Code finishes a flow (verify / reset confirm).
	Code string `form:"code" json:"code"`
}

type SignupSettings added in v0.9.0

type SignupSettings struct {
	// Enabled allows self-registration through /oauth2/signup.
	Enabled bool `json:"enabled"`
	// EmailVerification requires confirming the address before the account
	// is created. Default true; without it signup creates active users.
	EmailVerification *bool `json:"email_verification"`
	// PasswordReset enables the forgot-password flow; independent of Enabled.
	PasswordReset bool `json:"password_reset"`
	// DefaultRoleIDs are granted to users created through signup.
	DefaultRoleIDs []string `json:"default_role_ids"`
	// PasswordMinLength is the minimum length for signup/reset/change
	// passwords. Default 8 when unset (0).
	PasswordMinLength int `json:"password_min_length"`
	// CodeLifetime of verification/reset codes. Default 1h.
	CodeLifetime string `json:"code_lifetime"`

	// Go text/template mail templates; empty uses built-in defaults.
	VerifySubject      string `json:"verify_subject"`
	VerifyBodyTemplate string `json:"verify_body_template"`
	ResetSubject       string `json:"reset_subject"`
	ResetBodyTemplate  string `json:"reset_body_template"`
	// contains filtered or unexported fields
}

SignupSettings is the decoded "signup" setting namespace for self-registration and password reset over email. Everything is optional and managed from the UI; signup is off by default.

func (SignupSettings) GetCodeLifetime added in v0.9.0

func (s SignupSettings) GetCodeLifetime() time.Duration

func (SignupSettings) GetEmailVerification added in v0.9.0

func (s SignupSettings) GetEmailVerification() bool

func (SignupSettings) GetPasswordMinLength added in v0.9.0

func (s SignupSettings) GetPasswordMinLength() int

GetPasswordMinLength returns the configured minimum password length, or the built-in default (minPasswordLength) when unset.

type Snapshot added in v0.9.0

type Snapshot struct {
	Version uint64

	Users   map[string]*data.User
	UserIDs []string
	Alias   map[string]string

	Roles       map[string]*data.Role
	RoleIDs     []string
	RoleNames   map[string]string
	Permissions map[string]*data.Permission
	PermIDs     []string
	PermNames   map[string]string

	LMaps     map[string]*data.LMap
	LMapNames []string

	OAuthClients   map[string]AccessClient
	OAuthProviders map[string]ProviderConfig
	LDAP           []LDAPSettings
	SAMLProviders  map[string]SAMLProviderConfig

	Token         TokenSettings
	Admin         AdminSettings
	OAuth2        OAuth2Settings
	Check         data.CheckConfig
	Cache         CacheSettings
	Passkey       PasskeySettings
	Password      PasswordSettings
	JWTKey        jwtSetting
	APIKey        APIKeySettings
	Device        DeviceSettings
	TokenExchange TokenExchangeSettings
	TOTP          TOTPSettings
	Email         EmailSettings
	Signup        SignupSettings
	MTLS          MTLSSettings
	SAMLKey       samlSetting
	CustomInfo    CustomInfoSettings
}

Snapshot is the immutable in-memory read model of the auth database.

func (*Snapshot) UserByAlias added in v0.9.0

func (sn *Snapshot) UserByAlias(alias string) *data.User

type Store added in v0.9.0

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

func NewStore added in v0.9.0

func NewStore(db *sql.DB, cipher *Cipher) *Store

func (*Store) ConfirmTOTPSecret added in v0.9.0

func (s *Store) ConfirmTOTPSecret(ctx context.Context, userID string) error

ConfirmTOTPSecret marks the user's totp secret as confirmed.

func (*Store) ConsumeTOTPRecoveryCode added in v0.9.0

func (s *Store) ConsumeTOTPRecoveryCode(ctx context.Context, userID, code string) bool

ConsumeTOTPRecoveryCode validates and removes a recovery code; each code is single use.

func (*Store) CreateAPIKey added in v0.9.0

func (s *Store) CreateAPIKey(ctx context.Context, meta APIKeyMeta, keyHash string, expiresAt *time.Time) (string, error)

CreateAPIKey stores a new api key principal and returns its id.

func (*Store) CreateFlowCode added in v0.9.0

func (s *Store) CreateFlowCode(ctx context.Context, kind, id string, payload any, ttl time.Duration) error

CreateFlowCode stores a short-lived flow payload with an absolute expiry.

func (*Store) CreateLMap added in v0.9.0

func (s *Store) CreateLMap(ctx context.Context, lmap data.LMap) error

func (*Store) CreatePasskeyCredential added in v0.9.0

func (s *Store) CreatePasskeyCredential(ctx context.Context, userID, name string, cred *passkey.Credential) error

CreatePasskeyCredential persists a credential produced by FinishRegistration.

func (*Store) CreatePermission added in v0.9.0

func (s *Store) CreatePermission(ctx context.Context, permission data.Permission) (string, error)

func (*Store) CreatePermissions added in v0.9.0

func (s *Store) CreatePermissions(ctx context.Context, permissions []data.Permission) ([]string, error)

func (*Store) CreateRole added in v0.9.0

func (s *Store) CreateRole(ctx context.Context, role data.Role) (string, error)

func (*Store) CreateUser added in v0.9.0

func (s *Store) CreateUser(ctx context.Context, user data.User) (string, error)

func (*Store) DeleteAPIKey added in v0.9.0

func (s *Store) DeleteAPIKey(ctx context.Context, userID, id string) error

DeleteAPIKey removes an api key owned by the user.

func (*Store) DeleteAPIKeyByID added in v0.9.0

func (s *Store) DeleteAPIKeyByID(ctx context.Context, id string) error

DeleteAPIKeyByID removes an api key without owner scoping.

func (*Store) DeleteFlowCode added in v0.9.0

func (s *Store) DeleteFlowCode(ctx context.Context, kind, id string) error

DeleteFlowCode removes a flow entry and opportunistically prunes expired rows.

func (*Store) DeleteLDAPConfig added in v0.9.0

func (s *Store) DeleteLDAPConfig(ctx context.Context, id string) (uint64, error)

func (*Store) DeleteLMap added in v0.9.0

func (s *Store) DeleteLMap(ctx context.Context, name string) error

func (*Store) DeleteOAuthClient added in v0.9.0

func (s *Store) DeleteOAuthClient(ctx context.Context, id string) (uint64, error)

func (*Store) DeleteOAuthProvider added in v0.9.0

func (s *Store) DeleteOAuthProvider(ctx context.Context, id string) (uint64, error)

func (*Store) DeletePasskeyCredential added in v0.9.0

func (s *Store) DeletePasskeyCredential(ctx context.Context, id string) error

DeletePasskeyCredential removes a stored credential.

func (*Store) DeletePermission added in v0.9.0

func (s *Store) DeletePermission(ctx context.Context, id string) error

func (*Store) DeleteRole added in v0.9.0

func (s *Store) DeleteRole(ctx context.Context, id string) error

func (*Store) DeleteSAMLProvider added in v0.9.0

func (s *Store) DeleteSAMLProvider(ctx context.Context, id string) (uint64, error)

func (*Store) DeleteSetting added in v0.9.0

func (s *Store) DeleteSetting(ctx context.Context, namespace string) (uint64, error)

func (*Store) DeleteTOTPSecret added in v0.9.0

func (s *Store) DeleteTOTPSecret(ctx context.Context, userID string) error

DeleteTOTPSecret removes the user's totp secret.

func (*Store) DeleteUser added in v0.9.0

func (s *Store) DeleteUser(ctx context.Context, id string) error

func (*Store) EnsureLMaps added in v0.9.0

func (s *Store) EnsureLMaps(ctx context.Context, checks []data.LMapCheckCreate) error

EnsureLMaps creates missing roles and lmaps for the given LDAP groups.

func (*Store) GetAPIKeyMeta added in v0.9.0

func (s *Store) GetAPIKeyMeta(ctx context.Context, id string) (*APIKeyMeta, error)

func (*Store) GetAPIKeyPrincipal added in v0.9.0

func (s *Store) GetAPIKeyPrincipal(ctx context.Context, key string) (*APIKeyMeta, error)

GetAPIKeyPrincipal resolves an api key to its own principal metadata. Expired keys are rejected; last_used_at is updated on success.

func (*Store) GetAPIKeyPrincipalByID added in v0.9.0

func (s *Store) GetAPIKeyPrincipalByID(ctx context.Context, id string) (*APIKeyMeta, error)

func (*Store) GetFlowCode added in v0.9.0

func (s *Store) GetFlowCode(ctx context.Context, kind, id string, payload any) error

GetFlowCode loads a flow payload; expired entries count as not found.

func (*Store) GetLDAPConfig added in v0.9.0

func (s *Store) GetLDAPConfig(ctx context.Context, id string) (*ConfigResource, error)

func (*Store) GetOAuthClient added in v0.9.0

func (s *Store) GetOAuthClient(ctx context.Context, id string) (*ConfigResource, error)

func (*Store) GetOAuthProvider added in v0.9.0

func (s *Store) GetOAuthProvider(ctx context.Context, id string) (*ConfigResource, error)

func (*Store) GetPasskeyCredential added in v0.9.0

func (s *Store) GetPasskeyCredential(ctx context.Context, credentialID []byte) (string, *passkey.Credential, error)

GetPasskeyCredential loads a credential and its owner by raw credential ID.

func (*Store) GetPasskeyCredentialMeta added in v0.9.0

func (s *Store) GetPasskeyCredentialMeta(ctx context.Context, id string) (*PasskeyCredentialMeta, error)

func (*Store) GetRoleRelation added in v0.9.0

func (s *Store) GetRoleRelation(ctx context.Context) (map[string]data.RoleRelation, error)

func (*Store) GetSAMLProvider added in v0.9.0

func (s *Store) GetSAMLProvider(ctx context.Context, id string) (*ConfigResource, error)

func (*Store) GetSetting added in v0.9.0

func (s *Store) GetSetting(ctx context.Context, namespace string) (*Setting, error)

func (*Store) GetSettingValue added in v0.9.0

func (s *Store) GetSettingValue(ctx context.Context, namespace string) (types.RawJSON, error)

GetSettingValue returns the decrypted setting value, or nil when missing.

func (*Store) GetTOTPSecret added in v0.9.0

func (s *Store) GetTOTPSecret(ctx context.Context, userID string) (string, bool, error)

GetTOTPSecret loads the user's totp secret and confirmation state.

func (*Store) KeepPermissions added in v0.9.0

func (s *Store) KeepPermissions(ctx context.Context, keep map[string]struct{}) ([]data.IDName, error)

func (*Store) ListAPIKeys added in v0.9.0

func (s *Store) ListAPIKeys(ctx context.Context, userID string) ([]APIKeyMeta, error)

ListAPIKeys returns api key metadata for a user.

func (*Store) ListAllAPIKeys added in v0.9.0

func (s *Store) ListAllAPIKeys(ctx context.Context) ([]APIKeyMeta, error)

ListAllAPIKeys returns metadata for every api key principal.

func (*Store) ListLDAPConfigs added in v0.9.0

func (s *Store) ListLDAPConfigs(ctx context.Context) ([]ConfigMeta, error)

func (*Store) ListOAuthClients added in v0.9.0

func (s *Store) ListOAuthClients(ctx context.Context) ([]ConfigMeta, error)

func (*Store) ListOAuthProviders added in v0.9.0

func (s *Store) ListOAuthProviders(ctx context.Context) ([]ConfigMeta, error)

func (*Store) ListPasskeyCredentialIDs added in v0.9.0

func (s *Store) ListPasskeyCredentialIDs(ctx context.Context, userID string) ([][]byte, error)

ListPasskeyCredentialIDs returns raw credential IDs for a user, used for allowCredentials in login and excludeCredentials in registration.

func (*Store) ListPasskeyCredentials added in v0.9.0

func (s *Store) ListPasskeyCredentials(ctx context.Context, userID string) ([]PasskeyCredentialMeta, error)

ListPasskeyCredentials returns credential metadata for a user.

func (*Store) ListSAMLProviders added in v0.9.0

func (s *Store) ListSAMLProviders(ctx context.Context) ([]ConfigMeta, error)

func (*Store) ListSettings added in v0.9.0

func (s *Store) ListSettings(ctx context.Context) ([]SettingMeta, error)

func (*Store) LoadConfigResources added in v0.9.0

func (s *Store) LoadConfigResources(ctx context.Context, kind configKind) (map[string]types.RawJSON, error)

func (*Store) LoadLMaps added in v0.9.0

func (s *Store) LoadLMaps(ctx context.Context) ([]*data.LMap, error)

func (*Store) LoadPermissions added in v0.9.0

func (s *Store) LoadPermissions(ctx context.Context) ([]*data.Permission, error)

func (*Store) LoadRoles added in v0.9.0

func (s *Store) LoadRoles(ctx context.Context) ([]*data.Role, error)

func (*Store) LoadUsers added in v0.9.0

func (s *Store) LoadUsers(ctx context.Context) ([]*data.User, error)

func (*Store) PatchPermission added in v0.9.0

func (s *Store) PatchPermission(ctx context.Context, id string, patch data.PermissionPatch) error

func (*Store) PatchRole added in v0.9.0

func (s *Store) PatchRole(ctx context.Context, id string, patch data.RolePatch) error

func (*Store) PatchUser added in v0.9.0

func (s *Store) PatchUser(ctx context.Context, id string, patch data.UserPatch) error

func (*Store) PatchUserAccess added in v0.9.0

func (s *Store) PatchUserAccess(ctx context.Context, id string, userAccess data.UserAccess) error

func (*Store) PutLDAPConfig added in v0.9.0

func (s *Store) PutLDAPConfig(ctx context.Context, id string, config json.RawMessage, enabled bool, updatedBy string) (uint64, error)

func (*Store) PutLMap added in v0.9.0

func (s *Store) PutLMap(ctx context.Context, lmap data.LMap) error

func (*Store) PutOAuthClient added in v0.9.0

func (s *Store) PutOAuthClient(ctx context.Context, id string, config json.RawMessage, enabled bool, updatedBy string) (uint64, error)

func (*Store) PutOAuthProvider added in v0.9.0

func (s *Store) PutOAuthProvider(ctx context.Context, id string, config json.RawMessage, enabled bool, updatedBy string) (uint64, error)

func (*Store) PutPermission added in v0.9.0

func (s *Store) PutPermission(ctx context.Context, permission data.Permission) error

func (*Store) PutRole added in v0.9.0

func (s *Store) PutRole(ctx context.Context, role data.Role) error

func (*Store) PutRoleRelation added in v0.9.0

func (s *Store) PutRoleRelation(ctx context.Context, relation map[string]data.RoleRelation) error

func (*Store) PutSAMLProvider added in v0.9.0

func (s *Store) PutSAMLProvider(ctx context.Context, id string, config json.RawMessage, enabled bool, updatedBy string) (uint64, error)

func (*Store) PutSetting added in v0.9.0

func (s *Store) PutSetting(ctx context.Context, namespace string, value json.RawMessage, updatedBy string) (uint64, error)

func (*Store) PutUser added in v0.9.0

func (s *Store) PutUser(ctx context.Context, user data.User) error

func (*Store) SetTOTPRecoveryCodes added in v0.9.0

func (s *Store) SetTOTPRecoveryCodes(ctx context.Context, userID string, hashes []string) error

SetTOTPRecoveryCodes replaces the user's recovery code hashes.

func (*Store) UpdateAPIKey added in v0.9.0

func (s *Store) UpdateAPIKey(ctx context.Context, userID, id string, update APIKeyUpdate) error

UpdateAPIKey updates metadata and access attached to a user's api key.

func (*Store) UpdateAPIKeyByID added in v0.9.0

func (s *Store) UpdateAPIKeyByID(ctx context.Context, id string, update APIKeyUpdate) error

UpdateAPIKeyByID updates api key metadata without owner scoping.

func (*Store) UpdateFlowCode added in v0.9.0

func (s *Store) UpdateFlowCode(ctx context.Context, kind, id string, payload any) error

UpdateFlowCode replaces the payload of an existing flow entry.

func (*Store) UpdatePasskeySignCount added in v0.9.0

func (s *Store) UpdatePasskeySignCount(ctx context.Context, credentialID []byte, signCount uint32) error

UpdatePasskeySignCount persists the new sign counter after a login.

func (*Store) UpdateUserPassword added in v0.9.0

func (s *Store) UpdateUserPassword(ctx context.Context, id string, password string) error

UpdateUserPassword sets only the password detail of a user; the plaintext password is bcrypt hashed in place. Other details stay untouched.

func (*Store) UpdateUserSyncRoles added in v0.9.0

func (s *Store) UpdateUserSyncRoles(ctx context.Context, id string, roleIDs []string) error

func (*Store) UpsertTOTPSecret added in v0.9.0

func (s *Store) UpsertTOTPSecret(ctx context.Context, userID, secret string) error

UpsertTOTPSecret stores a fresh (unconfirmed) totp secret for the user.

func (*Store) Version added in v0.9.0

func (s *Store) Version(ctx context.Context) (uint64, error)

type TOTPConfirmRequest added in v0.9.0

type TOTPConfirmRequest struct {
	Code string `json:"code"`
}

type TOTPRegisterResponse added in v0.9.0

type TOTPRegisterResponse struct {
	Secret string `json:"secret"`
	URL    string `json:"url"`
}

type TOTPSettings added in v0.9.0

type TOTPSettings struct {
	// Disabled turns off totp registration and enforcement.
	Disabled bool `json:"disabled"`
	// Issuer shown in authenticator apps. Default "Turna Auth".
	Issuer string `json:"issuer"`
	// Skew allowed periods in each direction. Default 1 (+/-30s).
	Skew *int `json:"skew"`
}

TOTPSettings is the decoded "totp" setting namespace.

func (TOTPSettings) GetIssuer added in v0.9.0

func (t TOTPSettings) GetIssuer() string

func (TOTPSettings) GetSkew added in v0.9.0

func (t TOTPSettings) GetSkew() int

type TokenExchangeSettings added in v0.9.0

type TokenExchangeSettings struct {
	// Disabled turns off the token exchange grant.
	Disabled bool `json:"disabled"`
}

TokenExchangeSettings is the decoded "token_exchange" setting namespace (RFC 8693).

type TokenSettings added in v0.9.0

type TokenSettings struct {
	TokenLifetime   string `json:"token_lifetime"`
	RefreshLifetime string `json:"refresh_lifetime"`
	// RolesClaim is the dot path where the scope-derived roles are written
	// in the access token. Empty defaults to "roles" (flat top-level array).
	// Use "realm_access.roles" for Keycloak-style nesting, or any dot path
	// such as "resource_access.app.roles". A per-client override in
	// AccessClient.RolesClaim takes precedence when set.
	RolesClaim string `json:"roles_claim"`
	// contains filtered or unexported fields
}

TokenSettings is the decoded "token" setting namespace.

func (TokenSettings) GetRefreshLifetime added in v0.9.0

func (t TokenSettings) GetRefreshLifetime() time.Duration

func (TokenSettings) GetRolesClaim added in v0.9.0

func (t TokenSettings) GetRolesClaim() string

GetRolesClaim returns the configured dot path for the roles claim, or the flat "roles" default when unset.

func (TokenSettings) GetTokenLifetime added in v0.9.0

func (t TokenSettings) GetTokenLifetime() time.Duration

Jump to

Keyboard shortcuts

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