feat(api): declare identity contract for registration, verification, and sessions

This commit is contained in:
shira committed 2026-10-05 22:57:19 +03:00
1 parent 197661145e
commit 653f3775f8
86 files changed
+11826 -148

No files matched your search

@@ -8,12 +8,162 @@ import (
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// ConfirmEmail implements ConfirmEmail operation.
//
// Public operation without a session. The verification link has the form
// `<frontend origin>/verify-email#token=<token>`: the token travels in the URL fragment, so it never
// reaches a server log or a Referer header. The page first removes the fragment with
// `history.replaceState`, then waits for an explicit user action, such as a Confirm button, before it
// posts the token here. A link scanner that only fetches the page therefore does not consume the
// token.
//
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
// expired, and bound to the current registration version, marks it used, and marks the email verified.
// Only one of several parallel requests with the same token succeeds. An expired token answers
// verification_token_expired; an unknown, used, replaced, or superseded token answers
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
// sign-in, because the address may already be verified.
//
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
// either outcome is sign-in anyway.
//
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
// a session must come only from the password. The response returns the scenario and the saved
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
// an allowed Origin.
//
// POST /api/v1/identity/email-verifications
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error)
// GetConsentText implements GetConsentText operation.
//
// Public operation without a session. Returns the current text of a consent that is given before an
// account exists; only `c1` is available. The registration page shows this text and sends its
// `text_version` with RegisterAccount, and the server hashes the same stored text when it records the
// acceptance. If the text changes while the page is open, RegisterAccount answers 400
// validation_failed with the pointer `/consent_c1/text_version`, and the page reads the text again. An
// unknown purpose fails parameter validation with 400.
//
// GET /api/v1/identity/consent-texts/{purpose}
GetConsentText(ctx context.Context, params GetConsentTextParams) (GetConsentTextRes, error)
// GetCurrentAccount implements GetCurrentAccount operation.
//
// Requires the session cookie. The account comes from the session, never from a request parameter. The
// client uses `scenario` and `onboarding_step` to return the user to the unfinished onboarding step. A
// missing, unknown, expired, or revoked session answers 401 unauthenticated. An unverified account
// never has a session, because login answers 403 email_not_verified for it, so this operation also
// answers 401 for such an account.
//
// GET /api/v1/identity/me
GetCurrentAccount(ctx context.Context) (GetCurrentAccountRes, error)
// GetCurrentSession implements GetCurrentSession operation.
//
// Requires the session cookie. Returns the account and the CSRF token of the current session, so the
// client can restore the token after a page reload or after 403 csrf_check_failed. A missing, unknown,
// expired, or revoked session answers 401 unauthenticated. Cross-origin pages cannot read the token,
// because the API sends no Access-Control-Allow-Origin header.
//
// GET /api/v1/identity/sessions/current
GetCurrentSession(ctx context.Context) (GetCurrentSessionRes, error)
// GetHealthz implements GetHealthz operation.
//
// Check whether the API process is responding.
//
// GET /api/v1/healthz
GetHealthz(ctx context.Context) (*HealthResponse, error)
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
// an unknown email it verifies against a fixed dummy hash, so the response time does not reveal
// whether the account exists. An unknown email and a wrong password both answer 401
// invalid_credentials.
//
// Correct credentials for an unverified email answer 403 email_not_verified and create no session.
// This reveals the verification state only to someone who already knows the password, which proves
// more than the state itself; the client offers to resend the link.
//
// On success the server revokes the session that the request carried, if any, creates a new random
// session in PostgreSQL with a new identifier and a new CSRF token, sets the HttpOnly session cookie,
// and returns the account and the CSRF token. The new session follows the idle and absolute timeouts
// of the sessionCookie scheme. The client keeps the token in memory and sends it in X-CSRF-Token with
// every mutating request that requires a session.
//
// Login is rate-limited per client and per email and answers 429 with Retry-After. Like every unsafe
// request, it requires an allowed Origin, which protects against login CSRF, and answers 403
// csrf_check_failed otherwise.
//
// POST /api/v1/identity/sessions
Login(ctx context.Context, req *LoginRequest) (LoginRes, error)
// Logout implements Logout operation.
//
// Requires the session cookie and the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The server revokes the session in PostgreSQL, so the cookie value stops working even if a
// copy remains, and clears the cookie. A missing, expired, or revoked session answers 401
// unauthenticated and also clears the cookie, so a stale cookie does not stay in the browser; a
// missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed and keeps the
// session and the cookie. The client clears its private query cache after the response.
//
// DELETE /api/v1/identity/sessions/current
Logout(ctx context.Context) (LogoutRes, error)
// RegisterAccount implements RegisterAccount operation.
//
// Public operation without a session. The client reads the current C1 text with GetConsentText and
// sends the email, the password, the chosen scenario, and consent C1 with the version of the text the
// user accepted.
//
// The answer is the same 202 whether the email is new, registered but not verified, or verified, so
// registration does not enumerate accounts:
//
// - New email: the server creates an unverified account with the scenario and the first onboarding
// step, records C1 with its text version and text hash, stores only the hash of a one-time
// verification token, and queues the verification message, all in one transaction.
// - Registered but not verified: the server treats the request as a new registration of that address.
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
// record, advances the registration version, invalidates every earlier verification token, and
// queues a message with a new token. A pre-registration with someone else's password therefore
// never survives the address owner's own registration.
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
// notice to the address.
//
// Every verification token is bound to the registration version it was issued for, so a token issued
// before a re-registration can never confirm the newer credentials. An account that stays unverified
// is deleted with its consent record and tokens 7 days after its last registration (planned value from
// configuration). Verification tokens live 24 hours (planned value from configuration).
//
// The response does not depend on the branch in content or timing. Before it looks up the email, the
// server validates the whole body, including the password bounds after normalization, the password
// blocklist, and the C1 version, and it computes the Argon2id hash on every branch; a 400 therefore
// never depends on whether the email exists. Mail is delivered asynchronously from the outbox.
//
// The operation requires Idempotency-Key. For this anonymous operation the key is scoped by the
// operation, the key, and an HMAC of the normalized email, and the request fingerprint is an
// HMAC-SHA-256 with a server secret over the canonical JSON body. The server never stores the body,
// the password, or a plain hash of either; the secret keeps the fingerprint from serving as an offline
// password check. A retry with the same key, email, and body replays the stored 202 without a second
// message; the same key and email with a different body answers 422 idempotency_key_reused.
//
// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is
// reached. Like every unsafe request, it requires an allowed Origin and answers 403 csrf_check_failed
// otherwise.
//
// POST /api/v1/identity/registrations
RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error)
// ResendEmailVerification implements ResendEmailVerification operation.
//
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
// email, and an unverified one, so it does not enumerate accounts. Only for an unverified account does
// the server issue a new one-time token bound to the current registration version, invalidate every
// earlier token of that account, and queue the message. Resend never changes the password, the
// scenario, or the consent record; a user who did not start the pending registration registers again
// instead, which replaces it.
//
// It is rate-limited per client and per email and answers 429 with Retry-After when the limit is
// reached. A retry is safe without Idempotency-Key: at worst it replaces the token again within the
// rate limit. Like every unsafe request, it requires an allowed Origin and answers 403
// csrf_check_failed otherwise.
//
// POST /api/v1/identity/email-verification-requests
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// NewError creates *ProblemStatusCode from error returned by handler.
//
// Used for common default response.
@@ -23,18 +173,20 @@ type Handler interface {
// Server implements http server based on OpenAPI v3 specification and
// calls Handler to handle requests.
type Server struct {
h Handler
h Handler
sec SecurityHandler
baseServer
}
// NewServer creates new Server.
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
s, err := newServerConfig(opts...).baseServer()
if err != nil {
return nil, err
}
return &Server{
h: h,
sec: sec,
baseServer: s,
}, nil
}