### Run the net/http example with Docker and Go Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Starts the PostgreSQL service, generates distinct random keys, sets required environment variables, and runs the example server. The key file is written to /tmp/goauth-example-keys.env and must be protected and retained. The server never prints secrets. ```sh docker compose -f examples/nethttp/compose.yaml up -d --wait # Generate distinct random keys once. Protect and retain this file between runs. (umask 077; GENERATE_KEYS=1 go run ./examples/nethttp > /tmp/goauth-example-keys.env) . /tmp/goauth-example-keys.env export DATABASE_URL='postgres://goauth:local-development-only@127.0.0.1:5432/goauth?sslmode=disable' export PUBLIC_ORIGIN='http://localhost:8080' export LOCALHOST_DEV=1 go run ./examples/nethttp ``` -------------------------------- ### Run the email-less host session example Source: https://github.com/assurrussa/goauth/blob/master/examples/hostsession/README.md Run the example from the repository root with Go 1.27.2 and an existing disposable PostgreSQL database. The DATABASE_URL must point to a database where the role can create tables and apply migrations. Never use a production or shared database. ```sh DATABASE_URL='postgres://localhost/goauth_hostsession_demo?sslmode=disable' go run ./examples/hostsession ``` -------------------------------- ### BeginLocalLoginEnrollment Source: https://github.com/assurrussa/goauth/blob/master/docs/required-mfa.md Starts the enrollment flow for a local factor, returning a setup secret/URL and ten recovery codes. Must be CSRF-protected. ```APIDOC ## BeginLocalLoginEnrollment ### Description Starts the enrollment flow for a local factor, returning a setup secret/URL and ten recovery codes. Must be CSRF-protected. ### Method POST ### Endpoint BeginLocalLoginEnrollment ### Response #### Success Response - **MFAEnrollment** (object) - Contains the setup secret/URL and ten recovery codes. #### Response Example ```json { "MFAEnrollment": { "secret": "...", "url": "...", "recoveryCodes": ["..."] } } ``` ``` -------------------------------- ### Run release candidate verification with disposable integration services Source: https://github.com/assurrussa/goauth/blob/master/README.md For an unreleased candidate, select installed browser tools as described in release verification, then start disposable integration services. Run these commands in sequence. ```sh make integration-up make release-candidate-readiness make integration-down ``` -------------------------------- ### BeginLocalLogin Source: https://github.com/assurrussa/goauth/blob/master/docs/required-mfa.md Starts a local login flow, returning a pending challenge of kind 'factor' or 'enrollment', or the existing final login for an unenrolled optional account. ```APIDOC ## BeginLocalLogin ### Description Starts a local login flow, returning a pending challenge of kind `factor` or `enrollment`, or the existing final login for an unenrolled optional account. ### Method POST ### Endpoint BeginLocalLogin ### Response #### Success Response - **pending challenge** (object) - A pending challenge of kind `factor` or `enrollment`, or the existing final login for an unenrolled optional account. #### Response Example ```json { "kind": "factor" } ``` ``` -------------------------------- ### Expected output of the host session example Source: https://github.com/assurrussa/goauth/blob/master/examples/hostsession/README.md The expected output after a successful run. It confirms that the email-less identity was authenticated, host membership was checked, and the host session was accepted. ```text Email-less identity authenticated; host membership checked; host session accepted. ``` -------------------------------- ### CompleteLocalLoginEnrollment Source: https://github.com/assurrussa/goauth/blob/master/docs/required-mfa.md Completes the enrollment flow by accepting a pending ID, exact enrollment ID, browser binding, and one TOTP. Atomically activates the setup and creates a new factor-admitted session. ```APIDOC ## CompleteLocalLoginEnrollment ### Description Completes the enrollment flow by accepting a pending ID, exact enrollment ID, browser binding, and one TOTP. Atomically activates the setup and creates a new factor-admitted session. ### Method POST ### Endpoint CompleteLocalLoginEnrollment ### Parameters #### Request Body - **pendingID** (string) - Required - The pending ID from the login flow. - **enrollmentID** (string) - Required - The exact enrollment ID. - **browserBinding** (string) - Required - The browser binding. - **totp** (string) - Required - One TOTP code. ### Response #### Success Response - **LoginResult** (object) - The existing final login result. #### Response Example ```json { "LoginResult": {} } ``` ``` -------------------------------- ### GET /api/me Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Returns the current authenticated user's profile information. Requires a bearer token. ```APIDOC ## GET /api/me ### Description Returns the current authenticated user's profile information. Requires a bearer token. ### Method GET ### Endpoint /api/me ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### Curl commands for API flow Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md A sequence of curl commands demonstrating the API flow: register, send email, verify email, login, get user info, and refresh token. The commands use placeholders like , , , and . ```sh curl -sS http://localhost:8080/api/register \ -H 'Content-Type: application/json' \ -d '{"email":"api@example.test","password":"Unique-API-Passphrase-1"}' # Paste the access token from the JSON response: curl -sS http://localhost:8080/api/email-send \ -H 'Authorization: Bearer ' -H 'Content-Type: application/json' -d '{}' # Then use the code delivered to Mailpit: curl -sS http://localhost:8080/api/email-verify \ -H 'Authorization: Bearer ' -H 'Content-Type: application/json' \ -d '{"code":""}' curl -sS http://localhost:8080/api/login \ -H 'Content-Type: application/json' \ -d '{"scheme":"email","identifier":"api@example.test","password":"Unique-API-Passphrase-1","realm":"user"}' curl -sS http://localhost:8080/api/me -H 'Authorization: Bearer ' curl -sS http://localhost:8080/api/refresh -H 'Content-Type: application/json' \ -d '{"refreshToken":""}' ``` -------------------------------- ### GET /me Source: https://github.com/assurrussa/goauth/blob/master/README.md Returns the current user's subject ID. Requires a valid access token with realm "user". ```APIDOC ## GET /me ### Description Returns the current user's subject ID. ### Method GET ### Endpoint /me ### Authentication Requires a valid access token with realm "user". ### Response #### Success Response (200) - **subjectId** (string) - The subject ID of the authenticated user. ``` -------------------------------- ### InAuthTransaction Source: https://github.com/assurrussa/goauth/blob/master/docs/owned-auth-transactions.md Starts an auth transaction on the Runtime. The callback receives a managed context; the executor is obtained separately via SQLExecutor(ctx). ```APIDOC ## InAuthTransaction ### Description Starts an auth transaction on the Runtime. The callback receives a managed context; the executor is obtained separately via SQLExecutor(ctx). ### Method Function ### Signature ```go func (r *Runtime) InAuthTransaction(ctx context.Context, fn func(context.Context) error) error ``` ### Parameters - **ctx** (context.Context) - Required - The context. - **fn** (func(context.Context) error) - Required - Callback that receives the managed context. Use the same context for participating auth operations and host SQL. ### Return Value - **error** - Returns nil on successful commit; otherwise an error. ``` -------------------------------- ### InOwnedAuthTransaction Source: https://github.com/assurrussa/goauth/blob/master/docs/owned-auth-transactions.md Starts an owned auth transaction on the Runtime's exact *sql.DB handle. Requires ownership of one outermost managed auth transaction and is intended for host entry points that prepare a shown-once credential, token or final authorization response and must confirm commit before publishing it. ```APIDOC ## InOwnedAuthTransaction ### Description Starts an owned auth transaction on the Runtime's exact *sql.DB handle. Requires ownership of one outermost managed auth transaction and is intended for host entry points that prepare a shown-once credential, token or final authorization response and must confirm commit before publishing it. ### Method Function ### Signature ```go func (r *Runtime) InOwnedAuthTransaction(ctx context.Context, fn func(context.Context) error) error ``` ### Parameters - **ctx** (context.Context) - Required - The context. Must not have a managed transaction on the same handle; otherwise returns postgres.ErrAuthTransactionAlreadyActive. - **fn** (func(context.Context) error) - Required - Callback that receives the managed context. Must not publish provisional results; errors roll back. ### Return Value - **error** - Returns nil only after successful commit and existing commit callbacks. Callback errors roll back. Cancellation and commit errors use existing auth transaction classification. goauth.ErrOperationOutcomeUnknown means commit could have happened. ### Behavior - If a context with a managed transaction on the same handle is used, returns postgres.ErrAuthTransactionAlreadyActive before fn, writes or a second BEGIN. - A context from a different handle is rejected even when its DSN is identical. - With no managed scope, starts one read-committed transaction. Existing InAuthTransaction, canonical operations, audit, enqueue, RBAC and host SQL using SQLExecutor(ctx) can join it. - Callback errors roll back. Nil is returned only after a successful commit and existing commit callbacks. ### Request Example ```go func prepareResponse(ctx context.Context, runtime *postgres.Runtime) (string, error) { var prepared string err := runtime.InOwnedAuthTransaction(ctx, func(txctx context.Context) error { // Perform participating checks and writes using txctx. // Assign the provisional response without publishing it here. prepared = "prepared response" return nil }) if err != nil { return "", err } return prepared, nil } ``` ``` -------------------------------- ### Wire PostgreSQL runtime and Fiber auth routes Source: https://github.com/assurrussa/goauth/blob/master/README.md Sets up a goauth PostgreSQL runtime with auto-migration, signing keys, token HMAC keys, outbox AEAD keys, and a notification sender, then mounts a Fiber app with register, login, refresh, password reset, email challenge, and /me routes. Requires a PostgreSQL DSN, three 32-byte key rings, and a NotificationSender. The /me route uses RequireRealm with RealmUser and returns the subject ID. ```go import ( "context" "net/url" "github.com/assurrussa/goauth" goauthfiber "github.com/assurrussa/goauth/fiber" "github.com/assurrussa/goauth/postgres" "github.com/gofiber/fiber/v3" ) func wireAuth( dsn string, signingKeys, tokenKeys, notificationKeys goauth.KeyRing, sender goauth.NotificationSender, ) (*fiber.App, *postgres.Runtime, error) { auth, err := postgres.NewRuntime(postgres.Config{ DSN: dsn, AutoMigrate: true, // use the host's migration lifecycle in production NotificationSender: sender, Runtime: goauth.Config{ Signing: goauth.SigningConfig{ Issuer: "https://auth.example.com", Audience: "example-app", Keys: signingKeys, }, TokenHMACKeys: tokenKeys, OutboxAEADKeys: notificationKeys, URLBuilder: goauth.URLBuilderFunc(func(_ context.Context, token string) (string, error) { return "https://app.example.com/reset?token=" + url.QueryEscape(token), nil }), }, }) if err != nil { return nil, nil, err } adapter, err := goauthfiber.New(auth) if err != nil { _ = auth.Close() return nil, nil, err } app := fiber.New() app.Post("/auth/register", adapter.Register) app.Post("/auth/login", adapter.Login) app.Post("/auth/refresh", adapter.Refresh) app.Post("/auth/password-reset", adapter.RequestPasswordReset) app.Post("/auth/email-challenge", adapter.RequireRealm(goauth.RealmUser, goauthfiber.RealmMiddlewareOptions{AllowConfirmation: true}), adapter.SendEmailChallenge) app.Post("/auth/email-challenge/verify", adapter.RequireRealm(goauth.RealmUser, goauthfiber.RealmMiddlewareOptions{AllowConfirmation: true}), adapter.VerifyEmailChallenge) app.Get("/me", adapter.RequireRealm(goauth.RealmUser, goauthfiber.RealmMiddlewareOptions{}), func(c fiber.Ctx) error { authContext, _ := goauthfiber.AuthContext(c) return c.JSON(fiber.Map{"subjectId": authContext.SubjectID.String()}) }) return app, auth, nil } ``` -------------------------------- ### Run standard verification commands Source: https://github.com/assurrussa/goauth/blob/master/README.md Use these commands to prepare the environment, run checks, integration tests, and vulnerability scans. Requires the Go version/toolchain in go.mod and tool versions in .github/workflows/ci.yml. ```sh make prepare make check make integration-local make vulnerability-check ``` -------------------------------- ### SQL: Preflight migration query for local credential profiles Source: https://github.com/assurrussa/goauth/blob/master/docs/local-identities.md Run this read-only query before enabling mixed mode to inspect every local credential's profile against the current and legacy profiles. It returns bounded profile metadata and counts without exposing PHC, salt, digest, or password contents. For the default current profile, expect argon2id, v=19, m=19456,t=2,p=1, salt length 22 and digest length 43 in unpadded Base64; the legacy profile uses m=65536,t=3,p=1 with the same encoded lengths. This grouping detects unsupported cost/length groups but does not replace the Runtime's bounded PHC parser and cryptographic checks. ```sql SELECT password_input_policy, CASE WHEN split_part(password_phc, '$', 2) = 'argon2id' THEN 'argon2id' ELSE 'invalid' END AS algorithm, CASE WHEN split_part(password_phc, '$', 3) = 'v=19' THEN 'v=19' ELSE 'invalid' END AS version, CASE WHEN split_part(password_phc, '$', 4) ~ '^m=[0-9]{1,7},t=[0-9]{1,2},p=[0-9]{1,2}$' THEN split_part(password_phc, '$', 4) ELSE 'invalid' END AS parameters, length(split_part(password_phc, '$', 5)) AS salt_encoded_length, length(split_part(password_phc, '$', 6)) AS digest_encoded_length, count(*) FROM auth_local_credentials GROUP BY 1, 2, 3, 4, 5, 6; ``` -------------------------------- ### Run tests and tear down Docker Compose Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Commands to run the Go tests with the race detector and to bring down the Docker Compose environment defined in examples/nethttp/compose.yaml. ```sh go test -race ./nethttp ./examples/nethttp docker compose -f examples/nethttp/compose.yaml down ``` -------------------------------- ### Run scheduled rate-limit event cleanup with default cutoff Source: https://github.com/assurrussa/goauth/blob/master/docs/rate-event-maintenance.md Shows a host running one scheduled batch with the default cutoff after validating the shared retention requirement. Uses `auth.CleanupRateLimitEvents` with a `Limit` of 500 and a 5-second timeout. The timeout and limit are host choices, not a cleanup cadence or a promise of execution time. ```go ctx, cancel := context.WithTimeout(maintenanceContext, 5*time.Second) defer cancel() removed, err := auth.CleanupRateLimitEvents(ctx, postgres.RateLimitCleanupRequest{ Limit: 500, }) ``` -------------------------------- ### Suggested verification commands Source: https://github.com/assurrussa/goauth/blob/master/docs/reauth-email-logout.md Commands to run on the declared toolchain and disposable services. These scoped checks do not replace the full make release-candidate-readiness gate. ```sh node --test examples/nethttp/app.test.mjs make check make integration make vulnerability-check make browser-acceptance ``` -------------------------------- ### POST /auth/login Source: https://github.com/assurrussa/goauth/blob/master/README.md Signs in a user with email and password. Returns account and tokens (accessToken, refreshToken, expiry, realm, scope). ```APIDOC ## POST /auth/login ### Description Signs in a user with email and password. ### Method POST ### Endpoint /auth/login ### Request Body - **scheme** (string) - Required - The authentication scheme, e.g., "email". - **identifier** (string) - Required - The user identifier, e.g., email address. - **password** (string) - Required - The user's password. - **realm** (string) - Required - The realm, e.g., "user". ### Response #### Success Response (200) - **account** - The authenticated account. - **tokens** - Contains accessToken, refreshToken, expiry, realm, and scope. ### Request Example ```json {"scheme":"email","identifier":"user@example.com","password":"...","realm":"user"} ``` ``` -------------------------------- ### Run integration tests for host session Source: https://github.com/assurrussa/goauth/blob/master/examples/hostsession/README.md Run the integration test suite with a dedicated DSN. The integration tests cover successful login, wrong password, missing membership, disabled subjects, stale prepared proofs, ambient-transaction refusal, pool ownership, project binding, and session rejection after changes. The command fails if the DSN is absent. ```sh GOAUTH_HOSTSESSION_TEST_DSN='postgres://localhost/goauth_hostsession_test?sslmode=disable' go test -race -tags=integration ./examples/hostsession ``` -------------------------------- ### Add host words while retaining the built-ins Source: https://github.com/assurrussa/goauth/blob/master/docs/local-password-blocklist.md Constructs a local common-password checker with host-supplied entries and the built-in common passwords, then assigns it to `PasswordPolicy.Blocklist`. The host owns dictionary selection and loading; do not use real user passwords. The constructor returns the existing `CommonPasswordChecker` interface. ```go checker, err := goauth.NewLocalCommonPasswordChecker( []string{"Tenant-Example-Passphrase", "Another-Example-Passphrase"}, goauth.WithBuiltInCommonPasswords(), ) if err != nil { return err } config.PasswordPolicy = goauth.PasswordPolicy{Blocklist: checker} // Use config with the existing goauth.NewRuntime assembly. ``` -------------------------------- ### POST /auth/register Source: https://github.com/assurrussa/goauth/blob/master/README.md Registers a new user and returns a confirmation-scoped session. Use the returned access token to request an email code and verify it. ```APIDOC ## POST /auth/register ### Description Registers a new user and returns a confirmation-scoped session. ### Method POST ### Endpoint /auth/register ### Response #### Success Response (200) - **account** - The created account details. - **tokens** - Contains accessToken, refreshToken, expiry, realm, and scope. ``` -------------------------------- ### POST /api/register Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Registers a new user with email and password. Returns an access token in the JSON response. ```APIDOC ## POST /api/register ### Description Registers a new user with email and password. Returns an access token in the JSON response. ### Method POST ### Endpoint /api/register ### Parameters #### Request Body - **email** (string) - Required - User's email address. - **password** (string) - Required - User's password. ### Request Example { "email": "api@example.test", "password": "Unique-API-Passphrase-1" } ### Response #### Success Response (200) - **accessToken** (string) - Access token for authenticated requests. #### Response Example { "accessToken": "" } ``` -------------------------------- ### postgres.Runtime.CleanupBatch(ctx, policy, perCategoryLimit) Source: https://github.com/assurrussa/goauth/blob/master/docs/bounded-maintenance.md Performs one explicit, opt-in maintenance pass to clean up expired sessions, notifications, rate limit events, and OIDC data. The perCategoryLimit must be between 1 and 1000, and the result includes OIDC request and code counts. ```APIDOC ## postgres.Runtime.CleanupBatch(ctx, policy, perCategoryLimit) ### Description Performs one explicit, opt-in maintenance pass to clean up expired sessions, notifications, rate limit events, and OIDC data. It does not schedule itself; callers must invoke it as needed. ### Method Function call ### Endpoint postgres.Runtime.CleanupBatch(ctx, policy, perCategoryLimit) ### Parameters - **ctx** (context.Context) - Required - The context for the operation. - **policy** (CleanupPolicy) - Required - The cleanup policy, including a Now function for time-based decisions. - **perCategoryLimit** (int) - Required - The maximum number of rows to clean per category. Must be between 1 and 1000 inclusive; zero is invalid. ### Response #### Success Response Returns a result that embeds the unchanged CleanupResult and adds OIDCRequests and OIDCCodes fields. Each numeric field is independently capped at perCategoryLimit, with RefreshFamilies and OIDCRefreshFamilies additionally capped at 32. The maximum total row changes is 12 * perCategoryLimit + 2 * min(perCategoryLimit, 32). ### Notes - No cursor or has_more flag is provided; call again later to continue eligible rows. - Busy subjects, locked rows, dependent parents, and remaining chain prefixes can leave backlog after any pass, including a zero-count pass. - Only row changes are bounded; scans may examine more rows, and no wall-clock or query work bound is promised. - No indexes or schema changes are added. ``` -------------------------------- ### POST /api/login Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Authenticates a user and returns a new access token. Supports email-based login with a password. ```APIDOC ## POST /api/login ### Description Authenticates a user and returns a new access token. Supports email-based login with a password. ### Method POST ### Endpoint /api/login ### Parameters #### Request Body - **scheme** (string) - Required - Authentication scheme (e.g., "email"). - **identifier** (string) - Required - User identifier (e.g., email address). - **password** (string) - Required - User's password. - **realm** (string) - Required - Realm for the user (e.g., "user"). ### Request Example { "scheme": "email", "identifier": "api@example.test", "password": "Unique-API-Passphrase-1", "realm": "user" } ### Response #### Success Response (200) - **accessToken** (string) - New access token. #### Response Example { "accessToken": "" } ``` -------------------------------- ### Runtime.AuthorizationSnapshot(ctx, project) Source: https://github.com/assurrussa/goauth/blob/master/docs/host-authorization-snapshots.md Reads RBAC and host-owned projections in a single read-only REPEATABLE READ transaction. The returned snapshot may be published only after a nil return; discard on failure. ```APIDOC ## Runtime.AuthorizationSnapshot(ctx, project) ### Description Reads RBAC and host-owned projections in a single read-only REPEATABLE READ transaction. The returned snapshot may be published only after a nil return; discard on failure. ### Method Function call ### Parameters - **ctx** (context) - Required - Context for the operation. - **project** (SQLExecutor) - Required - Receives an opaque SQLExecutor; use it, consume/close all rows, and never retain it. ### Response - **RBAC snapshot** - Returned on success; publish only after nil return. - **host data** - Captured host data; publish only after nil return. - **error** - Returned on failure; discard both snapshot and host data. ### Notes - Ambient managed transactions are rejected, including foreign database handles. - Avoids mixed membership/permission generations without copying canonical SQL. ``` -------------------------------- ### POST /auth/email-challenge/verify Source: https://github.com/assurrussa/goauth/blob/master/README.md Verifies an email challenge code. After verification, log in again to obtain a full-scope session. ```APIDOC ## POST /auth/email-challenge/verify ### Description Verifies an email challenge code. ### Method POST ### Endpoint /auth/email-challenge/verify ### Authentication Requires a valid access token with realm "user" and confirmation allowed. ### Request Body - **code** (string) - Required - The email verification code. ### Request Example ```json {"code":"..."} ``` ``` -------------------------------- ### ExpireNotifications(ctx, limit) Source: https://github.com/assurrussa/goauth/blob/master/docs/notification-outcomes.md Documents the optional host-maintenance method ExpireNotifications on postgres.Runtime, including its purpose, parameters, and constraints. ```APIDOC ## ExpireNotifications(ctx, limit) ### Description Provides optional bounded maintenance for expiring encrypted notification envelopes. It retires only expired envelopes, skips locked rows, clears payload and lease, and leaves all receipt rows, reset records, sessions, identities, and audit events intact. Calls join an existing managed transaction on the same database and reject foreign transaction contexts. Repeated batches are idempotent. Hosts may schedule bounded calls but must choose their own cadence. ### Method ExpireNotifications is a method of the `postgres.Runtime` type. ### Endpoint postgres.Runtime.ExpireNotifications(ctx, limit) ### Parameters - **ctx** (context.Context) - Required - Context for the operation. - **limit** (int) - Required - Limit for the number of notifications to process; must be between 1 and 1000. ### Response #### Success Response Returns nil on success. On error, returns an error value. ### Notes - The Runtime clock supplies the cutoff time. - Schema requirement: PostgreSQL schema 5 with the partial index and validated constraint. ``` -------------------------------- ### prepareResponse using InOwnedAuthTransaction Source: https://github.com/assurrussa/goauth/blob/master/docs/owned-auth-transactions.md Prepares a provisional response inside the owned auth transaction callback and publishes it only after the method returns nil. The callback must not write HTTP responses, send tokens, or expose prepared data. Every error returns an empty response to the caller, including unknown outcomes. ```go func prepareResponse(ctx context.Context, runtime *postgres.Runtime) (string, error) { var prepared string err := runtime.InOwnedAuthTransaction(ctx, func(txctx context.Context) error { // Perform participating checks and writes using txctx. // Assign the provisional response without publishing it here. prepared = "prepared response" return nil }) if err != nil { return "", err } return prepared, nil } ``` -------------------------------- ### POST /api/logout-all Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Logs out all sessions for the user. Requires a full user bearer token. ```APIDOC ## POST /api/logout-all ### Description Logs out all sessions for the user. Requires a full user bearer token. ### Method POST ### Endpoint /api/logout-all ### Parameters #### Request Body - (empty object) - Required - No body fields. ### Request Example {} ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### AuthenticateSession Source: https://github.com/assurrussa/goauth/blob/master/docs/required-mfa.md Authenticates a session, enforcing MFA policy and revocation. Used by standard adapters for live session authentication. ```APIDOC ## AuthenticateSession ### Description Authenticates a session, enforcing MFA policy and revocation. Used by standard adapters for live session authentication. ### Method POST ### Endpoint AuthenticateSession ### Response #### Success Response - **session** (object) - The authenticated session. #### Response Example ```json { "session": {} } ``` ``` -------------------------------- ### POST /auth/email-challenge Source: https://github.com/assurrussa/goauth/blob/master/README.md Sends an email challenge code to the authenticated user. Requires a user realm and allows confirmation. ```APIDOC ## POST /auth/email-challenge ### Description Sends an email challenge code to the authenticated user. ### Method POST ### Endpoint /auth/email-challenge ### Authentication Requires a valid access token with realm "user" and confirmation allowed. ``` -------------------------------- ### Call rate-limited Runtime operation with request context Source: https://github.com/assurrussa/goauth/blob/master/docs/rate-limit-transactions.md Use the Runtime's own transaction for an ordinary operation, such as ChangePassword, with the request context. Do not wrap this call in store.InAuthTransaction. ```go account, err := runtime.ChangePassword(requestContext, request) ``` -------------------------------- ### Runtime.ObserveAuthTransaction(ctx, observer) Source: https://github.com/assurrussa/goauth/blob/master/docs/host-authorization-snapshots.md Registers a bounded host callback before host writes in a managed auth transaction. The callback receives only the final outer outcome: Committed, RolledBack, or Unknown. ```APIDOC ## Runtime.ObserveAuthTransaction(ctx, observer) ### Description Registers a bounded host callback before host writes in a managed auth transaction. The callback receives only the final outer outcome: Committed, RolledBack, or Unknown. ### Method Function call ### Parameters - **ctx** (context) - Required - Context for the operation. - **observer** (callback) - Required - Bounded host callback; reuse one pointer per cache. ### Response - **error** - Registration error; propagate it. ### Callback Outcomes - **Committed** - Invalidate/fence the local cache and request a fresh snapshot. - **RolledBack** - Release any host reservation; no mutation became committed. - **Unknown** - Fence the cache and reconcile storage; do not assume rollback/retry. ### Notes - Observers run synchronously outside registration locks after completion. - Use a bounded context independent of HTTP cancellation. - Do not panic; if an observer panics, remaining hooks still run before propagation. - Callback delivery is process-local, not durable. - Completed, foreign, and absent transaction scopes are rejected. - Register before mutations and propagate registration errors. - Standalone operations must be wrapped explicitly in InAuthTransaction. ``` -------------------------------- ### POST /api/reset Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Resets the password using a reset token and a new password. ```APIDOC ## POST /api/reset ### Description Resets the password using a reset token and a new password. ### Method POST ### Endpoint /api/reset ### Parameters #### Request Body - **token** (string) - Required - The reset token received via email. - **newPassword** (string) - Required - The new password. ### Request Example { "token": "", "newPassword": "" } ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### POST /auth/password-reset Source: https://github.com/assurrussa/goauth/blob/master/README.md Requests a password reset. The host's notification sender delivers the reset link. ```APIDOC ## POST /auth/password-reset ### Description Requests a password reset. ### Method POST ### Endpoint /auth/password-reset ``` -------------------------------- ### postgres.Runtime.CleanupRateLimitEvents(ctx, request) Source: https://github.com/assurrussa/goauth/blob/master/docs/rate-event-maintenance.md Deletes one bounded batch from auth_rate_limit_events and returns the number of removed events. It is a rate-event-only maintenance API that does not expire notifications, remove audit or session records, or call the broad Cleanup. ```APIDOC ## postgres.Runtime.CleanupRateLimitEvents(ctx, request) ### Description Deletes one bounded batch from `auth_rate_limit_events` and returns the number of removed events. It is a supported, rate-event-only maintenance API. It does not expire notifications, remove audit or session records, or call the existing broad `Runtime.Cleanup`. ### Method Function call ### Endpoint `postgres.Runtime.CleanupRateLimitEvents(ctx, request)` ### Parameters #### Request Body - **ctx** (context.Context) - Required - The context for the operation. Should be outside any managed auth transaction. - **request** (postgres.RateLimitCleanupRequest) - Required - The cleanup request with the following fields: - **Before** (time.Time) - Optional - Only events with `occurred_at < Before` are eligible. An event exactly at the cutoff is retained. A zero value selects the configured Runtime clock minus 25 hours. An explicit cutoff must be no later than that same Runtime clock minus 24 hours. - **Limit** (int) - Required - Number of events to delete, from 1 through 1000 inclusive. Zero is not a default. ### Request Example ```go ctx, cancel := context.WithTimeout(maintenanceContext, 5*time.Second) defer cancel() removed, err := auth.CleanupRateLimitEvents(ctx, postgres.RateLimitCleanupRequest{ Limit: 500, }) ``` ### Response #### Success Response - **removed** (int64) - The number of events deleted. - **err** (error) - An error, if any. #### Response Example ```go removed, err := auth.CleanupRateLimitEvents(ctx, postgres.RateLimitCleanupRequest{ Limit: 500, }) ``` ### Notes - The clock is `postgres.Config.Runtime.Now`, defaulting to `time.Now`; this API does not use `CleanupPolicy.Now`. - A valid cutoff is a minimum safety guard, not proof that retention is safe for every caller sharing the database. - Choose a cutoff that preserves the longest effective window across all consumers of the shared `auth_rate_limit_events` table, plus allowances for clock skew and request latency. - The default 25-hour retention is suitable only when it covers the complete requirement. - Coordinate changes to admission windows and every cleanup scheduler, including any use of broad `Cleanup`. ``` -------------------------------- ### POST /api/reset-request Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Requests a password reset token for the given email. ```APIDOC ## POST /api/reset-request ### Description Requests a password reset token for the given email. ### Method POST ### Endpoint /api/reset-request ### Parameters #### Request Body - **email** (string) - Required - The email address associated with the account. ### Request Example { "email": "api@example.test" } ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### POST /api/email-verify Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Verifies the email using the code sent to the user's email. Requires a bearer token. ```APIDOC ## POST /api/email-verify ### Description Verifies the email using the code sent to the user's email. Requires a bearer token. ### Method POST ### Endpoint /api/email-verify ### Parameters #### Request Body - **code** (string) - Required - The verification code received via email. ### Request Example { "code": "" } ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### POST /api/logout Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Logs out the current session. Requires a bearer token and confirmation session. ```APIDOC ## POST /api/logout ### Description Logs out the current session. Requires a bearer token and confirmation session. ### Method POST ### Endpoint /api/logout ### Parameters #### Request Body - (empty object) - Required - No body fields. ### Request Example {} ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### POST /api/email-send Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Sends an email verification code to the authenticated user's email. Requires a bearer token and confirmation session. ```APIDOC ## POST /api/email-send ### Description Sends an email verification code to the authenticated user's email. Requires a bearer token and confirmation session. ### Method POST ### Endpoint /api/email-send ### Parameters #### Request Body - (empty object) - Required - No body fields. ### Request Example {} ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### Runtime.RetireLocalIdentity Source: https://github.com/assurrussa/goauth/blob/master/docs/subject-retirement.md Retires the entire authentication subject, releasing exactly one selected primary custom login. This is a terminal operation that disables the subject, advances the security version, deletes the selected login and local credential, revokes sessions and related tokens, and records a mandatory audit event. ```APIDOC ## Runtime.RetireLocalIdentity ### Description Retires the entire authentication subject while releasing exactly one selected primary custom login. This is a privileged, transport-neutral host API. It is not alias deletion, business-account erasure, or a reversible disabled status. ### Method Runtime.RetireLocalIdentity ### Parameters #### Required Parameters - **SubjectID** (string) - Required - The exact immutable subject identifier to authorize. - **ExpectedIdentifier** (string) - Required - The explicitly registered non-email custom login identifier to release. - **ExpectedSecurityVersion** (integer) - Required - The positive expected security version of the subject. ### Behavior - The configured identifier resolver defines normalization; GoAuth does not lowercase custom logins implicitly. - The store locks the canonical subject before the selected primary identifier and local credential. - Compares current lifecycle, security version, normalized old login, and credential existence. - Secondary aliases are never selected, promoted, or bulk-deleted. ### Transaction Steps 1. Sets `status=disabled` and the previously absent `retired_at` timestamp. 2. Advances security version exactly once, including for an ordinary-disabled subject. Overflow fails without mutation. 3. Deletes only the selected custom primary identifier and the subject's local credential, including its password-input policy. 4. Revokes local sessions, local and OIDC refresh families, password resets, pending email changes, and pending email challenges. 5. Records mandatory `SecurityEventSubjectRetired` audit without credentials, login values, email codes, or tokens. No notification is enqueued. ### Retained Bindings - Subject UUID, creation timestamp, profile, audit references, RBAC assignments, other primary/secondary email and custom identifiers, and external issuer/sub links remain owned by the terminal old subject. - Retained identifiers and links are reserved, deny-only bindings. Retained emails can block a new account using those emails; they are never silently transferred or linked. - The released login can be provisioned only as a new subject, with no old grants, roles, families, or external links. ### Terminal Nature - Retirement is terminal. Status setters, rename, local-password/credential writes, and identity linking cannot revive or attach authentication to a tombstone. - Existing reads may still show it. - Ordinary disabled subjects remain reversible and retain existing trusted-password and rename behavior. ### Error Handling - Repeating retirement returns `ErrSubjectRetired` with no additional audit, timestamp, or version change. ``` -------------------------------- ### POST /auth/refresh Source: https://github.com/assurrussa/goauth/blob/master/README.md Rotates the refresh token. Send the current refresh token to obtain a new one. ```APIDOC ## POST /auth/refresh ### Description Rotates the refresh token. ### Method POST ### Endpoint /auth/refresh ### Request Body - **refreshToken** (string) - Required - The current refresh token. ### Response #### Success Response (200) - **tokens** - Contains new accessToken, refreshToken, expiry, realm, and scope. ### Request Example ```json {"refreshToken":"..."} ``` ``` -------------------------------- ### Runtime.SetTrustedLocalPassword Source: https://github.com/assurrussa/goauth/blob/master/docs/local-identities.md Replaces an existing local credential without requiring the previous password. This is a privileged operator action that must be authorized and rate-limited by the host. It is available through postgres.Runtime and does not expose an HTTP endpoint. ```APIDOC ## Runtime.SetTrustedLocalPassword ### Description Replaces an existing local credential without requiring the previous password. This is a privileged operator action that must be authorized and rate-limited by the host. It is available through postgres.Runtime and does not expose an HTTP endpoint. ### Method Runtime method call ### Endpoint `Runtime.SetTrustedLocalPassword(ctx, SetTrustedLocalPasswordRequest{SubjectID, NewPassword})` ### Parameters #### Request Body - **SubjectID** (string) - Required - The subject identifier of the account whose local credential is to be replaced. - **NewPassword** (string) - Required - The new plaintext password to set. ### Response #### Success Response Returns an account object (provisional until the outer `InAuthTransaction` returns success). #### Error Responses - **ErrAccountNotFound** - Returned when the subject does not exist or is SSO-only. - **ErrTrustedLocalPasswordUnsupported** - Returned when the store does not support the `TrustedLocalPasswordStore` capability. - **ErrSecurityVersionMismatch** - Returned when the security version has changed. - **ErrPasswordChangeConflict** - Returned when the PHC or input policy has changed. - **ErrOperationOutcomeUnknown** - Returned on commit failure; never returns a successful account. ### Notes - Must be called before acquiring host project locks; add project/event outbox and actor audit writes afterward. - Can join `InAuthTransaction`; nested calls join without committing. - Does not consume credential-attempt admission. - No implicit idempotency is provided. ``` -------------------------------- ### POST /api/refresh Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Refreshes the access token using a refresh token. The refresh token is single-use and should not be retried after uncertain outcomes. ```APIDOC ## POST /api/refresh ### Description Refreshes the access token using a refresh token. The refresh token is single-use and should not be retried after uncertain outcomes. ### Method POST ### Endpoint /api/refresh ### Parameters #### Request Body - **refreshToken** (string) - Required - The refresh token. ### Request Example { "refreshToken": "" } ### Response #### Success Response (200) - **accessToken** (string) - New access token. #### Response Example { "accessToken": "" } ``` -------------------------------- ### POST /api/password Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Changes the current user's password. Requires a bearer token. ```APIDOC ## POST /api/password ### Description Changes the current user's password. Requires a bearer token. ### Method POST ### Endpoint /api/password ### Parameters #### Request Body - **currentPassword** (string) - Required - The current password. - **newPassword** (string) - Required - The new password. ### Request Example { "currentPassword": "", "newPassword": "" } ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### ScopedAuthorizationSnapshot(ctx, selectSubjects) Source: https://github.com/assurrussa/goauth/blob/master/docs/host-authorization-snapshots.md Admin-only cache: reads host membership using the supplied executor and returns canonical subject IDs before canonical RBAC reads, all within the same read-only Repeatable Read transaction. ```APIDOC ## ScopedAuthorizationSnapshot(ctx, selectSubjects) ### Description Admin-only cache: reads host membership using the supplied executor and returns canonical subject IDs before canonical RBAC reads, all within the same read-only Repeatable Read transaction. ### Method Function call ### Parameters - **ctx** (context) - Required - Context for the operation. - **selectSubjects** (selector) - Required - Reads host membership using the supplied executor and returns canonical subject IDs. Nil selector is an error. ### Response - **RBAC snapshot** - Includes complete role/permission catalog and selected subjects' assignments. - **error** - Returned on failure; captured selector results are provisional until the entire call succeeds. ### Notes - Subject assignments are filtered by subject_id=ANY($1::uuid[]) in PostgreSQL using the existing subject-first primary key. - Empty/nil selected IDs return no assignments. - Catalog entries are not grants; authorization must use only the selected subjects' assignments. - Memory scales with the catalog plus the selected assignments, not all customer assignments. ``` -------------------------------- ### Runtime.RenameLocalIdentity Source: https://github.com/assurrussa/goauth/blob/master/docs/local-identities.md Renames a primary custom login for a subject. It requires a local credential and an existing primary custom identifier, and performs a compare-and-swap with security version checks. ```APIDOC ## Runtime.RenameLocalIdentity ### Description Renames a primary custom login for a subject. It requires a local credential and an existing primary custom identifier. It performs a compare-and-swap with security version checks and returns a `LocalIdentityView`. ### Method RenameLocalIdentity ### Endpoint Runtime.RenameLocalIdentity(ctx, RenameLocalIdentityRequest{SubjectID, ExpectedIdentifier, ExpectedSecurityVersion, NewIdentifier}) ### Parameters #### Request Body - **SubjectID** (string) - Required - The immutable subject ID. - **ExpectedIdentifier** (string) - Required - The expected current primary identifier (normalized). - **ExpectedSecurityVersion** (integer) - Required - The expected security version. - **NewIdentifier** (string) - Required - The new primary identifier (normalized). ### Response #### Success Response Returns `LocalIdentityView{Account, Identifier}`. #### Error Responses - `ErrAccountNotFound` - Missing subject or credential. - `ErrLocalIdentifierConflict` - Missing or mismatching primary. - `ErrSecurityVersionMismatch` - Stale version. - `ErrIdentifierAlreadyExists` - Collision with any primary or secondary identifier. - `ErrIdentifierUnchanged` - Exact display-and-normalized no-op. ``` -------------------------------- ### POST /api/email-confirm Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Confirms the email change using a code. Requires a bearer token. ```APIDOC ## POST /api/email-confirm ### Description Confirms the email change using a code. Requires a bearer token. ### Method POST ### Endpoint /api/email-confirm ### Parameters #### Request Body - **code** (string) - Required - The confirmation code. ### Request Example { "code": "" } ### Response #### Success Response (200) - No specific response fields documented. ``` -------------------------------- ### Exported signatures of InAuthTransaction, InOwnedAuthTransaction, and SQLExecutor Source: https://github.com/assurrussa/goauth/blob/master/docs/owned-auth-transactions.md API declarations from postgres/host_transaction.go. Both transaction methods take func(context.Context) error, not func(SQLExecutor) error. Inside the callback, obtain the borrowed executor with runtime.SQLExecutor(txctx) and propagate the error. ```go func (r *Runtime) InAuthTransaction(ctx context.Context, fn func(context.Context) error) error func (r *Runtime) InOwnedAuthTransaction(ctx context.Context, fn func(context.Context) error) error func (r *Runtime) SQLExecutor(ctx context.Context) (SQLExecutor, error) ``` -------------------------------- ### POST /api/email-change Source: https://github.com/assurrussa/goauth/blob/master/examples/nethttp/README.md Changes the user's email address. Requires a full user bearer token. ```APIDOC ## POST /api/email-change ### Description Changes the user's email address. Requires a full user bearer token. ### Method POST ### Endpoint /api/email-change ### Parameters #### Request Body - **email** (string) - Required - The new email address. - **currentPassword** (string) - Required - The current password for verification. ### Request Example { "email": "new@example.test", "currentPassword": "" } ### Response #### Success Response (200) - No specific response fields documented. ```