Files
ARTEX/db/migrations/0029_users.sql
Marco Azarmaneche e39bf0ff08 feat(db): users, identities and sessions tables
Storage step of the multi-user work in #790 (phase 2a).

Migration 0029_users.sql adds three tables:
- users: case-insensitive unique username, display name, optional email,
  optional bcrypt hash (SSO-only users have none), account source
  (local now; oidc, saml, ldap, scim later), break-glass flag (local
  accounts only), disabled, login and update times.
- user_identities: links a subject at an identity provider to one user,
  unique on (provider_id, subject). An identity is never linked by
  matching email or username.
- user_sessions: one row per token id (jti) with expiry, last use,
  revocation, user agent and client address.

The migration seeds the existing ARTEX account as the break-glass local
user, so later changes have a row to point to. It does not copy the
password hash: login still reads the auth.password_hash setting, and a
copy would go stale when the password changes. The change that moves
login onto these tables moves the hash with it. An existing ARTEX row is
left unchanged.

Every CHECK constraint is named, so a later migration can alter it by
name. Usernames are at most 128 characters without control characters.
Only a local account can have a password (users_password_local_only), so
an account from an identity provider cannot gain a second way in. The
session user agent is at most 512 bytes and the client address 64; the
address is TEXT because the peer is not always an IP address.

db/users.go adds the store functions later phases need: create and look
up users, set a password, disable a user (which also revokes its
sessions), link and resolve identities, and create, read, touch and
revoke sessions and delete expired ones. The Go side applies the same
limits first (ErrUserInvalid; user agent and address are cut). A session
is created only for an existing, enabled user (ErrUserDisabled), is not
active and cannot be touched while its user is disabled, and a missing
row means no session. DisableUser refuses the last enabled break-glass
user (ErrLastBreakGlass), locking the break-glass rows so two concurrent
calls cannot disable the last two. Expired sessions are deleted by the
database clock, as TouchSession checks expiry.

Nothing reads these tables yet. Login still uses the single ARTEX account
and the setting, so behaviour does not change.
2026-12-03 14:01:19 +01:00

100 lines
5.3 KiB
SQL

-- User accounts, identity-provider links and server-side sessions (#790,
-- phase 2, storage only).
--
-- Nothing reads these tables yet: login still accepts only the ARTEX account,
-- checks the bcrypt hash in settings (auth.password_hash) and issues tokens
-- with subject "ARTEX". A later change moves login and session checks onto
-- these tables.
--
-- Every CHECK constraint is named, so a later migration can ALTER or DROP it
-- by name. Tables that later record a user id (approvals, audit) should
-- reference users(id) without ON DELETE CASCADE (RESTRICT or SET NULL): a
-- deleted user must not take its history with it.
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
-- Stored as typed; uniqueness is case-insensitive (uq_users_username_lower),
-- so "Alice" and "alice" cannot both exist.
-- TODO(#790): normalise to Unicode NFC once SCIM/LDAP provisioning
-- writes usernames, so look-alike forms cannot both exist.
username TEXT NOT NULL
CONSTRAINT users_username_nonblank CHECK (btrim(username) <> '')
CONSTRAINT users_username_limits
CHECK (length(username) <= 128 AND username !~ '[[:cntrl:]]'),
display_name TEXT NOT NULL DEFAULT '',
email TEXT,
-- bcrypt hash. NULL for a user who signs in only through an identity
-- provider: such a user has no local password (users_password_local_only).
password_hash TEXT,
-- Where the account comes from. Only 'local' is written today.
source TEXT NOT NULL DEFAULT 'local'
CONSTRAINT users_source_valid
CHECK (source IN ('local', 'oidc', 'saml', 'ldap', 'scim')),
-- The break-glass account signs in with its local password even when SSO
-- is enforced, so it must be a local account.
is_break_glass BOOLEAN NOT NULL DEFAULT FALSE
CONSTRAINT users_break_glass_local
CHECK (NOT is_break_glass OR source = 'local'),
disabled_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ,
-- Only a local account has a local password: an account from an identity
-- provider must not gain a second way in.
CONSTRAINT users_password_local_only CHECK (password_hash IS NULL OR source = 'local')
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username_lower ON users (lower(username));
-- Links a user to an account at an identity provider (OIDC, SAML, LDAP, SCIM).
-- provider_id names the configured provider, subject is the provider's stable
-- id for the account (OIDC "sub", SAML NameID, LDAP objectGUID, SCIM id).
-- A login through a provider finds the user by (provider_id, subject) only.
-- An identity is never linked to an existing user by matching email or
-- username: either can be set by whoever controls the provider account, so
-- that would let a provider account take over a local one.
CREATE TABLE IF NOT EXISTS user_identities (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
provider_id TEXT NOT NULL CONSTRAINT user_identities_provider_nonblank CHECK (provider_id <> ''),
subject TEXT NOT NULL CONSTRAINT user_identities_subject_nonblank CHECK (subject <> ''),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_user_identities_provider_subject UNIQUE (provider_id, subject)
);
CREATE INDEX IF NOT EXISTS idx_user_identities_user ON user_identities (user_id);
-- One row per issued session token. id is the token's jti. A session is valid
-- while revoked_at IS NULL, expires_at > now() and its user is not disabled;
-- revoked rows are kept until they expire so a revoked token is still
-- recognised as revoked. A token whose row is missing is invalid.
--
-- client_ip is TEXT, not INET: it holds what the server saw as the peer, which
-- is not always an IP address (a Unix socket listener has none).
CREATE TABLE IF NOT EXISTS user_sessions (
id TEXT PRIMARY KEY CONSTRAINT user_sessions_id_nonblank CHECK (id <> ''),
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
revoked_at TIMESTAMPTZ,
user_agent TEXT NOT NULL DEFAULT ''
CONSTRAINT user_sessions_user_agent_len CHECK (octet_length(user_agent) <= 512),
client_ip TEXT NOT NULL DEFAULT ''
CONSTRAINT user_sessions_client_ip_len CHECK (octet_length(client_ip) <= 64)
);
CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions (user_id);
CREATE INDEX IF NOT EXISTS idx_user_sessions_expires ON user_sessions (expires_at);
-- Seed the existing single account as the break-glass local user, so later
-- changes (user ids on approvals, role bindings) have a row to point to. An
-- existing ARTEX user, in any letter case, is left unchanged.
--
-- The password hash is not copied: login still reads the setting
-- auth.password_hash, and a copy here would go stale as soon as the password
-- changes. The change that moves login onto this table moves the hash with it.
INSERT INTO users (username, display_name, source, is_break_glass)
VALUES ('ARTEX', 'ARTEX', 'local', TRUE)
ON CONFLICT ((lower(username))) DO NOTHING;