ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

+130 -6
View File
@@ -7,6 +7,7 @@ import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
@@ -66,6 +67,17 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return errors.New("auth postgres pool is nil")
}
// Only a table that predates the role column needs its oldest account promoted, so the
// promotion below runs once, in the migration that adds the column.
var roleColumnMissing bool
if err := pool.QueryRow(ctx, `
SELECT NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
)`).Scan(&roleColumnMissing); err != nil {
return fmt.Errorf("check auth schema: %w", err)
}
_, err := pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
@@ -89,9 +101,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
-- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
ON auth_users (lower(email)) WHERE email <> '';
@@ -109,6 +118,20 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return fmt.Errorf("ensure auth schema: %w", err)
}
if err := ensureUsernameCaseIndex(ctx, pool); err != nil {
return err
}
if roleColumnMissing {
if _, err := pool.Exec(ctx, `
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
`); err != nil {
return fmt.Errorf("promote oldest auth user: %w", err)
}
}
if options.SingleUser {
if _, err := pool.Exec(ctx, `
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
@@ -153,6 +176,47 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
return nil
}
// ensureUsernameCaseIndex makes usernames unique ignoring case, so "Admin" and "admin" cannot both
// be registered. The index is created only while no such pair exists: a database that already
// holds one still starts, logs the clashing names, and gets the index on the first start after an
// operator has renamed or removed one of each pair.
func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
rows, err := pool.Query(ctx, `
SELECT min(username) FROM auth_users GROUP BY lower(username) HAVING count(*) > 1
ORDER BY 1 LIMIT 10
`)
if err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
var clashing []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
rows.Close()
return fmt.Errorf("check duplicate usernames: %w", err)
}
clashing = append(clashing, name)
}
rows.Close()
if err := rows.Err(); err != nil {
return fmt.Errorf("check duplicate usernames: %w", err)
}
if len(clashing) > 0 {
log.Printf("[auth] usernames that differ only by case exist (%q); the case-insensitive username index was not created. Rename or remove one account of each pair and restart.", clashing)
return nil
}
if _, err := pool.Exec(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username))`); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
// An account was registered between the check and the index build; the next start retries.
log.Printf("[auth] the case-insensitive username index was not created because a clashing username was just added: %v", err)
return nil
}
return fmt.Errorf("ensure username index: %w", err)
}
return nil
}
// TOTPState is the private provisioning state for one account. Secret must
// never be included in an API response.
type TOTPState struct {
@@ -176,15 +240,25 @@ func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, erro
return state, nil
}
// SetTOTPSecret stores a pending secret without enabling two-factor auth.
// SetTOTPSecret stores a pending secret without enabling two-factor auth. It refuses while TOTP is
// already enabled, so a replaced secret cannot silently switch the second factor off.
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
if err := s.validate(); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
if err != nil {
return fmt.Errorf("set TOTP secret: %w", err)
}
if tag.RowsAffected() == 0 {
state, err := s.GetTOTPState(ctx, userID)
if err != nil {
return err
}
if state.Enabled {
return ErrTOTPAlreadyEnabled
}
}
return nil
}
@@ -230,6 +304,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
if err := s.validate(); err != nil {
return nil, err
}
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
var user User
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
@@ -255,10 +332,19 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
if err := s.validate(); err != nil {
return nil, err
}
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
user, err := s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1
`, identifier)
if err != nil || user != nil {
return user, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
WHERE lower(email) = lower($1)
`, identifier)
}
@@ -278,12 +364,19 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email
if err := s.validate(); err != nil {
return err
}
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
_, err := s.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update auth credentials: %w", err)
}
return nil
@@ -319,6 +412,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
if err := s.validate(); err != nil {
return nil, err
}
if err := validateCredentials(username, passwordHash); err != nil {
return nil, err
}
role = NormalizeRole(string(role))
var user User
err := s.pool.QueryRow(ctx, `
@@ -343,6 +439,9 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
if err := s.validate(); err != nil {
return err
}
if err := validateCredentials(username, passwordHash); err != nil {
return err
}
if role == nil {
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
}
@@ -353,6 +452,10 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
WHERE id = $5
`, username, email, passwordHash, *role, id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return ErrUserExists
}
return fmt.Errorf("update managed auth user: %w", err)
}
return nil
@@ -627,6 +730,27 @@ func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project stri
var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
var ErrTOTPAlreadyEnabled = errors.New("auth: TOTP is already enabled; disable it before setting a new secret")
// ErrEmptyPasswordHash is returned when a credential write has no password hash.
var ErrEmptyPasswordHash = errors.New("auth: password hash is required")
// ErrInvalidUsername is returned for a username containing "@", which would be read as an email.
var ErrInvalidUsername = errors.New("auth: username cannot contain @")
// validateCredentials refuses a credential write that would leave an account without a password
// hash, or that stores a username which could be mistaken for another account's email.
func validateCredentials(username, passwordHash string) error {
if passwordHash == "" {
return ErrEmptyPasswordHash
}
if strings.Contains(username, "@") {
return ErrInvalidUsername
}
return nil
}
func (s *Store) validate() error {
if s == nil || s.pool == nil {
return errors.New("auth store has no postgres pool")