{"modulePath":"github.com/bitechdev/ResolveSpec","version":"v1.3.14","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package security\n\n## Constants\n\n```go\nconst (\n\t// Context keys for user information\n\tUserIDKey       contextKey = \"user_id\"\n\tUserNameKey     contextKey = \"user_name\"\n\tUserLevelKey    contextKey = \"user_level\"\n\tSessionIDKey    contextKey = \"session_id\"\n\tSessionRIDKey   contextKey = \"session_rid\"\n\tRemoteIDKey     contextKey = \"remote_id\"\n\tUserRolesKey    contextKey = \"user_roles\"\n\tUserEmailKey    contextKey = \"user_email\"\n\tUserContextKey  contextKey = \"user_context\"\n\tUserMetaKey     contextKey = \"user_meta\"\n\tSkipAuthKey     contextKey = \"skip_auth\"\n\tOptionalAuthKey contextKey = \"optional_auth\"\n\tModelRulesKey   contextKey = \"model_rules\"\n)\n```\n\n```go\nconst (\n\t// ClaimIPAddress is the login claim holding the client's IP address.\n\tClaimIPAddress = \"ip_address\"\n\t// ClaimPreviousSession is the login claim holding the session token the\n\t// client presented when it logged in again.\n\tClaimPreviousSession = \"previous_session\"\n\t// ClaimUserAgent is the login claim holding the client's User-Agent header.\n\tClaimUserAgent = \"user_agent\"\n\t// ClaimServerIPAddress is the login claim holding the IP of the server\n\t// address that accepted the connection.\n\tClaimServerIPAddress = \"server_ip_address\"\n\t// ClaimHost is the login claim holding the requested Host.\n\tClaimHost = \"host\"\n\t// ClaimOrigin is the login claim holding the Origin header.\n\tClaimOrigin = \"origin\"\n\t// ClaimReferer is the login claim holding the Referer header.\n\tClaimReferer = \"referer\"\n\t// ClaimClientPort is the login claim holding the port of the peer that\n\t// connected (the proxy's port when behind one).\n\tClaimClientPort = \"client_port\"\n\t// ClaimServerPort is the login claim holding the port of the server\n\t// address that accepted the connection.\n\tClaimServerPort = \"server_port\"\n\t// ClaimIsPrivateIP is the login claim (bool) that is true when the client\n\t// IP is private, loopback or link-local.\n\tClaimIsPrivateIP = \"is_private_ip\"\n\t// ClaimDeviceID is the login claim holding the client-supplied device id.\n\tClaimDeviceID = \"device_id\"\n\t// ClaimClientID is the login claim holding the client-supplied client id\n\t// (X-Client-ID header).\n\tClaimClientID = \"client_id\"\n)\n```\n\n```go\nconst (\n\tKeyTypeJWTSecret  = sectypes.KeyTypeJWTSecret\n\tKeyTypeHeaderAPI  = sectypes.KeyTypeHeaderAPI\n\tKeyTypeOAuth2     = sectypes.KeyTypeOAuth2\n\tKeyTypeGenericAPI = sectypes.KeyTypeGenericAPI\n)\n```\n\n## Variables\n\n```go\nvar ErrNoColumnSecurity = errors.New(\"no column security data\")\n```\nErrNoColumnSecurity is the column-security equivalent of ErrNoRowSecurity.\n\n```go\nvar ErrNoRowSecurity = errors.New(\"no row security data\")\n```\nErrNoRowSecurity is returned by GetRowSecurityTemplate when no row security entry is loaded for the user and table. It means \"no rules\", as opposed to a failure, which callers must treat as fatal.\n\n## Functions\n\n```go\nfunc ApplyColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error\n```\nApplyColumnSecurity is a public wrapper for applyColumnSecurity that accepts a SecurityContext This allows other packages to apply column-level security using the generic interface\n\n```go\nfunc ApplyRowSecurity(secCtx SecurityContext, securityList *SecurityList) error\n```\nApplyRowSecurity is a public wrapper for applyRowSecurity that accepts a SecurityContext This allows other packages to apply row-level security using the generic interface\n\n```go\nfunc ApplyTxSettings(secCtx SecurityContext, tx common.Database, settings map[string]string) error\n```\nApplyTxSettings sets each entry as a transaction-local setting on tx, in name order. Postgres only; any other driver with a non-empty map is an error so a missing RLS stamp fails closed. The SQL lives in lookup.ApplyTxSettings.\n\n```go\nfunc ApplyWriteColumnSecurity(secCtx SecurityContext, securityList *SecurityList) error\n```\nApplyWriteColumnSecurity removes columns the user may not see (column security \"hide\" or \"mask\") from the create/update payload in place, so a hidden or masked column can never be written. It only reads the rules cache (see PreloadSecurityRules) and never queries the provider, so it is safe inside the transaction. Models with security disabled are skipped. Without a loaded rule set for a known user it fails closed.\n\n```go\nfunc CheckModelAuthAllowed(secCtx SecurityContext, operation string) error\n```\nCheckModelAuthAllowed checks whether the requested operation is permitted based on model rules and the current user's authentication state. It is intended for use in a BeforeHandle hook, fired after model resolution.\n\nLogic:\n\n 1. Load model rules from context (set by NewModelAuthMiddleware) or fall back to registry.\n 2. SecurityDisabled → allow.\n 3. operation == \"read\" \u0026\u0026 CanPublicRead → allow.\n 4. operation == \"create\" \u0026\u0026 CanPublicCreate → allow.\n 5. operation == \"update\" \u0026\u0026 CanPublicUpdate → allow.\n 6. operation == \"delete\" \u0026\u0026 CanPublicDelete → allow.\n 7. Guest (UserID == 0) → return \"authentication required\".\n 8. Authenticated user → allow (operation-specific checks remain in BeforeUpdate/BeforeDelete).\n\n```go\nfunc CheckModelCreateAllowed(secCtx SecurityContext) error\n```\nCheckModelCreateAllowed returns an error if CanCreate is false for the model. Rules are read from context with a fallback to the model registry; an unregistered model is allowed.\n\n```go\nfunc CheckModelDeleteAllowed(secCtx SecurityContext) error\n```\nCheckModelDeleteAllowed is the public wrapper for checkModelDeleteAllowed.\n\n```go\nfunc CheckModelUpdateAllowed(secCtx SecurityContext) error\n```\nCheckModelUpdateAllowed is the public wrapper for checkModelUpdateAllowed.\n\n```go\nfunc ClearSessionCookie(w http.ResponseWriter, opts ...SessionCookieOptions)\n```\nClearSessionCookie expires the session\\_token cookie, effectively logging the user out on the browser side. Call this after a successful Authenticator.Logout() call.\n\nExample:\n\n\terr := auth.Logout(r.Context(), req)\n\tif err != nil { ... }\n\tsecurity.ClearSessionCookie(w)\n\n```go\nfunc ClientIP(r *http.Request) string\n```\nClientIP returns the client IP, trusting X-Forwarded-For (first entry) and X-Real-IP from any peer, then RemoteAddr without its port. Use RequestInfoOptions to restrict which peers are trusted.\n\n```go\nfunc ExampleOAuth2AllProviders()\n```\nExample: All OAuth2 Providers at Once\n\n```go\nfunc ExampleOAuth2Complete()\n```\nExample: Complete OAuth2 Integration with Database Setup\n\n```go\nfunc ExampleOAuth2Custom()\n```\nExample: Custom OAuth2 Provider\n\n```go\nfunc ExampleOAuth2FullClient()\n```\nExampleOAuth2FullClient is the relying-party side: log users in with any OpenID Connect provider (including the server above). Discovery, PKCE, nonce and id\\_token validation are automatic.\n\n```go\nfunc ExampleOAuth2FullServer()\n```\nExampleOAuth2FullServer runs a complete OAuth 2.1 / OpenID Connect provider: login, consent, rotating refresh tokens, JWT access tokens, DPoP, PAR, the device grant and token exchange. OAUTH2\\_SERVER.md walks through every endpoint.\n\n```go\nfunc ExampleOAuth2GitHub()\n```\nExample: OAuth2 Authentication with GitHub\n\n```go\nfunc ExampleOAuth2Google()\n```\nExample: OAuth2 Authentication with Google\n\n```go\nfunc ExampleOAuth2Logout()\n```\nExample: OAuth2 Logout\n\n```go\nfunc ExampleOAuth2MultiProvider()\n```\nExample: Multi-Provider OAuth2 with Security Integration\n\n```go\nfunc ExampleOAuth2TokenRefresh()\n```\nExample: OAuth2 with Token Refresh\n\n```go\nfunc GetModelRulesFromContext(ctx context.Context) (modelregistry.ModelRules, bool)\n```\nGetModelRulesFromContext extracts ModelRules stored by NewModelAuthMiddleware\n\n```go\nfunc GetRemoteID(ctx context.Context) (string, bool)\n```\nGetRemoteID extracts the remote ID from context\n\n```go\nfunc GetSessionCookie(r *http.Request, opts ...SessionCookieOptions) string\n```\nGetSessionCookie returns the session token value from the request cookie, or empty string if not present.\n\nExample:\n\n\ttoken := security.GetSessionCookie(r)\n\n```go\nfunc GetSessionID(ctx context.Context) (string, bool)\n```\nGetSessionID extracts the session ID from context\n\n```go\nfunc GetSessionRID(ctx context.Context) (int64, bool)\n```\nGetSessionID extracts the session ID from context\n\n```go\nfunc GetUserEmail(ctx context.Context) (string, bool)\n```\nGetUserEmail extracts user email from context\n\n```go\nfunc GetUserID(ctx context.Context) (int, bool)\n```\nGetUserID extracts the user ID from context\n\n```go\nfunc GetUserLevel(ctx context.Context) (int, bool)\n```\nGetUserLevel extracts the user level from context\n\n```go\nfunc GetUserMeta(ctx context.Context) (map[string]any, bool)\n```\nGetUserMeta extracts user metadata from context\n\n```go\nfunc GetUserName(ctx context.Context) (string, bool)\n```\nGetUserName extracts the user name from context\n\n```go\nfunc GetUserRoles(ctx context.Context) ([]string, bool)\n```\nGetUserRoles extracts user roles from context\n\n```go\nfunc IsModelSecurityDisabled(secCtx SecurityContext) bool\n```\nIsModelSecurityDisabled reports whether all model-level security processing is disabled for the model. This is distinct from ShouldSkipRowSecurity: CanPublicRead skips row filtering for reads but must still allow other read security, such as column masking, to be loaded.\n\n```go\nfunc LoadSecurityRules(secCtx SecurityContext, securityList *SecurityList) error\n```\nLoadSecurityRules is a public wrapper for loadSecurityRules that accepts a SecurityContext This allows other packages to load security rules using the generic interface\n\n```go\nfunc LogDataAccess(secCtx SecurityContext) error\n```\nLogDataAccess is a public wrapper for logDataAccess that accepts a SecurityContext This allows other packages to use the audit logging functionality\n\n```go\nfunc NewAuthHandler(securityList *SecurityList, next http.Handler) http.Handler\n```\nNewAuthHandler creates an authentication handler that can be used standalone This handler performs authentication and returns 401 if authentication fails Use this when you need authentication logic without middleware wrapping\n\n```go\nfunc NewAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler\n```\nNewAuthMiddleware creates an authentication middleware with the given security list This middleware extracts user authentication from the request and adds it to context Routes can skip authentication by setting SkipAuthKey context value (use SkipAuth helper) Routes can use optional authentication by setting OptionalAuthKey context value (use OptionalAuth helper) When authentication is skipped or fails with optional auth, a guest user context is set instead\n\n```go\nfunc NewModelAuthMiddleware(securityList *SecurityList, modelName string) func(http.Handler) http.Handler\n```\nNewModelAuthMiddleware creates authentication middleware that respects ModelRules for the given model name. It first checks if ModelRules are set for the model:\n\n  - If SecurityDisabled is true, authentication is skipped and a guest context is set.\n  - Otherwise, all checks from NewAuthMiddleware apply (SkipAuthKey, provider check, OptionalAuthKey, Authenticate).\n\nIf the model is not found in any registry, the middleware falls back to standard NewAuthMiddleware behaviour.\n\n```go\nfunc NewOptionalAuthHandler(securityList *SecurityList, next http.Handler) http.Handler\n```\nNewOptionalAuthHandler creates an optional authentication handler that can be used standalone This handler tries to authenticate but falls back to guest context if authentication fails Use this for routes that should show personalized content for authenticated users but still work for guests\n\n```go\nfunc NewOptionalAuthMiddleware(securityList *SecurityList) func(http.Handler) http.Handler\n```\nNewOptionalAuthMiddleware creates authentication middleware that always continues. On auth failure, a guest user context is set instead of returning 401. Intended for spec routes where auth enforcement is deferred to a BeforeHandle hook after model resolution.\n\n```go\nfunc OptionalAuth(ctx context.Context) context.Context\n```\nOptionalAuth returns a context with optional auth flag set to true Use this to mark routes that should try to authenticate, but fall back to guest if authentication fails\n\n```go\nfunc PasskeyAuthenticationExample()\n```\nPasskeyAuthenticationExample demonstrates passkey (WebAuthn/FIDO2) authentication\n\n```go\nfunc PasskeyClientSideExample() string\n```\nPasskeyClientSideExample shows the client-side JavaScript code needed\n\n```go\nfunc PasskeyHTTPHandlersExample(auth *DatabaseAuthenticator)\n```\nPasskeyHTTPHandlersExample shows HTTP handlers for passkey authentication\n\n```go\nfunc PreloadSecurityRules(secCtx SecurityContext, securityList *SecurityList, operation string) error\n```\nPreloadSecurityRules loads column/row security rules into the SecurityList cache for read operations. Call it from a BeforeHandle hook, i.e. before the handler opens its transaction, so the provider queries do not need a second pooled connection while the transaction holds one. Later LoadSecurityRules calls in the same request are then cache hits. Reads load column and row rules; create/update load the column rules that ApplyWriteColumnSecurity reads. Other operations and models with security disabled are skipped.\n\n```go\nfunc RequestInfoMiddleware(opts ...RequestInfoOptions) func(http.Handler) http.Handler\n```\nRequestInfoMiddleware stores the request details (see WithRequestInfo) in the request context for every route, including ones that skip authentication (such as login), so the login methods can send them as claims.\n\n```go\nfunc SetSecurityMiddleware(securityList *SecurityList) func(http.Handler) http.Handler\n```\nSetSecurityMiddleware adds security context to requests This middleware should be applied after AuthMiddleware\n\n```go\nfunc SetSessionCookie(w http.ResponseWriter, loginResp *LoginResponse, opts ...SessionCookieOptions)\n```\nSetSessionCookie writes the session\\_token cookie to the response after a successful login. Call this immediately after a successful Authenticator.Login() call.\n\nExample:\n\n\tresp, err := auth.Login(r.Context(), req)\n\tif err != nil { ... }\n\tsecurity.SetSessionCookie(w, resp)\n\tjson.NewEncoder(w).Encode(resp)\n\n```go\nfunc ShouldSkipRowSecurity(secCtx SecurityContext, operation string) bool\n```\nShouldSkipRowSecurity reports whether row-security enforcement should be skipped for the operation. It uses the same model-rule resolution as CheckModelAuthAllowed so the model registry remains the single source of truth for security behavior.\n\n```go\nfunc SkipAuth(ctx context.Context) context.Context\n```\nSkipAuth returns a context with skip auth flag set to true Use this to mark routes that should bypass authentication middleware\n\n```go\nfunc StampTxSettings(secCtx SecurityContext, list *SecurityList, tx common.Database) error\n```\nStampTxSettings runs the list's TxSettingsFunc and applies the result to tx as transaction-local settings (set\\_config(name, value, true)). No-op when no function is configured or it returns no settings. tx must be the transaction itself, never the pool: the settings are lost on any other connection.\n\n```go\nfunc WithAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)\n```\nWithAuth wraps an HTTPFuncType handler with required authentication This function performs authentication and returns 401 if authentication fails Use this for handlers that require authenticated users\n\nUsage:\n\n\thandler := funcspec.NewHandler(db)\n\twrappedHandler := security.WithAuth(handler.SqlQueryList(\"SELECT * FROM orders WHERE user_id = [rid_user]\", false, false, false), securityList)\n\trouter.HandleFunc(\"/api/orders\", wrappedHandler)\n\n```go\nfunc WithAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)\n```\nWithAuthAndSecurity wraps an HTTPFuncType handler with both authentication and security context This is a convenience function that combines WithAuth and WithSecurityContext Use this when you need both authentication and security context for a handler\n\nUsage:\n\n\thandler := funcspec.NewHandler(db)\n\twrappedHandler := security.WithAuthAndSecurity(handler.SqlQueryList(\"SELECT * FROM users\", false, false, false), securityList)\n\trouter.HandleFunc(\"/api/users\", wrappedHandler)\n\n```go\nfunc WithOptionalAuth(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)\n```\nWithOptionalAuth wraps an HTTPFuncType handler with optional authentication This function tries to authenticate but falls back to guest context if authentication fails Use this for handlers that should show personalized content for authenticated users but still work for guests\n\nUsage:\n\n\thandler := funcspec.NewHandler(db)\n\twrappedHandler := security.WithOptionalAuth(handler.SqlQueryList(\"SELECT * FROM products\", false, false, false), securityList)\n\trouter.HandleFunc(\"/api/products\", wrappedHandler)\n\n```go\nfunc WithOptionalAuthAndSecurity(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)\n```\nWithOptionalAuthAndSecurity wraps an HTTPFuncType handler with optional authentication and security context This is a convenience function that combines WithOptionalAuth and WithSecurityContext Use this when you want optional authentication and security context for a handler\n\nUsage:\n\n\thandler := funcspec.NewHandler(db)\n\twrappedHandler := security.WithOptionalAuthAndSecurity(handler.SqlQueryList(\"SELECT * FROM products\", false, false, false), securityList)\n\trouter.HandleFunc(\"/api/products\", wrappedHandler)\n\n```go\nfunc WithRequestInfo(ctx context.Context, r *http.Request, opts ...RequestInfoOptions) context.Context\n```\nWithRequestInfo returns a context carrying details of r: client IP and port, private-IP flag, previous session token, device id, client id, user agent, server IP and port, host, origin and referer. Login, LoginWithAPIKey and LoginWithPasskey add them to the login claims (see the Claim\\* constants); empty values are left out.\n\n```go\nfunc WithSecurityContext(handler func(http.ResponseWriter, *http.Request), securityList *SecurityList) func(http.ResponseWriter, *http.Request)\n```\nWithSecurityContext wraps an HTTPFuncType handler with security context This function allows you to add security context to specific handler functions without needing to apply middleware globally\n\nUsage:\n\n\thandler := funcspec.NewHandler(db)\n\twrappedHandler := security.WithSecurityContext(handler.SqlQueryList(\"SELECT * FROM users\", false, false, false), securityList)\n\trouter.HandleFunc(\"/api/users\", wrappedHandler)\n\n## Types\n\n```go\ntype APIKeyLoginable interface {\n\t// LoginWithAPIKey validates the raw API key and creates a session for its user.\n\t// Unknown, expired and inactive keys all yield the same generic error.\n\tLoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)\n}\n```\nAPIKeyLoginable allows providers to exchange a raw API key for a session.\n\n```go\ntype AccessTokenClaims struct {\n\tSubject   string\n\tUserID    int\n\tClientID  string\n\tScopes    []string\n\tAudience  []string\n\tJTI       string\n\tSessionID string\n\tExpiresAt time.Time\n\t// DPoPKey is the thumbprint of the key the token is bound to, or \"\".\n\tDPoPKey string\n\t// JWT is true for RFC 9068 JWT access tokens.\n\tJWT bool\n}\n```\nAccessTokenClaims describes a verified access token.\n\n```go\ntype Authenticator interface {\n\t// Login authenticates credentials and returns a token\n\tLogin(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n\n\t// LoginWithCookie authenticates credentials and, when cookie sessions are enabled,\n\t// writes the session cookie to w. Implementations that do not support cookies\n\t// should delegate to Login and ignore w.\n\tLoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)\n\n\t// Logout invalidates a user's session/token\n\tLogout(ctx context.Context, req LogoutRequest) error\n\n\t// LogoutWithCookie invalidates a user's session/token and, when cookie sessions are\n\t// enabled, clears the session cookie on w. Implementations that do not support cookies\n\t// should delegate to Logout and ignore w.\n\tLogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error\n\n\t// Authenticate extracts and validates user from HTTP request\n\t// Returns UserContext or error if authentication fails\n\tAuthenticate(r *http.Request) (*UserContext, error)\n\n\t// SetAuthenticateCallback registers a fallback called when primary authentication fails.\n\t// If the callback returns a non-nil UserContext, that result is used instead of the error.\n\tSetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))\n}\n```\nAuthenticator handles user authentication operations\n\n```go\ntype CONTEXT_KEY string\n```\n\n```go\nconst SECURITY_CONTEXT_KEY CONTEXT_KEY = \"SecurityList\"\n```\n\n```go\ntype Cacheable interface {\n\t// ClearCache clears cached security rules for a user/entity\n\tClearCache(ctx context.Context, userID int, schema, table string) error\n}\n```\nCacheable allows providers to support caching of security rules\n\n```go\ntype ChainAuthenticator struct {\n\t// contains filtered or unexported fields\n}\n```\nChainAuthenticator tries each authenticator in order, returning the first success. Login and Logout are delegated to the primary authenticator.\n\n```go\nfunc NewChainAuthenticator(primary Authenticator, rest ...Authenticator) *ChainAuthenticator\n```\nNewChainAuthenticator creates a ChainAuthenticator from the given authenticators. At least one authenticator is required; the first is treated as primary for Login/Logout.\n\n```go\nfunc (c *ChainAuthenticator) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (c *ChainAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (c *ChainAuthenticator) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)\n```\nLoginWithAPIKey tries each authenticator that supports API key login and returns the first success. Failures collapse to one generic error.\n\n```go\nfunc (c *ChainAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)\n```\n\n```go\nfunc (c *ChainAuthenticator) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\nfunc (c *ChainAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error\n```\n\n```go\nfunc (c *ChainAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))\n```\n\n```go\ntype ColumnSecurity = sectypes.ColumnSecurity\n```\n\n```go\ntype ColumnSecurityProvider interface {\n\t// GetColumnSecurity loads column security rules for a user and entity\n\tGetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)\n}\n```\nColumnSecurityProvider handles column-level security (masking/hiding)\n\n```go\ntype CompositeSecurityProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nCompositeSecurityProvider combines multiple security providers Allows separating authentication, column security, and row security concerns\n\n```go\nfunc NewCompositeSecurityProvider(\n\tauth Authenticator,\n\tcolSec ColumnSecurityProvider,\n\trowSec RowSecurityProvider,\n) (*CompositeSecurityProvider, error)\n```\nNewCompositeSecurityProvider creates a composite provider All parameters are required\n\n```go\nfunc (c *CompositeSecurityProvider) Authenticate(r *http.Request) (*UserContext, error)\n```\nAuthenticate delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) ClearCache(ctx context.Context, userID int, schema, table string) error\n```\nClearCache implements Cacheable if any provider supports it\n\n```go\nfunc (c *CompositeSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)\n```\nGetColumnSecurity delegates to the column security provider\n\n```go\nfunc (c *CompositeSecurityProvider) GetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)\n```\nGetRowSecurity delegates to the row security provider\n\n```go\nfunc (c *CompositeSecurityProvider) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\nLogin delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)\n```\nLoginWithAPIKey implements APIKeyLoginable if the authenticator supports it\n\n```go\nfunc (c *CompositeSecurityProvider) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)\n```\nLoginWithCookie delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) Logout(ctx context.Context, req LogoutRequest) error\n```\nLogout delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error\n```\nLogoutWithCookie delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)\n```\nRefreshToken implements Refreshable if the authenticator supports it\n\n```go\nfunc (c *CompositeSecurityProvider) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))\n```\nSetAuthenticateCallback delegates to the authenticator\n\n```go\nfunc (c *CompositeSecurityProvider) ValidateToken(ctx context.Context, token string) (bool, error)\n```\nValidateToken implements Validatable if the authenticator supports it\n\n```go\ntype CreateKeyRequest = sectypes.CreateKeyRequest\n```\n\n```go\ntype CreateKeyResponse = sectypes.CreateKeyResponse\n```\n\n```go\ntype DatabaseAuthenticator struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabaseAuthenticator provides session-based authentication with database storage All database operations go through stored procedures for security and consistency Procedure names and modes are configured through lookup.Config (see lookup.DefaultProcNames) See lookup/database\\_schema.sql for procedure definitions Also supports multiple OAuth2 providers configured with WithOAuth2() Also supports passkey authentication configured with WithPasskey()\n\n```go\nfunc NewDatabaseAuthenticator(db *sql.DB) *DatabaseAuthenticator\n```\n\n```go\nfunc NewDatabaseAuthenticatorWithOptions(db *sql.DB, opts DatabaseAuthenticatorOptions) *DatabaseAuthenticator\n```\n\n```go\nfunc NewFacebookAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator\n```\nNewFacebookAuthenticator creates a DatabaseAuthenticator configured for Facebook OAuth2\n\n```go\nfunc NewGitHubAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator\n```\nNewGitHubAuthenticator creates a DatabaseAuthenticator configured for GitHub OAuth2\n\n```go\nfunc NewGoogleAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator\n```\nNewGoogleAuthenticator creates a DatabaseAuthenticator configured for Google OAuth2\n\n```go\nfunc NewMicrosoftAuthenticator(clientID, clientSecret, redirectURL string, db *sql.DB) *DatabaseAuthenticator\n```\nNewMicrosoftAuthenticator creates a DatabaseAuthenticator configured for Microsoft OAuth2\n\n```go\nfunc NewMultiProviderAuthenticator(db *sql.DB, configs map[string]OAuth2Config) *DatabaseAuthenticator\n```\nNewMultiProviderAuthenticator creates a DatabaseAuthenticator with all major OAuth2 providers configured\n\n```go\nfunc (a *DatabaseAuthenticator) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (a *DatabaseAuthenticator) BeginPasskeyAuthentication(ctx context.Context, req PasskeyBeginAuthenticationRequest) (*PasskeyAuthenticationOptions, error)\n```\nBeginPasskeyAuthentication initiates passkey authentication\n\n```go\nfunc (a *DatabaseAuthenticator) BeginPasskeyRegistration(ctx context.Context, req PasskeyBeginRegistrationRequest) (*PasskeyRegistrationOptions, error)\n```\nBeginPasskeyRegistration initiates passkey registration for a user\n\n```go\nfunc (a *DatabaseAuthenticator) ClearCache(token string) error\n```\nClearCache removes a specific token from the cache or clears all cache if token is empty\n\n```go\nfunc (a *DatabaseAuthenticator) ClearUserCache(userID int) error\n```\nClearUserCache removes all cache entries for a specific user ID\n\n```go\nfunc (a *DatabaseAuthenticator) Close() error\n```\nClose stops the background OAuth2 state cleanup goroutines and waits for in-flight session activity updates. It is safe to call more than once.\n\n```go\nfunc (a *DatabaseAuthenticator) CompletePasskeyRegistration(ctx context.Context, req PasskeyRegisterRequest) (*PasskeyCredential, error)\n```\nCompletePasskeyRegistration completes passkey registration\n\n```go\nfunc (a *DatabaseAuthenticator) CompletePasswordReset(ctx context.Context, req PasswordResetCompleteRequest) error\n```\nCompletePasswordReset implements PasswordResettable. It validates the token and updates the user's password via resolvespec\\_password\\_reset.\n\n```go\nfunc (a *DatabaseAuthenticator) DeletePasskeyCredential(ctx context.Context, userID int, credentialID string) error\n```\nDeletePasskeyCredential removes a passkey credential\n\n```go\nfunc (a *DatabaseAuthenticator) GetPasskeyCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)\n```\nGetPasskeyCredentials returns all passkey credentials for a user\n\n```go\nfunc (a *DatabaseAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (a *DatabaseAuthenticator) LoginWithAPIKey(ctx context.Context, rawKey string, claims map[string]any) (*LoginResponse, error)\n```\nLoginWithAPIKey implements APIKeyLoginable. It validates a raw header/generic API key and creates a session for the key's user. Unknown, expired and inactive keys all return errInvalidAPIKey; the raw key is never logged. Procedure-only: the key and user lookup live in resolvespec\\_login\\_api\\_key so the underlying schema can differ per database; there is no direct-SQL path.\n\n```go\nfunc (a *DatabaseAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)\n```\nLoginWithCookie performs a login and, when EnableCookieSession is true, writes the session cookie to w using the configured CookieOptions. The LoginResponse is returned regardless of whether cookie sessions are enabled.\n\n```go\nfunc (a *DatabaseAuthenticator) LoginWithPasskey(ctx context.Context, req PasskeyLoginRequest) (*LoginResponse, error)\n```\nLoginWithPasskey authenticates a user using a passkey and creates a session\n\n```go\nfunc (a *DatabaseAuthenticator) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\nfunc (a *DatabaseAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error\n```\nLogoutWithCookie performs a logout and, when EnableCookieSession is true, clears the session cookie on w. The logout itself is performed regardless of the cookie flag.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2GenerateState() (string, error)\n```\nOAuth2GenerateState generates a random state string for CSRF protection\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2GetAuthURL(providerName, state string) (string, error)\n```\nOAuth2GetAuthURL returns the OAuth2 authorization URL for redirecting users\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2GetAuthURLWithOptions(providerName, state string, opts OAuth2AuthOptions) (string, error)\n```\nOAuth2GetAuthURLWithOptions is OAuth2GetAuthURL with OpenID Connect request parameters. For an OIDC provider (and with UsePKCE) it also creates the PKCE verifier and the nonce, which are kept with the state until the callback.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2GetProviders() []string\n```\nOAuth2GetProviders returns list of configured OAuth2 provider names\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2HandleCallback(ctx context.Context, providerName, code, state string) (*LoginResponse, error)\n```\nOAuth2HandleCallback handles the OAuth2 callback and exchanges code for token\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2HandleCallbackRequest(ctx context.Context, providerName string, r *http.Request) (*LoginResponse, error)\n```\nOAuth2HandleCallbackRequest is OAuth2HandleCallback for the redirect request itself. Besides code and state it honours the error parameters and the RFC 9207 \"iss\" parameter, which protects against mix-up attacks when several providers are in use.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2LogoutURL(ctx context.Context, providerName, idTokenHint, postLogoutRedirect, state string) (string, error)\n```\nOAuth2LogoutURL returns the provider's RP-initiated logout URL (OIDC RP-Initiated Logout 1.0). idTokenHint is LoginResponse.Meta\\[\"id\\_token\"]. It fails when the provider has no end\\_session\\_endpoint.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuth2RefreshToken(ctx context.Context, refreshToken, providerName string) (*LoginResponse, error)\n```\nOAuth2RefreshToken refreshes an expired OAuth2 access token using the refresh token Takes the refresh token and returns a new LoginResponse with updated tokens\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthDeleteClient(ctx context.Context, clientID string) error\n```\nOAuthDeleteClient deactivates a registered client (RFC 7592).\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthExchangeCode(ctx context.Context, code string) (*OAuthCode, error)\n```\nOAuthExchangeCode retrieves and deletes an authorization code (single use).\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthGetClient(ctx context.Context, clientID string) (*OAuthServerClient, error)\n```\nOAuthGetClient retrieves a registered client by ID.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthGetUser(ctx context.Context, userID int) (*UserContext, error)\n```\nOAuthGetUser returns the active user with the given id.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthGrants() lookup.OAuthGrantStore\n```\nOAuthGrants returns the store holding consents, managed refresh tokens, device codes, pushed authorization requests and the replay cache.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthIntrospectToken(ctx context.Context, token string) (*OAuthTokenInfo, error)\n```\nOAuthIntrospectToken validates a token and returns its metadata (RFC 7662).\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthRegisterClient(ctx context.Context, client *OAuthServerClient) (*OAuthServerClient, error)\n```\nOAuthRegisterClient persists an OAuth2 client registration.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthRevokeToken(ctx context.Context, token string) error\n```\nOAuthRevokeToken revokes a token by deleting the session (RFC 7009).\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthSaveCode(ctx context.Context, code *OAuthCode) error\n```\nOAuthSaveCode persists an authorization code.\n\n```go\nfunc (a *DatabaseAuthenticator) OAuthUpdateClient(ctx context.Context, client *OAuthServerClient) error\n```\nOAuthUpdateClient replaces the registered metadata of a client (RFC 7592).\n\n```go\nfunc (a *DatabaseAuthenticator) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)\n```\nRefreshToken implements Refreshable interface\n\n```go\nfunc (a *DatabaseAuthenticator) Register(ctx context.Context, req RegisterRequest) (*LoginResponse, error)\n```\nRegister implements Registrable interface\n\n```go\nfunc (a *DatabaseAuthenticator) RequestPasswordReset(ctx context.Context, req PasswordResetRequest) (*PasswordResetResponse, error)\n```\nRequestPasswordReset implements PasswordResettable. It calls the stored procedure resolvespec\\_password\\_reset\\_request and returns the reset token and expiry.\n\n```go\nfunc (a *DatabaseAuthenticator) SetAuthenticateCallback(fn func(r *http.Request) (*UserContext, error))\n```\n\n```go\nfunc (a *DatabaseAuthenticator) UpdatePasskeyCredentialName(ctx context.Context, userID int, credentialID string, name string) error\n```\nUpdatePasskeyCredentialName updates the friendly name of a credential\n\n```go\nfunc (a *DatabaseAuthenticator) WithOAuth2(cfg OAuth2Config) *DatabaseAuthenticator\n```\nWithOAuth2 configures OAuth2 support for the DatabaseAuthenticator Can be called multiple times to add multiple OAuth2 providers Returns the same DatabaseAuthenticator instance for method chaining\n\n```go\nfunc (a *DatabaseAuthenticator) WithOIDC(ctx context.Context, cfg OIDCConfig) (*DatabaseAuthenticator, error)\n```\nWithOIDC registers an OpenID Connect provider. The endpoints come from the issuer's discovery document. Login uses PKCE and a nonce, and the id\\_token is validated on callback and refresh.\n\n```go\nfunc (a *DatabaseAuthenticator) WithPasskey(provider PasskeyProvider) *DatabaseAuthenticator\n```\nWithPasskey configures the DatabaseAuthenticator with a passkey provider\n\n```go\ntype DatabaseAuthenticatorExample struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewDatabaseAuthenticatorExample(db *gorm.DB) *DatabaseAuthenticatorExample\n```\n\n```go\nfunc (a *DatabaseAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (a *DatabaseAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (a *DatabaseAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\nfunc (a *DatabaseAuthenticatorExample) RefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)\n```\nOptional: Implement Refreshable interface\n\n```go\ntype DatabaseAuthenticatorOptions struct {\n\t// CacheTTL is the duration to cache user contexts\n\t// Default: 5 minutes\n\tCacheTTL time.Duration\n\t// Cache is an optional cache instance. If nil, uses the default cache\n\tCache *cache.Cache\n\t// PasskeyProvider is an optional passkey provider for WebAuthn/FIDO2 authentication\n\tPasskeyProvider PasskeyProvider\n\t// Lookup selects dialect, query mode and procedure/table/column names.\n\t// The zero value uses stored procedures on Postgres and direct SQL elsewhere.\n\tLookup lookup.Config\n\t// LookupProvider, when set, is used instead of building one from Lookup and the db.\n\tLookupProvider *lookup.Provider\n\t// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.\n\t// If nil, reconnection is disabled.\n\tDBFactory func() (*sql.DB, error)\n\t// EnableCookieSession enables cookie-based session management.\n\t// When true, Authenticate reads the session token from the cookie named by\n\t// CookieOptions.Name (default \"session_token\") in addition to the Authorization header,\n\t// and LoginWithCookie / LogoutWithCookie automatically set / clear the cookie.\n\tEnableCookieSession bool\n\t// UpgradePasswordHash, when true, rewrites a legacy cleartext password as a\n\t// bcrypt hash after a successful login. It is off by default and is never\n\t// enabled automatically: legacy cleartext values are still accepted at login,\n\t// but stored rows are left untouched unless this is set.\n\tUpgradePasswordHash bool\n\t// CookieOptions configures the session cookie written by LoginWithCookie.\n\t// Only used when EnableCookieSession is true.\n\tCookieOptions SessionCookieOptions\n\t// AuthenticateCallback is a fallback called when the primary authentication (database\n\t// session lookup) fails. If non-nil and the callback returns a non-nil UserContext,\n\t// that result is used in place of the failure.\n\tAuthenticateCallback func(r *http.Request) (*UserContext, error)\n}\n```\nDatabaseAuthenticatorOptions configures the database authenticator\n\n```go\ntype DatabaseColumnSecurityProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabaseColumnSecurityProvider loads column security through the lookup package (stored procedure on Postgres by default, direct SQL elsewhere).\n\n```go\nfunc NewDatabaseColumnSecurityProvider(db *sql.DB) *DatabaseColumnSecurityProvider\n```\n\n```go\nfunc (p *DatabaseColumnSecurityProvider) GetColumnSecurity(ctx context.Context, userID int, schema, table string) ([]ColumnSecurity, error)\n```\n\n```go\nfunc (p *DatabaseColumnSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseColumnSecurityProvider\n```\n\n```go\nfunc (p *DatabaseColumnSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseColumnSecurityProvider\n```\nWithLookup configures dialect, query mode and names. Call before first use.\n\n```go\nfunc (p *DatabaseColumnSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseColumnSecurityProvider\n```\nWithLookupProvider uses an existing provider instead of building one.\n\n```go\nfunc (p *DatabaseColumnSecurityProvider) WithNoGroupTables() *DatabaseColumnSecurityProvider\n```\nWithNoGroupTables skips group membership when loading rules in direct mode.\n\n```go\ntype DatabaseKeyStore struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabaseKeyStore is a KeyStore backed by the lookup package (stored procedures on Postgres by default, direct SQL elsewhere). The raw key is never passed to the database.\n\nSee lookup/keystore\\_schema.sql for the required table and procedure definitions.\n\nNote: DeleteKey invalidates the cache entry for the deleted key. Due to the cache TTL, a deleted key may continue to authenticate for up to CacheTTL (default 2 minutes) if the cache entry cannot be invalidated.\n\n```go\nfunc NewDatabaseKeyStore(db *sql.DB, opts ...DatabaseKeyStoreOptions) *DatabaseKeyStore\n```\nNewDatabaseKeyStore creates a DatabaseKeyStore with optional configuration.\n\n```go\nfunc (ks *DatabaseKeyStore) CreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)\n```\nCreateKey generates a raw key, stores its SHA-256 hash via the create procedure, and returns the raw key once.\n\n```go\nfunc (ks *DatabaseKeyStore) DeleteKey(ctx context.Context, userID int, keyID int64) error\n```\nDeleteKey soft-deletes a key after verifying ownership and invalidates its cache entry. The delete procedure returns the key\\_hash so no separate lookup is needed. Note: cache invalidation is best-effort; a cached entry may persist for up to CacheTTL.\n\n```go\nfunc (ks *DatabaseKeyStore) GetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)\n```\nGetUserKeys returns all active, non-expired keys for the given user. Pass an empty KeyType to return all types.\n\n```go\nfunc (ks *DatabaseKeyStore) ValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)\n```\nValidateKey hashes the raw key and calls the validate procedure. Results are cached for CacheTTL to reduce DB load on hot paths.\n\n```go\ntype DatabaseKeyStoreOptions struct {\n\t// Cache is an optional cache instance. If nil, uses the default cache.\n\tCache *cache.Cache\n\t// CacheTTL is the duration to cache ValidateKey results.\n\t// Default: 2 minutes.\n\tCacheTTL time.Duration\n\t// Lookup selects dialect, query mode and procedure/table/column names.\n\t// The zero value uses stored procedures on Postgres and direct SQL elsewhere.\n\tLookup lookup.Config\n\t// LookupProvider, when set, is used instead of building one from Lookup and the db.\n\tLookupProvider *lookup.Provider\n\t// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.\n\t// If nil, reconnection is disabled.\n\tDBFactory func() (*sql.DB, error)\n}\n```\nDatabaseKeyStoreOptions configures DatabaseKeyStore.\n\n```go\ntype DatabasePasskeyProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabasePasskeyProvider implements PasskeyProvider on top of the lookup package (stored procedures on Postgres by default, direct SQL elsewhere).\n\n```go\nfunc NewDatabasePasskeyProvider(db *sql.DB, opts DatabasePasskeyProviderOptions) *DatabasePasskeyProvider\n```\nNewDatabasePasskeyProvider creates a new database-backed passkey provider\n\n```go\nfunc (p *DatabasePasskeyProvider) BeginAuthentication(ctx context.Context, username string) (*PasskeyAuthenticationOptions, error)\n```\nBeginAuthentication creates authentication options for passkey login\n\n```go\nfunc (p *DatabasePasskeyProvider) BeginRegistration(ctx context.Context, userID int, username, displayName string) (*PasskeyRegistrationOptions, error)\n```\nBeginRegistration creates registration options for a new passkey\n\n```go\nfunc (p *DatabasePasskeyProvider) CompleteAuthentication(ctx context.Context, response PasskeyAuthenticationResponse, expectedChallenge []byte) (int, error)\n```\nCompleteAuthentication verifies a passkey assertion and returns the user ID NOTE: This is a simplified implementation. In production, you should use a WebAuthn library like github.com/go-webauthn/webauthn to properly verify the assertion signature.\n\n```go\nfunc (p *DatabasePasskeyProvider) CompleteRegistration(ctx context.Context, userID int, response PasskeyRegistrationResponse, expectedChallenge []byte) (*PasskeyCredential, error)\n```\nCompleteRegistration verifies and stores a new passkey credential NOTE: This is a simplified implementation. In production, you should use a WebAuthn library like github.com/go-webauthn/webauthn to properly verify attestation and parse credentials.\n\n```go\nfunc (p *DatabasePasskeyProvider) DeleteCredential(ctx context.Context, userID int, credentialID string) error\n```\nDeleteCredential removes a passkey credential\n\n```go\nfunc (p *DatabasePasskeyProvider) GetCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)\n```\nGetCredentials returns all passkey credentials for a user\n\n```go\nfunc (p *DatabasePasskeyProvider) UpdateCredentialName(ctx context.Context, userID int, credentialID string, name string) error\n```\nUpdateCredentialName updates the friendly name of a credential\n\n```go\ntype DatabasePasskeyProviderOptions struct {\n\t// RPID is the Relying Party ID (typically your domain, e.g., \"example.com\")\n\tRPID string\n\t// RPName is the display name for your relying party\n\tRPName string\n\t// RPOrigin is the expected origin (e.g., \"https://example.com\")\n\tRPOrigin string\n\t// Timeout is the timeout for operations in milliseconds (default: 60000)\n\tTimeout int64\n\t// Lookup selects dialect, query mode and procedure/table/column names.\n\tLookup lookup.Config\n\t// LookupProvider, when set, is used instead of building one from Lookup and the db.\n\tLookupProvider *lookup.Provider\n\t// DBFactory is called to obtain a fresh *sql.DB when the existing connection is closed.\n\t// If nil, reconnection is disabled.\n\tDBFactory func() (*sql.DB, error)\n}\n```\nDatabasePasskeyProviderOptions configures the passkey provider\n\n```go\ntype DatabaseRowSecurityProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabaseRowSecurityProvider loads row security through the lookup package (stored procedure on Postgres by default, direct SQL elsewhere).\n\n```go\nfunc NewDatabaseRowSecurityProvider(db *sql.DB) *DatabaseRowSecurityProvider\n```\n\n```go\nfunc (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)\n```\n\n```go\nfunc (p *DatabaseRowSecurityProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseRowSecurityProvider\n```\n\n```go\nfunc (p *DatabaseRowSecurityProvider) WithLookup(cfg lookup.Config) *DatabaseRowSecurityProvider\n```\nWithLookup configures dialect, query mode and names. Call before first use.\n\n```go\nfunc (p *DatabaseRowSecurityProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseRowSecurityProvider\n```\nWithLookupProvider uses an existing provider instead of building one.\n\n```go\nfunc (p *DatabaseRowSecurityProvider) WithNoGroupTables() *DatabaseRowSecurityProvider\n```\nWithNoGroupTables skips group membership when loading rules in direct mode.\n\n```go\ntype DatabaseTwoFactorProvider struct {\n\t// contains filtered or unexported fields\n}\n```\nDatabaseTwoFactorProvider implements TwoFactorAuthProvider on top of the lookup package (stored procedures on Postgres by default, direct SQL elsewhere). See lookup/database\\_schema.sql for procedure definitions\n\n```go\nfunc NewDatabaseTwoFactorProvider(db *sql.DB, config *totp.Config) *DatabaseTwoFactorProvider\n```\nNewDatabaseTwoFactorProvider creates a new database-backed 2FA provider\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Disable2FA(userID int) error\n```\nDisable2FA deactivates 2FA for a user\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Enable2FA(userID int, secret string, backupCodes []string) error\n```\nEnable2FA activates 2FA for a user\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Generate2FASecret(userID int, issuer, accountName string) (*TwoFactorSecret, error)\n```\nGenerate2FASecret creates a new secret for a user\n\n```go\nfunc (p *DatabaseTwoFactorProvider) GenerateBackupCodes(userID int, count int) ([]string, error)\n```\nGenerateBackupCodes creates backup codes for 2FA\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Get2FASecret(userID int) (string, error)\n```\nGet2FASecret retrieves the user's 2FA secret\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Get2FAStatus(userID int) (bool, error)\n```\nGet2FAStatus checks if user has 2FA enabled\n\n```go\nfunc (p *DatabaseTwoFactorProvider) Validate2FACode(secret string, code string) (bool, error)\n```\nValidate2FACode verifies a TOTP code\n\n```go\nfunc (p *DatabaseTwoFactorProvider) ValidateBackupCode(userID int, code string) (bool, error)\n```\nValidateBackupCode checks and consumes a backup code\n\n```go\nfunc (p *DatabaseTwoFactorProvider) WithDBFactory(factory func() (*sql.DB, error)) *DatabaseTwoFactorProvider\n```\nWithDBFactory configures a factory used to reopen the database connection if it is closed.\n\n```go\nfunc (p *DatabaseTwoFactorProvider) WithLookup(cfg lookup.Config) *DatabaseTwoFactorProvider\n```\nWithLookup configures dialect, query mode and names. Call before first use.\n\n```go\nfunc (p *DatabaseTwoFactorProvider) WithLookupProvider(lp *lookup.Provider) *DatabaseTwoFactorProvider\n```\nWithLookupProvider uses an existing provider instead of building one.\n\n```go\ntype HeaderAuthenticatorExample struct {\n}\n```\n\n```go\nfunc NewHeaderAuthenticatorExample() *HeaderAuthenticatorExample\n```\n\n```go\nfunc (a *HeaderAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (a *HeaderAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (a *HeaderAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\ntype JWTAuthenticator struct {\n\t// contains filtered or unexported fields\n}\n```\nJWTAuthenticator provides JWT token-based authentication All database operations go through stored procedures Procedure names and modes are configured through lookup.Config (see lookup.DefaultProcNames) NOTE: JWT signing/verification requires github.com/golang-jwt/jwt/v5 to be installed and imported\n\n```go\nfunc NewJWTAuthenticator(secretKey string, db *sql.DB) *JWTAuthenticator\n```\n\n```go\nfunc (a *JWTAuthenticator) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (a *JWTAuthenticator) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (a *JWTAuthenticator) LoginWithCookie(ctx context.Context, req LoginRequest, w http.ResponseWriter) (*LoginResponse, error)\n```\n\n```go\nfunc (a *JWTAuthenticator) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\nfunc (a *JWTAuthenticator) LogoutWithCookie(ctx context.Context, req LogoutRequest, w http.ResponseWriter) error\n```\n\n```go\nfunc (a *JWTAuthenticator) WithDBFactory(factory func() (*sql.DB, error)) *JWTAuthenticator\n```\nWithDBFactory configures a factory used to reopen the database connection if it is closed.\n\n```go\nfunc (a *JWTAuthenticator) WithLookup(cfg lookup.Config) *JWTAuthenticator\n```\nWithLookup configures dialect, query mode and names. Call before first use.\n\n```go\nfunc (a *JWTAuthenticator) WithLookupProvider(p *lookup.Provider) *JWTAuthenticator\n```\nWithLookupProvider uses an existing provider instead of building one.\n\n```go\nfunc (a *JWTAuthenticator) WithPasswordHashUpgrade(enabled bool) *JWTAuthenticator\n```\nWithPasswordHashUpgrade explicitly enables (or disables) upgrading legacy cleartext passwords to bcrypt after a successful login. Off by default.\n\n```go\ntype JWTAuthenticatorExample struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewJWTAuthenticatorExample(secretKey string, db *gorm.DB) *JWTAuthenticatorExample\n```\n\n```go\nfunc (a *JWTAuthenticatorExample) Authenticate(r *http.Request) (*UserContext, error)\n```\n\n```go\nfunc (a *JWTAuthenticatorExample) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)\n```\n\n```go\nfunc (a *JWTAuthenticatorExample) Logout(ctx context.Context, req LogoutRequest) error\n```\n\n```go\ntype KeyStore interface {\n\t// CreateKey generates a new key, stores its hash, and returns the raw key once.\n\tCreateKey(ctx context.Context, req CreateKeyRequest) (*CreateKeyResponse, error)\n\n\t// GetUserKeys returns all active, non-expired keys for a user.\n\t// Pass an empty KeyType to return all types.\n\tGetUserKeys(ctx context.Context, userID int, keyType KeyType) ([]UserKey, error)\n\n\t// DeleteKey soft-deletes a key by ID after verifying ownership.\n\tDeleteKey(ctx context.Context, userID int, keyID int64) error\n\n\t// ValidateKey checks a raw key, returns the matching UserKey on success.\n\t// The implementation hashes the raw key before any lookup.\n\t// Pass an empty KeyType to accept any type.\n\tValidateKey(ctx context.Context, rawKey string, keyType KeyType) (*UserKey, error)\n}\n```\nKeyStore manages per-user auth keys with pluggable storage backends. Implementations: ConfigKeyStore (static list) and DatabaseKeyStore (stored procedures).\n\n```go\ntype KeyType = sectypes.KeyType\n```\n\n```go\ntype LoginRequest = sectypes.LoginRequest\n```\n\n```go\ntype LoginResponse = sectypes.LoginResponse\n```\n\n```go\ntype LogoutRequest = sectypes.LogoutRequest\n```\n\n```go\ntype OAuth2AuthOptions struct {\n\tLoginHint string\n\tPrompt    string // none, login, consent, select_account\n\tMaxAge    *int\n\tACRValues string\n\tExtra     map[string]string\n}\n```\nOAuth2AuthOptions are optional OpenID Connect authentication request parameters.\n\n```go\ntype OAuth2Config struct {\n\tClientID     string\n\tClientSecret string\n\tRedirectURL  string\n\tScopes       []string\n\tAuthURL      string\n\tTokenURL     string\n\tUserInfoURL  string\n\tProviderName string\n\n\t// Optional: Custom user info parser\n\t// If not provided, will use standard claims (sub, email, name)\n\tUserInfoParser func(userInfo map[string]any) (*UserContext, error)\n\n\t// Issuer turns the provider into an OpenID Connect provider: PKCE and a nonce are used and\n\t// the id_token returned by the token endpoint is validated (signature, iss, aud, exp, nonce,\n\t// at_hash). WithOIDC fills the endpoints in by discovery; with WithOAuth2 set JWKSURL\n\t// as well. UserInfoURL stays optional: the id_token claims are used when it is empty.\n\tIssuer string\n\t// JWKSURL is the provider's key set. Only needed with WithOAuth2; WithOIDC discovers it.\n\tJWKSURL string\n\t// EndSessionURL is the provider's RP-initiated logout endpoint (discovered by WithOIDC).\n\tEndSessionURL string\n\t// UsePKCE sends a PKCE S256 challenge for a provider that is not OIDC. It is always on in OIDC mode.\n\tUsePKCE bool\n\t// AllowedAlgs lists the id_token signature algorithms to accept. Default: RS256, PS256, ES256, ES384.\n\tAllowedAlgs []string\n\t// AuthStyle selects how the client authenticates at the token endpoint: \"basic\", \"post\" or \"\"\n\t// (try basic, fall back to post).\n\tAuthStyle string\n\t// HTTPClient is used for discovery, JWKS, token and userinfo requests.\n\tHTTPClient *http.Client\n\t// ClockSkew tolerates clock differences when validating the id_token. Default 1 minute.\n\tClockSkew time.Duration\n}\n```\nOAuth2Config contains configuration for OAuth2 authentication\n\n```go\ntype OAuth2Provider struct {\n\t// contains filtered or unexported fields\n}\n```\nOAuth2Provider holds configuration and state for a single OAuth2 provider\n\n```go\ntype OAuthClaimsProvider func(ctx context.Context, req OAuthClaimsRequest) (map[string]any, error)\n```\nOAuthClaimsProvider returns the claims for a user. The server only includes the standard claims the granted scopes entitle the client to (profile, email, address, phone) plus every claim the client requested explicitly; claims outside those sets are dropped.\n\n```go\ntype OAuthClaimsRequest struct {\n\tUserID int\n\tSub    string\n\tScopes []string\n\t// Requested holds the names the client asked for individually through the OIDC \"claims\"\n\t// request parameter for this destination.\n\tRequested []string\n\t// Destination is \"id_token\" or \"userinfo\".\n\tDestination string\n\t// Base are the claims the server already knows (sub, preferred_username, email).\n\tBase map[string]any\n}\n```\nOAuthClaimsRequest is the input of an OAuthClaimsProvider.\n\n```go\ntype OAuthCode = sectypes.OAuthCode\n```\n\n```go\ntype OAuthConsentPage struct {\n\tTitle      string\n\tAction     string\n\tState      string // opaque, must be posted back as the \"req\" field\n\tClientName string\n\tClientURI  string\n\tLogoURI    string\n\tScopes     []OAuthScopeInfo\n\tUser       string\n\tHidden     map[string]string\n}\n```\nOAuthConsentPage is the data of the consent page template.\n\n```go\ntype OAuthLoginPage struct {\n\tTitle      string\n\tError      string\n\tAction     string // form action\n\tState      string // opaque, must be posted back as the \"req\" field\n\tClientName string\n\tLoginHint  string\n\t// Extra hidden fields to post back (device flow).\n\tHidden map[string]string\n}\n```\nOAuthLoginPage is the data of the login page template.\n\n```go\ntype OAuthSSOCookieConfig struct {\n\tName     string        // default \"resolvespec_sso\"\n\tPath     string        // default \"/\"\n\tTTL      time.Duration // default 8h\n\tSameSite http.SameSite // default Lax\n\t// Insecure sends the cookie over plain HTTP. By default Secure is on whenever Issuer is https.\n\tInsecure bool\n\tDisable  bool // never set a cookie: every authorization request authenticates again\n}\n```\nOAuthSSOCookieConfig configures the SSO cookie.\n\n```go\ntype OAuthScopeInfo struct {\n\tName        string\n\tDescription string\n}\n```\nOAuthScopeInfo is one line of the consent screen.\n\n```go\ntype OAuthServer struct {\n\t// contains filtered or unexported fields\n}\n```\nOAuthServer is an OAuth 2.1 authorization server and OpenID Connect provider.\n\nIt can act as both:\n\n  - A direct identity provider using DatabaseAuthenticator username/password login\n  - A federation layer that delegates authentication to external OAuth2 providers (Google, GitHub, Microsoft, etc.) registered via RegisterExternalProvider\n\nEndpoints (see OAUTH2\\_SERVER.md for parameters and examples):\n\n\tGET  /.well-known/oauth-authorization-server   RFC 8414 server metadata\n\tGET  /.well-known/openid-configuration         OIDC Discovery\n\tGET  /.well-known/oauth-protected-resource     RFC 9728 protected resource metadata\n\tPOST /oauth/register                            RFC 7591 dynamic client registration\n\tGET|PUT|DELETE /oauth/register/{client_id}      RFC 7592 client management\n\tGET|POST /oauth/authorize                       authorization endpoint (PKCE S256 required)\n\tPOST /oauth/token                               authorization_code, refresh_token, client_credentials,\n\t                                                 device_code and token-exchange grants\n\tPOST /oauth/par                                 RFC 9126 pushed authorization requests\n\tPOST /oauth/device_authorization                RFC 8628 device authorization\n\tGET|POST /oauth/device                          device verification page\n\tPOST /oauth/revoke                              RFC 7009 token revocation\n\tPOST /oauth/introspect                          RFC 7662 token introspection\n\tGET|POST /oauth/userinfo                        OIDC UserInfo\n\tGET  /oauth/jwks.json                           JWKS\n\tGET|POST /oauth/logout                          OIDC RP-initiated logout\n\tGET  {ProviderCallbackPath}                     external provider callback\n\n```go\nfunc NewOAuthServer(cfg OAuthServerConfig, auth *DatabaseAuthenticator) *OAuthServer\n```\nNewOAuthServer creates a new OAuth2 / OIDC authorization server.\n\nPass a DatabaseAuthenticator to enable direct username/password login (the server acts as its own identity provider). Pass nil to use only external providers. External providers are added separately via RegisterExternalProvider.\n\nCall Close() to stop background goroutines when the server is no longer needed.\n\n```go\nfunc (s *OAuthServer) Close()\n```\nClose stops the background goroutines started by NewOAuthServer. It is safe to call Close multiple times.\n\n```go\nfunc (s *OAuthServer) HTTPHandler() http.Handler\n```\nHTTPHandler returns an http.Handler that serves all RFC-required OAuth2 endpoints. Mount it at the root of your HTTP server alongside the MCP transport.\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/\", oauthServer.HTTPHandler())\n\tmux.Handle(\"/mcp/\", mcpTransport)\n\n```go\nfunc (s *OAuthServer) ProviderCallbackPath() string\n```\nProviderCallbackPath returns the configured path for external provider callbacks.\n\n```go\nfunc (s *OAuthServer) RegisterExternalProvider(auth *DatabaseAuthenticator, providerName string)\n```\nRegisterExternalProvider adds an external OAuth2 provider (Google, GitHub, Microsoft, etc.) that handles user authentication via redirect. The DatabaseAuthenticator must have been configured with WithOAuth2(providerName, ...) before calling this. Multiple providers can be registered; the first is used as the default. All providers must be registered before the server starts serving requests.\n\n```go\nfunc (s *OAuthServer) RegisterTrustedClient(ctx context.Context, c OAuthServerClient) (registered *OAuthServerClient, plainSecret string, err error)\n```\nRegisterTrustedClient registers a client programmatically and returns its plaintext secret (empty for a public client). Unlike dynamic registration it may set FirstParty (skips the consent screen), RequireConsent and RequirePAR, which a remote caller must not control. ClientID is generated when empty. Leave ClientSecretHash empty and set TokenEndpointAuthMethod to a client\\_secret\\_\\* method to have a secret generated.\n\n```go\nfunc (s *OAuthServer) VerifyAccessToken(ctx context.Context, token string, opts VerifyAccessTokenOptions) (*AccessTokenClaims, error)\n```\nVerifyAccessToken validates an access token issued by this server (JWT or opaque) against the store, so revoked tokens are rejected.\n\n```go\ntype OAuthServerClient = sectypes.OAuthServerClient\n```\n\n```go\ntype OAuthServerConfig struct {\n\t// Issuer is the public base URL of this server (e.g. \"https://api.example.com\"). It is\n\t// the \"iss\" of every token and the base of every endpoint URL. A path is allowed\n\t// (\"https://example.com/auth\"); the server then also answers the RFC 8414 path-insertion\n\t// well-known URLs.\n\tIssuer string\n\n\t// ProviderCallbackPath is the path on this server that external OAuth2 providers\n\t// redirect back to. Defaults to \"/oauth/provider/callback\".\n\tProviderCallbackPath string\n\n\t// LoginTitle is shown on the built-in login form when the server acts as its own\n\t// identity provider. Defaults to \"Sign in\".\n\tLoginTitle string\n\n\t// PersistClients stores registered clients in the database when a DatabaseAuthenticator is provided.\n\t// Clients registered during a session survive server restarts.\n\tPersistClients bool\n\n\t// PersistCodes stores authorization codes in the database.\n\t// Useful for multi-instance deployments. Defaults to in-memory.\n\tPersistCodes bool\n\n\t// DefaultScopes lists scopes advertised in server metadata and granted to clients that\n\t// register without allowed_scopes. Defaults to [\"openid\",\"profile\",\"email\"].\n\tDefaultScopes []string\n\n\t// AccessTokenTTL is the issued token lifetime. Defaults to 24h.\n\tAccessTokenTTL time.Duration\n\n\t// AuthCodeTTL is the auth code lifetime. Defaults to 2 minutes.\n\tAuthCodeTTL time.Duration\n\n\t// ResourceIdentifier is this server's protected-resource identifier, advertised in\n\t// RFC 9728 metadata. Defaults to Issuer.\n\tResourceIdentifier string\n\n\t// SigningKey signs id_tokens (RS256) and is exposed via the JWKS endpoint. If nil and\n\t// SigningKeys is empty, an RSA-2048 key is generated in memory when the server starts.\n\t// Supply a persistent key for multi-instance deployments so tokens remain verifiable\n\t// across restarts and instances.\n\tSigningKey *rsa.PrivateKey\n\n\t// SigningKeys supersedes SigningKey. The first key is the default; all are published in\n\t// the JWKS, which is how a key is rotated (add the new key first, publish, then remove the\n\t// old one once its tokens have expired). RSA and ECDSA (P-256/P-384) keys are supported.\n\tSigningKeys []OAuthSigningKey\n\n\t// CookieSecret keys the HMAC that protects the SSO cookie and the state carried through\n\t// the login and consent forms. Defaults to a value derived from the first signing key, so\n\t// instances sharing a signing key share sessions.\n\tCookieSecret []byte\n\n\t// SSOCookie configures the browser session cookie that makes prompt=none, max_age,\n\t// single sign-on and logout work.\n\tSSOCookie OAuthSSOCookieConfig\n\n\t// RequireConsent shows a consent screen for every client that is not first-party and has\n\t// no stored consent covering the requested scopes. A client can also opt in with its\n\t// require_consent metadata.\n\tRequireConsent bool\n\n\t// ConsentTTL is how long a stored consent is honoured. Defaults to 90 days.\n\tConsentTTL time.Duration\n\n\t// ManagedRefreshTokens makes the server issue and rotate its own refresh tokens (stored\n\t// hashed, one family per grant, reuse of a rotated token revokes the family). When false,\n\t// the refresh token of the underlying DatabaseAuthenticator is passed through as before.\n\tManagedRefreshTokens bool\n\n\t// RefreshTokenTTL is the absolute lifetime of a refresh token family. Defaults to 30 days.\n\tRefreshTokenTTL time.Duration\n\n\t// JWTAccessTokens issues RFC 9068 JWT access tokens instead of opaque session tokens.\n\t// Resource servers can verify them locally (VerifyAccessToken).\n\tJWTAccessTokens bool\n\n\t// AccessTokenAudience is the \"aud\" of JWT access tokens that were not requested for a\n\t// specific resource. Defaults to ResourceIdentifier.\n\tAccessTokenAudience string\n\n\t// EnableDPoP accepts RFC 9449 DPoP proofs at the token and userinfo endpoints and binds\n\t// the issued tokens to the proof key.\n\tEnableDPoP bool\n\n\t// EnablePAR serves the RFC 9126 pushed authorization request endpoint; RequirePAR makes it\n\t// mandatory for every client.\n\tEnablePAR  bool\n\tRequirePAR bool\n\tPARTTL     time.Duration // default 90 seconds\n\n\t// EnableDeviceFlow serves the RFC 8628 device authorization grant.\n\tEnableDeviceFlow  bool\n\tDeviceCodeTTL     time.Duration // default 10 minutes\n\tDevicePollSeconds int           // minimum poll interval, default 5\n\n\t// EnableTokenExchange serves the RFC 8693 token exchange grant.\n\tEnableTokenExchange bool\n\n\t// ClaimsProvider supplies the user claims for id_tokens and UserInfo (profile, email,\n\t// address, phone, custom claims). The default returns sub, preferred_username and email.\n\tClaimsProvider OAuthClaimsProvider\n\n\t// SupportedACR lists the authentication context class references advertised and accepted.\n\tSupportedACR []string\n\n\t// DisableLogout does not serve the RP-initiated logout endpoint.\n\tDisableLogout bool\n\n\t// InitialAccessToken, when set, must be presented as a Bearer token to register a client.\n\tInitialAccessToken string\n\n\t// AllowAnonymousIntrospection lets callers without client credentials use the revocation\n\t// and introspection endpoints. By default they must authenticate as a client.\n\tAllowAnonymousIntrospection bool\n\n\t// RateLimiter, when set, is called for every request to a token-issuing endpoint\n\t// (\"authorize\", \"token\", \"par\", \"device\", \"register\", \"introspect\", \"revoke\", \"userinfo\",\n\t// \"logout\"). Returning false answers 429.\n\tRateLimiter func(r *http.Request, endpoint string) bool\n\n\t// AllowPrivateNetworkFetch lets the server fetch client jwks_uri documents from loopback and\n\t// private addresses. Leave false in production (SSRF protection).\n\tAllowPrivateNetworkFetch bool\n\n\t// ScopeDescriptions are shown next to each scope on the consent screen. Built-in\n\t// descriptions exist for openid, profile, email and offline_access.\n\tScopeDescriptions map[string]string\n\n\t// LoginTemplate and ConsentTemplate replace the built-in pages. They receive\n\t// OAuthLoginPage and OAuthConsentPage.\n\tLoginTemplate   *template.Template\n\tConsentTemplate *template.Template\n}\n```\nOAuthServerConfig configures the OAuth2 / OpenID Connect authorization server.\n\nEvery field except Issuer is optional. The zero value of each new option keeps the behaviour of earlier versions; see OAUTH2\\_SERVER.md for the full guide.\n\n```go\ntype OAuthSigningKey struct {\n\t// ID is the JWKS \"kid\". Derived from the public key (RFC 7638 thumbprint) when empty.\n\tID string\n\t// Key is an *rsa.PrivateKey (RS256) or an *ecdsa.PrivateKey (ES256 for P-256, ES384 for P-384).\n\tKey crypto.Signer\n\t// Alg overrides the algorithm inferred from Key (RS256, PS256, ES256, ES384).\n\tAlg string\n}\n```\nOAuthSigningKey is a key the authorization server signs tokens with. The first configured key is the default; the others are published in the JWKS so tokens signed before a rotation stay verifiable, and a client can ask for one by id\\_token\\_signed\\_response\\_alg.\n\n```go\ntype OAuthTokenInfo = sectypes.OAuthTokenInfo\n```\n\n```go\ntype OIDCConfig struct {\n\t// Issuer is the provider's issuer URL; /.well-known/openid-configuration is fetched from it.\n\tIssuer       string\n\tClientID     string\n\tClientSecret string\n\tRedirectURL  string\n\t// Scopes defaults to openid, profile, email.\n\tScopes       []string\n\tProviderName string // default \"oidc\"\n\n\t// Optional, see OAuth2Config.\n\tUserInfoParser func(userInfo map[string]any) (*UserContext, error)\n\tAllowedAlgs    []string\n\tAuthStyle      string\n\tHTTPClient     *http.Client\n\tClockSkew      time.Duration\n}\n```\nOIDCConfig configures an OpenID Connect provider found by discovery.\n\n```go\ntype PasskeyAuthenticationOptions = sectypes.PasskeyAuthenticationOptions\n```\n\n```go\ntype PasskeyAuthenticationResponse = sectypes.PasskeyAuthenticationResponse\n```\n\n```go\nfunc ParsePasskeyAuthenticationResponse(data []byte) (*PasskeyAuthenticationResponse, error)\n```\nParsePasskeyAuthenticationResponse parses a JSON passkey authentication response\n\n```go\ntype PasskeyAuthenticatorAssertionResponse = sectypes.PasskeyAuthenticatorAssertionResponse\n```\n\n```go\ntype PasskeyAuthenticatorAttestationResponse = sectypes.PasskeyAuthenticatorAttestationResponse\n```\n\n```go\ntype PasskeyAuthenticatorSelection = sectypes.PasskeyAuthenticatorSelection\n```\n\n```go\ntype PasskeyBeginAuthenticationRequest struct {\n\tUsername string `json:\"username,omitempty\"` // Optional for resident key flow\n}\n```\nPasskeyBeginAuthenticationRequest contains options for starting passkey authentication\n\n```go\ntype PasskeyBeginRegistrationRequest struct {\n\tUserID      int    `json:\"user_id\"`\n\tUsername    string `json:\"username\"`\n\tDisplayName string `json:\"display_name\"`\n}\n```\nPasskeyBeginRegistrationRequest contains options for starting passkey registration\n\n```go\ntype PasskeyCredential = sectypes.PasskeyCredential\n```\n\n```go\ntype PasskeyCredentialDescriptor = sectypes.PasskeyCredentialDescriptor\n```\n\n```go\ntype PasskeyCredentialParam = sectypes.PasskeyCredentialParam\n```\n\n```go\ntype PasskeyLoginRequest struct {\n\tResponse          PasskeyAuthenticationResponse `json:\"response\"`\n\tExpectedChallenge []byte                        `json:\"expected_challenge\"`\n\tClaims            map[string]any                `json:\"claims\"` // Additional login data\n}\n```\nPasskeyLoginRequest contains passkey authentication data\n\n```go\ntype PasskeyProvider interface {\n\t// BeginRegistration creates registration options for a new passkey\n\tBeginRegistration(ctx context.Context, userID int, username, displayName string) (*PasskeyRegistrationOptions, error)\n\n\t// CompleteRegistration verifies and stores a new passkey credential\n\tCompleteRegistration(ctx context.Context, userID int, response PasskeyRegistrationResponse, expectedChallenge []byte) (*PasskeyCredential, error)\n\n\t// BeginAuthentication creates authentication options for passkey login\n\tBeginAuthentication(ctx context.Context, username string) (*PasskeyAuthenticationOptions, error)\n\n\t// CompleteAuthentication verifies a passkey assertion and returns the user\n\tCompleteAuthentication(ctx context.Context, response PasskeyAuthenticationResponse, expectedChallenge []byte) (int, error)\n\n\t// GetCredentials returns all passkey credentials for a user\n\tGetCredentials(ctx context.Context, userID int) ([]PasskeyCredential, error)\n\n\t// DeleteCredential removes a passkey credential\n\tDeleteCredential(ctx context.Context, userID int, credentialID string) error\n\n\t// UpdateCredentialName updates the friendly name of a credential\n\tUpdateCredentialName(ctx context.Context, userID int, credentialID string, name string) error\n}\n```\nPasskeyProvider handles passkey registration and authentication\n\n```go\ntype PasskeyRegisterRequest struct {\n\tUserID            int                         `json:\"user_id\"`\n\tResponse          PasskeyRegistrationResponse `json:\"response\"`\n\tExpectedChallenge []byte                      `json:\"expected_challenge\"`\n\tCredentialName    string                      `json:\"credential_name,omitempty\"`\n}\n```\nPasskeyRegisterRequest contains passkey registration data\n\n```go\ntype PasskeyRegistrationOptions = sectypes.PasskeyRegistrationOptions\n```\n\n```go\ntype PasskeyRegistrationResponse = sectypes.PasskeyRegistrationResponse\n```\n\n```go\nfunc ParsePasskeyRegistrationResponse(data []byte) (*PasskeyRegistrationResponse, error)\n```\nParsePasskeyRegistrationResponse parses a JSON passkey registration response\n\n```go\ntype PasskeyRelyingParty = sectypes.PasskeyRelyingParty\n```\n\n```go\ntype PasskeyUser = sectypes.PasskeyUser\n```\n\n```go\ntype PasswordResetCompleteRequest = sectypes.PasswordResetCompleteRequest\n```\n\n```go\ntype PasswordResetRequest = sectypes.PasswordResetRequest\n```\n\n```go\ntype PasswordResetResponse = sectypes.PasswordResetResponse\n```\n\n```go\ntype PasswordResettable interface {\n\t// RequestPasswordReset creates a reset token for the given email/username\n\tRequestPasswordReset(ctx context.Context, req PasswordResetRequest) (*PasswordResetResponse, error)\n\n\t// CompletePasswordReset validates the token and sets the new password\n\tCompletePasswordReset(ctx context.Context, req PasswordResetCompleteRequest) error\n}\n```\nPasswordResettable allows providers to support self-service password reset\n\n```go\ntype Refreshable interface {\n\t// RefreshToken exchanges a refresh token for a new access token\n\tRefreshToken(ctx context.Context, refreshToken string) (*LoginResponse, error)\n}\n```\nRefreshable allows providers to support token refresh\n\n```go\ntype RegisterRequest = sectypes.RegisterRequest\n```\n\n```go\ntype Registrable interface {\n\t// Register creates a new user account\n\tRegister(ctx context.Context, req RegisterRequest) (*LoginResponse, error)\n}\n```\nRegistrable allows providers to support user registration\n\n```go\ntype RequestInfo struct {\n\tIPAddress       string // client IP\n\tClientPort      string // port of the connecting peer\n\tIsPrivateIP     bool   // IPAddress is private, loopback or link-local\n\tPreviousSession string // session token the client already held\n\tDeviceID        string\n\tClientID        string // client-supplied application/client id\n\tUserAgent       string\n\tServerIPAddress string // local address that accepted the connection\n\tServerPort      string\n\tHost            string\n\tOrigin          string\n\tReferer         string\n}\n```\nRequestInfo is what the login methods learn about the calling client.\n\n```go\nfunc RequestInfoFromContext(ctx context.Context) (RequestInfo, bool)\n```\nRequestInfoFromContext returns the info stored by WithRequestInfo.\n\n```go\ntype RequestInfoOptions struct {\n\t// Cookie is used to find the previous session token.\n\tCookie SessionCookieOptions\n\t// TrustedProxies lists the CIDRs or IPs allowed to set X-Forwarded-For /\n\t// X-Real-IP. When set, those headers are only honoured if the connecting\n\t// peer is in the list, and X-Forwarded-For is read from the right, skipping\n\t// trusted proxies. When empty, the headers are trusted from any peer.\n\tTrustedProxies []string\n\t// IgnoreProxyHeaders always uses the connecting peer as the client IP.\n\tIgnoreProxyHeaders bool\n\t// DeviceIDHeader and DeviceIDCookie name where the device id comes from.\n\t// Defaults: \"X-Device-ID\" and \"device_id\".\n\tDeviceIDHeader string\n\tDeviceIDCookie string\n\t// ClientIDHeader names the header carrying the client id.\n\t// Default: \"X-Client-ID\".\n\tClientIDHeader string\n}\n```\nRequestInfoOptions tunes what WithRequestInfo and RequestInfoMiddleware read. The zero value trusts proxy headers from any peer, reads the default session cookie and takes the device id from X-Device-ID or the device\\_id cookie.\n\n```go\ntype RowSecurity = sectypes.RowSecurity\n```\n\n```go\ntype RowSecurityProvider interface {\n\t// GetRowSecurity loads row security rules for a user and entity.\n\t// userRef identifies the user and is opaque to the caller: it may be an int ID,\n\t// a string/UUID, or the full *security.UserContext (see SecurityContext.GetUserRef),\n\t// so providers backed by non-integer user identifiers (e.g. UUIDs) or that need\n\t// access to JWT claims can implement row security without relying on a numeric ID.\n\tGetRowSecurity(ctx context.Context, userRef any, schema, table string) (RowSecurity, error)\n}\n```\nRowSecurityProvider handles row-level security (filtering)\n\n```go\ntype SecurityContext interface {\n\tGetContext() context.Context\n\tGetUserID() (int, bool)\n\t// GetUserRef returns an opaque user identifier for row security lookups.\n\t// Unlike GetUserID, it is not required to be an integer: implementations backed by\n\t// non-integer identifiers (e.g. UUIDs) can return a string, or the full\n\t// *security.UserContext so a RowSecurityProvider can read JWT claims directly.\n\tGetUserRef() (any, bool)\n\tGetSchema() string\n\tGetEntity() string\n\tGetModel() interface{}\n\tGetQuery() interface{}\n\tSetQuery(interface{})\n\tGetResult() interface{}\n\tSetResult(interface{})\n}\n```\nSecurityContext is a generic interface that any spec can implement to integrate with security features This interface abstracts the common security context needs across different specs\n\n```go\ntype SecurityList struct {\n\tColumnSecurityMutex sync.RWMutex\n\tColumnSecurity      map[string][]ColumnSecurity\n\tRowSecurityMutex    sync.RWMutex\n\tRowSecurity         map[string]RowSecurity\n\t// contains filtered or unexported fields\n}\n```\nSecurityList manages security state and caching It wraps a SecurityProvider and provides caching and utility methods\n\n```go\nfunc GetSecurityList(ctx context.Context) (*SecurityList, bool)\n```\nGetSecurityList extracts the SecurityList from request context\n\n```go\nfunc NewSecurityList(provider SecurityProvider) (*SecurityList, error)\n```\nNewSecurityList creates a new security list with the given provider\n\n```go\nfunc (m *SecurityList) ApplyColumnSecurity(records reflect.Value, modelType reflect.Type, pUserID int, pSchema, pTablename string) (out reflect.Value, err error)\n```\n\n```go\nfunc (m *SecurityList) ClearSecurity(pUserID int, pSchema, pTablename string) error\n```\n\n```go\nfunc (m *SecurityList) ColumSecurityApplyOnRecord(prevRecord reflect.Value, newRecord reflect.Value, modelType reflect.Type, pUserID int, pSchema, pTablename string) ([]string, error)\n```\n\n```go\nfunc (m *SecurityList) GetRowSecurityTemplate(pUserRef any, pSchema, pTablename string) (out RowSecurity, err error)\n```\n\n```go\nfunc (m *SecurityList) LoadColumnSecurity(ctx context.Context, pUserID int, pSchema, pTablename string, pOverwrite bool) error\n```\n\n```go\nfunc (m *SecurityList) LoadRowSecurity(ctx context.Context, pUserRef any, pSchema, pTablename string, pOverwrite bool) (RowSecurity, error)\n```\n\n```go\nfunc (m *SecurityList) Provider() SecurityProvider\n```\nProvider returns the underlying security provider\n\n```go\nfunc (m *SecurityList) SetTxSettings(fn TxSettingsFunc)\n```\nSetTxSettings sets the function that provides transaction-local settings for every transaction opened by a spec that registered its security hooks with this list. Pass nil to disable. May be called before or after RegisterSecurityHooks.\n\n```go\nfunc (m *SecurityList) TxSettings() TxSettingsFunc\n```\nTxSettings returns the configured TxSettingsFunc, or nil.\n\n```go\ntype SecurityProvider interface {\n\tAuthenticator\n\tColumnSecurityProvider\n\tRowSecurityProvider\n}\n```\nSecurityProvider is the main interface combining all security concerns\n\n```go\ntype SessionCookieOptions struct {\n\t// Name is the cookie name. Defaults to \"session_token\".\n\tName string\n\t// Path is the cookie path. Defaults to \"/\".\n\tPath string\n\t// Domain restricts the cookie to a specific domain. Empty means current host.\n\tDomain string\n\t// Secure sets the Secure flag. Defaults to true.\n\t// Set to false only in local development over HTTP.\n\tSecure *bool\n\t// SameSite sets the SameSite policy. Defaults to http.SameSiteLaxMode.\n\tSameSite http.SameSite\n}\n```\nSessionCookieOptions configures the session cookie set by SetSessionCookie. All fields are optional; sensible secure defaults are applied when omitted.\n\n```go\ntype TwoFactorSecret = sectypes.TwoFactorSecret\n```\n\n```go\ntype TxSettingsFunc func(secCtx SecurityContext) (map[string]string, error)\n```\nTxSettingsFunc returns the transaction-local settings (e.g. RLS GUCs such as \"app.user\\_id\") to stamp on a transaction. It runs once per transaction, at OnTxBegin, before any other SQL. Returning an error rolls the transaction back.\n\n```go\ntype UserContext = sectypes.UserContext\n```\n\n```go\nfunc GetUserContext(ctx context.Context) (*UserContext, bool)\n```\nGetUserContext extracts the full user context from request context\n\n```go\ntype UserKey = sectypes.UserKey\n```\n\n```go\ntype Validatable interface {\n\t// ValidateToken checks if a token is valid without extracting full user context\n\tValidateToken(ctx context.Context, token string) (bool, error)\n}\n```\nValidatable allows providers to validate tokens without full authentication\n\n```go\ntype VerifyAccessTokenOptions struct {\n\t// Audience, when set, must be one of the token's audiences.\n\tAudience string\n\t// Scopes that must all be granted.\n\tScopes []string\n}\n```\nVerifyAccessTokenOptions tunes VerifyAccessToken.\n\n```go\ntype WriteDataContext interface {\n\tGetData() interface{}\n\tSetData(interface{})\n}\n```\nWriteDataContext is implemented by security contexts that expose the create/update payload of the operation in flight.\n\n","path":"github.com/bitechdev/ResolveSpec/pkg/security","name":"security","synopsis":"","isRedistributable":true}
