mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 20:34:53 +00:00
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.
374 lines
14 KiB
Go
374 lines
14 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
// Users, identity-provider links and sessions (migration 0029_users.sql).
|
|
// Nothing outside this package calls these yet: login still uses the single
|
|
// ARTEX account in settings (server/auth.go).
|
|
|
|
// User sources: the only values the users.source CHECK allows.
|
|
const (
|
|
UserSourceLocal = "local"
|
|
UserSourceOIDC = "oidc"
|
|
UserSourceSAML = "saml"
|
|
UserSourceLDAP = "ldap"
|
|
UserSourceSCIM = "scim"
|
|
)
|
|
|
|
var (
|
|
ErrUsernameTaken = errors.New("a user with this username already exists")
|
|
ErrIdentityLinked = errors.New("this identity is already linked to a user")
|
|
ErrUserInvalid = errors.New("invalid user")
|
|
ErrSessionIDNeeded = errors.New("session id is required")
|
|
// ErrUserDisabled: no session is created for a disabled or missing user.
|
|
ErrUserDisabled = errors.New("user is disabled or does not exist")
|
|
// ErrLastBreakGlass: the last enabled break-glass account cannot be
|
|
// disabled, or no one could sign in when SSO is down.
|
|
ErrLastBreakGlass = errors.New("the last enabled break-glass user cannot be disabled")
|
|
)
|
|
|
|
// Limits the users and user_sessions CHECK constraints enforce; the store
|
|
// functions apply them first so a caller gets ErrUserInvalid or a cut value
|
|
// instead of a constraint error.
|
|
const (
|
|
UsernameMaxChars = 128 // users_username_limits
|
|
SessionUserAgentMax = 512 // bytes, user_sessions_user_agent_len
|
|
SessionClientIPMax = 64 // bytes, user_sessions_client_ip_len
|
|
)
|
|
|
|
// validUsername checks a trimmed username against users_username_nonblank and
|
|
// users_username_limits.
|
|
// TODO(#790): normalise to Unicode NFC once SCIM/LDAP provisioning writes
|
|
// usernames (see 0029_users.sql).
|
|
func validUsername(username string) error {
|
|
if username == "" {
|
|
return fmt.Errorf("%w: username is required", ErrUserInvalid)
|
|
}
|
|
if utf8.RuneCountInString(username) > UsernameMaxChars {
|
|
return fmt.Errorf("%w: username is longer than %d characters", ErrUserInvalid, UsernameMaxChars)
|
|
}
|
|
if !utf8.ValidString(username) || strings.IndexFunc(username, unicode.IsControl) >= 0 {
|
|
return fmt.Errorf("%w: username contains a control character", ErrUserInvalid)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// cutUTF8 returns s cut to at most max bytes, on a character boundary, as
|
|
// valid UTF-8.
|
|
func cutUTF8(s string, max int) string {
|
|
s = strings.ToValidUTF8(s, "")
|
|
if len(s) <= max {
|
|
return s
|
|
}
|
|
s = s[:max]
|
|
for len(s) > 0 && !utf8.ValidString(s) {
|
|
s = s[:len(s)-1]
|
|
}
|
|
return s
|
|
}
|
|
|
|
// User is one row of users. PasswordHash is "" when the user has no local
|
|
// password (an SSO-only account).
|
|
type User struct {
|
|
ID int64 `json:"id"`
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Email *string `json:"email,omitempty"`
|
|
PasswordHash string `json:"-"`
|
|
Source string `json:"source"`
|
|
IsBreakGlass bool `json:"is_break_glass"`
|
|
DisabledAt *time.Time `json:"disabled_at,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
|
|
}
|
|
|
|
// NewUser holds the fields CreateUser writes. An empty PasswordHash stores
|
|
// NULL; an empty Source means local. The break-glass flag is set only by the
|
|
// migration seed, never through this API.
|
|
type NewUser struct {
|
|
Username string
|
|
DisplayName string
|
|
Email *string
|
|
PasswordHash string
|
|
Source string
|
|
}
|
|
|
|
const userCols = `id, username, display_name, email, COALESCE(password_hash, ''), source, is_break_glass, disabled_at, created_at, updated_at, last_login_at`
|
|
|
|
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
|
|
var u User
|
|
if err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.Email, &u.PasswordHash, &u.Source,
|
|
&u.IsBreakGlass, &u.DisabledAt, &u.CreatedAt, &u.UpdatedAt, &u.LastLoginAt); err != nil {
|
|
return nil, err
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
// getUser runs a single-row user query and returns nil, nil when no row matches.
|
|
func (d *DB) getUser(query string, args ...any) (*User, error) {
|
|
u, err := scanUser(d.QueryRow(query, args...))
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return u, err
|
|
}
|
|
|
|
func userUniqueViolation(err error, constraint string) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
|
|
}
|
|
|
|
func userCheckViolation(err error, constraint string) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == "23514" && pgErr.ConstraintName == constraint
|
|
}
|
|
|
|
// CreateUser inserts a user. The username is trimmed and must not be empty,
|
|
// longer than UsernameMaxChars characters or hold a control character
|
|
// (ErrUserInvalid); a username that differs from an existing one only in
|
|
// letter case is refused with ErrUsernameTaken. Only a local user may have a
|
|
// password (ErrUserInvalid otherwise).
|
|
func (d *DB) CreateUser(n NewUser) (*User, error) {
|
|
username := strings.TrimSpace(n.Username)
|
|
if err := validUsername(username); err != nil {
|
|
return nil, err
|
|
}
|
|
source := n.Source
|
|
if source == "" {
|
|
source = UserSourceLocal
|
|
}
|
|
if n.PasswordHash != "" && source != UserSourceLocal {
|
|
return nil, fmt.Errorf("%w: only a local user can have a password", ErrUserInvalid)
|
|
}
|
|
u, err := scanUser(d.QueryRow(`INSERT INTO users (username, display_name, email, password_hash, source)
|
|
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
|
|
RETURNING `+userCols, username, n.DisplayName, n.Email, n.PasswordHash, source))
|
|
if userUniqueViolation(err, "uq_users_username_lower") {
|
|
return nil, ErrUsernameTaken
|
|
}
|
|
return u, err
|
|
}
|
|
|
|
// GetUserByID returns the user, or nil when there is none.
|
|
func (d *DB) GetUserByID(id int64) (*User, error) {
|
|
return d.getUser(`SELECT `+userCols+` FROM users WHERE id=$1`, id)
|
|
}
|
|
|
|
// GetUserByUsername matches the username case-insensitively, as the unique
|
|
// index does, and returns nil when there is no such user. Disabled users are
|
|
// returned too: the caller decides what a disabled account may do.
|
|
func (d *DB) GetUserByUsername(username string) (*User, error) {
|
|
return d.getUser(`SELECT `+userCols+` FROM users WHERE lower(username)=lower($1)`, strings.TrimSpace(username))
|
|
}
|
|
|
|
// SetUserPassword stores a new bcrypt hash; an empty hash clears the local
|
|
// password. A user from an identity provider cannot get one
|
|
// (ErrUserInvalid, users_password_local_only). It does not revoke sessions:
|
|
// the caller does that with RevokeUserSessions when the change must sign the
|
|
// user out. ok is false when the user does not exist.
|
|
func (d *DB) SetUserPassword(id int64, hash string) (ok bool, err error) {
|
|
res, err := d.Exec(`UPDATE users SET password_hash=NULLIF($2, ''), updated_at=now() WHERE id=$1`, id, hash)
|
|
if userCheckViolation(err, "users_password_local_only") {
|
|
return false, fmt.Errorf("%w: only a local user can have a password", ErrUserInvalid)
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n, err := res.RowsAffected()
|
|
return n > 0, err
|
|
}
|
|
|
|
// DisableUser marks the user disabled and revokes all of its sessions in the
|
|
// same transaction, so a disabled user keeps no working session. Disabling a
|
|
// disabled user keeps the first disabled_at. ok is false when the user does
|
|
// not exist. The last enabled break-glass user is not disabled
|
|
// (ErrLastBreakGlass). A server that caches session checks must drop its
|
|
// cache after calling this.
|
|
func (d *DB) DisableUser(id int64) (ok bool, err error) {
|
|
tx, err := d.Begin()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck // no-op after Commit
|
|
// Lock every enabled break-glass row, so two concurrent calls cannot each
|
|
// disable one of the last two: the second one waits and then no longer
|
|
// sees the row the first one disabled.
|
|
rows, err := tx.Query(`SELECT id FROM users WHERE is_break_glass AND disabled_at IS NULL ORDER BY id FOR UPDATE`)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
var enabledBreakGlass []int64
|
|
for rows.Next() {
|
|
var bid int64
|
|
if err := rows.Scan(&bid); err != nil {
|
|
rows.Close()
|
|
return false, err
|
|
}
|
|
enabledBreakGlass = append(enabledBreakGlass, bid)
|
|
}
|
|
rows.Close()
|
|
if err := rows.Err(); err != nil {
|
|
return false, err
|
|
}
|
|
if len(enabledBreakGlass) == 1 && enabledBreakGlass[0] == id {
|
|
return false, ErrLastBreakGlass
|
|
}
|
|
res, err := tx.Exec(`UPDATE users SET disabled_at=COALESCE(disabled_at, now()), updated_at=now() WHERE id=$1`, id)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
|
return false, err
|
|
}
|
|
if _, err := tx.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL`, id); err != nil {
|
|
return false, err
|
|
}
|
|
return true, tx.Commit()
|
|
}
|
|
|
|
// LinkIdentity links the account subject at identity provider providerID to
|
|
// the user. An identity belongs to one user only: linking one that is already
|
|
// linked, to this user or another, returns ErrIdentityLinked. Callers must
|
|
// never pick userID by matching the provider's email or username (see the
|
|
// comment on user_identities in 0029_users.sql).
|
|
func (d *DB) LinkIdentity(userID int64, providerID, subject string) error {
|
|
if providerID == "" || subject == "" {
|
|
return fmt.Errorf("%w: provider and subject are required", ErrUserInvalid)
|
|
}
|
|
_, err := d.Exec(`INSERT INTO user_identities (user_id, provider_id, subject) VALUES ($1, $2, $3)`, userID, providerID, subject)
|
|
if userUniqueViolation(err, "uq_user_identities_provider_subject") {
|
|
return ErrIdentityLinked
|
|
}
|
|
return err
|
|
}
|
|
|
|
// GetUserByIdentity returns the user linked to subject at providerID, or nil
|
|
// when the identity is not linked. The match is exact: subjects are opaque.
|
|
func (d *DB) GetUserByIdentity(providerID, subject string) (*User, error) {
|
|
return d.getUser(`SELECT `+userCols+` FROM users
|
|
WHERE id = (SELECT user_id FROM user_identities WHERE provider_id=$1 AND subject=$2)`, providerID, subject)
|
|
}
|
|
|
|
// UserSession is one row of user_sessions. ID is the session token's jti.
|
|
type UserSession struct {
|
|
ID string `json:"id"`
|
|
UserID int64 `json:"user_id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
LastSeenAt time.Time `json:"last_seen_at"`
|
|
RevokedAt *time.Time `json:"revoked_at,omitempty"`
|
|
UserAgent string `json:"user_agent"`
|
|
ClientIP string `json:"client_ip"`
|
|
// UserDisabled is set when the session's user is disabled (GetSession).
|
|
UserDisabled bool `json:"user_disabled,omitempty"`
|
|
}
|
|
|
|
// Active reports whether the session is neither revoked nor expired at now,
|
|
// and its user is not disabled.
|
|
func (s *UserSession) Active(now time.Time) bool {
|
|
return s.RevokedAt == nil && !s.UserDisabled && now.Before(s.ExpiresAt)
|
|
}
|
|
|
|
// CreateSession records a new session for an existing, enabled user
|
|
// (ErrUserDisabled otherwise). The caller generates id (the token's jti)
|
|
// from a cryptographic random source. userAgent is cut to
|
|
// SessionUserAgentMax and clientIP to SessionClientIPMax bytes.
|
|
func (d *DB) CreateSession(id string, userID int64, expiresAt time.Time, userAgent, clientIP string) (*UserSession, error) {
|
|
if id == "" {
|
|
return nil, ErrSessionIDNeeded
|
|
}
|
|
s := UserSession{ID: id, UserID: userID, ExpiresAt: expiresAt,
|
|
UserAgent: cutUTF8(userAgent, SessionUserAgentMax), ClientIP: cutUTF8(clientIP, SessionClientIPMax)}
|
|
err := d.QueryRow(`INSERT INTO user_sessions (id, user_id, expires_at, user_agent, client_ip)
|
|
SELECT $1, id, $3, $4, $5 FROM users WHERE id=$2 AND disabled_at IS NULL
|
|
RETURNING created_at, expires_at, last_seen_at`, s.ID, s.UserID, s.ExpiresAt, s.UserAgent, s.ClientIP).Scan(
|
|
&s.CreatedAt, &s.ExpiresAt, &s.LastSeenAt)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrUserDisabled
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
// GetSession returns the session, revoked or expired ones and those of a
|
|
// disabled user included (check Active), or nil when there is none. Callers
|
|
// must treat nil as an invalid session: a token whose row is gone is not
|
|
// valid.
|
|
func (d *DB) GetSession(id string) (*UserSession, error) {
|
|
var s UserSession
|
|
err := d.QueryRow(`SELECT s.id, s.user_id, s.created_at, s.expires_at, s.last_seen_at, s.revoked_at,
|
|
s.user_agent, s.client_ip, u.disabled_at IS NOT NULL
|
|
FROM user_sessions s JOIN users u ON u.id = s.user_id
|
|
WHERE s.id=$1`, id).Scan(
|
|
&s.ID, &s.UserID, &s.CreatedAt, &s.ExpiresAt, &s.LastSeenAt, &s.RevokedAt, &s.UserAgent, &s.ClientIP, &s.UserDisabled)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
// TouchSession sets last_seen_at to now on an active session. ok is false when
|
|
// the session does not exist, is revoked, has expired or belongs to a
|
|
// disabled user; nothing is written then.
|
|
func (d *DB) TouchSession(id string) (ok bool, err error) {
|
|
res, err := d.Exec(`UPDATE user_sessions s SET last_seen_at=now()
|
|
FROM users u
|
|
WHERE s.id=$1 AND u.id=s.user_id AND u.disabled_at IS NULL
|
|
AND s.revoked_at IS NULL AND s.expires_at > now()`, id)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n, err := res.RowsAffected()
|
|
return n > 0, err
|
|
}
|
|
|
|
// RevokeSession revokes one session. ok is false when the session does not
|
|
// exist or was already revoked; the first revoked_at is kept.
|
|
func (d *DB) RevokeSession(id string) (ok bool, err error) {
|
|
res, err := d.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE id=$1 AND revoked_at IS NULL`, id)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n, err := res.RowsAffected()
|
|
return n > 0, err
|
|
}
|
|
|
|
// RevokeUserSessions revokes every session of the user that is not revoked yet
|
|
// and returns how many it revoked.
|
|
func (d *DB) RevokeUserSessions(userID int64) (int64, error) {
|
|
res, err := d.Exec(`UPDATE user_sessions SET revoked_at=now() WHERE user_id=$1 AND revoked_at IS NULL`, userID)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return res.RowsAffected()
|
|
}
|
|
|
|
// DeleteExpiredSessions deletes the sessions that have expired by the
|
|
// database clock, revoked or not, and returns how many it deleted. It uses
|
|
// now(), as TouchSession does, so a server clock ahead of the database cannot
|
|
// delete a session the database still treats as live. A session that is
|
|
// revoked but not yet expired is kept, so it still reads as revoked.
|
|
func (d *DB) DeleteExpiredSessions() (int64, error) {
|
|
res, err := d.Exec(`DELETE FROM user_sessions WHERE expires_at <= now()`)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return res.RowsAffected()
|
|
}
|