From c615c21af12c418018abc9bc1f1938637b8a5a88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:48:02 +0100 Subject: [PATCH 01/22] build(dev): connect as non-superuser role so row-level security applies Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- compose.yaml | 10 +++++----- deploy/dev/postgres-init.sql | 7 +++++++ 2 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 deploy/dev/postgres-init.sql diff --git a/compose.yaml b/compose.yaml index c1ae869..c5de703 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,13 +4,13 @@ services: timescaledb: image: timescale/timescaledb:2.30.1-pg16 environment: - POSTGRES_USER: uptime - POSTGRES_PASSWORD: uptime - POSTGRES_DB: uptime + POSTGRES_PASSWORD: postgres ports: ["5432:5432"] - volumes: [pgdata:/var/lib/postgresql/data] + volumes: + - pgdata:/var/lib/postgresql/data + - ./deploy/dev/postgres-init.sql:/docker-entrypoint-initdb.d/10-uptime.sql:ro healthcheck: - test: ["CMD", "pg_isready", "-U", "uptime"] + test: ["CMD", "pg_isready", "-U", "uptime", "-d", "uptime"] interval: 2s retries: 30 diff --git a/deploy/dev/postgres-init.sql b/deploy/dev/postgres-init.sql new file mode 100644 index 0000000..5060fe0 --- /dev/null +++ b/deploy/dev/postgres-init.sql @@ -0,0 +1,7 @@ +-- Superusers bypass row-level security even with FORCE, so the application +-- must connect as an ordinary role for tenant isolation to be enforced. +CREATE ROLE uptime LOGIN PASSWORD 'uptime'; +CREATE DATABASE uptime OWNER uptime; +\connect uptime +CREATE EXTENSION IF NOT EXISTS timescaledb; +CREATE EXTENSION IF NOT EXISTS citext; -- 2.54.1 From 95da376ac1dce5ea8936c7c4004c6cb4ff9529f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:48:02 +0100 Subject: [PATCH 02/22] feat(store): add users and org memberships with single owner per org Refs #1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .../sql/00003_users_memberships.sql | 25 ++++ internal/store/memberships.sql.go | 127 ++++++++++++++++++ internal/store/models.go | 18 +++ internal/store/orgs.sql.go | 61 +++++++++ internal/store/querier.go | 12 ++ internal/store/queries/memberships.sql | 19 +++ internal/store/queries/orgs.sql | 9 ++ internal/store/queries/users.sql | 9 ++ internal/store/users.sql.go | 76 +++++++++++ 9 files changed, 356 insertions(+) create mode 100644 internal/migrations/sql/00003_users_memberships.sql create mode 100644 internal/store/memberships.sql.go create mode 100644 internal/store/queries/memberships.sql create mode 100644 internal/store/queries/users.sql create mode 100644 internal/store/users.sql.go diff --git a/internal/migrations/sql/00003_users_memberships.sql b/internal/migrations/sql/00003_users_memberships.sql new file mode 100644 index 0000000..dfb1ece --- /dev/null +++ b/internal/migrations/sql/00003_users_memberships.sql @@ -0,0 +1,25 @@ +-- +goose Up +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + email citext NOT NULL UNIQUE CHECK (length(email) BETWEEN 3 AND 320), + display_name text NOT NULL DEFAULT '' CHECK (length(display_name) <= 200), + password_hash text, + disabled_at timestamptz, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE memberships ( + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + is_owner boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, user_id) +); + +CREATE INDEX memberships_user_idx ON memberships (user_id); +CREATE UNIQUE INDEX memberships_one_owner_idx ON memberships (org_id) WHERE is_owner; + +-- +goose Down +DROP TABLE memberships; +DROP TABLE users; diff --git a/internal/store/memberships.sql.go b/internal/store/memberships.sql.go new file mode 100644 index 0000000..8c62aa0 --- /dev/null +++ b/internal/store/memberships.sql.go @@ -0,0 +1,127 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: memberships.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const addMembership = `-- name: AddMembership :exec +INSERT INTO memberships (org_id, user_id, is_owner) VALUES ($1, $2, $3) +` + +type AddMembershipParams struct { + OrgID uuid.UUID + UserID uuid.UUID + IsOwner bool +} + +func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) error { + _, err := q.db.Exec(ctx, addMembership, arg.OrgID, arg.UserID, arg.IsOwner) + return err +} + +const listOrgMembers = `-- name: ListOrgMembers :many +SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at +FROM memberships m +JOIN users u ON u.id = m.user_id +WHERE m.org_id = $1 +ORDER BY u.email +` + +type ListOrgMembersRow struct { + ID uuid.UUID + Email string + DisplayName string + IsOwner bool + JoinedAt time.Time +} + +func (q *Queries) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) { + rows, err := q.db.Query(ctx, listOrgMembers, orgID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListOrgMembersRow{} + for rows.Next() { + var i ListOrgMembersRow + if err := rows.Scan( + &i.ID, + &i.Email, + &i.DisplayName, + &i.IsOwner, + &i.JoinedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listUserOrgs = `-- name: ListUserOrgs :many +SELECT o.id, o.slug, o.name, m.is_owner +FROM memberships m +JOIN orgs o ON o.id = m.org_id +WHERE m.user_id = $1 +ORDER BY o.name +` + +type ListUserOrgsRow struct { + ID uuid.UUID + Slug string + Name string + IsOwner bool +} + +func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) { + rows, err := q.db.Query(ctx, listUserOrgs, userID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListUserOrgsRow{} + for rows.Next() { + var i ListUserOrgsRow + if err := rows.Scan( + &i.ID, + &i.Slug, + &i.Name, + &i.IsOwner, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const removeMembership = `-- name: RemoveMembership :execrows +DELETE FROM memberships WHERE org_id = $1 AND user_id = $2 AND NOT is_owner +` + +type RemoveMembershipParams struct { + OrgID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) { + result, err := q.db.Exec(ctx, removeMembership, arg.OrgID, arg.UserID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/store/models.go b/internal/store/models.go index 59f4a06..584bf5a 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -8,8 +8,16 @@ import ( "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" ) +type Membership struct { + OrgID uuid.UUID + UserID uuid.UUID + IsOwner bool + CreatedAt time.Time +} + type Org struct { ID uuid.UUID Slug string @@ -17,3 +25,13 @@ type Org struct { CreatedAt time.Time UpdatedAt time.Time } + +type User struct { + ID uuid.UUID + Email string + DisplayName string + PasswordHash *string + DisabledAt pgtype.Timestamptz + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/internal/store/orgs.sql.go b/internal/store/orgs.sql.go index e3b7ae3..445598d 100644 --- a/internal/store/orgs.sql.go +++ b/internal/store/orgs.sql.go @@ -7,6 +7,8 @@ package store import ( "context" + + "github.com/google/uuid" ) const createOrg = `-- name: CreateOrg :one @@ -32,6 +34,35 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro return i, err } +const deleteOrg = `-- name: DeleteOrg :execrows +DELETE FROM orgs WHERE id = $1 +` + +func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteOrg, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getOrg = `-- name: GetOrg :one +SELECT id, slug, name, created_at, updated_at FROM orgs WHERE id = $1 +` + +func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { + row := q.db.QueryRow(ctx, getOrg, id) + var i Org + err := row.Scan( + &i.ID, + &i.Slug, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + const getOrgBySlug = `-- name: GetOrgBySlug :one SELECT id, slug, name, created_at, updated_at FROM orgs WHERE slug = $1 ` @@ -48,3 +79,33 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { ) return i, err } + +const listOrgs = `-- name: ListOrgs :many +SELECT id, slug, name, created_at, updated_at FROM orgs ORDER BY name +` + +func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { + rows, err := q.db.Query(ctx, listOrgs) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Org{} + for rows.Next() { + var i Org + if err := rows.Scan( + &i.ID, + &i.Slug, + &i.Name, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/store/querier.go b/internal/store/querier.go index c6bedad..f785781 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -6,11 +6,23 @@ package store import ( "context" + + "github.com/google/uuid" ) type Querier interface { + AddMembership(ctx context.Context, arg AddMembershipParams) error CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) + CreateUser(ctx context.Context, arg CreateUserParams) (User, error) + DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) + GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) + GetUser(ctx context.Context, id uuid.UUID) (User, error) + GetUserByEmail(ctx context.Context, email string) (User, error) + ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) + ListOrgs(ctx context.Context) ([]Org, error) + ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) + RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/memberships.sql b/internal/store/queries/memberships.sql new file mode 100644 index 0000000..ef2bd0e --- /dev/null +++ b/internal/store/queries/memberships.sql @@ -0,0 +1,19 @@ +-- name: AddMembership :exec +INSERT INTO memberships (org_id, user_id, is_owner) VALUES ($1, $2, $3); + +-- name: RemoveMembership :execrows +DELETE FROM memberships WHERE org_id = $1 AND user_id = $2 AND NOT is_owner; + +-- name: ListOrgMembers :many +SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at +FROM memberships m +JOIN users u ON u.id = m.user_id +WHERE m.org_id = $1 +ORDER BY u.email; + +-- name: ListUserOrgs :many +SELECT o.id, o.slug, o.name, m.is_owner +FROM memberships m +JOIN orgs o ON o.id = m.org_id +WHERE m.user_id = $1 +ORDER BY o.name; diff --git a/internal/store/queries/orgs.sql b/internal/store/queries/orgs.sql index 2658c77..8fb19c6 100644 --- a/internal/store/queries/orgs.sql +++ b/internal/store/queries/orgs.sql @@ -2,5 +2,14 @@ INSERT INTO orgs (slug, name) VALUES ($1, $2) RETURNING *; +-- name: GetOrg :one +SELECT * FROM orgs WHERE id = $1; + -- name: GetOrgBySlug :one SELECT * FROM orgs WHERE slug = $1; + +-- name: ListOrgs :many +SELECT * FROM orgs ORDER BY name; + +-- name: DeleteOrg :execrows +DELETE FROM orgs WHERE id = $1; diff --git a/internal/store/queries/users.sql b/internal/store/queries/users.sql new file mode 100644 index 0000000..b1af3dc --- /dev/null +++ b/internal/store/queries/users.sql @@ -0,0 +1,9 @@ +-- name: CreateUser :one +INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) +RETURNING *; + +-- name: GetUser :one +SELECT * FROM users WHERE id = $1; + +-- name: GetUserByEmail :one +SELECT * FROM users WHERE email = $1; diff --git a/internal/store/users.sql.go b/internal/store/users.sql.go new file mode 100644 index 0000000..db14ac3 --- /dev/null +++ b/internal/store/users.sql.go @@ -0,0 +1,76 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: users.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const createUser = `-- name: CreateUser :one +INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) +RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at +` + +type CreateUserParams struct { + Email string + DisplayName string + PasswordHash *string +} + +func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) { + row := q.db.QueryRow(ctx, createUser, arg.Email, arg.DisplayName, arg.PasswordHash) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.DisplayName, + &i.PasswordHash, + &i.DisabledAt, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getUser = `-- name: GetUser :one +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE id = $1 +` + +func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { + row := q.db.QueryRow(ctx, getUser, id) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.DisplayName, + &i.PasswordHash, + &i.DisabledAt, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getUserByEmail = `-- name: GetUserByEmail :one +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE email = $1 +` + +func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) { + row := q.db.QueryRow(ctx, getUserByEmail, email) + var i User + err := row.Scan( + &i.ID, + &i.Email, + &i.DisplayName, + &i.PasswordHash, + &i.DisabledAt, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} -- 2.54.1 From ccc0fe58b85d4167ea4a1451115d9e6ab29f467c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:48:02 +0100 Subject: [PATCH 03/22] feat(tenant): enforce tenant isolation with row-level security Every query runs inside a transaction carrying app.org_id, app.user_id or the explicit system scope. Without a scope no rows are visible. Closes #2 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .../sql/00004_row_level_security.sql | 53 +++++ internal/platform/run.go | 11 + internal/tenant/tenant.go | 66 ++++++ internal/tenant/tenant_test.go | 188 ++++++++++++++++++ 4 files changed, 318 insertions(+) create mode 100644 internal/migrations/sql/00004_row_level_security.sql create mode 100644 internal/tenant/tenant.go create mode 100644 internal/tenant/tenant_test.go diff --git a/internal/migrations/sql/00004_row_level_security.sql b/internal/migrations/sql/00004_row_level_security.sql new file mode 100644 index 0000000..5065ee4 --- /dev/null +++ b/internal/migrations/sql/00004_row_level_security.sql @@ -0,0 +1,53 @@ +-- +goose Up +-- Tenant context is carried in transaction-local settings (set_config(..., true)). +-- Without any setting nothing is visible, so a forgotten scope fails closed. +-- app.scope = 'system' is reserved for cross-tenant work such as scheduling. + +-- +goose StatementBegin +CREATE FUNCTION app_scope_system() RETURNS boolean +LANGUAGE sql STABLE AS $$ + SELECT coalesce(current_setting('app.scope', true), '') = 'system' +$$; + +CREATE FUNCTION app_org_id() RETURNS uuid +LANGUAGE sql STABLE AS $$ + SELECT nullif(current_setting('app.org_id', true), '')::uuid +$$; + +CREATE FUNCTION app_user_id() RETURNS uuid +LANGUAGE sql STABLE AS $$ + SELECT nullif(current_setting('app.user_id', true), '')::uuid +$$; +-- +goose StatementEnd + +ALTER TABLE orgs ENABLE ROW LEVEL SECURITY; +ALTER TABLE orgs FORCE ROW LEVEL SECURITY; +CREATE POLICY orgs_read ON orgs FOR SELECT + USING ( + app_scope_system() OR id = app_org_id() + OR EXISTS (SELECT 1 FROM memberships m WHERE m.org_id = orgs.id AND m.user_id = app_user_id()) + ); +CREATE POLICY orgs_write ON orgs FOR ALL + USING (app_scope_system() OR id = app_org_id()) + WITH CHECK (app_scope_system() OR id = app_org_id()); + +ALTER TABLE memberships ENABLE ROW LEVEL SECURITY; +ALTER TABLE memberships FORCE ROW LEVEL SECURITY; +CREATE POLICY memberships_read ON memberships FOR SELECT + USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id()); +CREATE POLICY memberships_write ON memberships FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- +goose Down +DROP POLICY memberships_write ON memberships; +DROP POLICY memberships_read ON memberships; +ALTER TABLE memberships NO FORCE ROW LEVEL SECURITY; +ALTER TABLE memberships DISABLE ROW LEVEL SECURITY; +DROP POLICY orgs_write ON orgs; +DROP POLICY orgs_read ON orgs; +ALTER TABLE orgs NO FORCE ROW LEVEL SECURITY; +ALTER TABLE orgs DISABLE ROW LEVEL SECURITY; +DROP FUNCTION app_user_id(); +DROP FUNCTION app_org_id(); +DROP FUNCTION app_scope_system(); diff --git a/internal/platform/run.go b/internal/platform/run.go index 66e08a9..7eefe7f 100644 --- a/internal/platform/run.go +++ b/internal/platform/run.go @@ -60,5 +60,16 @@ func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, err d.Close() return nil, err } + warnIfRLSBypassed(ctx, d) return d, nil } + +// warnIfRLSBypassed flags deployments where tenant isolation silently degrades +// to application-level filtering only. +func warnIfRLSBypassed(ctx context.Context, d *Deps) { + var bypass bool + err := d.DB.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass) + if err == nil && bypass { + d.Log.Warn("database role bypasses row-level security; connect as a non-superuser role without BYPASSRLS") + } +} diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go new file mode 100644 index 0000000..fb802ff --- /dev/null +++ b/internal/tenant/tenant.go @@ -0,0 +1,66 @@ +package tenant + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" +) + +// Scope is the row-level-security context of one transaction. The zero value +// sees nothing. +type Scope struct { + OrgID uuid.UUID + UserID uuid.UUID + system bool +} + +func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } + +// User grants access to the user's own memberships and the orgs behind them, +// which is what login and the org switcher need before an org is chosen. +func User(user uuid.UUID) Scope { return Scope{UserID: user} } + +// System bypasses tenant isolation. Reserve it for work that is inherently +// cross-tenant, never for request handling. +func System() Scope { return Scope{system: true} } + +var ErrNoScope = errors.New("tenant: empty scope") + +type DB struct{ pool *pgxpool.Pool } + +func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} } + +func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error { + if s == (Scope{}) { + return ErrNoScope + } + return pgx.BeginFunc(ctx, d.pool, func(tx pgx.Tx) error { + if _, err := tx.Exec(ctx, + `SELECT set_config('app.org_id', $1, true), set_config('app.user_id', $2, true), set_config('app.scope', $3, true)`, + idOrEmpty(s.OrgID), idOrEmpty(s.UserID), scopeName(s), + ); err != nil { + return fmt.Errorf("tenant: %w", err) + } + return fn(store.New(tx)) + }) +} + +func idOrEmpty(id uuid.UUID) string { + if id == uuid.Nil { + return "" + } + return id.String() +} + +func scopeName(s Scope) string { + if s.system { + return "system" + } + return "" +} diff --git a/internal/tenant/tenant_test.go b/internal/tenant/tenant_test.go new file mode 100644 index 0000000..910d541 --- /dev/null +++ b/internal/tenant/tenant_test.go @@ -0,0 +1,188 @@ +package tenant_test + +import ( + "context" + "errors" + "os" + "testing" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +func setup(t *testing.T) (*tenant.DB, *pgxpool.Pool) { + t.Helper() + dsn := os.Getenv("UPTIME_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("UPTIME_TEST_DATABASE_URL not set") + } + ctx := context.Background() + if _, err := migrations.Up(ctx, dsn); err != nil { + t.Fatal(err) + } + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + var bypass bool + if err := pool.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass); err != nil { + t.Fatal(err) + } + if bypass { + t.Fatal("test role bypasses RLS; use a non-superuser role") + } + return tenant.New(pool), pool +} + +type fixture struct { + orgA, orgB store.Org + alice, bob store.User +} + +func seed(t *testing.T, db *tenant.DB) fixture { + t.Helper() + ctx := context.Background() + var f fixture + suffix := uuid.NewString()[:8] + err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "a-" + suffix, Name: "A"}); err != nil { + return err + } + if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "b-" + suffix, Name: "B"}); err != nil { + return err + } + if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil { + return err + } + if f.bob, err = q.CreateUser(ctx, store.CreateUserParams{Email: "bob-" + suffix + "@example.test"}); err != nil { + return err + } + if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.alice.ID, IsOwner: true}); err != nil { + return err + } + return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.bob.ID, IsOwner: true}) + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = db.Tx(context.Background(), tenant.System(), func(q *store.Queries) error { + for _, id := range []uuid.UUID{f.orgA.ID, f.orgB.ID} { + if _, err := q.DeleteOrg(context.Background(), id); err != nil { + return err + } + } + return nil + }) + }) + return f +} + +func TestOrgScopeHidesOtherTenants(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + + err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error { + if _, err := q.GetOrg(ctx, f.orgA.ID); err != nil { + t.Errorf("own org not visible: %v", err) + } + own, err := q.ListOrgMembers(ctx, f.orgA.ID) + if err != nil || len(own) != 1 { + t.Errorf("own members: %v %v", own, err) + } + if _, err := q.GetOrg(ctx, f.orgB.ID); !errors.Is(err, pgx.ErrNoRows) { + t.Errorf("org B visible from org A: %v", err) + } + members, err := q.ListOrgMembers(ctx, f.orgB.ID) + if err != nil { + return err + } + if len(members) != 0 { + t.Errorf("members of org B visible from org A: %v", members) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestOrgScopeCannotWriteIntoOtherTenant(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + + err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error { + return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.alice.ID}) + }) + if err == nil { + t.Fatal("membership in org B was created from org A scope") + } +} + +func TestUserScopeSeesOnlyOwnOrgs(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + + err := db.Tx(ctx, tenant.User(f.alice.ID), func(q *store.Queries) error { + orgs, err := q.ListUserOrgs(ctx, f.alice.ID) + if err != nil { + return err + } + if len(orgs) != 1 || orgs[0].ID != f.orgA.ID { + t.Errorf("unexpected orgs for alice: %v", orgs) + } + bobs, err := q.ListUserOrgs(ctx, f.bob.ID) + if err != nil { + return err + } + if len(bobs) != 0 { + t.Errorf("alice sees bob's orgs: %v", bobs) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestUnscopedConnectionSeesNothing(t *testing.T) { + db, pool := setup(t) + seed(t, db) + var n int + if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM orgs`).Scan(&n); err != nil { + t.Fatal(err) + } + if n != 0 { + t.Fatalf("unscoped query returned %d orgs", n) + } +} + +func TestEmptyScopeIsRejected(t *testing.T) { + db, _ := setup(t) + err := db.Tx(context.Background(), tenant.Scope{}, func(*store.Queries) error { return nil }) + if !errors.Is(err, tenant.ErrNoScope) { + t.Fatalf("got %v", err) + } +} + +func TestSingleOwnerPerOrg(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error { + return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.bob.ID, IsOwner: true}) + }) + if err == nil { + t.Fatal("second owner accepted") + } +} -- 2.54.1 From dae55d8c187173cb3b90d02cd35f81e80d480549 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:49:08 +0100 Subject: [PATCH 04/22] feat(auth): store sessions in redis with sliding and absolute expiry Tokens are only kept as SHA-256 hashes. A per-user index allows ending all sessions of an account at once. Closes #1 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/session.go | 174 ++++++++++++++++++++++++++++++++++ internal/auth/session_test.go | 100 +++++++++++++++++++ 2 files changed, 274 insertions(+) create mode 100644 internal/auth/session.go create mode 100644 internal/auth/session_test.go diff --git a/internal/auth/session.go b/internal/auth/session.go new file mode 100644 index 0000000..245e004 --- /dev/null +++ b/internal/auth/session.go @@ -0,0 +1,174 @@ +package auth + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "strconv" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +var ErrNoSession = errors.New("auth: no session") + +type Session struct { + Token string + UserID uuid.UUID + OrgID uuid.UUID + CSRF string + CreatedAt time.Time +} + +func (s *Session) CheckCSRF(token string) bool { + return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1 +} + +type Sessions struct { + rdb redis.UniversalClient + idle time.Duration + absolute time.Duration + now func() time.Time +} + +func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions { + return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now} +} + +// Only the hash of the token is stored, so a leaked Redis dump does not +// contain usable session cookies. +func key(token string) string { + sum := sha256.Sum256([]byte(token)) + return "session:" + hex.EncodeToString(sum[:]) +} + +func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() } + +func randomToken() string { + b := make([]byte, 32) + _, _ = rand.Read(b) + return base64.RawURLEncoding.EncodeToString(b) +} + +func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, error) { + sess := &Session{ + Token: randomToken(), + UserID: user, + OrgID: org, + CSRF: randomToken(), + CreatedAt: s.now(), + } + k := key(sess.Token) + _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.HSet(ctx, k, map[string]any{ + "user": sess.UserID.String(), + "org": orgString(org), + "csrf": sess.CSRF, + "created": sess.CreatedAt.Unix(), + }) + p.Expire(ctx, k, s.idle) + p.SAdd(ctx, userIndex(user), k) + p.Expire(ctx, userIndex(user), s.absolute) + return nil + }) + if err != nil { + return nil, fmt.Errorf("auth: create session: %w", err) + } + return sess, nil +} + +func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) { + if token == "" { + return nil, ErrNoSession + } + k := key(token) + vals, err := s.rdb.HGetAll(ctx, k).Result() + if err != nil { + return nil, fmt.Errorf("auth: load session: %w", err) + } + if len(vals) == 0 { + return nil, ErrNoSession + } + sess, err := decode(token, vals) + if err != nil { + _ = s.rdb.Del(ctx, k).Err() + return nil, ErrNoSession + } + if s.now().Sub(sess.CreatedAt) > s.absolute { + _ = s.Delete(ctx, sess) + return nil, ErrNoSession + } + // Sliding expiry, but never beyond the absolute lifetime. + remaining := s.absolute - s.now().Sub(sess.CreatedAt) + if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil { + return nil, fmt.Errorf("auth: touch session: %w", err) + } + return sess, nil +} + +func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error { + if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil { + return fmt.Errorf("auth: switch org: %w", err) + } + sess.OrgID = org + return nil +} + +func (s *Sessions) Delete(ctx context.Context, sess *Session) error { + k := key(sess.Token) + _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.Del(ctx, k) + p.SRem(ctx, userIndex(sess.UserID), k) + return nil + }) + return err +} + +// DeleteAllForUser ends every session of a user, e.g. after a password change +// or when an admin disables the account. +func (s *Sessions) DeleteAllForUser(ctx context.Context, user uuid.UUID) error { + idx := userIndex(user) + keys, err := s.rdb.SMembers(ctx, idx).Result() + if err != nil { + return err + } + _, err = s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + if len(keys) > 0 { + p.Del(ctx, keys...) + } + p.Del(ctx, idx) + return nil + }) + return err +} + +func decode(token string, v map[string]string) (*Session, error) { + user, err := uuid.Parse(v["user"]) + if err != nil { + return nil, err + } + var org uuid.UUID + if v["org"] != "" { + if org, err = uuid.Parse(v["org"]); err != nil { + return nil, err + } + } + created, err := strconv.ParseInt(v["created"], 10, 64) + if err != nil { + return nil, err + } + return &Session{Token: token, UserID: user, OrgID: org, CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil +} + +func orgString(id uuid.UUID) string { + if id == uuid.Nil { + return "" + } + return id.String() +} diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go new file mode 100644 index 0000000..ea70be4 --- /dev/null +++ b/internal/auth/session_test.go @@ -0,0 +1,100 @@ +package auth + +import ( + "context" + "errors" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +func testSessions(t *testing.T) (*Sessions, *time.Time) { + t.Helper() + url := os.Getenv("UPTIME_TEST_REDIS_URL") + if url == "" { + t.Skip("UPTIME_TEST_REDIS_URL not set") + } + opts, err := redis.ParseURL(url) + if err != nil { + t.Fatal(err) + } + rdb := redis.NewClient(opts) + t.Cleanup(func() { _ = rdb.Close() }) + now := time.Now() + s := NewSessions(rdb, time.Hour, 24*time.Hour) + s.now = func() time.Time { return now } + return s, &now +} + +func TestSessionRoundTrip(t *testing.T) { + s, _ := testSessions(t) + ctx := context.Background() + user, org := uuid.New(), uuid.New() + + created, err := s.Create(ctx, user, org) + if err != nil { + t.Fatal(err) + } + got, err := s.Get(ctx, created.Token) + if err != nil { + t.Fatal(err) + } + if got.UserID != user || got.OrgID != org || got.CSRF != created.CSRF { + t.Fatalf("mismatch: %+v vs %+v", got, created) + } + if !got.CheckCSRF(created.CSRF) || got.CheckCSRF("") || got.CheckCSRF("x") { + t.Fatal("csrf check wrong") + } + if err := s.Delete(ctx, got); err != nil { + t.Fatal(err) + } + if _, err := s.Get(ctx, created.Token); !errors.Is(err, ErrNoSession) { + t.Fatalf("deleted session still valid: %v", err) + } +} + +func TestSessionAbsoluteLifetime(t *testing.T) { + s, now := testSessions(t) + ctx := context.Background() + sess, err := s.Create(ctx, uuid.New(), uuid.Nil) + if err != nil { + t.Fatal(err) + } + *now = now.Add(25 * time.Hour) + if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) { + t.Fatalf("expired session accepted: %v", err) + } +} + +func TestDeleteAllForUser(t *testing.T) { + s, _ := testSessions(t) + ctx := context.Background() + user := uuid.New() + a, _ := s.Create(ctx, user, uuid.Nil) + b, _ := s.Create(ctx, user, uuid.Nil) + other, _ := s.Create(ctx, uuid.New(), uuid.Nil) + + if err := s.DeleteAllForUser(ctx, user); err != nil { + t.Fatal(err) + } + for _, tok := range []string{a.Token, b.Token} { + if _, err := s.Get(ctx, tok); !errors.Is(err, ErrNoSession) { + t.Fatal("session survived DeleteAllForUser") + } + } + if _, err := s.Get(ctx, other.Token); err != nil { + t.Fatalf("unrelated session removed: %v", err) + } +} + +func TestTokenNotStoredInPlain(t *testing.T) { + s, _ := testSessions(t) + ctx := context.Background() + sess, _ := s.Create(ctx, uuid.New(), uuid.Nil) + if n, _ := s.rdb.Exists(ctx, "session:"+sess.Token).Result(); n != 0 { + t.Fatal("raw token used as redis key") + } +} -- 2.54.1 From 9667e121f172070500cabfca274a9b20372f7bc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:49:08 +0100 Subject: [PATCH 05/22] feat(auth): add session middleware and csrf protection Unsafe methods require the session's synchronizer token and a matching Origin, which also covers login requests that have no session yet. Refs #5 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/middleware.go | 113 +++++++++++++++++++++++++++++++ internal/auth/middleware_test.go | 63 +++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 internal/auth/middleware.go create mode 100644 internal/auth/middleware_test.go diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go new file mode 100644 index 0000000..f703540 --- /dev/null +++ b/internal/auth/middleware.go @@ -0,0 +1,113 @@ +package auth + +import ( + "errors" + "net/http" + "net/url" + + "github.com/gin-gonic/gin" +) + +const ( + CookieName = "__Host-session" + CSRFHeader = "X-CSRF-Token" + CSRFField = "_csrf" + ctxKey = "auth.session" +) + +func SetCookie(c *gin.Context, sess *Session, maxAge int) { + http.SetCookie(c.Writer, &http.Cookie{ + Name: CookieName, + Value: sess.Token, + Path: "/", + MaxAge: maxAge, + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + }) +} + +func ClearCookie(c *gin.Context) { + http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) +} + +// Load attaches the session if one exists. It never rejects; use Require for that. +func (s *Sessions) Load() gin.HandlerFunc { + return func(c *gin.Context) { + token, err := c.Cookie(CookieName) + if err != nil { + c.Next() + return + } + sess, err := s.Get(c.Request.Context(), token) + switch { + case errors.Is(err, ErrNoSession): + ClearCookie(c) + case err != nil: + _ = c.Error(err) + c.AbortWithStatus(http.StatusServiceUnavailable) + return + default: + c.Set(ctxKey, sess) + } + c.Next() + } +} + +func Require() gin.HandlerFunc { + return func(c *gin.Context) { + if Current(c) == nil { + c.AbortWithStatus(http.StatusUnauthorized) + return + } + c.Next() + } +} + +// CSRF uses the synchronizer token stored in the session. SameSite=Lax alone +// does not cover same-site subdomains such as customer status pages. +func CSRF() gin.HandlerFunc { + return func(c *gin.Context) { + switch c.Request.Method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + c.Next() + return + } + // Covers requests without a session (login CSRF) as well. + if !sameOrigin(c.Request) { + c.AbortWithStatus(http.StatusForbidden) + return + } + sess := Current(c) + if sess == nil { + c.Next() + return + } + token := c.GetHeader(CSRFHeader) + if token == "" { + token = c.PostForm(CSRFField) + } + if !sess.CheckCSRF(token) { + c.AbortWithStatus(http.StatusForbidden) + return + } + c.Next() + } +} + +func sameOrigin(r *http.Request) bool { + origin := r.Header.Get("Origin") + if origin == "" || origin == "null" { + return origin == "" + } + u, err := url.Parse(origin) + return err == nil && u.Host == r.Host +} + +func Current(c *gin.Context) *Session { + v, ok := c.Get(ctxKey) + if !ok { + return nil + } + return v.(*Session) +} diff --git a/internal/auth/middleware_test.go b/internal/auth/middleware_test.go new file mode 100644 index 0000000..a727514 --- /dev/null +++ b/internal/auth/middleware_test.go @@ -0,0 +1,63 @@ +package auth + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func csrfRouter(sess *Session) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + r.Use(func(c *gin.Context) { + if sess != nil { + c.Set(ctxKey, sess) + } + }, CSRF()) + r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + return r +} + +func TestCSRF(t *testing.T) { + sess := &Session{CSRF: "good"} + cases := []struct { + name string + sess *Session + method string + header string + origin string + form string + want int + }{ + {"safe method", sess, http.MethodGet, "", "", "", 204}, + {"missing token", sess, http.MethodPost, "", "", "", 403}, + {"wrong token", sess, http.MethodPost, "bad", "", "", 403}, + {"header token", sess, http.MethodPost, "good", "", "", 204}, + {"form token", sess, http.MethodPost, "", "", "_csrf=good", 204}, + {"no session", nil, http.MethodPost, "", "", "", 204}, + {"same origin", nil, http.MethodPost, "", "http://example.com", "", 204}, + {"foreign origin without session", nil, http.MethodPost, "", "https://evil.test", "", 403}, + {"foreign origin with token", sess, http.MethodPost, "good", "https://evil.test", "", 403}, + {"opaque origin", nil, http.MethodPost, "", "null", "", 403}, + } + for _, tc := range cases { + req := httptest.NewRequest(tc.method, "/x", strings.NewReader(tc.form)) + if tc.form != "" { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + if tc.origin != "" { + req.Header.Set("Origin", tc.origin) + } + if tc.header != "" { + req.Header.Set(CSRFHeader, tc.header) + } + w := httptest.NewRecorder() + csrfRouter(tc.sess).ServeHTTP(w, req) + if w.Code != tc.want { + t.Errorf("%s: got %d want %d", tc.name, w.Code, tc.want) + } + } +} -- 2.54.1 From 96c1555889f6781f04c33ba3905261c672dec320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH 06/22] feat(sealed): encrypt secrets at rest with a rotatable keyring Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/sealed/sealed.go | 84 ++++++++++++++++++++++++++++++++++ internal/sealed/sealed_test.go | 60 ++++++++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 internal/sealed/sealed.go create mode 100644 internal/sealed/sealed_test.go diff --git a/internal/sealed/sealed.go b/internal/sealed/sealed.go new file mode 100644 index 0000000..7ad1752 --- /dev/null +++ b/internal/sealed/sealed.go @@ -0,0 +1,84 @@ +// Package sealed encrypts small secrets (TOTP seeds, integration credentials) +// before they are written to the database. +package sealed + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "strings" +) + +var ErrUnknownKey = errors.New("sealed: unknown key id") + +// Keyring holds one active key for sealing and any number of retired keys +// that can still open old values, so keys can be rotated without downtime. +type Keyring struct { + active string + aeads map[string]cipher.AEAD +} + +// Parse reads "id:base64key,id2:base64key2"; the first entry is active. +func Parse(spec string) (*Keyring, error) { + kr := &Keyring{aeads: map[string]cipher.AEAD{}} + for i, part := range strings.Split(spec, ",") { + id, b64, ok := strings.Cut(strings.TrimSpace(part), ":") + if !ok || id == "" { + return nil, fmt.Errorf("sealed: entry %d must be id:base64", i+1) + } + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil || len(raw) != 32 { + return nil, fmt.Errorf("sealed: key %q must be 32 bytes, base64 encoded", id) + } + block, err := aes.NewCipher(raw) + if err != nil { + return nil, err + } + aead, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + if _, dup := kr.aeads[id]; dup { + return nil, fmt.Errorf("sealed: duplicate key id %q", id) + } + kr.aeads[id] = aead + if i == 0 { + kr.active = id + } + } + return kr, nil +} + +// Seal binds the ciphertext to aad (e.g. the owning row id) so a sealed value +// cannot be copied onto another row. +func (k *Keyring) Seal(plain, aad []byte) []byte { + aead := k.aeads[k.active] + nonce := make([]byte, aead.NonceSize()) + _, _ = rand.Read(nonce) + out := append([]byte(k.active+":"), nonce...) + return aead.Seal(out, nonce, plain, aad) +} + +func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { + id, rest, ok := strings.Cut(string(sealed), ":") + if !ok { + return nil, errors.New("sealed: malformed value") + } + aead, ok := k.aeads[id] + if !ok { + return nil, ErrUnknownKey + } + body := []byte(rest) + if len(body) < aead.NonceSize() { + return nil, errors.New("sealed: malformed value") + } + return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad) +} + +func (k *Keyring) NeedsReseal(sealed []byte) bool { + id, _, _ := strings.Cut(string(sealed), ":") + return id != k.active +} diff --git a/internal/sealed/sealed_test.go b/internal/sealed/sealed_test.go new file mode 100644 index 0000000..f46ad7a --- /dev/null +++ b/internal/sealed/sealed_test.go @@ -0,0 +1,60 @@ +package sealed + +import ( + "bytes" + "crypto/rand" + "encoding/base64" + "errors" + "testing" +) + +func key() string { + b := make([]byte, 32) + _, _ = rand.Read(b) + return base64.StdEncoding.EncodeToString(b) +} + +func TestRotation(t *testing.T) { + k1, k2 := key(), key() + old, err := Parse("a:" + k1) + if err != nil { + t.Fatal(err) + } + box := old.Seal([]byte("secret"), []byte("row-1")) + + rotated, err := Parse("b:" + k2 + ",a:" + k1) + if err != nil { + t.Fatal(err) + } + got, err := rotated.Open(box, []byte("row-1")) + if err != nil || !bytes.Equal(got, []byte("secret")) { + t.Fatalf("open with retired key: %q %v", got, err) + } + if !rotated.NeedsReseal(box) { + t.Fatal("old value not flagged for reseal") + } + if rotated.NeedsReseal(rotated.Seal([]byte("x"), nil)) { + t.Fatal("fresh value flagged for reseal") + } + + dropped, _ := Parse("b:" + k2) + if _, err := dropped.Open(box, []byte("row-1")); !errors.Is(err, ErrUnknownKey) { + t.Fatalf("got %v", err) + } +} + +func TestAADBinding(t *testing.T) { + kr, _ := Parse("a:" + key()) + box := kr.Seal([]byte("secret"), []byte("row-1")) + if _, err := kr.Open(box, []byte("row-2")); err == nil { + t.Fatal("value opened under different aad") + } +} + +func TestParseRejectsBadKeys(t *testing.T) { + for _, spec := range []string{"", "nokey", "a:short", "a:" + key() + ",a:" + key()} { + if _, err := Parse(spec); err == nil { + t.Errorf("accepted %q", spec) + } + } +} -- 2.54.1 From caff396264f5aca4d624e9d40ffa577f1cf5e795 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH 07/22] feat(auth): add argon2id passwords, replay-safe totp and redis rate limits Refs #3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/password.go | 82 ++++++++++++++++++++++++++++++++++ internal/auth/password_test.go | 41 +++++++++++++++++ internal/auth/ratelimit.go | 32 +++++++++++++ internal/auth/session.go | 6 +-- internal/auth/totp.go | 42 +++++++++++++++++ internal/auth/totp_test.go | 43 ++++++++++++++++++ 6 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 internal/auth/password.go create mode 100644 internal/auth/password_test.go create mode 100644 internal/auth/ratelimit.go create mode 100644 internal/auth/totp.go create mode 100644 internal/auth/totp_test.go diff --git a/internal/auth/password.go b/internal/auth/password.go new file mode 100644 index 0000000..8e1ebb1 --- /dev/null +++ b/internal/auth/password.go @@ -0,0 +1,82 @@ +package auth + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +// OWASP 2024 baseline for argon2id. +type argonParams struct { + memory uint32 + time uint32 + threads uint8 + keyLen uint32 +} + +var current = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32} + +const MinPasswordLength = 12 + +var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength) + +func HashPassword(pw string) (string, error) { + if len([]rune(pw)) < MinPasswordLength { + return "", ErrPasswordTooShort + } + salt := make([]byte, 16) + _, _ = rand.Read(salt) + p := current + hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen) + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, p.memory, p.time, p.threads, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(hash)), nil +} + +// VerifyPassword reports whether pw matches and whether the stored hash uses +// outdated parameters and should be replaced on this successful login. +func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) { + p, salt, want, err := decodeHash(encoded) + if err != nil { + return false, false, err + } + got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want))) + ok = subtle.ConstantTimeCompare(got, want) == 1 + return ok, ok && p != current, nil +} + +// dummyHash keeps the response time of unknown accounts equal to known ones. +var dummyHash, _ = HashPassword("not-a-real-password-for-timing") + +func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash, pw) } + +func decodeHash(s string) (argonParams, []byte, []byte, error) { + var p argonParams + parts := strings.Split(s, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return p, nil, nil, errors.New("auth: unsupported password hash") + } + var v int + if _, err := fmt.Sscanf(parts[2], "v=%d", &v); err != nil || v != argon2.Version { + return p, nil, nil, errors.New("auth: unsupported argon2 version") + } + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.threads); err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + hash, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return p, nil, nil, errors.New("auth: malformed password hash") + } + p.keyLen = uint32(len(hash)) + return p, salt, hash, nil +} diff --git a/internal/auth/password_test.go b/internal/auth/password_test.go new file mode 100644 index 0000000..cb85041 --- /dev/null +++ b/internal/auth/password_test.go @@ -0,0 +1,41 @@ +package auth + +import ( + "strings" + "testing" +) + +func TestPasswordHash(t *testing.T) { + h, err := HashPassword("correct horse battery") + if err != nil { + t.Fatal(err) + } + if ok, rehash, err := VerifyPassword(h, "correct horse battery"); !ok || rehash || err != nil { + t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) + } + if ok, _, _ := VerifyPassword(h, "correct horse batterz"); ok { + t.Fatal("wrong password accepted") + } + if _, err := HashPassword("short"); err != ErrPasswordTooShort { + t.Fatalf("got %v", err) + } +} + +func TestPasswordRehashOnWeakerParams(t *testing.T) { + saved := current + current = argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32} + h, _ := HashPassword("correct horse battery") + current = saved + ok, rehash, err := VerifyPassword(h, "correct horse battery") + if !ok || !rehash || err != nil { + t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) + } +} + +func TestPasswordHashRejectsForeignFormats(t *testing.T) { + for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash, "argon2id", "argon2i", 1)} { + if _, _, err := VerifyPassword(h, "x"); err == nil { + t.Errorf("accepted %q", h) + } + } +} diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go new file mode 100644 index 0000000..c4410d4 --- /dev/null +++ b/internal/auth/ratelimit.go @@ -0,0 +1,32 @@ +package auth + +import ( + "context" + "time" + + "github.com/redis/go-redis/v9" +) + +type Limiter struct { + rdb redis.UniversalClient +} + +func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } + +var incrWithTTL = redis.NewScript(` +local n = redis.call("INCR", KEYS[1]) +if n == 1 then redis.call("PEXPIRE", KEYS[1], ARGV[1]) end +return n`) + +// Allow counts one attempt in a fixed window shared by all replicas. +func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.Duration) (bool, error) { + n, err := incrWithTTL.Run(ctx, l.rdb, []string{"rl:" + key}, window.Milliseconds()).Int() + if err != nil { + return false, err + } + return n <= limit, nil +} + +func (l *Limiter) Reset(ctx context.Context, key string) error { + return l.rdb.Del(ctx, "rl:"+key).Err() +} diff --git a/internal/auth/session.go b/internal/auth/session.go index 245e004..c7831dc 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -50,7 +50,7 @@ func key(token string) string { func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() } -func randomToken() string { +func RandomToken() string { b := make([]byte, 32) _, _ = rand.Read(b) return base64.RawURLEncoding.EncodeToString(b) @@ -58,10 +58,10 @@ func randomToken() string { func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, error) { sess := &Session{ - Token: randomToken(), + Token: RandomToken(), UserID: user, OrgID: org, - CSRF: randomToken(), + CSRF: RandomToken(), CreatedAt: s.now(), } k := key(sess.Token) diff --git a/internal/auth/totp.go b/internal/auth/totp.go new file mode 100644 index 0000000..1ea913d --- /dev/null +++ b/internal/auth/totp.go @@ -0,0 +1,42 @@ +package auth + +import ( + "context" + "time" + + "github.com/google/uuid" + "github.com/pquerna/otp" + "github.com/pquerna/otp/totp" + "github.com/redis/go-redis/v9" +) + +const totpIssuer = "uptimesebi" + +func NewTOTPKey(account string) (*otp.Key, error) { + return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) +} + +// TOTPVerifier rejects a code that was already accepted once, so an observed +// code cannot be replayed within its validity window. +type TOTPVerifier struct { + rdb redis.UniversalClient + now func() time.Time +} + +func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { + return &TOTPVerifier{rdb: rdb, now: time.Now} +} + +func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) { + ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ + Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, + }) + if err != nil || !ok { + return false, nil + } + fresh, err := v.rdb.SetNX(ctx, "totp_used:"+user.String()+":"+code, 1, 2*time.Minute).Result() + if err != nil { + return false, err + } + return fresh, nil +} diff --git a/internal/auth/totp_test.go b/internal/auth/totp_test.go new file mode 100644 index 0000000..d673ffc --- /dev/null +++ b/internal/auth/totp_test.go @@ -0,0 +1,43 @@ +package auth + +import ( + "context" + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/pquerna/otp/totp" + "github.com/redis/go-redis/v9" +) + +func TestTOTPRejectsReplay(t *testing.T) { + url := os.Getenv("UPTIME_TEST_REDIS_URL") + if url == "" { + t.Skip("UPTIME_TEST_REDIS_URL not set") + } + opts, _ := redis.ParseURL(url) + rdb := redis.NewClient(opts) + defer rdb.Close() + + key, err := NewTOTPKey("a@example.test") + if err != nil { + t.Fatal(err) + } + now := time.Now() + code, _ := totp.GenerateCode(key.Secret(), now) + v := NewTOTPVerifier(rdb) + v.now = func() time.Time { return now } + user := uuid.New() + ctx := context.Background() + + if ok, err := v.Verify(ctx, user, key.Secret(), code); !ok || err != nil { + t.Fatalf("first use rejected: %v", err) + } + if ok, _ := v.Verify(ctx, user, key.Secret(), code); ok { + t.Fatal("replayed code accepted") + } + if ok, _ := v.Verify(ctx, user, key.Secret(), "000000"); ok { + t.Fatal("wrong code accepted") + } +} -- 2.54.1 From 99e9b1e57dcb7b16cec218e20ad372eb75d5e1bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH 08/22] feat(store): add totp columns, org totp policy and global scope Orgs are created inside their own tenant scope, so signup needs no system scope. Refs #3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/migrations/sql/00005_totp.sql | 14 +++++ internal/store/memberships.sql.go | 12 +++-- internal/store/models.go | 28 +++++----- internal/store/orgs.sql.go | 17 +++--- internal/store/querier.go | 5 ++ internal/store/queries/memberships.sql | 2 +- internal/store/queries/orgs.sql | 2 +- internal/store/queries/users.sql | 15 ++++++ internal/store/users.sql.go | 72 ++++++++++++++++++++++++-- internal/tenant/tenant.go | 5 ++ internal/tenant/tenant_test.go | 51 +++++++++++++++++- sqlc.yaml | 11 ++++ 12 files changed, 203 insertions(+), 31 deletions(-) create mode 100644 internal/migrations/sql/00005_totp.sql diff --git a/internal/migrations/sql/00005_totp.sql b/internal/migrations/sql/00005_totp.sql new file mode 100644 index 0000000..544c962 --- /dev/null +++ b/internal/migrations/sql/00005_totp.sql @@ -0,0 +1,14 @@ +-- +goose Up +ALTER TABLE users + ADD COLUMN totp_secret bytea, + ADD COLUMN totp_enabled_at timestamptz, + ADD CONSTRAINT users_totp_consistent CHECK ((totp_secret IS NULL) = (totp_enabled_at IS NULL)); + +ALTER TABLE orgs ADD COLUMN require_totp boolean NOT NULL DEFAULT false; + +-- +goose Down +ALTER TABLE orgs DROP COLUMN require_totp; +ALTER TABLE users + DROP CONSTRAINT users_totp_consistent, + DROP COLUMN totp_enabled_at, + DROP COLUMN totp_secret; diff --git a/internal/store/memberships.sql.go b/internal/store/memberships.sql.go index 8c62aa0..ee9eee7 100644 --- a/internal/store/memberships.sql.go +++ b/internal/store/memberships.sql.go @@ -70,7 +70,7 @@ func (q *Queries) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOr } const listUserOrgs = `-- name: ListUserOrgs :many -SELECT o.id, o.slug, o.name, m.is_owner +SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner FROM memberships m JOIN orgs o ON o.id = m.org_id WHERE m.user_id = $1 @@ -78,10 +78,11 @@ ORDER BY o.name ` type ListUserOrgsRow struct { - ID uuid.UUID - Slug string - Name string - IsOwner bool + ID uuid.UUID + Slug string + Name string + RequireTotp bool + IsOwner bool } func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) { @@ -97,6 +98,7 @@ func (q *Queries) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUse &i.ID, &i.Slug, &i.Name, + &i.RequireTotp, &i.IsOwner, ); err != nil { return nil, err diff --git a/internal/store/models.go b/internal/store/models.go index 584bf5a..ccccfaa 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -8,7 +8,6 @@ import ( "time" "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgtype" ) type Membership struct { @@ -19,19 +18,22 @@ type Membership struct { } type Org struct { - ID uuid.UUID - Slug string - Name string - CreatedAt time.Time - UpdatedAt time.Time + ID uuid.UUID + Slug string + Name string + CreatedAt time.Time + UpdatedAt time.Time + RequireTotp bool } type User struct { - ID uuid.UUID - Email string - DisplayName string - PasswordHash *string - DisabledAt pgtype.Timestamptz - CreatedAt time.Time - UpdatedAt time.Time + ID uuid.UUID + Email string + DisplayName string + PasswordHash *string + DisabledAt *time.Time + CreatedAt time.Time + UpdatedAt time.Time + TotpSecret []byte + TotpEnabledAt *time.Time } diff --git a/internal/store/orgs.sql.go b/internal/store/orgs.sql.go index 445598d..168fef1 100644 --- a/internal/store/orgs.sql.go +++ b/internal/store/orgs.sql.go @@ -12,17 +12,18 @@ import ( ) const createOrg = `-- name: CreateOrg :one -INSERT INTO orgs (slug, name) VALUES ($1, $2) -RETURNING id, slug, name, created_at, updated_at +INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) +RETURNING id, slug, name, created_at, updated_at, require_totp ` type CreateOrgParams struct { + ID uuid.UUID Slug string Name string } func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) { - row := q.db.QueryRow(ctx, createOrg, arg.Slug, arg.Name) + row := q.db.QueryRow(ctx, createOrg, arg.ID, arg.Slug, arg.Name) var i Org err := row.Scan( &i.ID, @@ -30,6 +31,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } @@ -47,7 +49,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) { } const getOrg = `-- name: GetOrg :one -SELECT id, slug, name, created_at, updated_at FROM orgs WHERE id = $1 +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE id = $1 ` func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { @@ -59,12 +61,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } const getOrgBySlug = `-- name: GetOrgBySlug :one -SELECT id, slug, name, created_at, updated_at FROM orgs WHERE slug = $1 +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs WHERE slug = $1 ` func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { @@ -76,12 +79,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ) return i, err } const listOrgs = `-- name: ListOrgs :many -SELECT id, slug, name, created_at, updated_at FROM orgs ORDER BY name +SELECT id, slug, name, created_at, updated_at, require_totp FROM orgs ORDER BY name ` func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { @@ -99,6 +103,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { &i.Name, &i.CreatedAt, &i.UpdatedAt, + &i.RequireTotp, ); err != nil { return nil, err } diff --git a/internal/store/querier.go b/internal/store/querier.go index f785781..6f20f1c 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -12,9 +12,13 @@ import ( type Querier interface { AddMembership(ctx context.Context, arg AddMembershipParams) error + AnyUserExists(ctx context.Context) (bool, error) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) + DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) + DisableTOTP(ctx context.Context, id uuid.UUID) error + EnableTOTP(ctx context.Context, arg EnableTOTPParams) error GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) @@ -23,6 +27,7 @@ type Querier interface { ListOrgs(ctx context.Context) ([]Org, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) + SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/memberships.sql b/internal/store/queries/memberships.sql index ef2bd0e..443a104 100644 --- a/internal/store/queries/memberships.sql +++ b/internal/store/queries/memberships.sql @@ -12,7 +12,7 @@ WHERE m.org_id = $1 ORDER BY u.email; -- name: ListUserOrgs :many -SELECT o.id, o.slug, o.name, m.is_owner +SELECT o.id, o.slug, o.name, o.require_totp, m.is_owner FROM memberships m JOIN orgs o ON o.id = m.org_id WHERE m.user_id = $1 diff --git a/internal/store/queries/orgs.sql b/internal/store/queries/orgs.sql index 8fb19c6..98a20f3 100644 --- a/internal/store/queries/orgs.sql +++ b/internal/store/queries/orgs.sql @@ -1,5 +1,5 @@ -- name: CreateOrg :one -INSERT INTO orgs (slug, name) VALUES ($1, $2) +INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) RETURNING *; -- name: GetOrg :one diff --git a/internal/store/queries/users.sql b/internal/store/queries/users.sql index b1af3dc..4c0420e 100644 --- a/internal/store/queries/users.sql +++ b/internal/store/queries/users.sql @@ -7,3 +7,18 @@ SELECT * FROM users WHERE id = $1; -- name: GetUserByEmail :one SELECT * FROM users WHERE email = $1; + +-- name: AnyUserExists :one +SELECT EXISTS (SELECT 1 FROM users); + +-- name: SetPasswordHash :exec +UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1; + +-- name: EnableTOTP :exec +UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1; + +-- name: DisableTOTP :exec +UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1; + +-- name: DeleteUser :execrows +DELETE FROM users WHERE id = $1; diff --git a/internal/store/users.sql.go b/internal/store/users.sql.go index db14ac3..5db19c4 100644 --- a/internal/store/users.sql.go +++ b/internal/store/users.sql.go @@ -11,9 +11,20 @@ import ( "github.com/google/uuid" ) +const anyUserExists = `-- name: AnyUserExists :one +SELECT EXISTS (SELECT 1 FROM users) +` + +func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) { + row := q.db.QueryRow(ctx, anyUserExists) + var exists bool + err := row.Scan(&exists) + return exists, err +} + const createUser = `-- name: CreateUser :one INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) -RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at +RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at ` type CreateUserParams struct { @@ -33,12 +44,49 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } +const deleteUser = `-- name: DeleteUser :execrows +DELETE FROM users WHERE id = $1 +` + +func (q *Queries) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteUser, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const disableTOTP = `-- name: DisableTOTP :exec +UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() WHERE id = $1 +` + +func (q *Queries) DisableTOTP(ctx context.Context, id uuid.UUID) error { + _, err := q.db.Exec(ctx, disableTOTP, id) + return err +} + +const enableTOTP = `-- name: EnableTOTP :exec +UPDATE users SET totp_secret = $2, totp_enabled_at = now(), updated_at = now() WHERE id = $1 +` + +type EnableTOTPParams struct { + ID uuid.UUID + TotpSecret []byte +} + +func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error { + _, err := q.db.Exec(ctx, enableTOTP, arg.ID, arg.TotpSecret) + return err +} + const getUser = `-- name: GetUser :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE id = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE id = $1 ` func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { @@ -52,12 +100,14 @@ func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } const getUserByEmail = `-- name: GetUserByEmail :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at FROM users WHERE email = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE email = $1 ` func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) { @@ -71,6 +121,22 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error &i.DisabledAt, &i.CreatedAt, &i.UpdatedAt, + &i.TotpSecret, + &i.TotpEnabledAt, ) return i, err } + +const setPasswordHash = `-- name: SetPasswordHash :exec +UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1 +` + +type SetPasswordHashParams struct { + ID uuid.UUID + PasswordHash *string +} + +func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error { + _, err := q.db.Exec(ctx, setPasswordHash, arg.ID, arg.PasswordHash) + return err +} diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go index fb802ff..8a10fdc 100644 --- a/internal/tenant/tenant.go +++ b/internal/tenant/tenant.go @@ -18,6 +18,7 @@ type Scope struct { OrgID uuid.UUID UserID uuid.UUID system bool + global bool } func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } @@ -26,6 +27,10 @@ func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } // which is what login and the org switcher need before an org is chosen. func User(user uuid.UUID) Scope { return Scope{UserID: user} } +// Global carries no tenant context: only tables without row-level security, +// such as users, are usable. Login runs here before the user is known. +func Global() Scope { return Scope{global: true} } + // System bypasses tenant isolation. Reserve it for work that is inherently // cross-tenant, never for request handling. func System() Scope { return Scope{system: true} } diff --git a/internal/tenant/tenant_test.go b/internal/tenant/tenant_test.go index 910d541..421384a 100644 --- a/internal/tenant/tenant_test.go +++ b/internal/tenant/tenant_test.go @@ -52,10 +52,10 @@ func seed(t *testing.T, db *tenant.DB) fixture { suffix := uuid.NewString()[:8] err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error - if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "a-" + suffix, Name: "A"}); err != nil { + if f.orgA, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "a-" + suffix, Name: "A"}); err != nil { return err } - if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{Slug: "b-" + suffix, Name: "B"}); err != nil { + if f.orgB, err = q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "b-" + suffix, Name: "B"}); err != nil { return err } if f.alice, err = q.CreateUser(ctx, store.CreateUserParams{Email: "alice-" + suffix + "@example.test"}); err != nil { @@ -79,6 +79,11 @@ func seed(t *testing.T, db *tenant.DB) fixture { return err } } + for _, id := range []uuid.UUID{f.alice.ID, f.bob.ID} { + if _, err := q.DeleteUser(context.Background(), id); err != nil { + return err + } + } return nil }) }) @@ -186,3 +191,45 @@ func TestSingleOwnerPerOrg(t *testing.T) { t.Fatal("second owner accepted") } } + +func TestGlobalScopeSeesNoTenantRows(t *testing.T) { + db, _ := setup(t) + f := seed(t, db) + ctx := context.Background() + err := db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + if _, err := q.GetOrg(ctx, f.orgA.ID); !errors.Is(err, pgx.ErrNoRows) { + t.Errorf("org visible in global scope: %v", err) + } + if _, err := q.GetUser(ctx, f.alice.ID); err != nil { + t.Errorf("users must be readable in global scope: %v", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestNewOrgCanBeCreatedInItsOwnScope(t *testing.T) { + db, _ := setup(t) + ctx := context.Background() + id := uuid.New() + err := db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error { + _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: id, Slug: "n-" + id.String()[:8], Name: "N"}) + return err + }) + if err != nil { + t.Fatal(err) + } + _ = db.Tx(ctx, tenant.Org(id, uuid.Nil), func(q *store.Queries) error { + _, err := q.DeleteOrg(ctx, id) + return err + }) + err = db.Tx(ctx, tenant.Org(uuid.New(), uuid.Nil), func(q *store.Queries) error { + _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: uuid.New(), Slug: "x-" + id.String()[:8], Name: "X"}) + return err + }) + if err == nil { + t.Fatal("org created outside its own scope") + } +} diff --git a/sqlc.yaml b/sqlc.yaml index 793ff72..2a12748 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -18,3 +18,14 @@ sql: go_type: string - db_type: timestamptz go_type: time.Time + - db_type: timestamptz + nullable: true + go_type: + type: time.Time + pointer: true + - db_type: uuid + nullable: true + go_type: + import: github.com/google/uuid + type: UUID + pointer: true -- 2.54.1 From db44fedc722a20220c1dadd08d4dfdbbfd617bbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sat, 21 Nov 2026 23:55:23 +0100 Subject: [PATCH 09/22] feat(api): add signup, login with totp and account security pages Signup is limited to the first user by default (UPTIME_SIGNUP). TOTP secrets are sealed with UPTIME_SECRET_KEYS and bound to the user id. Closes #3 Closes #5 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 3 + cmd/api/main.go | 20 ++- go.mod | 14 +- go.sum | 18 ++ internal/api/auth.go | 299 +++++++++++++++++++++++++++++++++ internal/api/me.go | 261 +++++++++++++++++++++++++++++ internal/api/pages.go | 82 +++++++++ internal/api/server.go | 101 ++++++++++++ internal/config/config.go | 32 +++- internal/web/assets/app.js | 79 ++++++++- internal/web/auth.templ | 37 +++++ internal/web/auth_templ.go | 176 ++++++++++++++++++++ internal/web/console.templ | 90 ++++++++++ internal/web/console_templ.go | 301 ++++++++++++++++++++++++++++++++++ internal/web/index.templ | 9 - internal/web/index_templ.go | 55 ------- internal/web/layout.templ | 45 ++++- internal/web/layout_templ.go | 261 ++++++++++++++++++++++++++++- 18 files changed, 1792 insertions(+), 91 deletions(-) create mode 100644 internal/api/auth.go create mode 100644 internal/api/me.go create mode 100644 internal/api/pages.go create mode 100644 internal/api/server.go create mode 100644 internal/web/auth.templ create mode 100644 internal/web/auth_templ.go create mode 100644 internal/web/console.templ create mode 100644 internal/web/console_templ.go delete mode 100644 internal/web/index.templ delete mode 100644 internal/web/index_templ.go diff --git a/.env.example b/.env.example index ccd30d6..095a33c 100644 --- a/.env.example +++ b/.env.example @@ -5,3 +5,6 @@ UPTIME_CHECKER_REGION=local # Sentinel instead of a single redis (docker compose --profile sentinel up -d) # UPTIME_REDIS_SENTINEL_MASTER=uptime # UPTIME_REDIS_SENTINEL_ADDRS=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 + +# Generate with: echo "k1:$(head -c32 /dev/urandom | base64)" +UPTIME_SECRET_KEYS=dev:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= diff --git a/cmd/api/main.go b/cmd/api/main.go index 6541ed6..092d55f 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -4,15 +4,16 @@ import ( "context" "errors" "log/slog" - "net/http" "os" "time" - "github.com/gin-gonic/gin" - + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) @@ -40,17 +41,28 @@ func run(log *slog.Logger, args []string) error { return errors.New("usage: api [serve | migrate up|down|status]") } + if err := cfg.Validate(); err != nil { + return err + } + keys, err := sealed.Parse(cfg.SecretKeys) + if err != nil { + return err + } deps, err := platform.Connect(ctx, cfg.Common, log) if err != nil { return err } defer deps.Close() + srv := api.New(cfg, log, tenant.New(deps.DB), deps.Redis, keys) health := platform.NewHealth(deps.Probes()) r := platform.NewRouter(log) health.Register(r) r.StaticFS("/static", web.Static()) - r.GET("/", func(c *gin.Context) { web.Render(c, http.StatusOK, web.Index()) }) + + app := r.Group("/", srv.Sessions().Load(), auth.CSRF()) + srv.Register(app) + srv.RegisterPages(app) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } diff --git a/go.mod b/go.mod index d060a62..6d3d9d8 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( require ( github.com/a-h/parse v0.0.42 // indirect github.com/andybalholm/brotli v1.3.0 // indirect + github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect @@ -24,11 +25,11 @@ require ( github.com/cloudwego/base64x v0.1.6 // indirect github.com/fatih/color v1.19.0 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gabriel-vasile/mimetype v1.4.16 // indirect github.com/gin-contrib/sse v1.1.0 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/go-playground/locales v0.14.2 // indirect + github.com/go-playground/universal-translator v0.18.2 // indirect + github.com/go-playground/validator/v10 v10.30.6 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect @@ -36,7 +37,7 @@ require ( github.com/jackc/puddle/v2 v2.2.3 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.4.0 // indirect - github.com/leodido/go-urn v1.4.0 // indirect + github.com/leodido/go-urn v1.5.0 // indirect github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/mfridman/interpolate v0.2.0 // indirect @@ -44,6 +45,7 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pquerna/otp v1.5.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect @@ -53,7 +55,7 @@ require ( go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.58.0 // indirect + golang.org/x/crypto v0.59.0 // indirect golang.org/x/mod v0.43.0 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.25.0 // indirect diff --git a/go.sum b/go.sum index be41d9f..22633bb 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI= github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjPuCS4= github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY= github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= +github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= @@ -35,6 +37,8 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5 github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= +github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= @@ -43,10 +47,16 @@ github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lY github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= +github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= +github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= +github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= @@ -70,6 +80,8 @@ github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV91 github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= @@ -88,6 +100,8 @@ github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2K github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs= +github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= @@ -100,6 +114,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= +github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -134,6 +150,8 @@ golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= diff --git a/internal/api/auth.go b/internal/api/auth.go new file mode 100644 index 0000000..71472ea --- /dev/null +++ b/internal/api/auth.go @@ -0,0 +1,299 @@ +package api + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const ( + mfaCookie = "__Host-mfa" + mfaTTL = 5 * time.Minute +) + +type signupRequest struct { + Email string `json:"email" binding:"required,email,max=320"` + Password string `json:"password" binding:"required,max=1024"` + DisplayName string `json:"display_name" binding:"max=200"` + OrgName string `json:"org_name" binding:"required,max=200"` + OrgSlug string `json:"org_slug" binding:"required,max=63"` +} + +func (s *Server) signup(c *gin.Context) { + var req signupRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + if !s.limit(c, "signup:"+c.ClientIP(), 10, time.Hour) { + return + } + if allowed, err := s.signupAllowed(ctx); err != nil { + internalError(c, err) + return + } else if !allowed { + fail(c, http.StatusForbidden, "signup_closed", "Registrierung ist deaktiviert.") + return + } + hash, err := auth.HashPassword(req.Password) + if errors.Is(err, auth.ErrPasswordTooShort) { + fail(c, http.StatusUnprocessableEntity, "password_too_short", err.Error()) + return + } else if err != nil { + internalError(c, err) + return + } + + orgID := uuid.New() + var user store.User + err = s.db.Tx(ctx, tenant.Org(orgID, uuid.Nil), func(q *store.Queries) error { + var err error + user, err = q.CreateUser(ctx, store.CreateUserParams{ + Email: normalizeEmail(req.Email), + DisplayName: strings.TrimSpace(req.DisplayName), + PasswordHash: &hash, + }) + if err != nil { + return err + } + if _, err := q.CreateOrg(ctx, store.CreateOrgParams{ID: orgID, Slug: strings.ToLower(req.OrgSlug), Name: strings.TrimSpace(req.OrgName)}); err != nil { + return err + } + return q.AddMembership(ctx, store.AddMembershipParams{OrgID: orgID, UserID: user.ID, IsOwner: true}) + }) + switch { + case isUniqueViolation(err, "users_email_key"): + fail(c, http.StatusConflict, "email_taken", "Diese E-Mail-Adresse ist bereits registriert.") + return + case isUniqueViolation(err, "orgs_slug_key"): + fail(c, http.StatusConflict, "slug_taken", "Dieser Kurzname ist bereits vergeben.") + return + case isCheckViolation(err): + fail(c, http.StatusUnprocessableEntity, "invalid_input", "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.") + return + case err != nil: + internalError(c, err) + return + } + s.startSession(c, user.ID, orgID) +} + +func (s *Server) signupAllowed(ctx context.Context) (bool, error) { + switch s.cfg.Signup { + case config.SignupOpen: + return true, nil + case config.SignupFirstUser: + var exists bool + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + exists, err = q.AnyUserExists(ctx) + return err + }) + return !exists, err + } + return false, nil +} + +type loginRequest struct { + Email string `json:"email" binding:"required,max=320"` + Password string `json:"password" binding:"required,max=1024"` +} + +func (s *Server) login(c *gin.Context) { + var req loginRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + email := normalizeEmail(req.Email) + if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) { + return + } + + var user store.User + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + user, err = q.GetUserByEmail(ctx, email) + return err + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && user.PasswordHash == nil) { + auth.BurnPasswordCheck(req.Password) + invalidCredentials(c) + return + } + if err != nil { + internalError(c, err) + return + } + ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password) + if err != nil { + internalError(c, err) + return + } + if !ok || user.DisabledAt != nil { + invalidCredentials(c) + return + } + if rehash { + s.rehashPassword(ctx, user.ID, req.Password) + } + + if user.TotpSecret != nil { + token := randomToken() + if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil { + internalError(c, err) + return + } + setCookie(c, mfaCookie, token, int(mfaTTL.Seconds())) + c.JSON(http.StatusOK, gin.H{"status": "totp_required"}) + return + } + s.finishLogin(c, user.ID) +} + +type totpRequest struct { + Code string `json:"code" binding:"required,len=6,numeric"` +} + +func (s *Server) loginTOTP(c *gin.Context) { + var req totpRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + token, _ := c.Cookie(mfaCookie) + if token == "" { + fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.") + return + } + if !s.limit(c, "mfa:"+mfaKey(token), 5, mfaTTL) { + return + } + raw, err := s.rdb.Get(ctx, mfaKey(token)).Result() + if err != nil { + fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.") + return + } + userID, err := uuid.Parse(raw) + if err != nil { + internalError(c, err) + return + } + ok, err := s.verifyUserTOTP(ctx, userID, req.Code) + if err != nil { + internalError(c, err) + return + } + if !ok { + fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.") + return + } + _ = s.rdb.Del(ctx, mfaKey(token)).Err() + setCookie(c, mfaCookie, "", -1) + s.finishLogin(c, userID) +} + +func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) { + ctx := c.Request.Context() + var orgs []store.ListUserOrgsRow + err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error { + var err error + orgs, err = q.ListUserOrgs(ctx, userID) + return err + }) + if err != nil { + internalError(c, err) + return + } + var org uuid.UUID + if len(orgs) > 0 { + org = orgs[0].ID + } + s.startSession(c, userID, org) +} + +func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID) { + if old := auth.Current(c); old != nil { + _ = s.sessions.Delete(c.Request.Context(), old) + } + sess, err := s.sessions.Create(c.Request.Context(), userID, orgID) + if err != nil { + internalError(c, err) + return + } + auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds())) + c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF}) +} + +func (s *Server) logout(c *gin.Context) { + if sess := auth.Current(c); sess != nil { + if err := s.sessions.Delete(c.Request.Context(), sess); err != nil { + internalError(c, err) + return + } + } + auth.ClearCookie(c) + c.Status(http.StatusNoContent) +} + +func (s *Server) rehashPassword(ctx context.Context, user uuid.UUID, pw string) { + hash, err := auth.HashPassword(pw) + if err != nil { + return + } + err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + return q.SetPasswordHash(ctx, store.SetPasswordHashParams{ID: user, PasswordHash: &hash}) + }) + if err != nil { + s.log.WarnContext(ctx, "password rehash failed", "error", err) + } +} + +func (s *Server) limit(c *gin.Context, key string, n int, window time.Duration) bool { + ok, err := s.limiter.Allow(c.Request.Context(), key, n, window) + if err != nil { + internalError(c, err) + return false + } + if !ok { + c.Header("Retry-After", "60") + fail(c, http.StatusTooManyRequests, "rate_limited", "Zu viele Versuche, bitte später erneut.") + return false + } + return true +} + +func mfaKey(token string) string { + sum := sha256.Sum256([]byte(token)) + return "login_mfa:" + hex.EncodeToString(sum[:]) +} + +func normalizeEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) } + +func invalidCredentials(c *gin.Context) { + fail(c, http.StatusUnauthorized, "invalid_credentials", "E-Mail oder Passwort falsch.") +} + +func isUniqueViolation(err error, constraint string) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == constraint +} + +func isCheckViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23514" +} diff --git a/internal/api/me.go b/internal/api/me.go new file mode 100644 index 0000000..b7b60f7 --- /dev/null +++ b/internal/api/me.go @@ -0,0 +1,261 @@ +package api + +import ( + "bytes" + "context" + "encoding/base64" + "errors" + "image/png" + "net/http" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/pquerna/otp" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const totpSetupTTL = 10 * time.Minute + +type orgView struct { + ID uuid.UUID `json:"id"` + Slug string `json:"slug"` + Name string `json:"name"` + IsOwner bool `json:"is_owner"` + RequireTOTP bool `json:"require_totp"` +} + +type meView struct { + ID uuid.UUID `json:"id"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + TOTP bool `json:"totp_enabled"` + ActiveOrg uuid.UUID `json:"active_org"` + Orgs []orgView `json:"orgs"` + // Set when an org the user belongs to enforces TOTP and the user has none. + TOTPEnrollmentRequired bool `json:"totp_enrollment_required"` +} + +func (s *Server) loadMe(ctx context.Context, sess *auth.Session) (meView, error) { + var me meView + err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + u, err := q.GetUser(ctx, sess.UserID) + if err != nil { + return err + } + orgs, err := q.ListUserOrgs(ctx, sess.UserID) + if err != nil { + return err + } + me = meView{ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, TOTP: u.TotpSecret != nil, ActiveOrg: sess.OrgID, Orgs: []orgView{}} + for _, o := range orgs { + me.Orgs = append(me.Orgs, orgView{ID: o.ID, Slug: o.Slug, Name: o.Name, IsOwner: o.IsOwner, RequireTOTP: o.RequireTotp}) + if o.RequireTotp && !me.TOTP { + me.TOTPEnrollmentRequired = true + } + } + return nil + }) + return me, err +} + +func (s *Server) me(c *gin.Context) { + me, err := s.loadMe(c.Request.Context(), auth.Current(c)) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, me) +} + +type switchOrgRequest struct { + OrgID uuid.UUID `json:"org_id" binding:"required"` +} + +func (s *Server) switchOrg(c *gin.Context) { + var req switchOrgRequest + if !bind(c, &req) { + return + } + sess := auth.Current(c) + me, err := s.loadMe(c.Request.Context(), sess) + if err != nil { + internalError(c, err) + return + } + for _, o := range me.Orgs { + if o.ID == req.OrgID { + if err := s.sessions.SwitchOrg(c.Request.Context(), sess, o.ID); err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) + return + } + } + fail(c, http.StatusNotFound, "org_not_found", "Organisation nicht gefunden.") +} + +func totpSetupKey(user uuid.UUID) string { return "totp_setup:" + user.String() } + +func (s *Server) totpSetup(c *gin.Context) { + ctx := c.Request.Context() + me, err := s.loadMe(ctx, auth.Current(c)) + if err != nil { + internalError(c, err) + return + } + if me.TOTP { + fail(c, http.StatusConflict, "totp_already_enabled", "TOTP ist bereits aktiv.") + return + } + key, err := auth.NewTOTPKey(me.Email) + if err != nil { + internalError(c, err) + return + } + if err := s.rdb.Set(ctx, totpSetupKey(me.ID), key.Secret(), totpSetupTTL).Err(); err != nil { + internalError(c, err) + return + } + qr, err := qrDataURI(key) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"secret": key.Secret(), "otpauth_url": key.URL(), "qr": qr}) +} + +func (s *Server) totpEnable(c *gin.Context) { + var req totpRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + sess := auth.Current(c) + secret, err := s.rdb.Get(ctx, totpSetupKey(sess.UserID)).Result() + if err != nil { + fail(c, http.StatusConflict, "totp_setup_expired", "Einrichtung abgelaufen, bitte neu starten.") + return + } + if !s.limit(c, "totp_enable:"+sess.UserID.String(), 10, totpSetupTTL) { + return + } + ok, err := s.totp.Verify(ctx, sess.UserID, secret, req.Code) + if err != nil { + internalError(c, err) + return + } + if !ok { + fail(c, http.StatusUnprocessableEntity, "invalid_code", "Code ungültig.") + return + } + sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:]) + err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + return q.EnableTOTP(ctx, store.EnableTOTPParams{ID: sess.UserID, TotpSecret: sealedSecret}) + }) + if err != nil { + internalError(c, err) + return + } + _ = s.rdb.Del(ctx, totpSetupKey(sess.UserID)).Err() + c.Status(http.StatusNoContent) +} + +type totpDisableRequest struct { + Password string `json:"password" binding:"required,max=1024"` + Code string `json:"code" binding:"required,len=6,numeric"` +} + +func (s *Server) totpDisable(c *gin.Context) { + var req totpDisableRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + sess := auth.Current(c) + if !s.limit(c, "totp_disable:"+sess.UserID.String(), 5, 15*time.Minute) { + return + } + me, err := s.loadMe(ctx, sess) + if err != nil { + internalError(c, err) + return + } + for _, o := range me.Orgs { + if o.RequireTOTP { + fail(c, http.StatusConflict, "totp_required_by_org", "Eine deiner Organisationen verlangt TOTP.") + return + } + } + var user store.User + err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + var err error + user, err = q.GetUser(ctx, sess.UserID) + return err + }) + if err != nil { + internalError(c, err) + return + } + if user.PasswordHash == nil { + fail(c, http.StatusConflict, "no_password", "Konto ohne Passwort.") + return + } + if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok { + invalidCredentials(c) + return + } + if ok, err := s.verifyUserTOTP(ctx, sess.UserID, req.Code); err != nil { + internalError(c, err) + return + } else if !ok { + fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.") + return + } + err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + return q.DisableTOTP(ctx, sess.UserID) + }) + if err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) +} + +var errNoTOTP = errors.New("api: user has no totp") + +func (s *Server) verifyUserTOTP(ctx context.Context, userID uuid.UUID, code string) (bool, error) { + var user store.User + err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error { + var err error + user, err = q.GetUser(ctx, userID) + return err + }) + if err != nil { + return false, err + } + if user.TotpSecret == nil { + return false, errNoTOTP + } + secret, err := s.keys.Open(user.TotpSecret, userID[:]) + if err != nil { + return false, err + } + return s.totp.Verify(ctx, userID, string(secret), code) +} + +func qrDataURI(key *otp.Key) (string, error) { + img, err := key.Image(240, 240) + if err != nil { + return "", err + } + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + return "", err + } + return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()), nil +} diff --git a/internal/api/pages.go b/internal/api/pages.go new file mode 100644 index 0000000..cc3a283 --- /dev/null +++ b/internal/api/pages.go @@ -0,0 +1,82 @@ +package api + +import ( + "net/http" + + "github.com/a-h/templ" + "github.com/gin-gonic/gin" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +func (s *Server) RegisterPages(r gin.IRouter) { + r.GET("/login", s.loginPage) + r.GET("/signup", s.signupPage) + r.GET("/", s.page("Übersicht", web.Dashboard)) + r.GET("/settings/security", s.page("Sicherheit", web.Security)) +} + +func pageFor(c *gin.Context, title string) web.Page { + p := web.Page{Title: title} + if sess := auth.Current(c); sess != nil { + p.CSRF = sess.CSRF + } + return p +} + +func (s *Server) loginPage(c *gin.Context) { + if auth.Current(c) != nil { + c.Redirect(http.StatusSeeOther, "/") + return + } + allowed, err := s.signupAllowed(c.Request.Context()) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.Login(pageFor(c, "Anmelden"), allowed)) +} + +func (s *Server) signupPage(c *gin.Context) { + allowed, err := s.signupAllowed(c.Request.Context()) + if err != nil { + internalError(c, err) + return + } + if !allowed { + c.Redirect(http.StatusSeeOther, "/login") + return + } + web.Render(c, http.StatusOK, web.Signup(pageFor(c, "Konto anlegen"))) +} + +func (s *Server) page(title string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc { + return func(c *gin.Context) { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login") + return + } + me, err := s.loadMe(c.Request.Context(), sess) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, view(pageFor(c, title), toWebMe(me))) + } +} + +func toWebMe(m meView) web.Me { + out := web.Me{ + Email: m.Email, + DisplayName: m.DisplayName, + TOTP: m.TOTP, + ActiveOrg: m.ActiveOrg.String(), + TOTPMissing: m.TOTPEnrollmentRequired, + } + for _, o := range m.Orgs { + out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner}) + } + return out +} diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 0000000..7d99408 --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,101 @@ +package api + +import ( + "errors" + "log/slog" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" + "github.com/redis/go-redis/v9" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +type Server struct { + cfg config.API + log *slog.Logger + db *tenant.DB + rdb redis.UniversalClient + keys *sealed.Keyring + sessions *auth.Sessions + limiter *auth.Limiter + totp *auth.TOTPVerifier +} + +func New(cfg config.API, log *slog.Logger, db *tenant.DB, rdb redis.UniversalClient, keys *sealed.Keyring) *Server { + return &Server{ + cfg: cfg, + log: log, + db: db, + rdb: rdb, + keys: keys, + sessions: auth.NewSessions(rdb, cfg.SessionIdle, cfg.SessionAbsolute), + limiter: auth.NewLimiter(rdb), + totp: auth.NewTOTPVerifier(rdb), + } +} + +func (s *Server) Sessions() *auth.Sessions { return s.sessions } + +// Register mounts the JSON API. The caller must already have installed +// Sessions().Load() and auth.CSRF() on the engine. +func (s *Server) Register(r gin.IRouter) { + v1 := r.Group("/api/v1") + + a := v1.Group("/auth") + a.POST("/signup", s.signup) + a.POST("/login", s.login) + a.POST("/login/totp", s.loginTOTP) + a.POST("/logout", s.logout) + + me := v1.Group("/me", auth.Require()) + me.GET("", s.me) + me.POST("/org", s.switchOrg) + me.POST("/totp/setup", s.totpSetup) + me.POST("/totp/enable", s.totpEnable) + me.POST("/totp/disable", s.totpDisable) +} + +type apiError struct { + Error string `json:"error"` + Message string `json:"message"` + Fields map[string]string `json:"fields,omitempty"` +} + +func fail(c *gin.Context, status int, code, msg string) { + c.AbortWithStatusJSON(status, apiError{Error: code, Message: msg}) +} + +func internalError(c *gin.Context, err error) { + _ = c.Error(err) + c.AbortWithStatusJSON(http.StatusInternalServerError, apiError{Error: "internal", Message: "Interner Fehler."}) +} + +func bind(c *gin.Context, dst any) bool { + if err := c.ShouldBindJSON(dst); err != nil { + e := apiError{Error: "invalid_input", Message: "Eingaben prüfen."} + var ve validator.ValidationErrors + if errors.As(err, &ve) { + e.Fields = map[string]string{} + for _, f := range ve { + e.Fields[f.Field()] = f.Tag() + } + } + c.AbortWithStatusJSON(http.StatusBadRequest, e) + return false + } + return true +} + +func setCookie(c *gin.Context, name, value string, maxAge int) { + http.SetCookie(c.Writer, &http.Cookie{ + Name: name, Value: value, Path: "/", MaxAge: maxAge, + Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode, + }) +} + +func randomToken() string { return auth.RandomToken() } diff --git a/internal/config/config.go b/internal/config/config.go index ab0ba76..3705616 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -35,9 +35,39 @@ type Sentinel struct { func (s Sentinel) Enabled() bool { return s.Master != "" } +type SignupMode string + +const ( + SignupOpen SignupMode = "open" + SignupFirstUser SignupMode = "first-user" + SignupClosed SignupMode = "closed" +) + type API struct { Common - Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` + Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` + SecretKeys string `env:"UPTIME_SECRET_KEYS"` + Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"` + SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"` + SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` +} + +func (a API) Validate() error { + if err := a.Common.Validate(); err != nil { + return err + } + if a.SecretKeys == "" { + return fmt.Errorf("config: UPTIME_SECRET_KEYS is required (format id:base64-32-bytes)") + } + switch a.Signup { + case SignupOpen, SignupFirstUser, SignupClosed: + default: + return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup) + } + if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle { + return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0") + } + return nil } type Checker struct { diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index 35d650f..3aa3820 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -1,8 +1,77 @@ (() => { - const token = document.querySelector('meta[name="csrf-token"]')?.content; - window.api = axios.create({ - baseURL: "/api/v1", - headers: token ? { "X-CSRF-Token": token } : {}, - withCredentials: true, + const meta = document.querySelector('meta[name="csrf-token"]'); + const api = axios.create({ baseURL: "/api/v1", withCredentials: true }); + api.interceptors.request.use((cfg) => { + if (meta?.content) cfg.headers["X-CSRF-Token"] = meta.content; + return cfg; + }); + window.api = api; + + const message = (err) => + err.response?.data?.message ?? "Verbindung fehlgeschlagen."; + + const showError = (form, text) => { + const el = form.querySelector("[data-error]"); + if (!el) return; + el.textContent = text; + el.classList.toggle("hidden", !text); + }; + + document.addEventListener("submit", async (ev) => { + const form = ev.target.closest("form[data-api]"); + if (!form) return; + ev.preventDefault(); + const button = form.querySelector("button[type=submit]"); + const body = Object.fromEntries( + [...new FormData(form)].filter(([k]) => { + const step = form.querySelector(`[name="${k}"]`)?.closest("[data-step]"); + return !step || !step.hidden; + }), + ); + const totpStep = form.querySelector('[data-step="totp"]'); + const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api; + + showError(form, ""); + button && (button.disabled = true); + try { + const res = await api.post(url, body); + if (res.data?.status === "totp_required" && totpStep) { + form.querySelector('[data-step="password"]').hidden = true; + totpStep.hidden = false; + totpStep.querySelector("input")?.focus(); + return; + } + location.assign(form.dataset.next || location.href); + } catch (err) { + showError(form, message(err)); + } finally { + button && (button.disabled = false); + } + }); + + document.addEventListener("click", async (ev) => { + if (ev.target.closest("[data-logout]")) { + await api.post("/auth/logout").catch(() => {}); + location.assign("/login"); + } + if (ev.target.closest("[data-totp-start]")) { + const root = ev.target.closest("[data-totp-setup]"); + try { + const { data } = await api.post("/me/totp/setup"); + root.querySelector("[data-totp-qr]").src = data.qr; + root.querySelector("[data-totp-secret]").textContent = data.secret; + root.querySelector("[data-totp-panel]").hidden = false; + ev.target.hidden = true; + } catch (err) { + alert(message(err)); + } + } + }); + + document.addEventListener("change", async (ev) => { + const sel = ev.target.closest("[data-switch-org]"); + if (!sel) return; + await api.post("/me/org", { org_id: sel.value }); + location.reload(); }); })(); diff --git a/internal/web/auth.templ b/internal/web/auth.templ new file mode 100644 index 0000000..912a2d7 --- /dev/null +++ b/internal/web/auth.templ @@ -0,0 +1,37 @@ +package web + +templ Login(p Page, signupAllowed bool) { + @authShell(p, "Anmelden") { +
+ @formError() +
+ @field("E-Mail", "email", "email", "username", true) + @field("Passwort", "password", "password", "current-password", true) +
+ + @submit("Weiter") +
+ if signupAllowed { +

Noch kein Konto? Registrieren

+ } + } +} + +templ Signup(p Page) { + @authShell(p, "Konto anlegen") { +
+ @formError() + @field("Name", "display_name", "text", "name", false) + @field("E-Mail", "email", "email", "username", true) + @field("Passwort (min. 12 Zeichen)", "password", "password", "new-password", true) +
+ @field("Organisation", "org_name", "text", "organization", true) + @field("Kurzname (a–z, 0–9, -)", "org_slug", "text", "off", true) + @submit("Anlegen") +
+

Zur Anmeldung

+ } +} diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go new file mode 100644 index 0000000..3fac225 --- /dev/null +++ b/internal/web/auth_templ.go @@ -0,0 +1,176 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +func Login(p Page, signupAllowed bool) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("E-Mail", "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Passwort", "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit("Weiter").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if signupAllowed { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

Noch kein Konto? Registrieren

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) + templ_7745c5c3_Err = authShell(p, "Anmelden").Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func Signup(p Page) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var4 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Name", "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("E-Mail", "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Passwort (min. 12 Zeichen)", "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Organisation", "org_name", "text", "organization", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Kurzname (a–z, 0–9, -)", "org_slug", "text", "off", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit("Anlegen").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

Zur Anmeldung

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = authShell(p, "Konto anlegen").Render(templ.WithChildren(ctx, templ_7745c5c3_Var4), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +var _ = templruntime.GeneratedTemplate diff --git a/internal/web/console.templ b/internal/web/console.templ new file mode 100644 index 0000000..5645c7b --- /dev/null +++ b/internal/web/console.templ @@ -0,0 +1,90 @@ +package web + +type Me struct { + Email string + DisplayName string + TOTP bool + ActiveOrg string + Orgs []Org + TOTPMissing bool +} + +type Org struct { + ID string + Name string + Slug string + IsOwner bool +} + +templ consoleShell(p Page, me Me) { + @Layout(p) { +
+
+ uptimesebi + if len(me.Orgs) > 1 { + + } else if len(me.Orgs) == 1 { + { me.Orgs[0].Name } + } + +
+
+ if me.TOTPMissing { +
+

+ Deine Organisation verlangt Zwei-Faktor-Anmeldung. + Jetzt einrichten +

+
+ } +
+ { children... } +
+ } +} + +templ Dashboard(p Page, me Me) { + @consoleShell(p, me) { +

Monitore

+

Noch keine Monitore angelegt.

+ } +} + +templ Security(p Page, me Me) { + @consoleShell(p, me) { +

Sicherheit

+
+

Zwei-Faktor (TOTP)

+ if me.TOTP { +

● aktiv

+
+ @formError() + @field("Passwort", "password", "password", "current-password", true) + @field("Aktueller Code", "code", "text", "one-time-code", true) + @submit("Deaktivieren") +
+ } else { +

● nicht eingerichtet

+
+ + +
+ } +
+ } +} diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go new file mode 100644 index 0000000..0ff048f --- /dev/null +++ b/internal/web/console_templ.go @@ -0,0 +1,301 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +type Me struct { + Email string + DisplayName string + TOTP bool + ActiveOrg string + Orgs []Org + TOTPMissing bool +} + +type Org struct { + ID string + Name string + Slug string + IsOwner bool +} + +func consoleShell(p Page, me Me) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var1 := templ.GetChildren(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
uptimesebi ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(me.Orgs) > 1 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else if len(me.Orgs) == 1 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 31, Col: 47} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if me.TOTPMissing { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

Deine Organisation verlangt Zwei-Faktor-Anmeldung. Jetzt einrichten

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templ_7745c5c3_Var1.Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func Dashboard(p Page, me Me) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "

Monitore

Noch keine Monitore angelegt.

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func Security(p Page, me Me) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var9 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "

Sicherheit

Zwei-Faktor (TOTP)

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if me.TOTP { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

● aktiv

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Passwort", "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = field("Aktueller Code", "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit("Deaktivieren").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "

● nicht eingerichtet

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var9), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +var _ = templruntime.GeneratedTemplate diff --git a/internal/web/index.templ b/internal/web/index.templ deleted file mode 100644 index e8d5885..0000000 --- a/internal/web/index.templ +++ /dev/null @@ -1,9 +0,0 @@ -package web - -templ Index() { - @Layout("uptimesebi") { -
-

uptimesebi

-
- } -} diff --git a/internal/web/index_templ.go b/internal/web/index_templ.go deleted file mode 100644 index e4f212e..0000000 --- a/internal/web/index_templ.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by templ - DO NOT EDIT. - -// templ: version: v0.3.1118 - -package web - -//lint:file-ignore SA4006 This context is only used if a nested component is present. - -import "github.com/a-h/templ" -import templruntime "github.com/a-h/templ/runtime" - -func Index() templ.Component { - return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { - templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context - if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { - return templ_7745c5c3_CtxErr - } - templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) - if !templ_7745c5c3_IsBuffer { - defer func() { - templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) - if templ_7745c5c3_Err == nil { - templ_7745c5c3_Err = templ_7745c5c3_BufErr - } - }() - } - ctx = templ.InitializeContext(ctx) - ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { - templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context - templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) - if !templ_7745c5c3_IsBuffer { - defer func() { - templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) - if templ_7745c5c3_Err == nil { - templ_7745c5c3_Err = templ_7745c5c3_BufErr - } - }() - } - ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "

uptimesebi

") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - return nil - }) - templ_7745c5c3_Err = Layout("uptimesebi").Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - return nil - }) -} - -var _ = templruntime.GeneratedTemplate diff --git a/internal/web/layout.templ b/internal/web/layout.templ index 0a74f49..14e93e0 100644 --- a/internal/web/layout.templ +++ b/internal/web/layout.templ @@ -1,12 +1,20 @@ package web -templ Layout(title string) { +type Page struct { + Title string + CSRF string +} + +templ Layout(p Page) { - { title } + if p.CSRF != "" { + + } + { p.Title } · uptimesebi @@ -16,3 +24,36 @@ templ Layout(title string) { } + +templ authShell(p Page, heading string) { + @Layout(p) { +
+

uptimesebi

+

{ heading }

+ { children... } +
+ } +} + +templ field(label, name, typ, autocomplete string, required bool) { + +} + +templ submit(label string) { + +} + +templ formError() { + +} diff --git a/internal/web/layout_templ.go b/internal/web/layout_templ.go index 63ee121..da45854 100644 --- a/internal/web/layout_templ.go +++ b/internal/web/layout_templ.go @@ -9,7 +9,12 @@ package web import "github.com/a-h/templ" import templruntime "github.com/a-h/templ/runtime" -func Layout(title string) templ.Component { +type Page struct { + Title string + CSRF string +} + +func Layout(p Page) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { @@ -27,20 +32,43 @@ func Layout(title string) templ.Component { ctx = templ.InitializeContext(ctx) templ_7745c5c3_Var1 := templ.GetChildren(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<!doctype html><html lang=\"de\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var2 string - templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(title) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 9, Col: 17} + if p.CSRF != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "<meta name=\"csrf-token\" content=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 string + templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(p.CSRF).Resolve(ctx) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 15, Col: 44} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "<title>") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "") + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(p.Title) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 17, Col: 19} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, " · uptimesebi") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -48,7 +76,222 @@ func Layout(title string) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func authShell(p Page, heading string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var4 := templ.GetChildren(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var5 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

uptimesebi

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(heading) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 32, Col: 51} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templ_7745c5c3_Var4.Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) + templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var5), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func field(label, name, typ, autocomplete string, required bool) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func submit(label string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func formError() templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } -- 2.54.1 From 7dd1f87ffe61ed734c64639e546e024951f28f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:07:00 +0100 Subject: [PATCH 10/22] feat(i18n): add english and german message catalogs Tests fail on catalogs with diverging keys and on message IDs used in code or templates that no catalog defines. Refs #42 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- go.mod | 1 + go.sum | 2 + internal/i18n/i18n.go | 164 ++++++++++++++++++++++++++++++++++ internal/i18n/i18n_test.go | 155 ++++++++++++++++++++++++++++++++ internal/i18n/locales/de.json | 57 ++++++++++++ internal/i18n/locales/en.json | 57 ++++++++++++ 6 files changed, 436 insertions(+) create mode 100644 internal/i18n/i18n.go create mode 100644 internal/i18n/i18n_test.go create mode 100644 internal/i18n/locales/de.json create mode 100644 internal/i18n/locales/en.json diff --git a/go.mod b/go.mod index 6d3d9d8..6efc2e3 100644 --- a/go.mod +++ b/go.mod @@ -44,6 +44,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect + github.com/nicksnyder/go-i18n/v2 v2.7.0 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect github.com/pquerna/otp v1.5.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect diff --git a/go.sum b/go.sum index 22633bb..dc44847 100644 --- a/go.sum +++ b/go.sum @@ -97,6 +97,8 @@ github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0 github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0= +github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..2a68e32 --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,164 @@ +// Package i18n translates user-facing text. Message catalogs are embedded +// JSON files, one per language, keyed by message ID. English is the source +// language and the fallback for missing translations. +package i18n + +import ( + "context" + "embed" + "encoding/json" + "fmt" + "io/fs" + "path" + "strings" + + goi18n "github.com/nicksnyder/go-i18n/v2/i18n" + "golang.org/x/text/language" +) + +//go:embed locales/*.json +var locales embed.FS + +// Catalog holds all translations and picks the best supported language for +// a list of preferences. +type Catalog struct { + bundle *goi18n.Bundle + tags []language.Tag + matcher language.Matcher +} + +// Load parses the embedded catalogs. English is always listed first so the +// matcher falls back to it. +func Load() (*Catalog, error) { + b := goi18n.NewBundle(language.English) + b.RegisterUnmarshalFunc("json", json.Unmarshal) + files, err := fs.Glob(locales, "locales/*.json") + if err != nil { + return nil, err + } + tags := []language.Tag{language.English} + for _, f := range files { + data, err := locales.ReadFile(f) + if err != nil { + return nil, err + } + mf, err := b.ParseMessageFileBytes(data, path.Base(f)) + if err != nil { + return nil, fmt.Errorf("i18n: parse %s: %w", f, err) + } + if mf.Tag != language.English { + tags = append(tags, mf.Tag) + } + } + return &Catalog{bundle: b, tags: tags, matcher: language.NewMatcher(tags)}, nil +} + +// Supported returns the base language codes, e.g. "en" and "de". +func (c *Catalog) Supported() []string { + out := make([]string, len(c.tags)) + for i, t := range c.tags { + out[i] = t.String() + } + return out +} + +// IsSupported reports whether code names one of the catalog languages exactly. +func (c *Catalog) IsSupported(code string) bool { + for _, t := range c.tags { + if t.String() == code { + return true + } + } + return false +} + +// Match picks a language from preferences in priority order. Each entry may +// be a single code or an Accept-Language header value; empty entries are +// skipped. +func (c *Catalog) Match(prefs ...string) *Localizer { + for _, p := range prefs { + if p == "" { + continue + } + tags, _, err := language.ParseAcceptLanguage(p) + if err != nil || len(tags) == 0 { + continue + } + if _, idx, conf := c.matcher.Match(tags...); conf > language.No { + return c.localizer(c.tags[idx]) + } + } + return c.localizer(language.English) +} + +func (c *Catalog) localizer(t language.Tag) *Localizer { + return &Localizer{lang: t.String(), l: goi18n.NewLocalizer(c.bundle, t.String())} +} + +// Localizer translates into one language. +type Localizer struct { + lang string + l *goi18n.Localizer +} + +// Lang returns the language code, suitable for . +func (l *Localizer) Lang() string { return l.lang } + +// T translates id. data fills template placeholders such as {{.Min}}; an +// integer "Count" entry also selects the plural form. A missing ID is +// returned unchanged so it stands out instead of rendering empty text. +func (l *Localizer) T(id string, data map[string]any) string { + cfg := &goi18n.LocalizeConfig{MessageID: id, TemplateData: data} + if n, ok := data["Count"].(int); ok { + cfg.PluralCount = n + } + s, err := l.l.Localize(cfg) + if err != nil && s == "" { + return id + } + return s +} + +type ctxKey struct{} + +// NewContext returns ctx carrying l. +func NewContext(ctx context.Context, l *Localizer) context.Context { + return context.WithValue(ctx, ctxKey{}, l) +} + +// FromContext returns the localizer in ctx, or nil. +func FromContext(ctx context.Context) *Localizer { + l, _ := ctx.Value(ctxKey{}).(*Localizer) + return l +} + +// T translates id with the localizer in ctx. It is the entry point for +// templates, which always have ctx in scope. +func T(ctx context.Context, id string, kv ...any) string { + l := FromContext(ctx) + if l == nil { + return id + } + return l.T(id, pairs(kv)) +} + +// Lang returns the language of the localizer in ctx, defaulting to "en". +func Lang(ctx context.Context) string { + if l := FromContext(ctx); l != nil { + return l.Lang() + } + return "en" +} + +func pairs(kv []any) map[string]any { + if len(kv) == 0 { + return nil + } + m := make(map[string]any, len(kv)/2) + for i := 0; i+1 < len(kv); i += 2 { + if k, ok := kv[i].(string); ok { + m[strings.TrimSpace(k)] = kv[i+1] + } + } + return m +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go new file mode 100644 index 0000000..614fe8c --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,155 @@ +package i18n + +import ( + "context" + "encoding/json" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" +) + +func catalogKeys(t *testing.T) map[string]map[string]bool { + t.Helper() + files, err := fs.Glob(locales, "locales/*.json") + if err != nil { + t.Fatal(err) + } + out := map[string]map[string]bool{} + for _, f := range files { + data, err := locales.ReadFile(f) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("%s: %v", f, err) + } + keys := map[string]bool{} + for k := range m { + keys[k] = true + } + out[strings.TrimSuffix(filepath.Base(f), ".json")] = keys + } + return out +} + +func TestCatalogsHaveSameKeys(t *testing.T) { + cats := catalogKeys(t) + en := cats["en"] + for lang, keys := range cats { + for k := range en { + if !keys[k] { + t.Errorf("%s.json is missing %q", lang, k) + } + } + for k := range keys { + if !en[k] { + t.Errorf("%s.json has %q which en.json lacks", lang, k) + } + } + } +} + +var usagePatterns = []struct { + re *regexp.Regexp + prefix string +}{ + {regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""}, + {regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."}, + {regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""}, +} + +// TestUsedKeysExist scans the source tree for literal message IDs so a typo +// fails the build instead of showing a raw ID in production. +func TestUsedKeysExist(t *testing.T) { + en := catalogKeys(t)["en"] + var missing []string + err := filepath.WalkDir("..", func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + if !strings.HasSuffix(p, ".go") && !strings.HasSuffix(p, ".templ") { + return nil + } + if strings.HasSuffix(p, "_templ.go") || strings.HasSuffix(p, "_test.go") { + return nil + } + src, err := os.ReadFile(p) + if err != nil { + return err + } + for _, u := range usagePatterns { + for _, m := range u.re.FindAllStringSubmatch(string(src), -1) { + if id := u.prefix + m[1]; !en[id] { + missing = append(missing, p+": "+id) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + sort.Strings(missing) + for _, m := range missing { + t.Errorf("unknown message ID %s", m) + } +} + +// The language switcher builds "lang." dynamically. +func TestEveryLanguageHasAName(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + en := catalogKeys(t)["en"] + for _, l := range c.Supported() { + if !en["lang."+l] { + t.Errorf("en.json is missing %q", "lang."+l) + } + } +} + +func TestMatch(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + tests := []struct { + prefs []string + want string + }{ + {nil, "en"}, + {[]string{"de"}, "de"}, + {[]string{"", "de-AT,en;q=0.5"}, "de"}, + {[]string{"fr-FR,fr;q=0.9"}, "en"}, + {[]string{"en", "de"}, "en"}, + {[]string{"garbage", "de"}, "de"}, + } + for _, tt := range tests { + if got := c.Match(tt.prefs...).Lang(); got != tt.want { + t.Errorf("Match(%q) = %q, want %q", tt.prefs, got, tt.want) + } + } +} + +func TestT(t *testing.T) { + c, err := Load() + if err != nil { + t.Fatal(err) + } + ctx := NewContext(context.Background(), c.Match("de")) + if got, want := T(ctx, "error.password_too_short", "Min", 12), "Das Passwort braucht mindestens 12 Zeichen."; got != want { + t.Errorf("T(de, password_too_short) = %q, want %q", got, want) + } + if got, want := T(ctx, "no.such.key"), "no.such.key"; got != want { + t.Errorf("T(missing) = %q, want %q", got, want) + } + if got, want := T(context.Background(), "auth.login.title"), "auth.login.title"; got != want { + t.Errorf("T(no localizer) = %q, want %q", got, want) + } +} diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json new file mode 100644 index 0000000..b59be86 --- /dev/null +++ b/internal/i18n/locales/de.json @@ -0,0 +1,57 @@ +{ + "app.network_error": "Verbindung fehlgeschlagen.", + "lang.en": "English", + "lang.de": "Deutsch", + + "auth.login.title": "Anmelden", + "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", + "auth.login.submit": "Weiter", + "auth.login.no_account": "Noch kein Konto?", + "auth.login.to_signup": "Registrieren", + "auth.signup.title": "Konto anlegen", + "auth.signup.submit": "Anlegen", + "auth.signup.to_login": "Zur Anmeldung", + "auth.field.name": "Name", + "auth.field.email": "E-Mail", + "auth.field.password": "Passwort", + "auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)", + "auth.field.org_name": "Organisation", + "auth.field.org_slug": "Kurzname (a–z, 0–9, -)", + "auth.field.code": "Code", + + "console.nav.security": "Sicherheit", + "console.nav.logout": "Abmelden", + "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.", + "console.totp_missing_action": "Jetzt einrichten", + "console.monitors.title": "Monitore", + "console.monitors.empty": "Noch keine Monitore angelegt.", + + "security.title": "Sicherheit", + "security.totp.heading": "Zwei-Faktor (TOTP)", + "security.totp.active": "aktiv", + "security.totp.inactive": "nicht eingerichtet", + "security.totp.disable": "Deaktivieren", + "security.totp.current_code": "Aktueller Code", + "security.totp.start": "Einrichten", + "security.totp.qr_alt": "QR-Code für die Authenticator-App", + "security.totp.app_code": "Code aus der App", + "security.totp.confirm": "Bestätigen", + + "error.internal": "Interner Fehler.", + "error.invalid_input": "Eingaben prüfen.", + "error.rate_limited": "Zu viele Versuche, bitte später erneut.", + "error.signup_closed": "Registrierung ist deaktiviert.", + "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", + "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", + "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", + "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.invalid_credentials": "E-Mail oder Passwort falsch.", + "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", + "error.invalid_code": "Code ungültig.", + "error.org_not_found": "Organisation nicht gefunden.", + "error.totp_already_enabled": "TOTP ist bereits aktiv.", + "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", + "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", + "error.no_password": "Konto ohne Passwort.", + "error.unsupported_locale": "Sprache wird nicht unterstützt." +} diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json new file mode 100644 index 0000000..8023c23 --- /dev/null +++ b/internal/i18n/locales/en.json @@ -0,0 +1,57 @@ +{ + "app.network_error": "Connection failed.", + "lang.en": "English", + "lang.de": "Deutsch", + + "auth.login.title": "Sign in", + "auth.login.totp_hint": "Enter the code from your authenticator app.", + "auth.login.submit": "Continue", + "auth.login.no_account": "No account yet?", + "auth.login.to_signup": "Sign up", + "auth.signup.title": "Create account", + "auth.signup.submit": "Create", + "auth.signup.to_login": "Back to sign in", + "auth.field.name": "Name", + "auth.field.email": "Email", + "auth.field.password": "Password", + "auth.field.new_password": "Password (min. {{.Min}} characters)", + "auth.field.org_name": "Organization", + "auth.field.org_slug": "Short name (a–z, 0–9, -)", + "auth.field.code": "Code", + + "console.nav.security": "Security", + "console.nav.logout": "Sign out", + "console.totp_missing": "Your organization requires two-factor sign-in.", + "console.totp_missing_action": "Set up now", + "console.monitors.title": "Monitors", + "console.monitors.empty": "No monitors yet.", + + "security.title": "Security", + "security.totp.heading": "Two-factor (TOTP)", + "security.totp.active": "active", + "security.totp.inactive": "not set up", + "security.totp.disable": "Disable", + "security.totp.current_code": "Current code", + "security.totp.start": "Set up", + "security.totp.qr_alt": "QR code for your authenticator app", + "security.totp.app_code": "Code from the app", + "security.totp.confirm": "Confirm", + + "error.internal": "Internal error.", + "error.invalid_input": "Please check your input.", + "error.rate_limited": "Too many attempts, please try again later.", + "error.signup_closed": "Sign-up is disabled.", + "error.password_too_short": "The password needs at least {{.Min}} characters.", + "error.email_taken": "This email address is already registered.", + "error.slug_taken": "This short name is already taken.", + "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.invalid_credentials": "Wrong email or password.", + "error.mfa_expired": "Sign-in expired, please start again.", + "error.invalid_code": "Invalid code.", + "error.org_not_found": "Organization not found.", + "error.totp_already_enabled": "TOTP is already active.", + "error.totp_setup_expired": "Setup expired, please start again.", + "error.totp_required_by_org": "One of your organizations requires TOTP.", + "error.no_password": "This account has no password.", + "error.unsupported_locale": "Unsupported language." +} -- 2.54.1 From dde7b890b8cde9152a03f87cf80347f40ef7fa3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:07:00 +0100 Subject: [PATCH 11/22] feat(auth): persist preferred language per user and session Refs #42 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/session.go | 15 +++++++-- internal/auth/session_test.go | 14 ++++---- internal/migrations/sql/00006_user_locale.sql | 6 ++++ internal/store/models.go | 1 + internal/store/querier.go | 1 + internal/store/queries/users.sql | 5 ++- internal/store/users.sql.go | 33 ++++++++++++++++--- 7 files changed, 60 insertions(+), 15 deletions(-) create mode 100644 internal/migrations/sql/00006_user_locale.sql diff --git a/internal/auth/session.go b/internal/auth/session.go index c7831dc..32341ce 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -22,6 +22,7 @@ type Session struct { Token string UserID uuid.UUID OrgID uuid.UUID + Locale string CSRF string CreatedAt time.Time } @@ -56,11 +57,12 @@ func RandomToken() string { return base64.RawURLEncoding.EncodeToString(b) } -func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, error) { +func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) { sess := &Session{ Token: RandomToken(), UserID: user, OrgID: org, + Locale: locale, CSRF: RandomToken(), CreatedAt: s.now(), } @@ -69,6 +71,7 @@ func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, e p.HSet(ctx, k, map[string]any{ "user": sess.UserID.String(), "org": orgString(org), + "locale": locale, "csrf": sess.CSRF, "created": sess.CreatedAt.Unix(), }) @@ -120,6 +123,14 @@ func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) return nil } +func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error { + if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil { + return fmt.Errorf("auth: set locale: %w", err) + } + sess.Locale = locale + return nil +} + func (s *Sessions) Delete(ctx context.Context, sess *Session) error { k := key(sess.Token) _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { @@ -163,7 +174,7 @@ func decode(token string, v map[string]string) (*Session, error) { if err != nil { return nil, err } - return &Session{Token: token, UserID: user, OrgID: org, CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil + return &Session{Token: token, UserID: user, OrgID: org, Locale: v["locale"], CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil } func orgString(id uuid.UUID) string { diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go index ea70be4..6e5363a 100644 --- a/internal/auth/session_test.go +++ b/internal/auth/session_test.go @@ -34,7 +34,7 @@ func TestSessionRoundTrip(t *testing.T) { ctx := context.Background() user, org := uuid.New(), uuid.New() - created, err := s.Create(ctx, user, org) + created, err := s.Create(ctx, user, org, "de") if err != nil { t.Fatal(err) } @@ -42,7 +42,7 @@ func TestSessionRoundTrip(t *testing.T) { if err != nil { t.Fatal(err) } - if got.UserID != user || got.OrgID != org || got.CSRF != created.CSRF { + if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.CSRF != created.CSRF { t.Fatalf("mismatch: %+v vs %+v", got, created) } if !got.CheckCSRF(created.CSRF) || got.CheckCSRF("") || got.CheckCSRF("x") { @@ -59,7 +59,7 @@ func TestSessionRoundTrip(t *testing.T) { func TestSessionAbsoluteLifetime(t *testing.T) { s, now := testSessions(t) ctx := context.Background() - sess, err := s.Create(ctx, uuid.New(), uuid.Nil) + sess, err := s.Create(ctx, uuid.New(), uuid.Nil, "") if err != nil { t.Fatal(err) } @@ -73,9 +73,9 @@ func TestDeleteAllForUser(t *testing.T) { s, _ := testSessions(t) ctx := context.Background() user := uuid.New() - a, _ := s.Create(ctx, user, uuid.Nil) - b, _ := s.Create(ctx, user, uuid.Nil) - other, _ := s.Create(ctx, uuid.New(), uuid.Nil) + a, _ := s.Create(ctx, user, uuid.Nil, "") + b, _ := s.Create(ctx, user, uuid.Nil, "") + other, _ := s.Create(ctx, uuid.New(), uuid.Nil, "") if err := s.DeleteAllForUser(ctx, user); err != nil { t.Fatal(err) @@ -93,7 +93,7 @@ func TestDeleteAllForUser(t *testing.T) { func TestTokenNotStoredInPlain(t *testing.T) { s, _ := testSessions(t) ctx := context.Background() - sess, _ := s.Create(ctx, uuid.New(), uuid.Nil) + sess, _ := s.Create(ctx, uuid.New(), uuid.Nil, "") if n, _ := s.rdb.Exists(ctx, "session:"+sess.Token).Result(); n != 0 { t.Fatal("raw token used as redis key") } diff --git a/internal/migrations/sql/00006_user_locale.sql b/internal/migrations/sql/00006_user_locale.sql new file mode 100644 index 0000000..ab67855 --- /dev/null +++ b/internal/migrations/sql/00006_user_locale.sql @@ -0,0 +1,6 @@ +-- +goose Up +-- Validated against the supported catalogs in code; the check only guards the format. +ALTER TABLE users ADD COLUMN locale text CHECK (locale ~ '^[a-z]{2}(-[A-Z]{2})?$'); + +-- +goose Down +ALTER TABLE users DROP COLUMN locale; diff --git a/internal/store/models.go b/internal/store/models.go index ccccfaa..899f582 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -36,4 +36,5 @@ type User struct { UpdatedAt time.Time TotpSecret []byte TotpEnabledAt *time.Time + Locale *string } diff --git a/internal/store/querier.go b/internal/store/querier.go index 6f20f1c..aa4f651 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -28,6 +28,7 @@ type Querier interface { ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error + SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/users.sql b/internal/store/queries/users.sql index 4c0420e..a4a951a 100644 --- a/internal/store/queries/users.sql +++ b/internal/store/queries/users.sql @@ -1,5 +1,5 @@ -- name: CreateUser :one -INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) +INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4) RETURNING *; -- name: GetUser :one @@ -22,3 +22,6 @@ UPDATE users SET totp_secret = NULL, totp_enabled_at = NULL, updated_at = now() -- name: DeleteUser :execrows DELETE FROM users WHERE id = $1; + +-- name: SetUserLocale :exec +UPDATE users SET locale = $2, updated_at = now() WHERE id = $1; diff --git a/internal/store/users.sql.go b/internal/store/users.sql.go index 5db19c4..e734baa 100644 --- a/internal/store/users.sql.go +++ b/internal/store/users.sql.go @@ -23,18 +23,24 @@ func (q *Queries) AnyUserExists(ctx context.Context) (bool, error) { } const createUser = `-- name: CreateUser :one -INSERT INTO users (email, display_name, password_hash) VALUES ($1, $2, $3) -RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at +INSERT INTO users (email, display_name, password_hash, locale) VALUES ($1, $2, $3, $4) +RETURNING id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale ` type CreateUserParams struct { Email string DisplayName string PasswordHash *string + Locale *string } func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) { - row := q.db.QueryRow(ctx, createUser, arg.Email, arg.DisplayName, arg.PasswordHash) + row := q.db.QueryRow(ctx, createUser, + arg.Email, + arg.DisplayName, + arg.PasswordHash, + arg.Locale, + ) var i User err := row.Scan( &i.ID, @@ -46,6 +52,7 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (User, e &i.UpdatedAt, &i.TotpSecret, &i.TotpEnabledAt, + &i.Locale, ) return i, err } @@ -86,7 +93,7 @@ func (q *Queries) EnableTOTP(ctx context.Context, arg EnableTOTPParams) error { } const getUser = `-- name: GetUser :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE id = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE id = $1 ` func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { @@ -102,12 +109,13 @@ func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) { &i.UpdatedAt, &i.TotpSecret, &i.TotpEnabledAt, + &i.Locale, ) return i, err } const getUserByEmail = `-- name: GetUserByEmail :one -SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at FROM users WHERE email = $1 +SELECT id, email, display_name, password_hash, disabled_at, created_at, updated_at, totp_secret, totp_enabled_at, locale FROM users WHERE email = $1 ` func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error) { @@ -123,6 +131,7 @@ func (q *Queries) GetUserByEmail(ctx context.Context, email string) (User, error &i.UpdatedAt, &i.TotpSecret, &i.TotpEnabledAt, + &i.Locale, ) return i, err } @@ -140,3 +149,17 @@ func (q *Queries) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams _, err := q.db.Exec(ctx, setPasswordHash, arg.ID, arg.PasswordHash) return err } + +const setUserLocale = `-- name: SetUserLocale :exec +UPDATE users SET locale = $2, updated_at = now() WHERE id = $1 +` + +type SetUserLocaleParams struct { + ID uuid.UUID + Locale *string +} + +func (q *Queries) SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error { + _, err := q.db.Exec(ctx, setUserLocale, arg.ID, arg.Locale) + return err +} -- 2.54.1 From 70190446ff39b90b0f746a37aad692dba86eacb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:07:00 +0100 Subject: [PATCH 12/22] feat(api): localize console pages and api error messages The language comes from the user setting, then the lang cookie, then Accept-Language, falling back to English. Errors keep a stable code and carry a translated message. Closes #42 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- cmd/api/main.go | 13 +- internal/api/auth.go | 40 +++--- internal/api/me.go | 14 +- internal/api/pages.go | 18 +-- internal/api/server.go | 141 +++++++++++++++---- internal/web/assets/app.js | 8 +- internal/web/auth.templ | 38 +++-- internal/web/auth_templ.go | 97 ++++++++++--- internal/web/console.templ | 39 +++--- internal/web/console_templ.go | 214 +++++++++++++++++++++++++---- internal/web/layout.templ | 35 +++-- internal/web/layout_templ.go | 252 ++++++++++++++++++++++++++-------- 12 files changed, 698 insertions(+), 211 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index 092d55f..d94334f 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -8,8 +8,8 @@ import ( "time" "git.zb-server.de/ZB-Server/uptimesebi/internal/api" - "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" @@ -54,15 +54,16 @@ func run(log *slog.Logger, args []string) error { } defer deps.Close() - srv := api.New(cfg, log, tenant.New(deps.DB), deps.Redis, keys) + catalog, err := i18n.Load() + if err != nil { + return err + } + srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog}) health := platform.NewHealth(deps.Probes()) r := platform.NewRouter(log) health.Register(r) r.StaticFS("/static", web.Static()) - - app := r.Group("/", srv.Sessions().Load(), auth.CSRF()) - srv.Register(app) - srv.RegisterPages(app) + srv.Mount(r) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } diff --git a/internal/api/auth.go b/internal/api/auth.go index 71472ea..f650cd4 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -16,6 +16,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) @@ -46,12 +47,12 @@ func (s *Server) signup(c *gin.Context) { internalError(c, err) return } else if !allowed { - fail(c, http.StatusForbidden, "signup_closed", "Registrierung ist deaktiviert.") + fail(c, http.StatusForbidden, "signup_closed") return } hash, err := auth.HashPassword(req.Password) if errors.Is(err, auth.ErrPasswordTooShort) { - fail(c, http.StatusUnprocessableEntity, "password_too_short", err.Error()) + fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength) return } else if err != nil { internalError(c, err) @@ -66,6 +67,7 @@ func (s *Server) signup(c *gin.Context) { Email: normalizeEmail(req.Email), DisplayName: strings.TrimSpace(req.DisplayName), PasswordHash: &hash, + Locale: ptr(i18n.Lang(ctx)), }) if err != nil { return err @@ -77,19 +79,19 @@ func (s *Server) signup(c *gin.Context) { }) switch { case isUniqueViolation(err, "users_email_key"): - fail(c, http.StatusConflict, "email_taken", "Diese E-Mail-Adresse ist bereits registriert.") + fail(c, http.StatusConflict, "email_taken") return case isUniqueViolation(err, "orgs_slug_key"): - fail(c, http.StatusConflict, "slug_taken", "Dieser Kurzname ist bereits vergeben.") + fail(c, http.StatusConflict, "slug_taken") return case isCheckViolation(err): - fail(c, http.StatusUnprocessableEntity, "invalid_input", "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.") + fail(c, http.StatusUnprocessableEntity, "invalid_slug") return case err != nil: internalError(c, err) return } - s.startSession(c, user.ID, orgID) + s.startSession(c, user.ID, orgID, i18n.Lang(ctx)) } func (s *Server) signupAllowed(ctx context.Context) (bool, error) { @@ -153,7 +155,7 @@ func (s *Server) login(c *gin.Context) { } if user.TotpSecret != nil { - token := randomToken() + token := auth.RandomToken() if err := s.rdb.Set(ctx, mfaKey(token), user.ID.String(), mfaTTL).Err(); err != nil { internalError(c, err) return @@ -177,7 +179,7 @@ func (s *Server) loginTOTP(c *gin.Context) { ctx := c.Request.Context() token, _ := c.Cookie(mfaCookie) if token == "" { - fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.") + fail(c, http.StatusUnauthorized, "mfa_expired") return } if !s.limit(c, "mfa:"+mfaKey(token), 5, mfaTTL) { @@ -185,7 +187,7 @@ func (s *Server) loginTOTP(c *gin.Context) { } raw, err := s.rdb.Get(ctx, mfaKey(token)).Result() if err != nil { - fail(c, http.StatusUnauthorized, "mfa_expired", "Anmeldung abgelaufen, bitte erneut anmelden.") + fail(c, http.StatusUnauthorized, "mfa_expired") return } userID, err := uuid.Parse(raw) @@ -199,7 +201,7 @@ func (s *Server) loginTOTP(c *gin.Context) { return } if !ok { - fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.") + fail(c, http.StatusUnauthorized, "invalid_code") return } _ = s.rdb.Del(ctx, mfaKey(token)).Err() @@ -209,9 +211,15 @@ func (s *Server) loginTOTP(c *gin.Context) { func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) { ctx := c.Request.Context() - var orgs []store.ListUserOrgsRow + var ( + user store.User + orgs []store.ListUserOrgsRow + ) err := s.db.Tx(ctx, tenant.User(userID), func(q *store.Queries) error { var err error + if user, err = q.GetUser(ctx, userID); err != nil { + return err + } orgs, err = q.ListUserOrgs(ctx, userID) return err }) @@ -223,14 +231,14 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID) { if len(orgs) > 0 { org = orgs[0].ID } - s.startSession(c, userID, org) + s.startSession(c, userID, org, deref(user.Locale)) } -func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID) { +func (s *Server) startSession(c *gin.Context, userID, orgID uuid.UUID, locale string) { if old := auth.Current(c); old != nil { _ = s.sessions.Delete(c.Request.Context(), old) } - sess, err := s.sessions.Create(c.Request.Context(), userID, orgID) + sess, err := s.sessions.Create(c.Request.Context(), userID, orgID, locale) if err != nil { internalError(c, err) return @@ -271,7 +279,7 @@ func (s *Server) limit(c *gin.Context, key string, n int, window time.Duration) } if !ok { c.Header("Retry-After", "60") - fail(c, http.StatusTooManyRequests, "rate_limited", "Zu viele Versuche, bitte später erneut.") + fail(c, http.StatusTooManyRequests, "rate_limited") return false } return true @@ -285,7 +293,7 @@ func mfaKey(token string) string { func normalizeEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) } func invalidCredentials(c *gin.Context) { - fail(c, http.StatusUnauthorized, "invalid_credentials", "E-Mail oder Passwort falsch.") + fail(c, http.StatusUnauthorized, "invalid_credentials") } func isUniqueViolation(err error, constraint string) bool { diff --git a/internal/api/me.go b/internal/api/me.go index b7b60f7..d60e2b6 100644 --- a/internal/api/me.go +++ b/internal/api/me.go @@ -96,7 +96,7 @@ func (s *Server) switchOrg(c *gin.Context) { return } } - fail(c, http.StatusNotFound, "org_not_found", "Organisation nicht gefunden.") + fail(c, http.StatusNotFound, "org_not_found") } func totpSetupKey(user uuid.UUID) string { return "totp_setup:" + user.String() } @@ -109,7 +109,7 @@ func (s *Server) totpSetup(c *gin.Context) { return } if me.TOTP { - fail(c, http.StatusConflict, "totp_already_enabled", "TOTP ist bereits aktiv.") + fail(c, http.StatusConflict, "totp_already_enabled") return } key, err := auth.NewTOTPKey(me.Email) @@ -138,7 +138,7 @@ func (s *Server) totpEnable(c *gin.Context) { sess := auth.Current(c) secret, err := s.rdb.Get(ctx, totpSetupKey(sess.UserID)).Result() if err != nil { - fail(c, http.StatusConflict, "totp_setup_expired", "Einrichtung abgelaufen, bitte neu starten.") + fail(c, http.StatusConflict, "totp_setup_expired") return } if !s.limit(c, "totp_enable:"+sess.UserID.String(), 10, totpSetupTTL) { @@ -150,7 +150,7 @@ func (s *Server) totpEnable(c *gin.Context) { return } if !ok { - fail(c, http.StatusUnprocessableEntity, "invalid_code", "Code ungültig.") + fail(c, http.StatusUnprocessableEntity, "invalid_code") return } sealedSecret := s.keys.Seal([]byte(secret), sess.UserID[:]) @@ -187,7 +187,7 @@ func (s *Server) totpDisable(c *gin.Context) { } for _, o := range me.Orgs { if o.RequireTOTP { - fail(c, http.StatusConflict, "totp_required_by_org", "Eine deiner Organisationen verlangt TOTP.") + fail(c, http.StatusConflict, "totp_required_by_org") return } } @@ -202,7 +202,7 @@ func (s *Server) totpDisable(c *gin.Context) { return } if user.PasswordHash == nil { - fail(c, http.StatusConflict, "no_password", "Konto ohne Passwort.") + fail(c, http.StatusConflict, "no_password") return } if ok, _, err := auth.VerifyPassword(*user.PasswordHash, req.Password); err != nil || !ok { @@ -213,7 +213,7 @@ func (s *Server) totpDisable(c *gin.Context) { internalError(c, err) return } else if !ok { - fail(c, http.StatusUnauthorized, "invalid_code", "Code ungültig.") + fail(c, http.StatusUnauthorized, "invalid_code") return } err = s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { diff --git a/internal/api/pages.go b/internal/api/pages.go index cc3a283..2d208cd 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -10,15 +10,15 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) -func (s *Server) RegisterPages(r gin.IRouter) { +func (s *Server) registerPages(r gin.IRouter) { r.GET("/login", s.loginPage) r.GET("/signup", s.signupPage) - r.GET("/", s.page("Übersicht", web.Dashboard)) - r.GET("/settings/security", s.page("Sicherheit", web.Security)) + r.GET("/", s.page("console.monitors.title", web.Dashboard)) + r.GET("/settings/security", s.page("security.title", web.Security)) } -func pageFor(c *gin.Context, title string) web.Page { - p := web.Page{Title: title} +func (s *Server) pageFor(c *gin.Context, titleID string) web.Page { + p := web.Page{TitleID: titleID, Languages: s.catalog.Supported()} if sess := auth.Current(c); sess != nil { p.CSRF = sess.CSRF } @@ -35,7 +35,7 @@ func (s *Server) loginPage(c *gin.Context) { internalError(c, err) return } - web.Render(c, http.StatusOK, web.Login(pageFor(c, "Anmelden"), allowed)) + web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed)) } func (s *Server) signupPage(c *gin.Context) { @@ -48,10 +48,10 @@ func (s *Server) signupPage(c *gin.Context) { c.Redirect(http.StatusSeeOther, "/login") return } - web.Render(c, http.StatusOK, web.Signup(pageFor(c, "Konto anlegen"))) + web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"))) } -func (s *Server) page(title string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc { +func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Component) gin.HandlerFunc { return func(c *gin.Context) { sess := auth.Current(c) if sess == nil { @@ -63,7 +63,7 @@ func (s *Server) page(title string, view func(web.Page, web.Me) templ.Component) internalError(c, err) return } - web.Render(c, http.StatusOK, view(pageFor(c, title), toWebMe(me))) + web.Render(c, http.StatusOK, view(s.pageFor(c, titleID), toWebMe(me))) } } diff --git a/internal/api/server.go b/internal/api/server.go index 7d99408..56d6948 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -1,3 +1,5 @@ +// Package api serves the management JSON API under /api/v1 and the +// server-rendered console pages that call it. package api import ( @@ -11,40 +13,58 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) +const localeCookie = "lang" + +// Server holds the dependencies shared by all handlers. type Server struct { cfg config.API log *slog.Logger db *tenant.DB rdb redis.UniversalClient keys *sealed.Keyring + catalog *i18n.Catalog sessions *auth.Sessions limiter *auth.Limiter totp *auth.TOTPVerifier } -func New(cfg config.API, log *slog.Logger, db *tenant.DB, rdb redis.UniversalClient, keys *sealed.Keyring) *Server { +// Deps are the external resources a Server needs. +type Deps struct { + Log *slog.Logger + DB *tenant.DB + Redis redis.UniversalClient + Keys *sealed.Keyring + Catalog *i18n.Catalog +} + +// New returns a Server. It does not register any routes; see Mount. +func New(cfg config.API, d Deps) *Server { return &Server{ cfg: cfg, - log: log, - db: db, - rdb: rdb, - keys: keys, - sessions: auth.NewSessions(rdb, cfg.SessionIdle, cfg.SessionAbsolute), - limiter: auth.NewLimiter(rdb), - totp: auth.NewTOTPVerifier(rdb), + log: d.Log, + db: d.DB, + rdb: d.Redis, + keys: d.Keys, + catalog: d.Catalog, + sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute), + limiter: auth.NewLimiter(d.Redis), + totp: auth.NewTOTPVerifier(d.Redis), } } -func (s *Server) Sessions() *auth.Sessions { return s.sessions } +// Mount installs session loading, locale resolution and CSRF protection and +// registers the JSON API and the console pages below them. +func (s *Server) Mount(r gin.IRouter) { + g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF()) -// Register mounts the JSON API. The caller must already have installed -// Sessions().Load() and auth.CSRF() on the engine. -func (s *Server) Register(r gin.IRouter) { - v1 := r.Group("/api/v1") + v1 := g.Group("/api/v1") + v1.POST("/locale", s.setLocale) a := v1.Group("/auth") a.POST("/signup", s.signup) @@ -58,6 +78,55 @@ func (s *Server) Register(r gin.IRouter) { me.POST("/totp/setup", s.totpSetup) me.POST("/totp/enable", s.totpEnable) me.POST("/totp/disable", s.totpDisable) + + s.registerPages(g) +} + +// localize resolves the language from, in order: the signed-in user's +// setting, the lang cookie, and Accept-Language. +func (s *Server) localize() gin.HandlerFunc { + return func(c *gin.Context) { + var pref string + if sess := auth.Current(c); sess != nil { + pref = sess.Locale + } + cookie, _ := c.Cookie(localeCookie) + l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language")) + c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l)) + c.Header("Content-Language", l.Lang()) + c.Header("Vary", "Accept-Language, Cookie") + c.Next() + } +} + +type localeRequest struct { + Locale string `json:"locale" binding:"required,max=10"` +} + +func (s *Server) setLocale(c *gin.Context) { + var req localeRequest + if !bind(c, &req) { + return + } + if !s.catalog.IsSupported(req.Locale) { + fail(c, http.StatusUnprocessableEntity, "unsupported_locale") + return + } + ctx := c.Request.Context() + if sess := auth.Current(c); sess != nil { + err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error { + return q.SetUserLocale(ctx, store.SetUserLocaleParams{ID: sess.UserID, Locale: &req.Locale}) + }) + if err == nil { + err = s.sessions.SetLocale(ctx, sess, req.Locale) + } + if err != nil { + internalError(c, err) + return + } + } + setCookie(c, localeCookie, req.Locale, 365*24*3600) + c.Status(http.StatusNoContent) } type apiError struct { @@ -66,29 +135,35 @@ type apiError struct { Fields map[string]string `json:"fields,omitempty"` } -func fail(c *gin.Context, status int, code, msg string) { - c.AbortWithStatusJSON(status, apiError{Error: code, Message: msg}) +// fail aborts with a machine-readable code and a message translated from +// the catalog entry "error.". kv fills placeholders in that message. +func fail(c *gin.Context, status int, code string, kv ...any) { + c.AbortWithStatusJSON(status, apiError{ + Error: code, + Message: i18n.T(c.Request.Context(), "error."+code, kv...), + }) } func internalError(c *gin.Context, err error) { _ = c.Error(err) - c.AbortWithStatusJSON(http.StatusInternalServerError, apiError{Error: "internal", Message: "Interner Fehler."}) + fail(c, http.StatusInternalServerError, "internal") } func bind(c *gin.Context, dst any) bool { - if err := c.ShouldBindJSON(dst); err != nil { - e := apiError{Error: "invalid_input", Message: "Eingaben prüfen."} - var ve validator.ValidationErrors - if errors.As(err, &ve) { - e.Fields = map[string]string{} - for _, f := range ve { - e.Fields[f.Field()] = f.Tag() - } - } - c.AbortWithStatusJSON(http.StatusBadRequest, e) - return false + err := c.ShouldBindJSON(dst) + if err == nil { + return true } - return true + e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")} + var ve validator.ValidationErrors + if errors.As(err, &ve) { + e.Fields = map[string]string{} + for _, f := range ve { + e.Fields[f.Field()] = f.Tag() + } + } + c.AbortWithStatusJSON(http.StatusBadRequest, e) + return false } func setCookie(c *gin.Context, name, value string, maxAge int) { @@ -98,4 +173,12 @@ func setCookie(c *gin.Context, name, value string, maxAge int) { }) } -func randomToken() string { return auth.RandomToken() } +func ptr[T any](v T) *T { return &v } + +func deref[T any](p *T) T { + var zero T + if p == nil { + return zero + } + return *p +} diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index 3aa3820..9f8fb8b 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -8,7 +8,7 @@ window.api = api; const message = (err) => - err.response?.data?.message ?? "Verbindung fehlgeschlagen."; + err.response?.data?.message ?? document.body.dataset.msgNetwork; const showError = (form, text) => { const el = form.querySelector("[data-error]"); @@ -50,6 +50,12 @@ }); document.addEventListener("click", async (ev) => { + const locale = ev.target.closest("[data-locale]"); + if (locale) { + await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {}); + location.reload(); + return; + } if (ev.target.closest("[data-logout]")) { await api.post("/auth/logout").catch(() => {}); location.assign("/login"); diff --git a/internal/web/auth.templ b/internal/web/auth.templ index 912a2d7..c0f86d6 100644 --- a/internal/web/auth.templ +++ b/internal/web/auth.templ @@ -1,37 +1,45 @@ package web +import ( + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + templ Login(p Page, signupAllowed bool) { - @authShell(p, "Anmelden") { + @authShell(p) {
@formError()
- @field("E-Mail", "email", "email", "username", true) - @field("Passwort", "password", "password", "current-password", true) + @field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true) + @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true)
- @submit("Weiter") + @submit(i18n.T(ctx, "auth.login.submit"))
if signupAllowed { -

Noch kein Konto? Registrieren

+

+ { i18n.T(ctx, "auth.login.no_account") } + { i18n.T(ctx, "auth.login.to_signup") } +

} } } templ Signup(p Page) { - @authShell(p, "Konto anlegen") { + @authShell(p) {
@formError() - @field("Name", "display_name", "text", "name", false) - @field("E-Mail", "email", "email", "username", true) - @field("Passwort (min. 12 Zeichen)", "password", "password", "new-password", true) + @field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false) + @field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true) + @field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true)
- @field("Organisation", "org_name", "text", "organization", true) - @field("Kurzname (a–z, 0–9, -)", "org_slug", "text", "off", true) - @submit("Anlegen") + @field(i18n.T(ctx, "auth.field.org_name"), "org_name", "text", "organization", true) + @field(i18n.T(ctx, "auth.field.org_slug"), "org_slug", "text", "off", true) + @submit(i18n.T(ctx, "auth.signup.submit"))
-

Zur Anmeldung

+

{ i18n.T(ctx, "auth.signup.to_login") }

} } diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go index 3fac225..3e4ffba 100644 --- a/internal/web/auth_templ.go +++ b/internal/web/auth_templ.go @@ -9,6 +9,11 @@ package web import "github.com/a-h/templ" import templruntime "github.com/a-h/templ/runtime" +import ( + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + func Login(p Page, signupAllowed bool) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context @@ -50,43 +55,82 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("E-Mail", "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Passwort", "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = submit("Weiter").Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.code"), "code", "text", "one-time-code", false).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.login.submit")).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if signupAllowed { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

Noch kein Konto? Registrieren

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 42} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 25, Col: 105} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } return nil }) - templ_7745c5c3_Err = authShell(p, "Anmelden").Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -111,7 +155,7 @@ func Signup(p Page) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var4 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -123,7 +167,7 @@ func Signup(p Page) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -131,41 +175,54 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Name", "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.name"), "display_name", "text", "name", false).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("E-Mail", "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.email"), "email", "email", "username", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Passwort (min. 12 Zeichen)", "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.new_password", "Min", auth.MinPasswordLength), "password", "password", "new-password", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Organisation", "org_name", "text", "organization", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.org_name"), "org_name", "text", "organization", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Kurzname (a–z, 0–9, -)", "org_slug", "text", "off", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.org_slug"), "org_slug", "text", "off", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = submit("Anlegen").Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = submit(i18n.T(ctx, "auth.signup.submit")).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

Zur Anmeldung

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 43, Col: 137} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = authShell(p, "Konto anlegen").Render(templ.WithChildren(ctx, templ_7745c5c3_Var4), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/console.templ b/internal/web/console.templ index 5645c7b..4a7a5f0 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -1,5 +1,8 @@ package web +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Me is the signed-in user as the console templates see it. type Me struct { Email string DisplayName string @@ -9,6 +12,7 @@ type Me struct { TOTPMissing bool } +// Org is one entry of the organization switcher. type Org struct { ID string Name string @@ -31,16 +35,17 @@ templ consoleShell(p Page, me Me) { { me.Orgs[0].Name } } if me.TOTPMissing {

- Deine Organisation verlangt Zwei-Faktor-Anmeldung. - Jetzt einrichten + { i18n.T(ctx, "console.totp_missing") } + { i18n.T(ctx, "console.totp_missing_action") }

} @@ -52,35 +57,35 @@ templ consoleShell(p Page, me Me) { templ Dashboard(p Page, me Me) { @consoleShell(p, me) { -

Monitore

-

Noch keine Monitore angelegt.

+

{ i18n.T(ctx, "console.monitors.title") }

+

{ i18n.T(ctx, "console.monitors.empty") }

} } templ Security(p Page, me Me) { @consoleShell(p, me) { -

Sicherheit

+

{ i18n.T(ctx, "security.title") }

-

Zwei-Faktor (TOTP)

+

{ i18n.T(ctx, "security.totp.heading") }

if me.TOTP { -

● aktiv

+

● { i18n.T(ctx, "security.totp.active") }

@formError() - @field("Passwort", "password", "password", "current-password", true) - @field("Aktueller Code", "code", "text", "one-time-code", true) - @submit("Deaktivieren") + @field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true) + @field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true) + @submit(i18n.T(ctx, "security.totp.disable"))
} else { -

● nicht eingerichtet

+

● { i18n.T(ctx, "security.totp.inactive") }

- +
diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go index 0ff048f..08287aa 100644 --- a/internal/web/console_templ.go +++ b/internal/web/console_templ.go @@ -9,6 +9,9 @@ package web import "github.com/a-h/templ" import templruntime "github.com/a-h/templ/runtime" +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Me is the signed-in user as the console templates see it. type Me struct { Email string DisplayName string @@ -18,6 +21,7 @@ type Me struct { TOTPMissing bool } +// Org is one entry of the organization switcher. type Org struct { ID string Name string @@ -72,7 +76,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var3 string templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(o.ID).Resolve(ctx) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 27, Col: 27} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 31, Col: 27} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3) if templ_7745c5c3_Err != nil { @@ -95,7 +99,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var4 string templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 27, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 31, Col: 73} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) if templ_7745c5c3_Err != nil { @@ -118,7 +122,7 @@ func consoleShell(p Page, me Me) templ.Component { var templ_7745c5c3_Var5 string templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(me.Orgs[0].Name) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 31, Col: 47} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 35, Col: 47} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) if templ_7745c5c3_Err != nil { @@ -129,17 +133,77 @@ func consoleShell(p Page, me Me) templ.Component { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if me.TOTPMissing { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

Deine Organisation verlangt Zwei-Faktor-Anmeldung. Jetzt einrichten

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 47, Col: 42} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.totp_missing_action")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 48, Col: 115} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -147,7 +211,7 @@ func consoleShell(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -178,7 +242,7 @@ func Dashboard(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -190,13 +254,39 @@ func Dashboard(p Page, me Me) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "

Monitore

Noch keine Monitore angelegt.

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.title")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 60, Col: 75} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.monitors.empty")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 61, Col: 76} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -221,7 +311,7 @@ func Security(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var9 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var15 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -233,12 +323,51 @@ func Security(p Page, me Me) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "

Sicherheit

Zwei-Faktor (TOTP)

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.title")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 67, Col: 72} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var17 string + templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.heading")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 69, Col: 114} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if me.TOTP { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

● aktiv

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "

● ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var18 string + templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.totp.active")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 71, Col: 98} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -246,24 +375,63 @@ func Security(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Passwort", "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "auth.field.password"), "password", "password", "current-password", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = field("Aktueller Code", "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = field(i18n.T(ctx, "security.totp.current_code"), "code", "text", "one-time-code", true).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = submit("Deaktivieren").Render(ctx, templ_7745c5c3_Buffer) + templ_7745c5c3_Err = submit(i18n.T(ctx, "security.totp.disable")).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "

● nicht eingerichtet

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var9), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var15), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/layout.templ b/internal/web/layout.templ index 14e93e0..8dc679f 100644 --- a/internal/web/layout.templ +++ b/internal/web/layout.templ @@ -1,35 +1,54 @@ package web +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Page carries what every rendered page needs besides its own content. type Page struct { - Title string - CSRF string + TitleID string + CSRF string + Languages []string } templ Layout(p Page) { - + if p.CSRF != "" { } - { p.Title } · uptimesebi + { i18n.T(ctx, p.TitleID) } · uptimesebi - + { children... } } -templ authShell(p Page, heading string) { +templ languageSwitch(langs []string) { + + for _, l := range langs { + if l == i18n.Lang(ctx) { + { l } + } else { + + } + } + +} + +templ authShell(p Page) { @Layout(p) {
-

uptimesebi

-

{ heading }

+
+

uptimesebi

+ @languageSwitch(p.Languages) +
+

{ i18n.T(ctx, p.TitleID) }

{ children... }
} diff --git a/internal/web/layout_templ.go b/internal/web/layout_templ.go index da45854..515c1ee 100644 --- a/internal/web/layout_templ.go +++ b/internal/web/layout_templ.go @@ -9,9 +9,13 @@ package web import "github.com/a-h/templ" import templruntime "github.com/a-h/templ/runtime" +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// Page carries what every rendered page needs besides its own content. type Page struct { - Title string - CSRF string + TitleID string + CSRF string + Languages []string } func Layout(p Page) templ.Component { @@ -32,43 +36,69 @@ func Layout(p Page) templ.Component { ctx = templ.InitializeContext(ctx) templ_7745c5c3_Var1 := templ.GetChildren(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if p.CSRF != "" { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<title>") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var3 string - templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(p.Title) + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 17, Col: 19} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 21, Col: 34} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, " · uptimesebi") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, " · uptimesebi") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -76,7 +106,7 @@ func Layout(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -84,7 +114,7 @@ func Layout(p Page) templ.Component { }) } -func authShell(p Page, heading string) templ.Component { +func languageSwitch(langs []string) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { @@ -100,9 +130,103 @@ func authShell(p Page, heading string) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Var4 := templ.GetChildren(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var5 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, l := range langs { + if l == i18n.Lang(ctx) { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(l) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 36, Col: 50} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func authShell(p Page) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Var11 := templ.GetChildren(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var12 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -114,34 +238,42 @@ func authShell(p Page, heading string) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

uptimesebi

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

uptimesebi

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var6 string - templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(heading) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 32, Col: 51} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + templ_7745c5c3_Err = languageSwitch(p.Languages).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templ_7745c5c3_Var4.Render(ctx, templ_7745c5c3_Buffer) + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 51, Col: 66} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templ_7745c5c3_Var11.Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var5), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var12), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -166,69 +298,69 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -253,20 +385,20 @@ func submit(label string) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -291,7 +423,7 @@ func formError() templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } -- 2.54.1 From ea6f0221120be4c4a03870f1bf98ff06cac744ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:18:02 +0100 Subject: [PATCH 13/22] fix(config): reject an empty checker region UPTIME_CHECKER_REGION= passed the required check and started a checker that no monitor could ever be assigned to. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/config/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/config/config.go b/internal/config/config.go index 3705616..a01ceb2 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -72,7 +72,7 @@ func (a API) Validate() error { type Checker struct { Common - Region string `env:"UPTIME_CHECKER_REGION,required"` + Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` } -- 2.54.1 From 048e114fd91919192c8e95f4fe17c4fe12dd542e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:18:02 +0100 Subject: [PATCH 14/22] build: add golangci-lint configuration staticcheck and unused stay disabled until honnef.co/go/tools supports the Go 1.27 standard library. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .golangci.yml | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .golangci.yml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..f9af16d --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,48 @@ +version: "2" + +run: + tests: true + +linters: + # staticcheck and unused are left out until honnef.co/go/tools supports + # the Go 1.27 standard library; they panic during analysis otherwise. + default: none + enable: + - errcheck + - govet + - ineffassign + - revive + - errorlint + - gocritic + - misspell + - unconvert + - usestdlibvars + settings: + revive: + rules: + - name: exported + arguments: [checkPrivateReceivers, sayRepetitiveInsteadOfStutters] + - name: package-comments + - name: var-naming + - name: receiver-naming + - name: error-strings + - name: error-naming + - name: indent-error-flow + - name: context-as-argument + - name: unexported-return + - name: blank-imports + exclusions: + generated: strict + rules: + - path: _test\.go + linters: [revive] + text: "exported" + +formatters: + enable: + - gofmt + - goimports + settings: + goimports: + local-prefixes: + - git.zb-server.de/ZB-Server/uptimesebi -- 2.54.1 From d20225982a261bc8dfa54605c47ac770ac591f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:18:02 +0100 Subject: [PATCH 15/22] refactor: follow the google go style guide Document every package and exported identifier, return the log level from NewLogger instead of keeping it in a package variable, and stop tests from mutating the argon2 parameters. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- cmd/api/main.go | 12 ++++++++---- cmd/checker/main.go | 12 ++++++++---- cmd/statuspage/main.go | 12 ++++++++---- internal/auth/middleware.go | 6 ++++++ internal/auth/password.go | 25 +++++++++++++++++-------- internal/auth/ratelimit.go | 3 +++ internal/auth/session.go | 16 ++++++++++++++++ internal/auth/totp.go | 5 +++++ internal/buildinfo/buildinfo.go | 6 +++++- internal/config/config.go | 17 +++++++++++++++++ internal/migrations/migrations.go | 15 ++++++++++----- internal/platform/health.go | 4 ++++ internal/platform/log.go | 18 ++++++++---------- internal/platform/postgres.go | 3 +++ internal/platform/redis.go | 2 ++ internal/platform/router.go | 2 ++ internal/platform/run.go | 6 ++++++ internal/platform/server.go | 1 + internal/sealed/sealed.go | 5 +++++ internal/tenant/tenant.go | 8 ++++++++ internal/web/web.go | 5 +++++ 21 files changed, 147 insertions(+), 36 deletions(-) diff --git a/cmd/api/main.go b/cmd/api/main.go index d94334f..a7e7ac4 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -1,3 +1,5 @@ +// Command api serves the management API and console. It also owns schema +// migrations: run "api migrate up" before rolling out a new release. package main import ( @@ -18,19 +20,21 @@ import ( ) func main() { - log := platform.NewLogger("api") - if err := run(log, os.Args[1:]); err != nil { + log, level := platform.NewLogger("api") + // Route the standard log package and dependencies through the same handler. + slog.SetDefault(log) + if err := run(log, level, os.Args[1:]); err != nil { log.Error("exit", "error", err) os.Exit(1) } } -func run(log *slog.Logger, args []string) error { +func run(log *slog.Logger, level *slog.LevelVar, args []string) error { cfg, err := config.Load[config.API]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/cmd/checker/main.go b/cmd/checker/main.go index cb3d925..b813983 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -1,3 +1,5 @@ +// Command checker executes uptime checks for one region and pulls data from +// external sources. Any number of instances per region may run. package main import ( @@ -9,19 +11,21 @@ import ( ) func main() { - log := platform.NewLogger("checker") - if err := run(log); err != nil { + log, level := platform.NewLogger("checker") + // Route the standard log package and dependencies through the same handler. + slog.SetDefault(log) + if err := run(log, level); err != nil { log.Error("exit", "error", err) os.Exit(1) } } -func run(log *slog.Logger) error { +func run(log *slog.Logger, level *slog.LevelVar) error { cfg, err := config.Load[config.Checker]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 570ae37..c827959 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -1,3 +1,5 @@ +// Command statuspage serves public status pages, including on customer +// domains. package main import ( @@ -11,19 +13,21 @@ import ( ) func main() { - log := platform.NewLogger("statuspage") - if err := run(log); err != nil { + log, level := platform.NewLogger("statuspage") + // Route the standard log package and dependencies through the same handler. + slog.SetDefault(log) + if err := run(log, level); err != nil { log.Error("exit", "error", err) os.Exit(1) } } -func run(log *slog.Logger) error { +func run(log *slog.Logger, level *slog.LevelVar) error { cfg, err := config.Load[config.StatusPage]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index f703540..71267ab 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -8,6 +8,7 @@ import ( "github.com/gin-gonic/gin" ) +// Names shared with the browser side. const ( CookieName = "__Host-session" CSRFHeader = "X-CSRF-Token" @@ -15,6 +16,8 @@ const ( ctxKey = "auth.session" ) +// SetCookie sends the session cookie. The __Host- prefix makes browsers +// reject it unless it is Secure, host-only and scoped to /. func SetCookie(c *gin.Context, sess *Session, maxAge int) { http.SetCookie(c.Writer, &http.Cookie{ Name: CookieName, @@ -27,6 +30,7 @@ func SetCookie(c *gin.Context, sess *Session, maxAge int) { }) } +// ClearCookie removes the session cookie. func ClearCookie(c *gin.Context) { http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) } @@ -54,6 +58,7 @@ func (s *Sessions) Load() gin.HandlerFunc { } } +// Require aborts with 401 unless Load attached a session. func Require() gin.HandlerFunc { return func(c *gin.Context) { if Current(c) == nil { @@ -104,6 +109,7 @@ func sameOrigin(r *http.Request) bool { return err == nil && u.Host == r.Host } +// Current returns the session attached by Load, or nil. func Current(c *gin.Context) *Session { v, ok := c.Get(ctxKey) if !ok { diff --git a/internal/auth/password.go b/internal/auth/password.go index 8e1ebb1..5d02621 100644 --- a/internal/auth/password.go +++ b/internal/auth/password.go @@ -7,11 +7,11 @@ import ( "errors" "fmt" "strings" + "sync" "golang.org/x/crypto/argon2" ) -// OWASP 2024 baseline for argon2id. type argonParams struct { memory uint32 time uint32 @@ -19,24 +19,32 @@ type argonParams struct { keyLen uint32 } -var current = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32} +// defaultParams is the OWASP baseline for argon2id. Raising it makes +// VerifyPassword request a rehash of older hashes on their next login. +var defaultParams = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32} +// MinPasswordLength follows NIST SP 800-63B; no composition rules apply. const MinPasswordLength = 12 +// ErrPasswordTooShort is returned by HashPassword. var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength) +// HashPassword returns an argon2id hash in PHC string format. func HashPassword(pw string) (string, error) { if len([]rune(pw)) < MinPasswordLength { return "", ErrPasswordTooShort } + return hashPassword(pw, defaultParams), nil +} + +func hashPassword(pw string, p argonParams) string { salt := make([]byte, 16) _, _ = rand.Read(salt) - p := current hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen) return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.time, p.threads, base64.RawStdEncoding.EncodeToString(salt), - base64.RawStdEncoding.EncodeToString(hash)), nil + base64.RawStdEncoding.EncodeToString(hash)) } // VerifyPassword reports whether pw matches and whether the stored hash uses @@ -48,13 +56,14 @@ func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) { } got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want))) ok = subtle.ConstantTimeCompare(got, want) == 1 - return ok, ok && p != current, nil + return ok, ok && p != defaultParams, nil } -// dummyHash keeps the response time of unknown accounts equal to known ones. -var dummyHash, _ = HashPassword("not-a-real-password-for-timing") +var dummyHash = sync.OnceValue(func() string { return hashPassword("timing-equalizer", defaultParams) }) -func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash, pw) } +// BurnPasswordCheck spends the time of a real verification. Call it when the +// account does not exist so response times do not reveal that. +func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash(), pw) } func decodeHash(s string) (argonParams, []byte, []byte, error) { var p argonParams diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go index c4410d4..1f01c63 100644 --- a/internal/auth/ratelimit.go +++ b/internal/auth/ratelimit.go @@ -7,10 +7,12 @@ import ( "github.com/redis/go-redis/v9" ) +// Limiter counts attempts per key in fixed windows stored in Redis. type Limiter struct { rdb redis.UniversalClient } +// NewLimiter returns a Limiter backed by rdb. func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } var incrWithTTL = redis.NewScript(` @@ -27,6 +29,7 @@ func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time. return n <= limit, nil } +// Reset clears the counter for key, e.g. after a successful login. func (l *Limiter) Reset(ctx context.Context, key string) error { return l.rdb.Del(ctx, "rl:"+key).Err() } diff --git a/internal/auth/session.go b/internal/auth/session.go index 32341ce..5e5a6a7 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -1,3 +1,5 @@ +// Package auth implements sessions, password and TOTP verification, rate +// limiting and CSRF protection. package auth import ( @@ -16,8 +18,11 @@ import ( "github.com/redis/go-redis/v9" ) +// ErrNoSession is returned for unknown, expired or malformed sessions. var ErrNoSession = errors.New("auth: no session") +// Session is a signed-in browser. Token is the cookie value and never +// stored server side. type Session struct { Token string UserID uuid.UUID @@ -27,10 +32,12 @@ type Session struct { CreatedAt time.Time } +// CheckCSRF compares token with the session's CSRF token in constant time. func (s *Session) CheckCSRF(token string) bool { return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1 } +// Sessions stores sessions in Redis so any API replica can serve any request. type Sessions struct { rdb redis.UniversalClient idle time.Duration @@ -38,6 +45,8 @@ type Sessions struct { now func() time.Time } +// NewSessions returns a store whose sessions expire after idle without use +// and after absolute regardless of use. func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions { return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now} } @@ -51,12 +60,14 @@ func key(token string) string { func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() } +// RandomToken returns 256 bits of randomness, URL-safe encoded. func RandomToken() string { b := make([]byte, 32) _, _ = rand.Read(b) return base64.RawURLEncoding.EncodeToString(b) } +// Create starts a session. org and locale may be empty. func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) { sess := &Session{ Token: RandomToken(), @@ -86,6 +97,7 @@ func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale strin return sess, nil } +// Get loads the session for token and extends its idle expiry. func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) { if token == "" { return nil, ErrNoSession @@ -115,6 +127,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) { return sess, nil } +// SwitchOrg changes the active organization. Membership must be checked +// by the caller. func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error { if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil { return fmt.Errorf("auth: switch org: %w", err) @@ -123,6 +137,7 @@ func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) return nil } +// SetLocale changes the session language. func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error { if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil { return fmt.Errorf("auth: set locale: %w", err) @@ -131,6 +146,7 @@ func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) return nil } +// Delete ends sess. func (s *Sessions) Delete(ctx context.Context, sess *Session) error { k := key(sess.Token) _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { diff --git a/internal/auth/totp.go b/internal/auth/totp.go index 1ea913d..636e497 100644 --- a/internal/auth/totp.go +++ b/internal/auth/totp.go @@ -12,6 +12,8 @@ import ( const totpIssuer = "uptimesebi" +// NewTOTPKey generates a secret for account using the defaults every common +// authenticator app supports (SHA-1, 6 digits, 30 s). func NewTOTPKey(account string) (*otp.Key, error) { return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) } @@ -23,10 +25,13 @@ type TOTPVerifier struct { now func() time.Time } +// NewTOTPVerifier returns a verifier that records used codes in rdb. func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { return &TOTPVerifier{rdb: rdb, now: time.Now} } +// Verify accepts code for secret within one step of clock skew, at most once +// per user. func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) { ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index 37e8fec..00ca997 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -1,6 +1,10 @@ +// Package buildinfo exposes release metadata injected via -ldflags -X. package buildinfo +// Set by the release build; see Makefile and Dockerfile. var ( + // Version is the release tag, or "dev" for local builds. Version = "dev" - Commit = "none" + // Commit is the short git revision the binary was built from. + Commit = "none" ) diff --git a/internal/config/config.go b/internal/config/config.go index a01ceb2..92d7ae8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,3 +1,5 @@ +// Package config reads component settings from UPTIME_* environment +// variables. package config import ( @@ -8,13 +10,17 @@ import ( "github.com/caarlos0/env/v11" ) +// Edition switches features that only make sense when we operate the +// service, such as billing. type Edition string +// Editions. const ( EditionCloud Edition = "cloud" EditionSelfHosted Edition = "selfhosted" ) +// Common holds settings shared by all components. type Common struct { Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` @@ -33,16 +39,21 @@ type Sentinel struct { Password string `env:"UPTIME_REDIS_SENTINEL_PASSWORD"` } +// Enabled reports whether a sentinel master name is configured. func (s Sentinel) Enabled() bool { return s.Master != "" } +// SignupMode controls who may create an account and organization. type SignupMode string +// Signup modes. SignupFirstUser allows exactly one account, the operator of a +// fresh self-hosted installation. const ( SignupOpen SignupMode = "open" SignupFirstUser SignupMode = "first-user" SignupClosed SignupMode = "closed" ) +// API configures cmd/api. type API struct { Common Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` @@ -52,6 +63,7 @@ type API struct { SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` } +// Validate checks API-specific settings in addition to Common.Validate. func (a API) Validate() error { if err := a.Common.Validate(); err != nil { return err @@ -70,17 +82,21 @@ func (a API) Validate() error { return nil } +// Checker configures cmd/checker. Region names the location this instance +// checks from and must match the regions assigned to monitors. type Checker struct { Common Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` } +// StatusPage configures cmd/statuspage. type StatusPage struct { Common Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"` } +// Load parses the environment into a T, applying envDefault tags. func Load[T any]() (T, error) { var cfg T if err := env.Parse(&cfg); err != nil { @@ -89,6 +105,7 @@ func Load[T any]() (T, error) { return cfg, nil } +// Validate reports missing or contradictory settings. func (c Common) Validate() error { switch c.Edition { case EditionCloud, EditionSelfHosted: diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go index 0440d61..26587b3 100644 --- a/internal/migrations/migrations.go +++ b/internal/migrations/migrations.go @@ -1,3 +1,5 @@ +// Package migrations embeds the SQL schema migrations and applies them with +// goose. package migrations import ( @@ -7,7 +9,7 @@ import ( "fmt" "io/fs" - _ "github.com/jackc/pgx/v5/stdlib" + _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver "github.com/pressly/goose/v3" "github.com/pressly/goose/v3/lock" ) @@ -40,30 +42,33 @@ func newProvider(dsn string) (*goose.Provider, *sql.DB, error) { return p, db, nil } +// Up applies all pending migrations. func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Up(ctx) } +// Down rolls back the most recent migration. func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Down(ctx) } +// Status lists every migration with its applied state. func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Status(ctx) } @@ -74,6 +79,6 @@ func Pending(ctx context.Context, dsn string) (bool, error) { if err != nil { return false, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.HasPending(ctx) } diff --git a/internal/platform/health.go b/internal/platform/health.go index 1ab176b..a9645ef 100644 --- a/internal/platform/health.go +++ b/internal/platform/health.go @@ -9,6 +9,7 @@ import ( "github.com/gin-gonic/gin" ) +// Probe reports whether a dependency is usable. type Probe func(context.Context) error // Health separates liveness from readiness so a draining instance drops out @@ -18,12 +19,15 @@ type Health struct { draining atomic.Bool } +// NewHealth returns a Health that is ready while all probes pass. func NewHealth(probes map[string]Probe) *Health { return &Health{probes: probes} } +// Drain makes /readyz fail permanently. Call it before shutdown. func (h *Health) Drain() { h.draining.Store(true) } +// Register mounts /healthz (liveness) and /readyz (readiness). func (h *Health) Register(r gin.IRoutes) { r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) }) r.GET("/readyz", h.ready) diff --git a/internal/platform/log.go b/internal/platform/log.go index 313d5f9..5592947 100644 --- a/internal/platform/log.go +++ b/internal/platform/log.go @@ -7,15 +7,13 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" ) -var logLevel = new(slog.LevelVar) - -// NewLogger installs a JSON logger as the process default so output from the -// standard log package and dependencies ends up in the same format. -func NewLogger(component string) *slog.Logger { - l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})). +// NewLogger returns a JSON logger tagged with component and the release +// version, and the level variable controlling it. The level can be changed +// once configuration is loaded; the logger is needed before that to report +// configuration errors. +func NewLogger(component string) (*slog.Logger, *slog.LevelVar) { + level := new(slog.LevelVar) + l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})). With("component", component, "app_version", buildinfo.Version) - slog.SetDefault(l) - return l + return l, level } - -func SetLogLevel(l slog.Level) { logLevel.Set(l) } diff --git a/internal/platform/postgres.go b/internal/platform/postgres.go index 493d2bc..a3b4320 100644 --- a/internal/platform/postgres.go +++ b/internal/platform/postgres.go @@ -1,3 +1,5 @@ +// Package platform wires the infrastructure shared by all commands: +// logging, Postgres, Redis, HTTP serving and health probes. package platform import ( @@ -7,6 +9,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" ) +// OpenPostgres connects a pool and verifies it with a ping. func OpenPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) { cfg, err := pgxpool.ParseConfig(url) if err != nil { diff --git a/internal/platform/redis.go b/internal/platform/redis.go index bbd82ae..585704f 100644 --- a/internal/platform/redis.go +++ b/internal/platform/redis.go @@ -9,6 +9,8 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/config" ) +// OpenRedis connects to a single server or, when c.RedisSentinel is enabled, +// to the current master via sentinel with automatic failover. func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) { var rdb *redis.Client if c.RedisSentinel.Enabled() { diff --git a/internal/platform/router.go b/internal/platform/router.go index 06b32f7..2dd1219 100644 --- a/internal/platform/router.go +++ b/internal/platform/router.go @@ -12,6 +12,8 @@ import ( var quietPaths = map[string]bool{"/healthz": true, "/readyz": true} +// NewRouter returns a gin engine that logs requests and panics through log +// as JSON and writes nothing to stdout itself. func NewRouter(log *slog.Logger) *gin.Engine { gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = io.Discard diff --git a/internal/platform/run.go b/internal/platform/run.go index 7eefe7f..3b3a715 100644 --- a/internal/platform/run.go +++ b/internal/platform/run.go @@ -15,12 +15,14 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" ) +// Deps are the connections every command needs. type Deps struct { Log *slog.Logger DB *pgxpool.Pool Redis *redis.Client } +// Close releases all connections. It is safe on a partially built Deps. func (d *Deps) Close() { if d.DB != nil { d.DB.Close() @@ -30,6 +32,7 @@ func (d *Deps) Close() { } } +// Probes returns readiness probes for the connections. func (d *Deps) Probes() map[string]Probe { return map[string]Probe{ "postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) }, @@ -37,10 +40,13 @@ func (d *Deps) Probes() map[string]Probe { } } +// SignalContext is cancelled on SIGINT or SIGTERM. func SignalContext() (context.Context, context.CancelFunc) { return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) } +// Connect validates c, refuses to start against an outdated schema, and +// opens Postgres and Redis. func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) { if err := c.Validate(); err != nil { return nil, err diff --git a/internal/platform/server.go b/internal/platform/server.go index 441f132..9d3fb01 100644 --- a/internal/platform/server.go +++ b/internal/platform/server.go @@ -34,6 +34,7 @@ func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Heal return srv.Shutdown(sctx) } +// NewHTTPServer returns a server with timeouts that bound slow clients. func NewHTTPServer(addr string, h http.Handler) *http.Server { return &http.Server{ Addr: addr, diff --git a/internal/sealed/sealed.go b/internal/sealed/sealed.go index 7ad1752..4f64df3 100644 --- a/internal/sealed/sealed.go +++ b/internal/sealed/sealed.go @@ -12,6 +12,8 @@ import ( "strings" ) +// ErrUnknownKey is returned for values sealed with a key that was removed +// from the keyring. var ErrUnknownKey = errors.New("sealed: unknown key id") // Keyring holds one active key for sealing and any number of retired keys @@ -62,6 +64,7 @@ func (k *Keyring) Seal(plain, aad []byte) []byte { return aead.Seal(out, nonce, plain, aad) } +// Open decrypts a value produced by Seal with the same aad. func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { id, rest, ok := strings.Cut(string(sealed), ":") if !ok { @@ -78,6 +81,8 @@ func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad) } +// NeedsReseal reports whether sealed was produced with a retired key and +// should be rewritten. func (k *Keyring) NeedsReseal(sealed []byte) bool { id, _, _ := strings.Cut(string(sealed), ":") return id != k.active diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go index 8a10fdc..b9376e7 100644 --- a/internal/tenant/tenant.go +++ b/internal/tenant/tenant.go @@ -1,3 +1,5 @@ +// Package tenant runs queries inside a row-level-security context. All +// database access from request handlers must go through DB.Tx. package tenant import ( @@ -21,6 +23,7 @@ type Scope struct { global bool } +// Org scopes to one organization. user may be uuid.Nil for background work. func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } // User grants access to the user's own memberships and the orgs behind them, @@ -35,12 +38,17 @@ func Global() Scope { return Scope{global: true} } // cross-tenant, never for request handling. func System() Scope { return Scope{system: true} } +// ErrNoScope is returned by Tx for the zero Scope. var ErrNoScope = errors.New("tenant: empty scope") +// DB wraps a pool so that every transaction carries a Scope. type DB struct{ pool *pgxpool.Pool } +// New returns a DB using pool. func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} } +// Tx runs fn in a transaction whose row-level-security settings come from s. +// The transaction commits if fn returns nil and rolls back otherwise. func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error { if s == (Scope{}) { return ErrNoScope diff --git a/internal/web/web.go b/internal/web/web.go index b3191be..4823f6c 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,3 +1,5 @@ +// Package web contains the templ components and static assets shared by +// the console and status pages. package web import ( @@ -12,6 +14,7 @@ import ( //go:embed all:static var static embed.FS +// Static serves the embedded build output of npm run build. func Static() http.FileSystem { sub, err := fs.Sub(static, "static") if err != nil { @@ -20,6 +23,8 @@ func Static() http.FileSystem { return http.FS(sub) } +// Render writes comp as HTML. Rendering errors are attached to c so the +// access log records them; the status has already been sent. func Render(c *gin.Context, status int, comp templ.Component) { c.Status(status) c.Header("Content-Type", "text/html; charset=utf-8") -- 2.54.1 From b6843330a84c81879e840996617f42b73bd8fa94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:18:02 +0100 Subject: [PATCH 16/22] test: report failures as got/want and use subtests for tables Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/auth/middleware_test.go | 77 ++++++++++++++++--------------- internal/auth/password_test.go | 41 +++++++++-------- internal/auth/session_test.go | 78 ++++++++++++++++++-------------- internal/auth/totp_test.go | 35 +++++++------- internal/config/config_test.go | 34 +++++++------- internal/platform/redis_test.go | 13 +++--- internal/sealed/sealed_test.go | 50 ++++++++++---------- internal/tenant/tenant_test.go | 31 ++++++------- 8 files changed, 184 insertions(+), 175 deletions(-) diff --git a/internal/auth/middleware_test.go b/internal/auth/middleware_test.go index a727514..485e64a 100644 --- a/internal/auth/middleware_test.go +++ b/internal/auth/middleware_test.go @@ -9,21 +9,9 @@ import ( "github.com/gin-gonic/gin" ) -func csrfRouter(sess *Session) *gin.Engine { - gin.SetMode(gin.TestMode) - r := gin.New() - r.Use(func(c *gin.Context) { - if sess != nil { - c.Set(ctxKey, sess) - } - }, CSRF()) - r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) }) - return r -} - func TestCSRF(t *testing.T) { sess := &Session{CSRF: "good"} - cases := []struct { + tests := []struct { name string sess *Session method string @@ -32,32 +20,43 @@ func TestCSRF(t *testing.T) { form string want int }{ - {"safe method", sess, http.MethodGet, "", "", "", 204}, - {"missing token", sess, http.MethodPost, "", "", "", 403}, - {"wrong token", sess, http.MethodPost, "bad", "", "", 403}, - {"header token", sess, http.MethodPost, "good", "", "", 204}, - {"form token", sess, http.MethodPost, "", "", "_csrf=good", 204}, - {"no session", nil, http.MethodPost, "", "", "", 204}, - {"same origin", nil, http.MethodPost, "", "http://example.com", "", 204}, - {"foreign origin without session", nil, http.MethodPost, "", "https://evil.test", "", 403}, - {"foreign origin with token", sess, http.MethodPost, "good", "https://evil.test", "", 403}, - {"opaque origin", nil, http.MethodPost, "", "null", "", 403}, + {name: "safe method", sess: sess, method: http.MethodGet, want: http.StatusNoContent}, + {name: "missing token", sess: sess, method: http.MethodPost, want: http.StatusForbidden}, + {name: "wrong token", sess: sess, method: http.MethodPost, header: "bad", want: http.StatusForbidden}, + {name: "header token", sess: sess, method: http.MethodPost, header: "good", want: http.StatusNoContent}, + {name: "form token", sess: sess, method: http.MethodPost, form: "_csrf=good", want: http.StatusNoContent}, + {name: "no session", method: http.MethodPost, want: http.StatusNoContent}, + {name: "same origin", method: http.MethodPost, origin: "http://example.com", want: http.StatusNoContent}, + {name: "foreign origin without session", method: http.MethodPost, origin: "https://evil.test", want: http.StatusForbidden}, + {name: "foreign origin with token", sess: sess, method: http.MethodPost, header: "good", origin: "https://evil.test", want: http.StatusForbidden}, + {name: "opaque origin", method: http.MethodPost, origin: "null", want: http.StatusForbidden}, } - for _, tc := range cases { - req := httptest.NewRequest(tc.method, "/x", strings.NewReader(tc.form)) - if tc.form != "" { - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - } - if tc.origin != "" { - req.Header.Set("Origin", tc.origin) - } - if tc.header != "" { - req.Header.Set(CSRFHeader, tc.header) - } - w := httptest.NewRecorder() - csrfRouter(tc.sess).ServeHTTP(w, req) - if w.Code != tc.want { - t.Errorf("%s: got %d want %d", tc.name, w.Code, tc.want) - } + gin.SetMode(gin.TestMode) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := gin.New() + r.Use(func(c *gin.Context) { + if tt.sess != nil { + c.Set(ctxKey, tt.sess) + } + }, CSRF()) + r.Any("/x", func(c *gin.Context) { c.Status(http.StatusNoContent) }) + + req := httptest.NewRequest(tt.method, "/x", strings.NewReader(tt.form)) + if tt.form != "" { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + if tt.origin != "" { + req.Header.Set("Origin", tt.origin) + } + if tt.header != "" { + req.Header.Set(CSRFHeader, tt.header) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if w.Code != tt.want { + t.Errorf("%s /x = %d, want %d", tt.method, w.Code, tt.want) + } + }) } } diff --git a/internal/auth/password_test.go b/internal/auth/password_test.go index cb85041..811b22a 100644 --- a/internal/auth/password_test.go +++ b/internal/auth/password_test.go @@ -1,41 +1,42 @@ package auth import ( + "errors" "strings" "testing" ) -func TestPasswordHash(t *testing.T) { - h, err := HashPassword("correct horse battery") +func TestHashPassword(t *testing.T) { + const pw = "correct horse battery" + h, err := HashPassword(pw) if err != nil { - t.Fatal(err) + t.Fatalf("HashPassword(%q) failed: %v", pw, err) } - if ok, rehash, err := VerifyPassword(h, "correct horse battery"); !ok || rehash || err != nil { - t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) + ok, rehash, err := VerifyPassword(h, pw) + if err != nil || !ok || rehash { + t.Errorf("VerifyPassword(h, %q) = %v, %v, %v; want true, false, nil", pw, ok, rehash, err) } - if ok, _, _ := VerifyPassword(h, "correct horse batterz"); ok { - t.Fatal("wrong password accepted") + if ok, _, _ := VerifyPassword(h, pw+"x"); ok { + t.Errorf("VerifyPassword(h, %q) = true, want false", pw+"x") } - if _, err := HashPassword("short"); err != ErrPasswordTooShort { - t.Fatalf("got %v", err) + if _, err := HashPassword("short"); !errors.Is(err, ErrPasswordTooShort) { + t.Errorf("HashPassword(%q) error = %v, want %v", "short", err, ErrPasswordTooShort) } } -func TestPasswordRehashOnWeakerParams(t *testing.T) { - saved := current - current = argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32} - h, _ := HashPassword("correct horse battery") - current = saved - ok, rehash, err := VerifyPassword(h, "correct horse battery") - if !ok || !rehash || err != nil { - t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err) +func TestVerifyPasswordRequestsRehashForOldParams(t *testing.T) { + const pw = "correct horse battery" + weak := argonParams{memory: 8 * 1024, time: 1, threads: 1, keyLen: 32} + ok, rehash, err := VerifyPassword(hashPassword(pw, weak), pw) + if err != nil || !ok || !rehash { + t.Errorf("VerifyPassword(weak hash) = %v, %v, %v; want true, true, nil", ok, rehash, err) } } -func TestPasswordHashRejectsForeignFormats(t *testing.T) { - for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash, "argon2id", "argon2i", 1)} { +func TestVerifyPasswordRejectsForeignFormats(t *testing.T) { + for _, h := range []string{"", "$2a$10$abc", strings.Replace(dummyHash(), "argon2id", "argon2i", 1)} { if _, _, err := VerifyPassword(h, "x"); err == nil { - t.Errorf("accepted %q", h) + t.Errorf("VerifyPassword(%q, _) error = nil, want error", h) } } } diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go index 6e5363a..148b36b 100644 --- a/internal/auth/session_test.go +++ b/internal/auth/session_test.go @@ -11,7 +11,7 @@ import ( "github.com/redis/go-redis/v9" ) -func testSessions(t *testing.T) (*Sessions, *time.Time) { +func newTestRedis(t *testing.T) *redis.Client { t.Helper() url := os.Getenv("UPTIME_TEST_REDIS_URL") if url == "" { @@ -19,82 +19,92 @@ func testSessions(t *testing.T) (*Sessions, *time.Time) { } opts, err := redis.ParseURL(url) if err != nil { - t.Fatal(err) + t.Fatalf("redis.ParseURL(%q) failed: %v", url, err) } rdb := redis.NewClient(opts) t.Cleanup(func() { _ = rdb.Close() }) + return rdb +} + +func newTestSessions(t *testing.T) (*Sessions, *time.Time) { + t.Helper() now := time.Now() - s := NewSessions(rdb, time.Hour, 24*time.Hour) + s := NewSessions(newTestRedis(t), time.Hour, 24*time.Hour) s.now = func() time.Time { return now } return s, &now } +func mustCreate(t *testing.T, s *Sessions, user uuid.UUID) *Session { + t.Helper() + sess, err := s.Create(context.Background(), user, uuid.Nil, "") + if err != nil { + t.Fatalf("Create() failed: %v", err) + } + return sess +} + func TestSessionRoundTrip(t *testing.T) { - s, _ := testSessions(t) + s, _ := newTestSessions(t) ctx := context.Background() user, org := uuid.New(), uuid.New() created, err := s.Create(ctx, user, org, "de") if err != nil { - t.Fatal(err) + t.Fatalf("Create() failed: %v", err) } got, err := s.Get(ctx, created.Token) if err != nil { - t.Fatal(err) + t.Fatalf("Get() failed: %v", err) } if got.UserID != user || got.OrgID != org || got.Locale != "de" || got.CSRF != created.CSRF { - t.Fatalf("mismatch: %+v vs %+v", got, created) + t.Errorf("Get() = %+v, want user %v org %v locale de csrf %q", got, user, org, created.CSRF) } - if !got.CheckCSRF(created.CSRF) || got.CheckCSRF("") || got.CheckCSRF("x") { - t.Fatal("csrf check wrong") + for token, want := range map[string]bool{created.CSRF: true, "": false, "x": false} { + if ok := got.CheckCSRF(token); ok != want { + t.Errorf("CheckCSRF(%q) = %t, want %t", token, ok, want) + } } if err := s.Delete(ctx, got); err != nil { - t.Fatal(err) + t.Fatalf("Delete() failed: %v", err) } if _, err := s.Get(ctx, created.Token); !errors.Is(err, ErrNoSession) { - t.Fatalf("deleted session still valid: %v", err) + t.Errorf("Get(deleted) error = %v, want %v", err, ErrNoSession) } } func TestSessionAbsoluteLifetime(t *testing.T) { - s, now := testSessions(t) - ctx := context.Background() - sess, err := s.Create(ctx, uuid.New(), uuid.Nil, "") - if err != nil { - t.Fatal(err) - } + s, now := newTestSessions(t) + sess := mustCreate(t, s, uuid.New()) *now = now.Add(25 * time.Hour) - if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) { - t.Fatalf("expired session accepted: %v", err) + if _, err := s.Get(context.Background(), sess.Token); !errors.Is(err, ErrNoSession) { + t.Errorf("Get(after absolute lifetime) error = %v, want %v", err, ErrNoSession) } } func TestDeleteAllForUser(t *testing.T) { - s, _ := testSessions(t) + s, _ := newTestSessions(t) ctx := context.Background() user := uuid.New() - a, _ := s.Create(ctx, user, uuid.Nil, "") - b, _ := s.Create(ctx, user, uuid.Nil, "") - other, _ := s.Create(ctx, uuid.New(), uuid.Nil, "") + a, b := mustCreate(t, s, user), mustCreate(t, s, user) + other := mustCreate(t, s, uuid.New()) if err := s.DeleteAllForUser(ctx, user); err != nil { - t.Fatal(err) + t.Fatalf("DeleteAllForUser() failed: %v", err) } - for _, tok := range []string{a.Token, b.Token} { - if _, err := s.Get(ctx, tok); !errors.Is(err, ErrNoSession) { - t.Fatal("session survived DeleteAllForUser") + for _, sess := range []*Session{a, b} { + if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) { + t.Errorf("Get(session of removed user) error = %v, want %v", err, ErrNoSession) } } if _, err := s.Get(ctx, other.Token); err != nil { - t.Fatalf("unrelated session removed: %v", err) + t.Errorf("Get(session of other user) error = %v, want nil", err) } } -func TestTokenNotStoredInPlain(t *testing.T) { - s, _ := testSessions(t) - ctx := context.Background() - sess, _ := s.Create(ctx, uuid.New(), uuid.Nil, "") - if n, _ := s.rdb.Exists(ctx, "session:"+sess.Token).Result(); n != 0 { - t.Fatal("raw token used as redis key") +func TestTokenIsNotStoredInPlain(t *testing.T) { + s, _ := newTestSessions(t) + sess := mustCreate(t, s, uuid.New()) + if n, err := s.rdb.Exists(context.Background(), "session:"+sess.Token).Result(); err != nil || n != 0 { + t.Errorf("EXISTS session: = %d, %v; want 0, nil", n, err) } } diff --git a/internal/auth/totp_test.go b/internal/auth/totp_test.go index d673ffc..6411ea0 100644 --- a/internal/auth/totp_test.go +++ b/internal/auth/totp_test.go @@ -2,42 +2,39 @@ package auth import ( "context" - "os" "testing" "time" "github.com/google/uuid" "github.com/pquerna/otp/totp" - "github.com/redis/go-redis/v9" ) -func TestTOTPRejectsReplay(t *testing.T) { - url := os.Getenv("UPTIME_TEST_REDIS_URL") - if url == "" { - t.Skip("UPTIME_TEST_REDIS_URL not set") - } - opts, _ := redis.ParseURL(url) - rdb := redis.NewClient(opts) - defer rdb.Close() - +func TestTOTPVerifierRejectsReplay(t *testing.T) { key, err := NewTOTPKey("a@example.test") if err != nil { - t.Fatal(err) + t.Fatalf("NewTOTPKey() failed: %v", err) } now := time.Now() - code, _ := totp.GenerateCode(key.Secret(), now) - v := NewTOTPVerifier(rdb) + code, err := totp.GenerateCode(key.Secret(), now) + if err != nil { + t.Fatalf("GenerateCode() failed: %v", err) + } + v := NewTOTPVerifier(newTestRedis(t)) v.now = func() time.Time { return now } user := uuid.New() ctx := context.Background() if ok, err := v.Verify(ctx, user, key.Secret(), code); !ok || err != nil { - t.Fatalf("first use rejected: %v", err) + t.Errorf("Verify(fresh code) = %t, %v; want true, nil", ok, err) } - if ok, _ := v.Verify(ctx, user, key.Secret(), code); ok { - t.Fatal("replayed code accepted") + if ok, err := v.Verify(ctx, user, key.Secret(), code); ok || err != nil { + t.Errorf("Verify(replayed code) = %t, %v; want false, nil", ok, err) } - if ok, _ := v.Verify(ctx, user, key.Secret(), "000000"); ok { - t.Fatal("wrong code accepted") + wrong := "000000" + if wrong == code { + wrong = "000001" + } + if ok, err := v.Verify(ctx, user, key.Secret(), wrong); ok || err != nil { + t.Errorf("Verify(wrong code) = %t, %v; want false, nil", ok, err) } } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index aa66644..c62092a 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -2,24 +2,24 @@ package config import "testing" -func TestValidateRedisModes(t *testing.T) { - base := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"} - - cases := []struct { - name string - mod func(*Common) - ok bool +func TestCommonValidateRedisModes(t *testing.T) { + tests := []struct { + name string + modify func(*Common) + wantErr bool }{ - {"standalone", func(c *Common) { c.RedisURL = "redis://r" }, true}, - {"nothing", func(c *Common) {}, false}, - {"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, true}, - {"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, false}, + {"standalone", func(c *Common) { c.RedisURL = "redis://r" }, false}, + {"no redis", func(*Common) {}, true}, + {"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false}, + {"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, true}, } - for _, tc := range cases { - c := base - tc.mod(&c) - if err := c.Validate(); (err == nil) != tc.ok { - t.Errorf("%s: err=%v", tc.name, err) - } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"} + tt.modify(&c) + if err := c.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() = %v, want error: %t", err, tt.wantErr) + } + }) } } diff --git a/internal/platform/redis_test.go b/internal/platform/redis_test.go index 20bf880..ff2a905 100644 --- a/internal/platform/redis_test.go +++ b/internal/platform/redis_test.go @@ -7,18 +7,19 @@ import ( ) func TestFailoverOptionsTakesMasterAuthFromURL(t *testing.T) { + const url = "rediss://app:masterpw@ignored:6379/3" s := config.Sentinel{Master: "mymaster", Addrs: []string{"s1:26379", "s2:26379"}, Password: "sentinelpw"} - fo, err := failoverOptions("rediss://app:masterpw@ignored:6379/3", s) + fo, err := failoverOptions(url, s) if err != nil { - t.Fatal(err) + t.Fatalf("failoverOptions(%q) failed: %v", url, err) } - if fo.Password != "masterpw" || fo.Username != "app" || fo.DB != 3 { - t.Fatalf("master auth not applied: %+v", fo) + if fo.Username != "app" || fo.Password != "masterpw" || fo.DB != 3 { + t.Errorf("failoverOptions(%q) master auth = %q/%q db %d, want app/masterpw db 3", url, fo.Username, fo.Password, fo.DB) } if fo.SentinelPassword != "sentinelpw" || len(fo.SentinelAddrs) != 2 { - t.Fatalf("sentinel settings lost: %+v", fo) + t.Errorf("failoverOptions(%q) sentinel = %q %v, want sentinelpw with 2 addrs", url, fo.SentinelPassword, fo.SentinelAddrs) } if fo.TLSConfig == nil { - t.Fatal("rediss scheme must enable TLS") + t.Errorf("failoverOptions(%q).TLSConfig = nil, want TLS for rediss scheme", url) } } diff --git a/internal/sealed/sealed_test.go b/internal/sealed/sealed_test.go index f46ad7a..a17c4dd 100644 --- a/internal/sealed/sealed_test.go +++ b/internal/sealed/sealed_test.go @@ -8,53 +8,55 @@ import ( "testing" ) -func key() string { +func newKey() string { b := make([]byte, 32) _, _ = rand.Read(b) return base64.StdEncoding.EncodeToString(b) } -func TestRotation(t *testing.T) { - k1, k2 := key(), key() - old, err := Parse("a:" + k1) +func mustParse(t *testing.T, spec string) *Keyring { + t.Helper() + kr, err := Parse(spec) if err != nil { - t.Fatal(err) + t.Fatalf("Parse(%q) failed: %v", spec, err) } - box := old.Seal([]byte("secret"), []byte("row-1")) + return kr +} - rotated, err := Parse("b:" + k2 + ",a:" + k1) - if err != nil { - t.Fatal(err) - } - got, err := rotated.Open(box, []byte("row-1")) - if err != nil || !bytes.Equal(got, []byte("secret")) { - t.Fatalf("open with retired key: %q %v", got, err) +func TestKeyRotation(t *testing.T) { + k1, k2 := newKey(), newKey() + aad := []byte("row-1") + box := mustParse(t, "a:"+k1).Seal([]byte("secret"), aad) + + rotated := mustParse(t, "b:"+k2+",a:"+k1) + if got, err := rotated.Open(box, aad); err != nil || !bytes.Equal(got, []byte("secret")) { + t.Errorf("Open(value sealed with retired key) = %q, %v; want %q, nil", got, err, "secret") } if !rotated.NeedsReseal(box) { - t.Fatal("old value not flagged for reseal") + t.Error("NeedsReseal(value sealed with retired key) = false, want true") } if rotated.NeedsReseal(rotated.Seal([]byte("x"), nil)) { - t.Fatal("fresh value flagged for reseal") + t.Error("NeedsReseal(value sealed with active key) = true, want false") } - dropped, _ := Parse("b:" + k2) - if _, err := dropped.Open(box, []byte("row-1")); !errors.Is(err, ErrUnknownKey) { - t.Fatalf("got %v", err) + dropped := mustParse(t, "b:"+k2) + if _, err := dropped.Open(box, aad); !errors.Is(err, ErrUnknownKey) { + t.Errorf("Open(value sealed with removed key) error = %v, want %v", err, ErrUnknownKey) } } -func TestAADBinding(t *testing.T) { - kr, _ := Parse("a:" + key()) +func TestOpenRejectsOtherAAD(t *testing.T) { + kr := mustParse(t, "a:"+newKey()) box := kr.Seal([]byte("secret"), []byte("row-1")) if _, err := kr.Open(box, []byte("row-2")); err == nil { - t.Fatal("value opened under different aad") + t.Error("Open(box, other aad) error = nil, want error") } } -func TestParseRejectsBadKeys(t *testing.T) { - for _, spec := range []string{"", "nokey", "a:short", "a:" + key() + ",a:" + key()} { +func TestParseRejectsInvalidSpecs(t *testing.T) { + for _, spec := range []string{"", "nokey", "a:short", "a:" + newKey() + ",a:" + newKey()} { if _, err := Parse(spec); err == nil { - t.Errorf("accepted %q", spec) + t.Errorf("Parse(%q) error = nil, want error", spec) } } } diff --git a/internal/tenant/tenant_test.go b/internal/tenant/tenant_test.go index 421384a..b4d2c8a 100644 --- a/internal/tenant/tenant_test.go +++ b/internal/tenant/tenant_test.go @@ -35,7 +35,7 @@ func setup(t *testing.T) (*tenant.DB, *pgxpool.Pool) { t.Fatal(err) } if bypass { - t.Fatal("test role bypasses RLS; use a non-superuser role") + t.Fatal("test database role bypasses row-level security; connect as a non-superuser role") } return tenant.New(pool), pool } @@ -97,21 +97,20 @@ func TestOrgScopeHidesOtherTenants(t *testing.T) { err := db.Tx(ctx, tenant.Org(f.orgA.ID, f.alice.ID), func(q *store.Queries) error { if _, err := q.GetOrg(ctx, f.orgA.ID); err != nil { - t.Errorf("own org not visible: %v", err) + t.Errorf("GetOrg(own org) error = %v, want nil", err) } - own, err := q.ListOrgMembers(ctx, f.orgA.ID) - if err != nil || len(own) != 1 { - t.Errorf("own members: %v %v", own, err) + if own, err := q.ListOrgMembers(ctx, f.orgA.ID); err != nil || len(own) != 1 { + t.Errorf("ListOrgMembers(own org) = %d members, %v; want 1, nil", len(own), err) } if _, err := q.GetOrg(ctx, f.orgB.ID); !errors.Is(err, pgx.ErrNoRows) { - t.Errorf("org B visible from org A: %v", err) + t.Errorf("GetOrg(other org) error = %v, want %v", err, pgx.ErrNoRows) } members, err := q.ListOrgMembers(ctx, f.orgB.ID) if err != nil { return err } if len(members) != 0 { - t.Errorf("members of org B visible from org A: %v", members) + t.Errorf("ListOrgMembers(other org) = %v, want none", members) } return nil }) @@ -129,7 +128,7 @@ func TestOrgScopeCannotWriteIntoOtherTenant(t *testing.T) { return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgB.ID, UserID: f.alice.ID}) }) if err == nil { - t.Fatal("membership in org B was created from org A scope") + t.Error("AddMembership(other org) error = nil, want row-level security violation") } } @@ -144,14 +143,14 @@ func TestUserScopeSeesOnlyOwnOrgs(t *testing.T) { return err } if len(orgs) != 1 || orgs[0].ID != f.orgA.ID { - t.Errorf("unexpected orgs for alice: %v", orgs) + t.Errorf("ListUserOrgs(self) = %v, want only org A", orgs) } bobs, err := q.ListUserOrgs(ctx, f.bob.ID) if err != nil { return err } if len(bobs) != 0 { - t.Errorf("alice sees bob's orgs: %v", bobs) + t.Errorf("ListUserOrgs(other user) = %v, want none", bobs) } return nil }) @@ -168,7 +167,7 @@ func TestUnscopedConnectionSeesNothing(t *testing.T) { t.Fatal(err) } if n != 0 { - t.Fatalf("unscoped query returned %d orgs", n) + t.Errorf("SELECT count(*) FROM orgs without scope = %d, want 0", n) } } @@ -176,7 +175,7 @@ func TestEmptyScopeIsRejected(t *testing.T) { db, _ := setup(t) err := db.Tx(context.Background(), tenant.Scope{}, func(*store.Queries) error { return nil }) if !errors.Is(err, tenant.ErrNoScope) { - t.Fatalf("got %v", err) + t.Errorf("Tx(zero Scope) error = %v, want %v", err, tenant.ErrNoScope) } } @@ -188,7 +187,7 @@ func TestSingleOwnerPerOrg(t *testing.T) { return q.AddMembership(ctx, store.AddMembershipParams{OrgID: f.orgA.ID, UserID: f.bob.ID, IsOwner: true}) }) if err == nil { - t.Fatal("second owner accepted") + t.Error("AddMembership(second owner) error = nil, want unique violation") } } @@ -198,10 +197,10 @@ func TestGlobalScopeSeesNoTenantRows(t *testing.T) { ctx := context.Background() err := db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { if _, err := q.GetOrg(ctx, f.orgA.ID); !errors.Is(err, pgx.ErrNoRows) { - t.Errorf("org visible in global scope: %v", err) + t.Errorf("GetOrg() in global scope error = %v, want %v", err, pgx.ErrNoRows) } if _, err := q.GetUser(ctx, f.alice.ID); err != nil { - t.Errorf("users must be readable in global scope: %v", err) + t.Errorf("GetUser() in global scope error = %v, want nil", err) } return nil }) @@ -230,6 +229,6 @@ func TestNewOrgCanBeCreatedInItsOwnScope(t *testing.T) { return err }) if err == nil { - t.Fatal("org created outside its own scope") + t.Error("CreateOrg(other id) error = nil, want row-level security violation") } } -- 2.54.1 From c485d1a96f781c977ec451ca205de3a49afb1462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:20:57 +0100 Subject: [PATCH 17/22] feat(platform): tag requests, logs and api errors with a request id A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is generated. The ID is echoed in the response header, added to every log record written with the request context and returned in API error bodies. Closes #44 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/api/server.go | 17 ++++++--- internal/platform/log.go | 36 ++++++++++++++++-- internal/platform/log_test.go | 33 ++++++++++++++++ internal/platform/router.go | 8 ++-- internal/requestid/requestid.go | 53 ++++++++++++++++++++++++++ internal/requestid/requestid_test.go | 56 ++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 12 deletions(-) create mode 100644 internal/platform/log_test.go create mode 100644 internal/requestid/requestid.go create mode 100644 internal/requestid/requestid_test.go diff --git a/internal/api/server.go b/internal/api/server.go index 56d6948..537a894 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -14,6 +14,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" @@ -130,17 +131,20 @@ func (s *Server) setLocale(c *gin.Context) { } type apiError struct { - Error string `json:"error"` - Message string `json:"message"` - Fields map[string]string `json:"fields,omitempty"` + Error string `json:"error"` + Message string `json:"message"` + Fields map[string]string `json:"fields,omitempty"` + RequestID string `json:"request_id,omitempty"` } // fail aborts with a machine-readable code and a message translated from // the catalog entry "error.". kv fills placeholders in that message. func fail(c *gin.Context, status int, code string, kv ...any) { + ctx := c.Request.Context() c.AbortWithStatusJSON(status, apiError{ - Error: code, - Message: i18n.T(c.Request.Context(), "error."+code, kv...), + Error: code, + Message: i18n.T(ctx, "error."+code, kv...), + RequestID: requestid.FromContext(ctx), }) } @@ -154,7 +158,8 @@ func bind(c *gin.Context, dst any) bool { if err == nil { return true } - e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")} + ctx := c.Request.Context() + e := apiError{Error: "invalid_input", Message: i18n.T(ctx, "error.invalid_input"), RequestID: requestid.FromContext(ctx)} var ve validator.ValidationErrors if errors.As(err, &ve) { e.Fields = map[string]string{} diff --git a/internal/platform/log.go b/internal/platform/log.go index 5592947..640fed1 100644 --- a/internal/platform/log.go +++ b/internal/platform/log.go @@ -1,19 +1,49 @@ package platform import ( + "context" + "io" "log/slog" "os" "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" ) // NewLogger returns a JSON logger tagged with component and the release // version, and the level variable controlling it. The level can be changed // once configuration is loaded; the logger is needed before that to report // configuration errors. +// +// Records logged with a request context carry its request_id, so handlers +// should prefer the *Context logging methods. func NewLogger(component string) (*slog.Logger, *slog.LevelVar) { + return newLogger(os.Stderr, component) +} + +func newLogger(w io.Writer, component string) (*slog.Logger, *slog.LevelVar) { level := new(slog.LevelVar) - l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})). - With("component", component, "app_version", buildinfo.Version) - return l, level + h := contextHandler{slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})} + return slog.New(h).With("component", component, "app_version", buildinfo.Version), level +} + +// contextHandler adds attributes carried in the context to each record. +type contextHandler struct{ slog.Handler } + +// Handle implements slog.Handler. +func (h contextHandler) Handle(ctx context.Context, r slog.Record) error { + if id := requestid.FromContext(ctx); id != "" { + r.AddAttrs(slog.String("request_id", id)) + } + return h.Handler.Handle(ctx, r) +} + +// WithAttrs keeps the wrapper so derived loggers still add the request ID. +func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return contextHandler{h.Handler.WithAttrs(attrs)} +} + +// WithGroup keeps the wrapper so derived loggers still add the request ID. +func (h contextHandler) WithGroup(name string) slog.Handler { + return contextHandler{h.Handler.WithGroup(name)} } diff --git a/internal/platform/log_test.go b/internal/platform/log_test.go new file mode 100644 index 0000000..84e4ef1 --- /dev/null +++ b/internal/platform/log_test.go @@ -0,0 +1,33 @@ +package platform + +import ( + "bytes" + "context" + "encoding/json" + "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" +) + +func TestLoggerAddsRequestID(t *testing.T) { + var buf bytes.Buffer + log, _ := newLogger(&buf, "test") + log = log.With("extra", 1) + + log.InfoContext(requestid.NewContext(context.Background(), "abc"), "with id") + log.InfoContext(context.Background(), "without id") + + dec := json.NewDecoder(&buf) + for _, want := range []any{"abc", nil} { + var rec map[string]any + if err := dec.Decode(&rec); err != nil { + t.Fatalf("decoding log line: %v", err) + } + if got := rec["request_id"]; got != want { + t.Errorf("%q: request_id = %v, want %v", rec["msg"], got, want) + } + if rec["extra"] != float64(1) || rec["component"] != "test" { + t.Errorf("%q: lost attributes from With: %v", rec["msg"], rec) + } + } +} diff --git a/internal/platform/router.go b/internal/platform/router.go index 2dd1219..d9fae7c 100644 --- a/internal/platform/router.go +++ b/internal/platform/router.go @@ -8,18 +8,20 @@ import ( "time" "github.com/gin-gonic/gin" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" ) var quietPaths = map[string]bool{"/healthz": true, "/readyz": true} -// NewRouter returns a gin engine that logs requests and panics through log -// as JSON and writes nothing to stdout itself. +// NewRouter returns a gin engine that assigns request IDs, logs requests and +// panics through log as JSON and writes nothing to stdout itself. func NewRouter(log *slog.Logger) *gin.Engine { gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = io.Discard gin.DefaultErrorWriter = io.Discard r := gin.New() - r.Use(accessLog(log), recovery(log)) + r.Use(requestid.Middleware(), accessLog(log), recovery(log)) return r } diff --git a/internal/requestid/requestid.go b/internal/requestid/requestid.go new file mode 100644 index 0000000..f288d62 --- /dev/null +++ b/internal/requestid/requestid.go @@ -0,0 +1,53 @@ +// Package requestid assigns every HTTP request an ID that ties together the +// response, all log lines written for it and error reports from users. +package requestid + +import ( + "context" + "regexp" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +// Header carries the ID in both directions. +const Header = "X-Request-ID" + +// Incoming IDs end up in logs and response headers, so anything beyond a +// conservative token alphabet is replaced rather than passed through. +var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +type ctxKey struct{} + +// NewContext returns ctx carrying id. +func NewContext(ctx context.Context, id string) context.Context { + return context.WithValue(ctx, ctxKey{}, id) +} + +// FromContext returns the request ID in ctx, or "" outside a request. +func FromContext(ctx context.Context) string { + id, _ := ctx.Value(ctxKey{}).(string) + return id +} + +// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us +// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival. +// It must run before any middleware that logs. +func Middleware() gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader(Header) + if !valid.MatchString(id) { + id = newID() + } + c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id)) + c.Header(Header, id) + c.Next() + } +} + +func newID() string { + if id, err := uuid.NewV7(); err == nil { + return id.String() + } + return uuid.NewString() +} diff --git a/internal/requestid/requestid_test.go b/internal/requestid/requestid_test.go new file mode 100644 index 0000000..1af7f61 --- /dev/null +++ b/internal/requestid/requestid_test.go @@ -0,0 +1,56 @@ +package requestid + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +func TestMiddleware(t *testing.T) { + tests := []struct { + name string + incoming string + keep bool + }{ + {name: "none", incoming: "", keep: false}, + {name: "uuid from proxy", incoming: "0b9a7c3e-6a43-4d2c-9a55-2f3b1c0d4e5f", keep: true}, + {name: "trace style", incoming: "Root=1-5759e988-bd862e3fe1be46a994272793", keep: false}, + {name: "opaque token", incoming: "edge:abc.123_X", keep: true}, + {name: "header injection", incoming: "abc\r\nSet-Cookie: x=y", keep: false}, + {name: "too long", incoming: strings.Repeat("a", 129), keep: false}, + } + gin.SetMode(gin.TestMode) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var seen string + r := gin.New() + r.Use(Middleware()) + r.GET("/", func(c *gin.Context) { seen = FromContext(c.Request.Context()) }) + + req := httptest.NewRequest(http.MethodGet, "/", nil) + if tt.incoming != "" { + req.Header.Set(Header, tt.incoming) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + got := w.Header().Get(Header) + if got != seen { + t.Errorf("response header %q != context ID %q", got, seen) + } + if tt.keep { + if got != tt.incoming { + t.Errorf("ID = %q, want incoming %q", got, tt.incoming) + } + return + } + if u, err := uuid.Parse(got); err != nil || u.Version() != 7 { + t.Errorf("ID = %q, want generated UUIDv7", got) + } + }) + } +} -- 2.54.1 From d1976ed57aaffa9481aa347736f310c389b7b5c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:30:43 +0100 Subject: [PATCH 18/22] feat(store): add per-organization sso providers and linked identities Identities are keyed by provider and subject. Both tables are tenant scoped; org_id_by_slug resolves a slug before sign-in without opening a broader scope. Refs #4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/migrations/sql/00007_sso.sql | 70 +++++ internal/store/memberships.sql.go | 21 ++ internal/store/models.go | 25 ++ internal/store/querier.go | 13 + internal/store/queries/memberships.sql | 3 + internal/store/queries/sso.sql | 54 ++++ internal/store/sso.sql.go | 353 +++++++++++++++++++++++++ sqlc.yaml | 5 + 8 files changed, 544 insertions(+) create mode 100644 internal/migrations/sql/00007_sso.sql create mode 100644 internal/store/queries/sso.sql create mode 100644 internal/store/sso.sql.go diff --git a/internal/migrations/sql/00007_sso.sql b/internal/migrations/sql/00007_sso.sql new file mode 100644 index 0000000..2cb4957 --- /dev/null +++ b/internal/migrations/sql/00007_sso.sql @@ -0,0 +1,70 @@ +-- +goose Up +CREATE TABLE sso_providers ( + id uuid PRIMARY KEY, + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), + issuer text NOT NULL CHECK (issuer ~ '^https?://[^\s]+$' AND length(issuer) <= 500), + client_id text NOT NULL CHECK (length(client_id) BETWEEN 1 AND 500), + -- Sealed with the application keyring, bound to the provider id. + client_secret bytea, + scopes text[] NOT NULL DEFAULT '{openid,email,profile}', + -- Lower-case domains; empty means any. Applies to auto-provisioning only. + allowed_domains text[] NOT NULL DEFAULT '{}', + auto_provision boolean NOT NULL DEFAULT false, + enabled boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX sso_providers_org_idx ON sso_providers (org_id); + +-- Accounts are linked by issuer subject, never by email: an org admin +-- controls their IdP and could otherwise assert any address. +CREATE TABLE user_identities ( + provider_id uuid NOT NULL REFERENCES sso_providers (id) ON DELETE CASCADE, + subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 255), + org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + email citext, + created_at timestamptz NOT NULL DEFAULT now(), + last_login_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (provider_id, subject) +); + +CREATE INDEX user_identities_user_idx ON user_identities (user_id); + +ALTER TABLE sso_providers ENABLE ROW LEVEL SECURITY; +ALTER TABLE sso_providers FORCE ROW LEVEL SECURITY; +CREATE POLICY sso_providers_tenant ON sso_providers FOR ALL + USING (app_scope_system() OR org_id = app_org_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +ALTER TABLE user_identities ENABLE ROW LEVEL SECURITY; +ALTER TABLE user_identities FORCE ROW LEVEL SECURITY; +CREATE POLICY user_identities_tenant ON user_identities FOR ALL + USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id()) + WITH CHECK (app_scope_system() OR org_id = app_org_id()); + +-- SSO starts before anyone is signed in. This reveals only whether a slug +-- exists, which the public /sso/ URL does anyway. FORCE ROW LEVEL +-- SECURITY applies to the table owner too, so SECURITY DEFINER would not +-- help; the system scope is raised for this single lookup and restored. +-- +goose StatementBegin +CREATE FUNCTION org_id_by_slug(s citext) RETURNS uuid +LANGUAGE plpgsql VOLATILE AS $$ +DECLARE + prev text := coalesce(current_setting('app.scope', true), ''); + result uuid; +BEGIN + PERFORM set_config('app.scope', 'system', true); + SELECT id INTO result FROM orgs WHERE slug = s; + PERFORM set_config('app.scope', prev, true); + RETURN result; +END +$$; +-- +goose StatementEnd + +-- +goose Down +DROP FUNCTION org_id_by_slug(citext); +DROP TABLE user_identities; +DROP TABLE sso_providers; diff --git a/internal/store/memberships.sql.go b/internal/store/memberships.sql.go index ee9eee7..3551c0a 100644 --- a/internal/store/memberships.sql.go +++ b/internal/store/memberships.sql.go @@ -27,6 +27,27 @@ func (q *Queries) AddMembership(ctx context.Context, arg AddMembershipParams) er return err } +const getMembership = `-- name: GetMembership :one +SELECT org_id, user_id, is_owner, created_at FROM memberships WHERE org_id = $1 AND user_id = $2 +` + +type GetMembershipParams struct { + OrgID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) { + row := q.db.QueryRow(ctx, getMembership, arg.OrgID, arg.UserID) + var i Membership + err := row.Scan( + &i.OrgID, + &i.UserID, + &i.IsOwner, + &i.CreatedAt, + ) + return i, err +} + const listOrgMembers = `-- name: ListOrgMembers :many SELECT u.id, u.email, u.display_name, m.is_owner, m.created_at AS joined_at FROM memberships m diff --git a/internal/store/models.go b/internal/store/models.go index 899f582..d54331e 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -26,6 +26,21 @@ type Org struct { RequireTotp bool } +type SsoProvider struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Issuer string + ClientID string + ClientSecret []byte + Scopes []string + AllowedDomains []string + AutoProvision bool + Enabled bool + CreatedAt time.Time + UpdatedAt time.Time +} + type User struct { ID uuid.UUID Email string @@ -38,3 +53,13 @@ type User struct { TotpEnabledAt *time.Time Locale *string } + +type UserIdentity struct { + ProviderID uuid.UUID + Subject string + OrgID uuid.UUID + UserID uuid.UUID + Email *string + CreatedAt time.Time + LastLoginAt time.Time +} diff --git a/internal/store/querier.go b/internal/store/querier.go index aa4f651..1fc7a89 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -13,22 +13,35 @@ import ( type Querier interface { AddMembership(ctx context.Context, arg AddMembershipParams) error AnyUserExists(ctx context.Context) (bool, error) + CreateIdentity(ctx context.Context, arg CreateIdentityParams) error CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error) + CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) + DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DisableTOTP(ctx context.Context, id uuid.UUID) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error + GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) + GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrgBySlug(ctx context.Context, slug string) (Org, error) + GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error) + IsMember(ctx context.Context, arg IsMemberParams) (bool, error) + ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgs(ctx context.Context) ([]Org, error) + ListSSOProviders(ctx context.Context) ([]SsoProvider, error) + ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) + OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error + TouchIdentity(ctx context.Context, arg TouchIdentityParams) error + UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) } var _ Querier = (*Queries)(nil) diff --git a/internal/store/queries/memberships.sql b/internal/store/queries/memberships.sql index 443a104..faba066 100644 --- a/internal/store/queries/memberships.sql +++ b/internal/store/queries/memberships.sql @@ -17,3 +17,6 @@ FROM memberships m JOIN orgs o ON o.id = m.org_id WHERE m.user_id = $1 ORDER BY o.name; + +-- name: GetMembership :one +SELECT * FROM memberships WHERE org_id = $1 AND user_id = $2; diff --git a/internal/store/queries/sso.sql b/internal/store/queries/sso.sql new file mode 100644 index 0000000..32e25b6 --- /dev/null +++ b/internal/store/queries/sso.sql @@ -0,0 +1,54 @@ +-- name: OrgIDBySlug :one +SELECT coalesce(org_id_by_slug(sqlc.arg(slug)::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id; + +-- name: CreateSSOProvider :one +INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) +RETURNING *; + +-- name: UpdateSSOProvider :one +UPDATE sso_providers SET + name = $2, + issuer = $3, + client_id = $4, + client_secret = coalesce(sqlc.narg(client_secret), client_secret), + scopes = $5, + allowed_domains = $6, + auto_provision = $7, + enabled = $8, + updated_at = now() +WHERE id = $1 +RETURNING *; + +-- name: DeleteSSOProvider :execrows +DELETE FROM sso_providers WHERE id = $1; + +-- name: GetSSOProvider :one +SELECT * FROM sso_providers WHERE id = $1; + +-- name: ListSSOProviders :many +SELECT * FROM sso_providers ORDER BY name; + +-- name: ListEnabledSSOProviders :many +SELECT id, name FROM sso_providers WHERE enabled ORDER BY name; + +-- name: GetIdentity :one +SELECT * FROM user_identities WHERE provider_id = $1 AND subject = $2; + +-- name: CreateIdentity :exec +INSERT INTO user_identities (provider_id, subject, org_id, user_id, email) +VALUES ($1, $2, $3, $4, $5); + +-- name: TouchIdentity :exec +UPDATE user_identities SET email = $3, last_login_at = now() +WHERE provider_id = $1 AND subject = $2; + +-- name: IsMember :one +SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2); + +-- name: ListUserIdentitiesInOrg :many +SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at +FROM user_identities i +JOIN sso_providers p ON p.id = i.provider_id +WHERE i.user_id = $1 +ORDER BY p.name; diff --git a/internal/store/sso.sql.go b/internal/store/sso.sql.go new file mode 100644 index 0000000..2ed150f --- /dev/null +++ b/internal/store/sso.sql.go @@ -0,0 +1,353 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: sso.sql + +package store + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createIdentity = `-- name: CreateIdentity :exec +INSERT INTO user_identities (provider_id, subject, org_id, user_id, email) +VALUES ($1, $2, $3, $4, $5) +` + +type CreateIdentityParams struct { + ProviderID uuid.UUID + Subject string + OrgID uuid.UUID + UserID uuid.UUID + Email *string +} + +func (q *Queries) CreateIdentity(ctx context.Context, arg CreateIdentityParams) error { + _, err := q.db.Exec(ctx, createIdentity, + arg.ProviderID, + arg.Subject, + arg.OrgID, + arg.UserID, + arg.Email, + ) + return err +} + +const createSSOProvider = `-- name: CreateSSOProvider :one +INSERT INTO sso_providers (id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) +RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at +` + +type CreateSSOProviderParams struct { + ID uuid.UUID + OrgID uuid.UUID + Name string + Issuer string + ClientID string + ClientSecret []byte + Scopes []string + AllowedDomains []string + AutoProvision bool + Enabled bool +} + +func (q *Queries) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) { + row := q.db.QueryRow(ctx, createSSOProvider, + arg.ID, + arg.OrgID, + arg.Name, + arg.Issuer, + arg.ClientID, + arg.ClientSecret, + arg.Scopes, + arg.AllowedDomains, + arg.AutoProvision, + arg.Enabled, + ) + var i SsoProvider + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.Scopes, + &i.AllowedDomains, + &i.AutoProvision, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const deleteSSOProvider = `-- name: DeleteSSOProvider :execrows +DELETE FROM sso_providers WHERE id = $1 +` + +func (q *Queries) DeleteSSOProvider(ctx context.Context, id uuid.UUID) (int64, error) { + result, err := q.db.Exec(ctx, deleteSSOProvider, id) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getIdentity = `-- name: GetIdentity :one +SELECT provider_id, subject, org_id, user_id, email, created_at, last_login_at FROM user_identities WHERE provider_id = $1 AND subject = $2 +` + +type GetIdentityParams struct { + ProviderID uuid.UUID + Subject string +} + +func (q *Queries) GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error) { + row := q.db.QueryRow(ctx, getIdentity, arg.ProviderID, arg.Subject) + var i UserIdentity + err := row.Scan( + &i.ProviderID, + &i.Subject, + &i.OrgID, + &i.UserID, + &i.Email, + &i.CreatedAt, + &i.LastLoginAt, + ) + return i, err +} + +const getSSOProvider = `-- name: GetSSOProvider :one +SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers WHERE id = $1 +` + +func (q *Queries) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) { + row := q.db.QueryRow(ctx, getSSOProvider, id) + var i SsoProvider + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.Scopes, + &i.AllowedDomains, + &i.AutoProvision, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const isMember = `-- name: IsMember :one +SELECT EXISTS (SELECT 1 FROM memberships WHERE org_id = $1 AND user_id = $2) +` + +type IsMemberParams struct { + OrgID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) IsMember(ctx context.Context, arg IsMemberParams) (bool, error) { + row := q.db.QueryRow(ctx, isMember, arg.OrgID, arg.UserID) + var exists bool + err := row.Scan(&exists) + return exists, err +} + +const listEnabledSSOProviders = `-- name: ListEnabledSSOProviders :many +SELECT id, name FROM sso_providers WHERE enabled ORDER BY name +` + +type ListEnabledSSOProvidersRow struct { + ID uuid.UUID + Name string +} + +func (q *Queries) ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error) { + rows, err := q.db.Query(ctx, listEnabledSSOProviders) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListEnabledSSOProvidersRow{} + for rows.Next() { + var i ListEnabledSSOProvidersRow + if err := rows.Scan(&i.ID, &i.Name); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listSSOProviders = `-- name: ListSSOProviders :many +SELECT id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at FROM sso_providers ORDER BY name +` + +func (q *Queries) ListSSOProviders(ctx context.Context) ([]SsoProvider, error) { + rows, err := q.db.Query(ctx, listSSOProviders) + if err != nil { + return nil, err + } + defer rows.Close() + items := []SsoProvider{} + for rows.Next() { + var i SsoProvider + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.Scopes, + &i.AllowedDomains, + &i.AutoProvision, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listUserIdentitiesInOrg = `-- name: ListUserIdentitiesInOrg :many +SELECT p.name AS provider_name, i.email, i.created_at, i.last_login_at +FROM user_identities i +JOIN sso_providers p ON p.id = i.provider_id +WHERE i.user_id = $1 +ORDER BY p.name +` + +type ListUserIdentitiesInOrgRow struct { + ProviderName string + Email *string + CreatedAt time.Time + LastLoginAt time.Time +} + +func (q *Queries) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) { + rows, err := q.db.Query(ctx, listUserIdentitiesInOrg, userID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListUserIdentitiesInOrgRow{} + for rows.Next() { + var i ListUserIdentitiesInOrgRow + if err := rows.Scan( + &i.ProviderName, + &i.Email, + &i.CreatedAt, + &i.LastLoginAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const orgIDBySlug = `-- name: OrgIDBySlug :one +SELECT coalesce(org_id_by_slug($1::citext), '00000000-0000-0000-0000-000000000000')::uuid AS id +` + +func (q *Queries) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, orgIDBySlug, slug) + var id uuid.UUID + err := row.Scan(&id) + return id, err +} + +const touchIdentity = `-- name: TouchIdentity :exec +UPDATE user_identities SET email = $3, last_login_at = now() +WHERE provider_id = $1 AND subject = $2 +` + +type TouchIdentityParams struct { + ProviderID uuid.UUID + Subject string + Email *string +} + +func (q *Queries) TouchIdentity(ctx context.Context, arg TouchIdentityParams) error { + _, err := q.db.Exec(ctx, touchIdentity, arg.ProviderID, arg.Subject, arg.Email) + return err +} + +const updateSSOProvider = `-- name: UpdateSSOProvider :one +UPDATE sso_providers SET + name = $2, + issuer = $3, + client_id = $4, + client_secret = coalesce($9, client_secret), + scopes = $5, + allowed_domains = $6, + auto_provision = $7, + enabled = $8, + updated_at = now() +WHERE id = $1 +RETURNING id, org_id, name, issuer, client_id, client_secret, scopes, allowed_domains, auto_provision, enabled, created_at, updated_at +` + +type UpdateSSOProviderParams struct { + ID uuid.UUID + Name string + Issuer string + ClientID string + Scopes []string + AllowedDomains []string + AutoProvision bool + Enabled bool + ClientSecret []byte +} + +func (q *Queries) UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error) { + row := q.db.QueryRow(ctx, updateSSOProvider, + arg.ID, + arg.Name, + arg.Issuer, + arg.ClientID, + arg.Scopes, + arg.AllowedDomains, + arg.AutoProvision, + arg.Enabled, + arg.ClientSecret, + ) + var i SsoProvider + err := row.Scan( + &i.ID, + &i.OrgID, + &i.Name, + &i.Issuer, + &i.ClientID, + &i.ClientSecret, + &i.Scopes, + &i.AllowedDomains, + &i.AutoProvision, + &i.Enabled, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} diff --git a/sqlc.yaml b/sqlc.yaml index 2a12748..d017061 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -16,6 +16,11 @@ sql: go_type: github.com/google/uuid.UUID - db_type: citext go_type: string + - db_type: citext + nullable: true + go_type: + type: string + pointer: true - db_type: timestamptz go_type: time.Time - db_type: timestamptz -- 2.54.1 From 9ad5f29f1b608caf96cedff39dc3313345fd7ee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:30:43 +0100 Subject: [PATCH 19/22] feat(sso): add openid connect client with pkce and guarded discovery Issuer URLs come from customers, so requests to their IdPs refuse non-public addresses unless private networks are explicitly allowed. Refs #4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- go.mod | 13 ++- go.sum | 22 ++-- internal/sso/httpclient.go | 45 ++++++++ internal/sso/httpclient_test.go | 46 ++++++++ internal/sso/sso.go | 188 ++++++++++++++++++++++++++++++++ internal/sso/sso_test.go | 115 +++++++++++++++++++ internal/sso/ssotest/idp.go | 166 ++++++++++++++++++++++++++++ 7 files changed, 576 insertions(+), 19 deletions(-) create mode 100644 internal/sso/httpclient.go create mode 100644 internal/sso/httpclient_test.go create mode 100644 internal/sso/sso.go create mode 100644 internal/sso/sso_test.go create mode 100644 internal/sso/ssotest/idp.go diff --git a/go.mod b/go.mod index 6efc2e3..7c78cd5 100644 --- a/go.mod +++ b/go.mod @@ -5,11 +5,19 @@ go 1.27.1 require ( github.com/a-h/templ v0.3.1118 github.com/caarlos0/env/v11 v11.4.2 + github.com/coreos/go-oidc/v3 v3.21.0 github.com/gin-gonic/gin v1.12.0 + github.com/go-jose/go-jose/v4 v4.1.4 + github.com/go-playground/validator/v10 v10.30.6 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.13.0 + github.com/nicksnyder/go-i18n/v2 v2.7.0 + github.com/pquerna/otp v1.5.0 github.com/pressly/goose/v3 v3.30.1 github.com/redis/go-redis/v9 v9.23.0 + golang.org/x/crypto v0.59.0 + golang.org/x/oauth2 v0.38.0 + golang.org/x/text v0.44.0 ) require ( @@ -29,7 +37,6 @@ require ( github.com/gin-contrib/sse v1.1.0 // indirect github.com/go-playground/locales v0.14.2 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect - github.com/go-playground/validator/v10 v10.30.6 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect @@ -44,9 +51,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect - github.com/nicksnyder/go-i18n/v2 v2.7.0 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect - github.com/pquerna/otp v1.5.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect @@ -56,12 +61,10 @@ require ( go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect - golang.org/x/crypto v0.59.0 // indirect golang.org/x/mod v0.43.0 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect - golang.org/x/text v0.44.0 // indirect golang.org/x/tools v0.52.0 // indirect google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index dc44847..ea1bd41 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ= github.com/a-h/parse v0.0.42/go.mod h1:X9OHJ1IjgakwZoDSoHYhdtKKD0zXZ2agpoIztPAA95w= github.com/a-h/templ v0.3.1118 h1:rZv90g1xVb7ieNz4j5WK6yQePZfsg7j7fVvP8qVmeJI= @@ -26,6 +28,8 @@ github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo= github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM= +github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -35,26 +39,20 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= -github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= -github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= -github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= @@ -78,8 +76,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= @@ -116,8 +112,6 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= -github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= -github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -150,14 +144,14 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= +golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/internal/sso/httpclient.go b/internal/sso/httpclient.go new file mode 100644 index 0000000..c132918 --- /dev/null +++ b/internal/sso/httpclient.go @@ -0,0 +1,45 @@ +package sso + +import ( + "context" + "errors" + "net" + "net/http" + "net/netip" + "syscall" + "time" +) + +// ErrForbiddenAddress is returned when an IdP resolves to an address the +// client may not contact. +var ErrForbiddenAddress = errors.New("sso: issuer resolves to a non-public address") + +var cgnat = netip.MustParsePrefix("100.64.0.0/10") + +// SafeHTTPClient returns a client for talking to customer-configured IdPs. +// Unless allowPrivate is set it refuses to connect to loopback, private, +// link-local and similar ranges. The check runs on the resolved address at +// dial time, so DNS rebinding and redirects cannot bypass it. +func SafeHTTPClient(allowPrivate bool) *http.Client { + d := &net.Dialer{Timeout: 5 * time.Second} + if !allowPrivate { + d.Control = func(_, address string, _ syscall.RawConn) error { + ap, err := netip.ParseAddrPort(address) + if err != nil || !isPublic(ap.Addr()) { + return ErrForbiddenAddress + } + return nil + } + } + tr := http.DefaultTransport.(*http.Transport).Clone() + tr.Proxy = nil + tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + return d.DialContext(ctx, network, addr) + } + return &http.Client{Transport: tr, Timeout: 10 * time.Second} +} + +func isPublic(a netip.Addr) bool { + a = a.Unmap() + return a.IsGlobalUnicast() && !a.IsPrivate() && !cgnat.Contains(a) +} diff --git a/internal/sso/httpclient_test.go b/internal/sso/httpclient_test.go new file mode 100644 index 0000000..226344d --- /dev/null +++ b/internal/sso/httpclient_test.go @@ -0,0 +1,46 @@ +package sso + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/netip" + "testing" +) + +func TestIsPublic(t *testing.T) { + tests := map[string]bool{ + "8.8.8.8": true, + "2606:4700::1111": true, + "127.0.0.1": false, + "10.1.2.3": false, + "172.16.0.1": false, + "192.168.1.1": false, + "169.254.169.254": false, + "100.64.0.1": false, + "0.0.0.0": false, + "::1": false, + "fd00::1": false, + "fe80::1": false, + "::ffff:127.0.0.1": false, + } + for addr, want := range tests { + if got := isPublic(netip.MustParseAddr(addr)); got != want { + t.Errorf("isPublic(%s) = %t, want %t", addr, got, want) + } + } +} + +func TestSafeHTTPClientBlocksLoopback(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + defer srv.Close() + + if _, err := SafeHTTPClient(false).Get(srv.URL); !errors.Is(err, ErrForbiddenAddress) { + t.Errorf("Get(%s) with private networks denied: error = %v, want %v", srv.URL, err, ErrForbiddenAddress) + } + resp, err := SafeHTTPClient(true).Get(srv.URL) + if err != nil { + t.Fatalf("Get(%s) with private networks allowed failed: %v", srv.URL, err) + } + _ = resp.Body.Close() +} diff --git a/internal/sso/sso.go b/internal/sso/sso.go new file mode 100644 index 0000000..c46bb03 --- /dev/null +++ b/internal/sso/sso.go @@ -0,0 +1,188 @@ +// Package sso implements OpenID Connect sign-in against identity providers +// that each organization configures for itself. +package sso + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "sync" + "time" + + "github.com/coreos/go-oidc/v3/oidc" + "golang.org/x/oauth2" +) + +// Provider is one organization's IdP registration. +type Provider struct { + Issuer string + ClientID string + ClientSecret string + Scopes []string +} + +// Claims are the ID token fields used to identify and provision a user. +type Claims struct { + Subject string `json:"sub"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + Name string `json:"name"` +} + +// Flow holds the per-attempt secrets that must survive the redirect to the +// IdP. Callers store it server side, keyed by State. +type Flow struct { + State string + Nonce string + Verifier string +} + +// ErrInvalidIssuer is returned for issuer URLs that are malformed or use a +// scheme the client does not allow. +var ErrInvalidIssuer = errors.New("sso: invalid issuer url") + +const discoveryTTL = time.Hour + +// Client performs discovery, builds authorization URLs and verifies +// callbacks. Discovery documents are cached per issuer. +type Client struct { + http *http.Client + redirectURL string + allowHTTP bool + now func() time.Time + + mu sync.Mutex + cache map[string]cached +} + +type cached struct { + provider *oidc.Provider + expires time.Time +} + +// New returns a Client whose callbacks land on redirectURL. httpClient is +// used for every request to an IdP; pass one from SafeHTTPClient. allowHTTP +// permits plain-http issuers, which only makes sense for IdPs on a private +// network. +func New(httpClient *http.Client, redirectURL string, allowHTTP bool) *Client { + return &Client{ + http: httpClient, + redirectURL: redirectURL, + allowHTTP: allowHTTP, + now: time.Now, + cache: map[string]cached{}, + } +} + +// RedirectURL is the callback URL to register at the IdP. +func (c *Client) RedirectURL() string { return c.redirectURL } + +// ValidateIssuer checks the URL syntactically and runs discovery, so that +// misconfiguration surfaces when an admin saves the provider rather than +// when users try to sign in. +func (c *Client) ValidateIssuer(ctx context.Context, issuer string) error { + if err := c.checkIssuer(issuer); err != nil { + return err + } + _, err := c.discover(ctx, issuer) + return err +} + +func (c *Client) checkIssuer(issuer string) error { + u, err := url.Parse(issuer) + if err != nil || u.Host == "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil { + return ErrInvalidIssuer + } + if u.Scheme != "https" && !(c.allowHTTP && u.Scheme == "http") { + return ErrInvalidIssuer + } + return nil +} + +func (c *Client) discover(ctx context.Context, issuer string) (*oidc.Provider, error) { + c.mu.Lock() + if e, ok := c.cache[issuer]; ok && c.now().Before(e.expires) { + c.mu.Unlock() + return e.provider, nil + } + c.mu.Unlock() + + p, err := oidc.NewProvider(oidc.ClientContext(ctx, c.http), issuer) + if err != nil { + return nil, fmt.Errorf("sso: discovery for %s: %w", issuer, err) + } + c.mu.Lock() + c.cache[issuer] = cached{provider: p, expires: c.now().Add(discoveryTTL)} + c.mu.Unlock() + return p, nil +} + +func (c *Client) oauth(p Provider, op *oidc.Provider) *oauth2.Config { + scopes := p.Scopes + if !slices.Contains(scopes, oidc.ScopeOpenID) { + scopes = append([]string{oidc.ScopeOpenID}, scopes...) + } + return &oauth2.Config{ + ClientID: p.ClientID, + ClientSecret: p.ClientSecret, + Endpoint: op.Endpoint(), + RedirectURL: c.redirectURL, + Scopes: scopes, + } +} + +// NewFlow returns fresh state, nonce and PKCE verifier. +func NewFlow(random func() string) Flow { + return Flow{State: random(), Nonce: random(), Verifier: oauth2.GenerateVerifier()} +} + +// AuthURL returns the IdP URL to redirect the browser to. +func (c *Client) AuthURL(ctx context.Context, p Provider, f Flow) (string, error) { + if err := c.checkIssuer(p.Issuer); err != nil { + return "", err + } + op, err := c.discover(ctx, p.Issuer) + if err != nil { + return "", err + } + return c.oauth(p, op).AuthCodeURL(f.State, + oidc.Nonce(f.Nonce), + oauth2.S256ChallengeOption(f.Verifier), + ), nil +} + +// Exchange redeems the authorization code and verifies the ID token's +// signature, issuer, audience, expiry and nonce. +func (c *Client) Exchange(ctx context.Context, p Provider, f Flow, code string) (Claims, error) { + op, err := c.discover(ctx, p.Issuer) + if err != nil { + return Claims{}, err + } + ctx = oidc.ClientContext(ctx, c.http) + tok, err := c.oauth(p, op).Exchange(ctx, code, oauth2.VerifierOption(f.Verifier)) + if err != nil { + return Claims{}, fmt.Errorf("sso: code exchange: %w", err) + } + raw, ok := tok.Extra("id_token").(string) + if !ok { + return Claims{}, errors.New("sso: token response without id_token") + } + idt, err := op.VerifierContext(ctx, &oidc.Config{ClientID: p.ClientID, Now: c.now}).Verify(ctx, raw) + if err != nil { + return Claims{}, fmt.Errorf("sso: id token: %w", err) + } + if idt.Nonce != f.Nonce { + return Claims{}, errors.New("sso: id token nonce mismatch") + } + var cl Claims + if err := idt.Claims(&cl); err != nil { + return Claims{}, fmt.Errorf("sso: id token claims: %w", err) + } + if cl.Subject == "" { + return Claims{}, errors.New("sso: id token without subject") + } + return cl, nil +} diff --git a/internal/sso/sso_test.go b/internal/sso/sso_test.go new file mode 100644 index 0000000..d79cda0 --- /dev/null +++ b/internal/sso/sso_test.go @@ -0,0 +1,115 @@ +package sso_test + +import ( + "context" + "crypto/rand" + "errors" + "net/http" + "net/url" + "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest" +) + +const callback = "https://uptime.example/sso/callback" + +// authorize follows the IdP redirect and returns the code and state it +// would deliver to the callback. +func authorize(t *testing.T, authURL string) (code, state string) { + t.Helper() + noFollow := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := noFollow.Get(authURL) + if err != nil { + t.Fatalf("GET %s failed: %v", authURL, err) + } + _ = resp.Body.Close() + loc, err := url.Parse(resp.Header.Get("Location")) + if err != nil || resp.StatusCode != http.StatusFound { + t.Fatalf("authorize = %d %q, want 302 to callback", resp.StatusCode, resp.Header.Get("Location")) + } + return loc.Query().Get("code"), loc.Query().Get("state") +} + +func setup(t *testing.T) (*ssotest.IDP, *sso.Client, sso.Provider) { + t.Helper() + idp := ssotest.New(t) + c := sso.New(sso.SafeHTTPClient(true), callback, true) + p := sso.Provider{Issuer: idp.Issuer(), ClientID: idp.ClientID, ClientSecret: idp.Secret, Scopes: []string{"email"}} + return idp, c, p +} + +func TestFlow(t *testing.T) { + idp, c, p := setup(t) + idp.SetUser(ssotest.User{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"}) + ctx := context.Background() + + flow := sso.NewFlow(rand.Text) + authURL, err := c.AuthURL(ctx, p, flow) + if err != nil { + t.Fatalf("AuthURL() failed: %v", err) + } + code, state := authorize(t, authURL) + if state != flow.State { + t.Fatalf("state = %q, want %q", state, flow.State) + } + got, err := c.Exchange(ctx, p, flow, code) + if err != nil { + t.Fatalf("Exchange() failed: %v", err) + } + want := sso.Claims{Subject: "u-1", Email: "a@corp.test", EmailVerified: true, Name: "A"} + if got != want { + t.Errorf("Exchange() = %+v, want %+v", got, want) + } +} + +func TestExchangeRejects(t *testing.T) { + tests := []struct { + name string + tamper func(*ssotest.IDP, *sso.Flow) + }{ + {"wrong nonce", func(i *ssotest.IDP, _ *sso.Flow) { i.NonceOverride = "other" }}, + {"wrong audience", func(i *ssotest.IDP, _ *sso.Flow) { i.AudienceOverride = "someone-else" }}, + {"wrong pkce verifier", func(_ *ssotest.IDP, f *sso.Flow) { f.Verifier = "x" + f.Verifier[1:] }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + idp, c, p := setup(t) + idp.SetUser(ssotest.User{Subject: "u-1"}) + ctx := context.Background() + flow := sso.NewFlow(rand.Text) + authURL, err := c.AuthURL(ctx, p, flow) + if err != nil { + t.Fatalf("AuthURL() failed: %v", err) + } + code, _ := authorize(t, authURL) + tt.tamper(idp, &flow) + if _, err := c.Exchange(ctx, p, flow, code); err == nil { + t.Error("Exchange() error = nil, want rejection") + } + }) + } +} + +func TestValidateIssuer(t *testing.T) { + idp, _, _ := setup(t) + strict := sso.New(sso.SafeHTTPClient(false), callback, false) + tests := []struct { + issuer string + client *sso.Client + want error + }{ + {"ftp://idp.test", strict, sso.ErrInvalidIssuer}, + {"https://idp.test/?q=1", strict, sso.ErrInvalidIssuer}, + {"https://user@idp.test", strict, sso.ErrInvalidIssuer}, + {idp.Issuer(), strict, sso.ErrInvalidIssuer}, + {"https://127.0.0.1:1", strict, sso.ErrForbiddenAddress}, + {idp.Issuer(), sso.New(sso.SafeHTTPClient(true), callback, true), nil}, + } + for _, tt := range tests { + err := tt.client.ValidateIssuer(context.Background(), tt.issuer) + if !errors.Is(err, tt.want) { + t.Errorf("ValidateIssuer(%q) = %v, want %v", tt.issuer, err, tt.want) + } + } +} diff --git a/internal/sso/ssotest/idp.go b/internal/sso/ssotest/idp.go new file mode 100644 index 0000000..062a66a --- /dev/null +++ b/internal/sso/ssotest/idp.go @@ -0,0 +1,166 @@ +// Package ssotest provides a minimal OpenID Connect provider for tests. +package ssotest + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" +) + +// User is the identity the IDP asserts for the next login. +type User struct { + Subject string + Email string + EmailVerified bool + Name string +} + +// IDP is an in-memory authorization server. It signs ID tokens with a fresh +// RSA key and enforces PKCE. +type IDP struct { + Server *httptest.Server + ClientID string + Secret string + + key *rsa.PrivateKey + signer jose.Signer + + mu sync.Mutex + user User + codes map[string]grant + // NonceOverride, when set, replaces the nonce in issued tokens. + NonceOverride string + // AudienceOverride, when set, replaces the audience in issued tokens. + AudienceOverride string +} + +type grant struct { + nonce, challenge, redirect string + user User +} + +// New starts an IDP that is shut down when t ends. +func New(t *testing.T) *IDP { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: jose.JSONWebKey{Key: key, KeyID: "k1"}}, nil) + if err != nil { + t.Fatal(err) + } + idp := &IDP{ClientID: "client-1", Secret: "secret-1", key: key, signer: signer, codes: map[string]grant{}} + mux := http.NewServeMux() + mux.HandleFunc("GET /.well-known/openid-configuration", idp.discovery) + mux.HandleFunc("GET /keys", idp.keys) + mux.HandleFunc("GET /authorize", idp.authorize) + mux.HandleFunc("POST /token", idp.token) + idp.Server = httptest.NewServer(mux) + t.Cleanup(idp.Server.Close) + return idp +} + +// Issuer is the issuer URL to configure. +func (i *IDP) Issuer() string { return i.Server.URL } + +// SetUser selects who the next authorization asserts. +func (i *IDP) SetUser(u User) { + i.mu.Lock() + defer i.mu.Unlock() + i.user = u +} + +func (i *IDP) discovery(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, map[string]any{ + "issuer": i.Issuer(), + "authorization_endpoint": i.Issuer() + "/authorize", + "token_endpoint": i.Issuer() + "/token", + "jwks_uri": i.Issuer() + "/keys", + "response_types_supported": []string{"code"}, + "subject_types_supported": []string{"public"}, + "id_token_signing_alg_values_supported": []string{"RS256"}, + }) +} + +func (i *IDP) keys(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &i.key.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}}) +} + +// authorize skips the login screen and immediately redirects back with a code. +func (i *IDP) authorize(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("client_id") != i.ClientID || q.Get("code_challenge_method") != "S256" { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + code := rand.Text() + i.mu.Lock() + i.codes[code] = grant{nonce: q.Get("nonce"), challenge: q.Get("code_challenge"), redirect: q.Get("redirect_uri"), user: i.user} + i.mu.Unlock() + back, _ := url.Parse(q.Get("redirect_uri")) + v := back.Query() + v.Set("code", code) + v.Set("state", q.Get("state")) + back.RawQuery = v.Encode() + http.Redirect(w, r, back.String(), http.StatusFound) +} + +func (i *IDP) token(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return + } + id, secret, ok := r.BasicAuth() + if !ok { + id, secret = r.PostForm.Get("client_id"), r.PostForm.Get("client_secret") + } + if id != i.ClientID || secret != i.Secret { + http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized) + return + } + i.mu.Lock() + g, ok := i.codes[r.PostForm.Get("code")] + delete(i.codes, r.PostForm.Get("code")) + i.mu.Unlock() + sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier"))) + if !ok || base64.RawURLEncoding.EncodeToString(sum[:]) != g.challenge || r.PostForm.Get("redirect_uri") != g.redirect { + http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) + return + } + nonce, aud := g.nonce, i.ClientID + if i.NonceOverride != "" { + nonce = i.NonceOverride + } + if i.AudienceOverride != "" { + aud = i.AudienceOverride + } + now := time.Now() + claims := map[string]any{ + "iss": i.Issuer(), "sub": g.user.Subject, "aud": aud, "nonce": nonce, + "iat": now.Unix(), "exp": now.Add(5 * time.Minute).Unix(), + "email": g.user.Email, "email_verified": g.user.EmailVerified, "name": g.user.Name, + } + raw, err := jwt.Signed(i.signer).Claims(claims).Serialize() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + writeJSON(w, map[string]any{"access_token": "at", "token_type": "Bearer", "expires_in": 300, "id_token": raw}) +} + +func writeJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) +} -- 2.54.1 From 3f21361995a3f51dedc8671ccab59a4344479abc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:30:43 +0100 Subject: [PATCH 20/22] feat(api): let each organization sign in through its own identity provider Owners manage OIDC providers under /settings/sso. Users start at /sso/. New users can be provisioned for verified emails in allowed domains; existing accounts are never matched by email and must link their SSO sign-in while signed in. Closes #4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 5 + internal/api/pages.go | 102 ++++- internal/api/server.go | 15 + internal/api/sso.go | 436 ++++++++++++++++++ internal/api/sso_admin.go | 246 +++++++++++ internal/api/sso_test.go | 288 ++++++++++++ internal/config/config.go | 26 ++ internal/i18n/i18n_test.go | 3 + internal/i18n/locales/de.json | 119 +++-- internal/i18n/locales/en.json | 119 +++-- internal/web/assets/app.js | 34 +- internal/web/auth.templ | 14 + internal/web/auth_templ.go | 96 +++- internal/web/console.templ | 30 +- internal/web/console_templ.go | 355 ++++++++++----- internal/web/layout.templ | 14 + internal/web/layout_templ.go | 97 +++- internal/web/sso.templ | 156 +++++++ internal/web/sso_templ.go | 807 ++++++++++++++++++++++++++++++++++ 19 files changed, 2731 insertions(+), 231 deletions(-) create mode 100644 internal/api/sso.go create mode 100644 internal/api/sso_admin.go create mode 100644 internal/api/sso_test.go create mode 100644 internal/web/sso.templ create mode 100644 internal/web/sso_templ.go diff --git a/.env.example b/.env.example index 095a33c..b1b024e 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,8 @@ UPTIME_CHECKER_REGION=local # Generate with: echo "k1:$(head -c32 /dev/urandom | base64)" UPTIME_SECRET_KEYS=dev:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + +UPTIME_PUBLIC_URL=http://localhost:8080 +# Lets organizations use IdPs on private networks (e.g. an internal Keycloak). +# auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud. +UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto diff --git a/internal/api/pages.go b/internal/api/pages.go index 2d208cd..398e84f 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -2,11 +2,15 @@ package api import ( "net/http" + "strings" "github.com/a-h/templ" "github.com/gin-gonic/gin" + "github.com/google/uuid" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) @@ -14,7 +18,16 @@ func (s *Server) registerPages(r gin.IRouter) { r.GET("/login", s.loginPage) r.GET("/signup", s.signupPage) r.GET("/", s.page("console.monitors.title", web.Dashboard)) - r.GET("/settings/security", s.page("security.title", web.Security)) + r.GET("/settings/security", s.securityPage) + r.GET("/settings/sso", s.ssoSettingsPage) +} + +// flashErrors lists the codes a redirect may ask a page to display. Anything +// else in the query string is ignored so links cannot inject messages. +var flashErrors = map[ssoError]bool{ + "sso_unavailable": true, "sso_provider_error": true, "sso_expired": true, + "sso_denied": true, "sso_not_member": true, "sso_not_provisioned": true, + "sso_link_required": true, "sso_identity_taken": true, "invalid_credentials": true, } func (s *Server) pageFor(c *gin.Context, titleID string) web.Page { @@ -22,6 +35,12 @@ func (s *Server) pageFor(c *gin.Context, titleID string) web.Page { if sess := auth.Current(c); sess != nil { p.CSRF = sess.CSRF } + if code := ssoError(c.Query("sso_error")); flashErrors[code] { + p.ErrorID = "error." + string(code) + } + if c.Query("sso") == "linked" { + p.NoticeID = "security.sso.linked" + } return p } @@ -67,6 +86,83 @@ func (s *Server) page(titleID string, view func(web.Page, web.Me) templ.Componen } } +func (s *Server) securityPage(c *gin.Context) { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login") + return + } + ctx := c.Request.Context() + me, err := s.loadMe(ctx, sess) + if err != nil { + internalError(c, err) + return + } + var ( + identities []web.Identity + canLink bool + ) + if sess.OrgID != uuid.Nil { + err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { + rows, err := q.ListUserIdentitiesInOrg(ctx, sess.UserID) + if err != nil { + return err + } + for _, r := range rows { + identities = append(identities, web.Identity{Provider: r.ProviderName, Email: deref(r.Email)}) + } + providers, err := q.ListEnabledSSOProviders(ctx) + canLink = len(providers) > 0 + return err + }) + if err != nil { + internalError(c, err) + return + } + } + web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), toWebMe(me), identities, canLink)) +} + +func (s *Server) ssoSettingsPage(c *gin.Context) { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login") + return + } + ctx := c.Request.Context() + me, err := s.loadMe(ctx, sess) + if err != nil { + internalError(c, err) + return + } + wm := toWebMe(me) + if !wm.IsOwner { + c.Redirect(http.StatusSeeOther, "/") + return + } + var rows []store.SsoProvider + err = s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { + rows, err = q.ListSSOProviders(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + view := web.SSOSettings{ + RedirectURL: s.sso.RedirectURL(), + LoginURL: s.cfg.PublicURL + "/sso/" + wm.ActiveSlug, + } + for _, r := range rows { + view.Providers = append(view.Providers, web.SSOProvider{ + ID: r.ID.String(), Name: r.Name, Issuer: r.Issuer, ClientID: r.ClientID, + HasSecret: r.ClientSecret != nil, AllowedDomains: strings.Join(r.AllowedDomains, ", "), + AutoProvision: r.AutoProvision, Enabled: r.Enabled, + }) + } + web.Render(c, http.StatusOK, web.SSOSettingsPage(s.pageFor(c, "sso.settings.title"), wm, view)) +} + func toWebMe(m meView) web.Me { out := web.Me{ Email: m.Email, @@ -77,6 +173,10 @@ func toWebMe(m meView) web.Me { } for _, o := range m.Orgs { out.Orgs = append(out.Orgs, web.Org{ID: o.ID.String(), Name: o.Name, Slug: o.Slug, IsOwner: o.IsOwner}) + if o.ID == m.ActiveOrg { + out.IsOwner = o.IsOwner + out.ActiveSlug = o.Slug + } } return out } diff --git a/internal/api/server.go b/internal/api/server.go index 537a894..c0ba9d3 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -16,6 +16,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" ) @@ -33,6 +34,7 @@ type Server struct { sessions *auth.Sessions limiter *auth.Limiter totp *auth.TOTPVerifier + sso *sso.Client } // Deps are the external resources a Server needs. @@ -46,6 +48,7 @@ type Deps struct { // New returns a Server. It does not register any routes; see Mount. func New(cfg config.API, d Deps) *Server { + allowPrivate := cfg.SSOAllowPrivate() return &Server{ cfg: cfg, log: d.Log, @@ -56,6 +59,7 @@ func New(cfg config.API, d Deps) *Server { sessions: auth.NewSessions(d.Redis, cfg.SessionIdle, cfg.SessionAbsolute), limiter: auth.NewLimiter(d.Redis), totp: auth.NewTOTPVerifier(d.Redis), + sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate), } } @@ -80,6 +84,17 @@ func (s *Server) Mount(r gin.IRouter) { me.POST("/totp/enable", s.totpEnable) me.POST("/totp/disable", s.totpDisable) + org := v1.Group("/org", auth.Require(), s.requireOwner()) + org.GET("/sso", s.listSSOProviders) + org.POST("/sso", s.createSSOProvider) + org.PUT("/sso/:id", s.updateSSOProvider) + org.DELETE("/sso/:id", s.deleteSSOProvider) + + g.GET("/sso", s.ssoLookup) + g.GET("/sso/callback", s.ssoCallback) + g.GET("/sso/:slug", s.ssoChoose) + g.GET("/sso/:slug/:provider", s.ssoStartProvider) + s.registerPages(g) } diff --git a/internal/api/sso.go b/internal/api/sso.go new file mode 100644 index 0000000..252e9b5 --- /dev/null +++ b/internal/api/sso.go @@ -0,0 +1,436 @@ +package api + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "net/url" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +const ( + ssoCookie = "__Host-sso" + ssoFlowTTL = 10 * time.Minute +) + +// ssoFlow is kept in Redis between the redirect to the IdP and the callback. +type ssoFlow struct { + Provider uuid.UUID `json:"provider"` + Org uuid.UUID `json:"org"` + Nonce string `json:"nonce"` + Verifier string `json:"verifier"` + // LinkUser is set when a signed-in user connects this IdP to their + // existing account instead of signing in. + LinkUser uuid.UUID `json:"link_user,omitempty"` +} + +// ssoError aborts a browser flow by redirecting with a code the target page +// translates. Unlike JSON errors, the user has navigated away from our page. +type ssoError string + +func ssoFlowKey(state string) string { + sum := sha256.Sum256([]byte(state)) + return "sso_flow:" + hex.EncodeToString(sum[:]) +} + +func (s *Server) ssoProvider(row store.SsoProvider) (sso.Provider, error) { + p := sso.Provider{Issuer: row.Issuer, ClientID: row.ClientID, Scopes: row.Scopes} + if row.ClientSecret != nil { + secret, err := s.keys.Open(row.ClientSecret, row.ID[:]) + if err != nil { + return p, err + } + p.ClientSecret = string(secret) + } + return p, nil +} + +// ssoLookup redirects the login page's slug form to the org's SSO URL. +func (s *Server) ssoLookup(c *gin.Context) { + slug := strings.ToLower(strings.TrimSpace(c.Query("org"))) + if slug == "" { + c.Redirect(http.StatusSeeOther, "/login") + return + } + c.Redirect(http.StatusSeeOther, "/sso/"+url.PathEscape(slug)) +} + +// ssoChoose starts the flow if the org has exactly one enabled provider and +// otherwise lets the user pick. +func (s *Server) ssoChoose(c *gin.Context) { + ctx := c.Request.Context() + if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) { + return + } + org, err := s.orgIDBySlug(ctx, c.Param("slug")) + if err != nil { + internalError(c, err) + return + } + var providers []store.ListEnabledSSOProvidersRow + if org != uuid.Nil { + err = s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error { + providers, err = q.ListEnabledSSOProviders(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + } + switch len(providers) { + case 0: + s.ssoAbort(c, uuid.Nil, "sso_unavailable") + case 1: + s.ssoStart(c, org, providers[0].ID) + default: + opts := make([]web.SSOOption, len(providers)) + for i, p := range providers { + opts[i] = web.SSOOption{Name: p.Name, URL: "/sso/" + url.PathEscape(c.Param("slug")) + "/" + p.ID.String() + linkSuffix(c)} + } + web.Render(c, http.StatusOK, web.SSOChooser(s.pageFor(c, "sso.choose.title"), opts)) + } +} + +func linkSuffix(c *gin.Context) string { + if c.Query("link") == "1" { + return "?link=1" + } + return "" +} + +func (s *Server) ssoStartProvider(c *gin.Context) { + ctx := c.Request.Context() + if !s.limitPage(c, "sso:ip:"+c.ClientIP(), 30, time.Minute) { + return + } + org, err := s.orgIDBySlug(ctx, c.Param("slug")) + if err != nil { + internalError(c, err) + return + } + id, err := uuid.Parse(c.Param("provider")) + if err != nil || org == uuid.Nil { + s.ssoAbort(c, uuid.Nil, "sso_unavailable") + return + } + s.ssoStart(c, org, id) +} + +func (s *Server) ssoStart(c *gin.Context, org, providerID uuid.UUID) { + ctx := c.Request.Context() + var linkUser uuid.UUID + if c.Query("link") == "1" { + sess := auth.Current(c) + if sess == nil { + c.Redirect(http.StatusSeeOther, "/login") + return + } + linkUser = sess.UserID + } + var row store.SsoProvider + err := s.db.Tx(ctx, tenant.Org(org, uuid.Nil), func(q *store.Queries) error { + var err error + row, err = q.GetSSOProvider(ctx, providerID) + return err + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) { + s.ssoAbort(c, linkUser, "sso_unavailable") + return + } + if err != nil { + internalError(c, err) + return + } + p, err := s.ssoProvider(row) + if err != nil { + internalError(c, err) + return + } + flow := sso.NewFlow(auth.RandomToken) + authURL, err := s.sso.AuthURL(ctx, p, flow) + if err != nil { + s.log.WarnContext(ctx, "sso discovery failed", "provider", providerID, "error", err) + s.ssoAbort(c, linkUser, "sso_provider_error") + return + } + state, _ := json.Marshal(ssoFlow{Provider: row.ID, Org: org, Nonce: flow.Nonce, Verifier: flow.Verifier, LinkUser: linkUser}) + if err := s.rdb.Set(ctx, ssoFlowKey(flow.State), state, ssoFlowTTL).Err(); err != nil { + internalError(c, err) + return + } + // Binding the state to this browser stops an attacker from completing + // their own flow in a victim's browser (login CSRF). + setCookie(c, ssoCookie, flow.State, int(ssoFlowTTL.Seconds())) + c.Redirect(http.StatusFound, authURL) +} + +func (s *Server) ssoCallback(c *gin.Context) { + ctx := c.Request.Context() + state := c.Query("state") + cookie, _ := c.Cookie(ssoCookie) + setCookie(c, ssoCookie, "", -1) + if state == "" || cookie != state { + s.ssoAbort(c, uuid.Nil, "sso_expired") + return + } + raw, err := s.rdb.GetDel(ctx, ssoFlowKey(state)).Bytes() + if err != nil { + s.ssoAbort(c, uuid.Nil, "sso_expired") + return + } + var f ssoFlow + if err := json.Unmarshal(raw, &f); err != nil { + internalError(c, err) + return + } + if c.Query("error") != "" { + s.ssoAbort(c, f.LinkUser, "sso_denied") + return + } + + var row store.SsoProvider + err = s.db.Tx(ctx, tenant.Org(f.Org, uuid.Nil), func(q *store.Queries) error { + row, err = q.GetSSOProvider(ctx, f.Provider) + return err + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !row.Enabled) { + s.ssoAbort(c, f.LinkUser, "sso_unavailable") + return + } + if err != nil { + internalError(c, err) + return + } + p, err := s.ssoProvider(row) + if err != nil { + internalError(c, err) + return + } + claims, err := s.sso.Exchange(ctx, p, sso.Flow{State: state, Nonce: f.Nonce, Verifier: f.Verifier}, c.Query("code")) + if err != nil { + s.log.WarnContext(ctx, "sso exchange failed", "provider", row.ID, "error", err) + s.ssoAbort(c, f.LinkUser, "sso_provider_error") + return + } + + if f.LinkUser != uuid.Nil { + s.ssoLink(c, row, f.LinkUser, claims) + return + } + userID, code, err := s.ssoResolveUser(ctx, row, claims) + if err != nil { + internalError(c, err) + return + } + if code != "" { + s.ssoAbort(c, uuid.Nil, code) + return + } + var user store.User + err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + user, err = q.GetUser(ctx, userID) + return err + }) + if err != nil { + internalError(c, err) + return + } + if user.DisabledAt != nil { + s.ssoAbort(c, uuid.Nil, "invalid_credentials") + return + } + if old := auth.Current(c); old != nil { + _ = s.sessions.Delete(ctx, old) + } + locale := deref(user.Locale) + if locale == "" { + locale = i18n.Lang(ctx) + } + sess, err := s.sessions.Create(ctx, userID, row.OrgID, locale) + if err != nil { + internalError(c, err) + return + } + auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds())) + c.Redirect(http.StatusSeeOther, "/") +} + +// ssoResolveUser maps an IdP identity to a user. It returns a non-empty +// error code when sign-in must be refused. +// +// Existing accounts are only ever reached through a stored identity. A +// matching email is not enough: the org controls its IdP and could assert +// the address of a user who also belongs to other orgs. +func (s *Server) ssoResolveUser(ctx context.Context, row store.SsoProvider, cl sso.Claims) (uuid.UUID, ssoError, error) { + var ( + userID uuid.UUID + code ssoError + ) + email := normalizeEmail(cl.Email) + err := s.db.Tx(ctx, tenant.Org(row.OrgID, uuid.Nil), func(q *store.Queries) error { + ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject}) + switch { + case err == nil: + member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: ident.UserID}) + if err != nil { + return err + } + if !member { + code = "sso_not_member" + return nil + } + userID = ident.UserID + return q.TouchIdentity(ctx, store.TouchIdentityParams{ProviderID: row.ID, Subject: cl.Subject, Email: nonEmpty(email)}) + case !errors.Is(err, pgx.ErrNoRows): + return err + } + + if !row.AutoProvision || email == "" || !cl.EmailVerified || !domainAllowed(email, row.AllowedDomains) { + code = "sso_not_provisioned" + return nil + } + if _, err := q.GetUserByEmail(ctx, email); err == nil { + code = "sso_link_required" + return nil + } else if !errors.Is(err, pgx.ErrNoRows) { + return err + } + u, err := q.CreateUser(ctx, store.CreateUserParams{ + Email: email, + DisplayName: truncate(strings.TrimSpace(cl.Name), 200), + Locale: ptr(i18n.Lang(ctx)), + }) + if err != nil { + return err + } + if err := q.AddMembership(ctx, store.AddMembershipParams{OrgID: row.OrgID, UserID: u.ID}); err != nil { + return err + } + userID = u.ID + return q.CreateIdentity(ctx, store.CreateIdentityParams{ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: u.ID, Email: nonEmpty(email)}) + }) + return userID, code, err +} + +func (s *Server) ssoLink(c *gin.Context, row store.SsoProvider, userID uuid.UUID, cl sso.Claims) { + ctx := c.Request.Context() + sess := auth.Current(c) + if sess == nil || sess.UserID != userID { + s.ssoAbort(c, uuid.Nil, "sso_expired") + return + } + var code ssoError + err := s.db.Tx(ctx, tenant.Org(row.OrgID, userID), func(q *store.Queries) error { + member, err := q.IsMember(ctx, store.IsMemberParams{OrgID: row.OrgID, UserID: userID}) + if err != nil { + return err + } + if !member { + code = "sso_not_member" + return nil + } + ident, err := q.GetIdentity(ctx, store.GetIdentityParams{ProviderID: row.ID, Subject: cl.Subject}) + switch { + case err == nil && ident.UserID == userID: + return nil + case err == nil: + code = "sso_identity_taken" + return nil + case !errors.Is(err, pgx.ErrNoRows): + return err + } + return q.CreateIdentity(ctx, store.CreateIdentityParams{ + ProviderID: row.ID, Subject: cl.Subject, OrgID: row.OrgID, UserID: userID, Email: nonEmpty(normalizeEmail(cl.Email)), + }) + }) + if err != nil { + internalError(c, err) + return + } + if code != "" { + s.ssoAbort(c, userID, code) + return + } + c.Redirect(http.StatusSeeOther, "/settings/security?sso=linked") +} + +// ssoAbort sends the browser back to where the flow started with an error +// code the page renders in the user's language. +func (s *Server) ssoAbort(c *gin.Context, linkUser uuid.UUID, code ssoError) { + target := "/login" + if linkUser != uuid.Nil { + target = "/settings/security" + } + c.Redirect(http.StatusSeeOther, target+"?sso_error="+url.QueryEscape(string(code))) +} + +func (s *Server) orgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) { + var id uuid.UUID + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + id, err = q.OrgIDBySlug(ctx, strings.ToLower(slug)) + return err + }) + return id, err +} + +func (s *Server) limitPage(c *gin.Context, key string, n int, window time.Duration) bool { + ok, err := s.limiter.Allow(c.Request.Context(), key, n, window) + if err != nil { + internalError(c, err) + return false + } + if !ok { + c.Header("Retry-After", "60") + c.AbortWithStatus(http.StatusTooManyRequests) + return false + } + return true +} + +func domainAllowed(email string, allowed []string) bool { + if len(allowed) == 0 { + return true + } + at := strings.LastIndexByte(email, '@') + if at < 0 { + return false + } + domain := email[at+1:] + for _, d := range allowed { + if domain == d { + return true + } + } + return false +} + +func nonEmpty(s string) *string { + if s == "" { + return nil + } + return &s +} + +func truncate(s string, n int) string { + if r := []rune(s); len(r) > n { + return string(r[:n]) + } + return s +} diff --git a/internal/api/sso_admin.go b/internal/api/sso_admin.go new file mode 100644 index 0000000..5d72986 --- /dev/null +++ b/internal/api/sso_admin.go @@ -0,0 +1,246 @@ +package api + +import ( + "errors" + "net/http" + "regexp" + "slices" + "strings" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const ctxOrgKey = "api.org" + +// requireOwner admits only the owner of the session's active org. It is a +// stand-in until role-based permissions exist (#6). +func (s *Server) requireOwner() gin.HandlerFunc { + return func(c *gin.Context) { + sess := auth.Current(c) + if sess == nil || sess.OrgID == uuid.Nil { + fail(c, http.StatusForbidden, "forbidden") + return + } + ctx := c.Request.Context() + var m store.Membership + err := s.db.Tx(ctx, tenant.Org(sess.OrgID, sess.UserID), func(q *store.Queries) error { + var err error + m, err = q.GetMembership(ctx, store.GetMembershipParams{OrgID: sess.OrgID, UserID: sess.UserID}) + return err + }) + if errors.Is(err, pgx.ErrNoRows) || (err == nil && !m.IsOwner) { + fail(c, http.StatusForbidden, "forbidden") + return + } + if err != nil { + internalError(c, err) + return + } + c.Set(ctxOrgKey, sess.OrgID) + c.Next() + } +} + +func orgOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxOrgKey).(uuid.UUID) } + +type ssoProviderView struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + Issuer string `json:"issuer"` + ClientID string `json:"client_id"` + HasClientSecret bool `json:"has_client_secret"` + Scopes []string `json:"scopes"` + AllowedDomains []string `json:"allowed_domains"` + AutoProvision bool `json:"auto_provision"` + Enabled bool `json:"enabled"` +} + +func viewSSOProvider(p store.SsoProvider) ssoProviderView { + return ssoProviderView{ + ID: p.ID, Name: p.Name, Issuer: p.Issuer, ClientID: p.ClientID, + HasClientSecret: p.ClientSecret != nil, Scopes: p.Scopes, + AllowedDomains: p.AllowedDomains, AutoProvision: p.AutoProvision, Enabled: p.Enabled, + } +} + +type ssoProviderRequest struct { + Name string `json:"name" binding:"required,max=100"` + Issuer string `json:"issuer" binding:"required,max=500"` + ClientID string `json:"client_id" binding:"required,max=500"` + // Empty on update keeps the stored secret; it is never returned. + ClientSecret string `json:"client_secret" binding:"max=2000"` + Scopes []string `json:"scopes" binding:"max=20,dive,max=100"` + AllowedDomains []string `json:"allowed_domains" binding:"max=50,dive,max=253"` + AutoProvision bool `json:"auto_provision"` + Enabled *bool `json:"enabled"` +} + +var domainRE = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`) + +// normalize cleans the request and returns an error code for invalid input. +func (r *ssoProviderRequest) normalize() string { + r.Name = strings.TrimSpace(r.Name) + r.Issuer = strings.TrimSuffix(strings.TrimSpace(r.Issuer), "/") + r.ClientID = strings.TrimSpace(r.ClientID) + if r.Name == "" || r.ClientID == "" { + return "invalid_input" + } + scopes := []string{"openid"} + for _, sc := range r.Scopes { + if sc = strings.TrimSpace(sc); sc != "" && !slices.Contains(scopes, sc) { + scopes = append(scopes, sc) + } + } + if len(r.Scopes) == 0 { + scopes = append(scopes, "email", "profile") + } + r.Scopes = scopes + domains := []string{} + for _, d := range r.AllowedDomains { + d = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(d)), "@") + if d == "" { + continue + } + if !domainRE.MatchString(d) { + return "invalid_domain" + } + if !slices.Contains(domains, d) { + domains = append(domains, d) + } + } + r.AllowedDomains = domains + return "" +} + +func (s *Server) listSSOProviders(c *gin.Context) { + ctx := c.Request.Context() + var rows []store.SsoProvider + err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + var err error + rows, err = q.ListSSOProviders(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]ssoProviderView, len(rows)) + for i, r := range rows { + out[i] = viewSSOProvider(r) + } + c.JSON(http.StatusOK, gin.H{"providers": out, "redirect_url": s.sso.RedirectURL()}) +} + +func (s *Server) validateSSORequest(c *gin.Context, req *ssoProviderRequest) bool { + if code := req.normalize(); code != "" { + fail(c, http.StatusUnprocessableEntity, code) + return false + } + if err := s.sso.ValidateIssuer(c.Request.Context(), req.Issuer); err != nil { + code := "sso_discovery_failed" + switch { + case errors.Is(err, sso.ErrInvalidIssuer): + code = "sso_invalid_issuer" + case errors.Is(err, sso.ErrForbiddenAddress): + code = "sso_forbidden_address" + } + fail(c, http.StatusUnprocessableEntity, code) + return false + } + return true +} + +func (s *Server) createSSOProvider(c *gin.Context) { + var req ssoProviderRequest + if !bind(c, &req) || !s.validateSSORequest(c, &req) { + return + } + ctx := c.Request.Context() + id := uuid.New() + var secret []byte + if req.ClientSecret != "" { + secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) + } + var row store.SsoProvider + err := s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + var err error + row, err = q.CreateSSOProvider(ctx, store.CreateSSOProviderParams{ + ID: id, OrgID: orgOf(c), Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, + ClientSecret: secret, Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, + AutoProvision: req.AutoProvision, Enabled: req.Enabled == nil || *req.Enabled, + }) + return err + }) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusCreated, viewSSOProvider(row)) +} + +func (s *Server) updateSSOProvider(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + var req ssoProviderRequest + if !bind(c, &req) || !s.validateSSORequest(c, &req) { + return + } + ctx := c.Request.Context() + var secret []byte + if req.ClientSecret != "" { + secret = s.keys.Seal([]byte(req.ClientSecret), id[:]) + } + var row store.SsoProvider + err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + var err error + row, err = q.UpdateSSOProvider(ctx, store.UpdateSSOProviderParams{ + ID: id, Name: req.Name, Issuer: req.Issuer, ClientID: req.ClientID, ClientSecret: secret, + Scopes: req.Scopes, AllowedDomains: req.AllowedDomains, AutoProvision: req.AutoProvision, + Enabled: req.Enabled == nil || *req.Enabled, + }) + return err + }) + if errors.Is(err, pgx.ErrNoRows) { + fail(c, http.StatusNotFound, "not_found") + return + } + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, viewSSOProvider(row)) +} + +func (s *Server) deleteSSOProvider(c *gin.Context) { + id, err := uuid.Parse(c.Param("id")) + if err != nil { + fail(c, http.StatusNotFound, "not_found") + return + } + ctx := c.Request.Context() + var n int64 + err = s.db.Tx(ctx, tenant.Org(orgOf(c), auth.Current(c).UserID), func(q *store.Queries) error { + var err error + n, err = q.DeleteSSOProvider(ctx, id) + return err + }) + if err != nil { + internalError(c, err) + return + } + if n == 0 { + fail(c, http.StatusNotFound, "not_found") + return + } + c.Status(http.StatusNoContent) +} diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go new file mode 100644 index 0000000..9c9d57d --- /dev/null +++ b/internal/api/sso_test.go @@ -0,0 +1,288 @@ +package api_test + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "encoding/json" + "io" + "log/slog" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "os" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" + "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" + "git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +type env struct { + srv *httptest.Server + dbPool *pgxpool.Pool +} + +func newEnv(t *testing.T) *env { + t.Helper() + dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL") + if dsn == "" || redisURL == "" { + t.Skip("UPTIME_TEST_DATABASE_URL and UPTIME_TEST_REDIS_URL must be set") + } + ctx := context.Background() + if _, err := migrations.Up(ctx, dsn); err != nil { + t.Fatalf("migrations.Up() failed: %v", err) + } + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + opts, err := redis.ParseURL(redisURL) + if err != nil { + t.Fatal(err) + } + rdb := redis.NewClient(opts) + t.Cleanup(func() { _ = rdb.Close() }) + + key := make([]byte, 32) + _, _ = rand.Read(key) + keys, err := sealed.Parse("t:" + base64.StdEncoding.EncodeToString(key)) + if err != nil { + t.Fatal(err) + } + catalog, err := i18n.Load() + if err != nil { + t.Fatal(err) + } + log := slog.New(slog.DiscardHandler) + + e := &env{dbPool: pool} + r := platform.NewRouter(log) + e.srv = httptest.NewUnstartedServer(r) + e.srv.StartTLS() + t.Cleanup(e.srv.Close) + + cfg := config.API{ + Common: config.Common{Edition: config.EditionSelfHosted}, + Signup: config.SignupOpen, + SessionIdle: time.Hour, + SessionAbsolute: 24 * time.Hour, + PublicURL: e.srv.URL, + SSOPrivateNetworks: "true", + } + api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r) + return e +} + +// browser is a cookie-keeping client that follows redirects like a browser. +type browser struct { + t *testing.T + base string + hc *http.Client + csrf string +} + +func (e *env) browser(t *testing.T) *browser { + jar, _ := cookiejar.New(nil) + // Client() returns a shared instance; copy it so each browser has its own jar. + hc := *e.srv.Client() + hc.Jar = jar + return &browser{t: t, base: e.srv.URL, hc: &hc} +} + +func (b *browser) do(method, path string, body any) (int, map[string]any) { + b.t.Helper() + var rd io.Reader + if body != nil { + raw, _ := json.Marshal(body) + rd = bytes.NewReader(raw) + } + req, _ := http.NewRequest(method, b.base+path, rd) + req.Header.Set("Content-Type", "application/json") + if b.csrf != "" { + req.Header.Set("X-CSRF-Token", b.csrf) + } + resp, err := b.hc.Do(req) + if err != nil { + b.t.Fatalf("%s %s failed: %v", method, path, err) + } + defer func() { _ = resp.Body.Close() }() + var out map[string]any + _ = json.NewDecoder(resp.Body).Decode(&out) + if tok, ok := out["csrf_token"].(string); ok { + b.csrf = tok + } + return resp.StatusCode, out +} + +// visit follows redirects and returns the final URL. +func (b *browser) visit(path string) *url.URL { + b.t.Helper() + resp, err := b.hc.Get(b.base + path) + if err != nil { + b.t.Fatalf("GET %s failed: %v", path, err) + } + _ = resp.Body.Close() + return resp.Request.URL +} + +func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") } + +func (b *browser) signup(email, slug string) { + b.t.Helper() + st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{ + "email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug, + }) + if st != http.StatusOK { + b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body) + } +} + +func TestSSO(t *testing.T) { + e := newEnv(t) + idp := ssotest.New(t) + slug := uniq("sso-") + domain := uniq("d") + ".test" + + owner := e.browser(t) + owner.signup("owner@"+domain, slug) + + st, body := owner.do("POST", "/api/v1/org/sso", map[string]any{ + "name": "Corp IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret, + "allowed_domains": []string{domain}, "auto_provision": true, + }) + if st != http.StatusCreated { + t.Fatalf("create provider = %d %v, want 201", st, body) + } + if body["has_client_secret"] != true || body["client_secret"] != nil { + t.Errorf("create provider response = %v, want has_client_secret and no secret", body) + } + + t.Run("other org cannot see provider", func(t *testing.T) { + other := e.browser(t) + other.signup("x@"+uniq("o")+".test", uniq("other-")) + st, body := other.do("GET", "/api/v1/org/sso", nil) + if st != http.StatusOK || len(body["providers"].([]any)) != 0 { + t.Errorf("GET /api/v1/org/sso as other org = %d %v, want 200 with no providers", st, body) + } + }) + + t.Run("auto provisioning", func(t *testing.T) { + idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "new@" + domain, EmailVerified: true, Name: "New"}) + u := e.browser(t) + if got := u.visit("/sso/" + slug); got.Path != "/" || got.Query().Get("sso_error") != "" { + t.Fatalf("SSO login landed on %s, want /", got) + } + st, me := u.do("GET", "/api/v1/me", nil) + if st != http.StatusOK || me["email"] != "new@"+domain { + t.Errorf("GET /api/v1/me = %d %v, want new@%s", st, me, domain) + } + st, _ = u.do("GET", "/api/v1/org/sso", nil) + if st != http.StatusForbidden { + t.Errorf("GET /api/v1/org/sso as member = %d, want 403", st) + } + }) + + t.Run("unverified email is not provisioned", func(t *testing.T) { + idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "unverified@" + domain, EmailVerified: false}) + if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" { + t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got) + } + }) + + t.Run("foreign domain is not provisioned", func(t *testing.T) { + idp.SetUser(ssotest.User{Subject: uniq("s"), Email: "x@elsewhere.test", EmailVerified: true}) + if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_not_provisioned" { + t.Errorf("SSO login landed on %s, want sso_error=sso_not_provisioned", got) + } + }) + + t.Run("existing email requires explicit linking", func(t *testing.T) { + subject := uniq("s") + idp.SetUser(ssotest.User{Subject: subject, Email: "owner@" + domain, EmailVerified: true}) + if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_link_required" { + t.Fatalf("SSO login landed on %s, want sso_error=sso_link_required", got) + } + + if got := owner.visit("/sso/" + slug + "?link=1"); got.Path != "/settings/security" || got.Query().Get("sso") != "linked" { + t.Fatalf("link flow landed on %s, want /settings/security?sso=linked", got) + } + fresh := e.browser(t) + if got := fresh.visit("/sso/" + slug); got.Path != "/" { + t.Fatalf("SSO login after linking landed on %s, want /", got) + } + if _, me := fresh.do("GET", "/api/v1/me", nil); me["email"] != "owner@"+domain { + t.Errorf("GET /api/v1/me after linked login = %v, want owner", me) + } + }) + + t.Run("callback without browser binding is rejected", func(t *testing.T) { + attacker := e.browser(t) + attacker.hc.CheckRedirect = func(req *http.Request, _ []*http.Request) error { + if strings.HasPrefix(req.URL.Path, "/sso/callback") { + return http.ErrUseLastResponse + } + return nil + } + resp, err := attacker.hc.Get(attacker.base + "/sso/" + slug) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + callback := resp.Header.Get("Location") + if got := e.browser(t).visit(strings.TrimPrefix(callback, attacker.base)); got.Query().Get("sso_error") != "sso_expired" { + t.Errorf("replaying callback in another browser landed on %s, want sso_error=sso_expired", got) + } + }) + + t.Run("disabled provider", func(t *testing.T) { + _, list := owner.do("GET", "/api/v1/org/sso", nil) + p := list["providers"].([]any)[0].(map[string]any) + st, body := owner.do("PUT", "/api/v1/org/sso/"+p["id"].(string), map[string]any{ + "name": p["name"], "issuer": p["issuer"], "client_id": p["client_id"], "enabled": false, + }) + if st != http.StatusOK || body["has_client_secret"] != true { + t.Fatalf("PUT provider = %d %v, want 200 keeping the secret", st, body) + } + if got := e.browser(t).visit("/sso/" + slug); got.Query().Get("sso_error") != "sso_unavailable" { + t.Errorf("SSO login with disabled provider landed on %s, want sso_error=sso_unavailable", got) + } + }) +} + +func TestSSOProviderValidation(t *testing.T) { + e := newEnv(t) + owner := e.browser(t) + owner.signup("o@"+uniq("v")+".test", uniq("val-")) + tests := []struct { + name string + body map[string]any + want string + }{ + {"bad scheme", map[string]any{"name": "x", "issuer": "ftp://idp.test", "client_id": "c"}, "sso_invalid_issuer"}, + {"unreachable", map[string]any{"name": "x", "issuer": "http://127.0.0.1:1", "client_id": "c"}, "sso_discovery_failed"}, + {"bad domain", map[string]any{"name": "x", "issuer": "https://idp.test", "client_id": "c", "allowed_domains": []string{"not a domain"}}, "invalid_domain"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + st, body := owner.do("POST", "/api/v1/org/sso", tt.body) + if st != http.StatusUnprocessableEntity || body["error"] != tt.want { + t.Errorf("POST /api/v1/org/sso = %d %v, want 422 %s", st, body["error"], tt.want) + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 92d7ae8..3aead1d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -5,6 +5,8 @@ package config import ( "fmt" "log/slog" + "net/url" + "strings" "time" "github.com/caarlos0/env/v11" @@ -61,6 +63,22 @@ type API struct { Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"` SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"` SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` + // PublicURL is the externally reachable base URL, used for SSO callbacks. + PublicURL string `env:"UPTIME_PUBLIC_URL" envDefault:"http://localhost:8080"` + // SSOPrivateNetworks is "auto", "true" or "false". Auto allows + // organizations' IdPs on private networks only in the self-hosted edition. + SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"` +} + +// SSOAllowPrivate resolves SSOPrivateNetworks. +func (a API) SSOAllowPrivate() bool { + switch a.SSOPrivateNetworks { + case "true": + return true + case "false": + return false + } + return a.Edition == EditionSelfHosted } // Validate checks API-specific settings in addition to Common.Validate. @@ -76,6 +94,14 @@ func (a API) Validate() error { default: return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup) } + switch a.SSOPrivateNetworks { + case "auto", "true", "false": + default: + return fmt.Errorf("config: UPTIME_SSO_ALLOW_PRIVATE_NETWORKS must be auto, true or false") + } + if u, err := url.Parse(a.PublicURL); err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || strings.HasSuffix(a.PublicURL, "/") { + return fmt.Errorf("config: UPTIME_PUBLIC_URL must be an absolute http(s) URL without trailing slash") + } if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle { return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0") } diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 614fe8c..998a6d6 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -61,6 +61,9 @@ var usagePatterns = []struct { {regexp.MustCompile(`i18n\.T\(ctx, "([a-z0-9_.]+)"[,)]`), ""}, {regexp.MustCompile(`\bfail\(c, [^,]+, "([a-z_]+)"`), "error."}, {regexp.MustCompile(`\b(?:pageFor\(c|s\.page\()(?:, )?"([a-z0-9_.]+)"`), ""}, + {regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), "error."}, + {regexp.MustCompile(`return "(invalid_[a-z_]+)"`), "error."}, + {regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`), ""}, } // TestUsedKeysExist scans the source tree for literal message IDs so a typo diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index b59be86..df5e12e 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1,57 +1,96 @@ { "app.network_error": "Verbindung fehlgeschlagen.", - "lang.en": "English", - "lang.de": "Deutsch", - - "auth.login.title": "Anmelden", - "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", - "auth.login.submit": "Weiter", - "auth.login.no_account": "Noch kein Konto?", - "auth.login.to_signup": "Registrieren", - "auth.signup.title": "Konto anlegen", - "auth.signup.submit": "Anlegen", - "auth.signup.to_login": "Zur Anmeldung", - "auth.field.name": "Name", + "auth.field.code": "Code", "auth.field.email": "E-Mail", - "auth.field.password": "Passwort", + "auth.field.name": "Name", "auth.field.new_password": "Passwort (min. {{.Min}} Zeichen)", "auth.field.org_name": "Organisation", "auth.field.org_slug": "Kurzname (a–z, 0–9, -)", - "auth.field.code": "Code", - - "console.nav.security": "Sicherheit", + "auth.field.password": "Passwort", + "auth.login.no_account": "Noch kein Konto?", + "auth.login.submit": "Weiter", + "auth.login.title": "Anmelden", + "auth.login.to_signup": "Registrieren", + "auth.login.totp_hint": "Code aus der Authenticator-App eingeben.", + "auth.signup.submit": "Anlegen", + "auth.signup.title": "Konto anlegen", + "auth.signup.to_login": "Zur Anmeldung", + "auth.sso.heading": "Single Sign-on", + "auth.sso.org_placeholder": "Kurzname der Organisation", + "auth.sso.submit": "Weiter", + "common.no": "nein", + "common.save": "Speichern", + "common.yes": "ja", + "console.monitors.empty": "Noch keine Monitore angelegt.", + "console.monitors.title": "Monitore", "console.nav.logout": "Abmelden", + "console.nav.security": "Sicherheit", + "console.nav.sso": "SSO", "console.totp_missing": "Deine Organisation verlangt Zwei-Faktor-Anmeldung.", "console.totp_missing_action": "Jetzt einrichten", - "console.monitors.title": "Monitore", - "console.monitors.empty": "Noch keine Monitore angelegt.", - - "security.title": "Sicherheit", - "security.totp.heading": "Zwei-Faktor (TOTP)", - "security.totp.active": "aktiv", - "security.totp.inactive": "nicht eingerichtet", - "security.totp.disable": "Deaktivieren", - "security.totp.current_code": "Aktueller Code", - "security.totp.start": "Einrichten", - "security.totp.qr_alt": "QR-Code für die Authenticator-App", - "security.totp.app_code": "Code aus der App", - "security.totp.confirm": "Bestätigen", - + "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", + "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", + "error.invalid_code": "Code ungültig.", + "error.invalid_credentials": "E-Mail oder Passwort falsch.", + "error.invalid_domain": "Eine der Domains ist ungültig.", "error.invalid_input": "Eingaben prüfen.", + "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", + "error.no_password": "Konto ohne Passwort.", + "error.not_found": "Nicht gefunden.", + "error.org_not_found": "Organisation nicht gefunden.", + "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", "error.rate_limited": "Zu viele Versuche, bitte später erneut.", "error.signup_closed": "Registrierung ist deaktiviert.", - "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", - "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.slug_taken": "Dieser Kurzname ist bereits vergeben.", - "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", - "error.invalid_credentials": "E-Mail oder Passwort falsch.", - "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", - "error.invalid_code": "Code ungültig.", - "error.org_not_found": "Organisation nicht gefunden.", + "error.sso_denied": "Die Anmeldung wurde beim Identity Provider abgebrochen.", + "error.sso_discovery_failed": "Der Identity Provider ist nicht erreichbar oder lieferte keine gültige Konfiguration.", + "error.sso_expired": "Der Anmeldeversuch ist abgelaufen, bitte neu starten.", + "error.sso_forbidden_address": "Der Issuer zeigt auf eine nicht öffentliche Adresse.", + "error.sso_identity_taken": "Diese SSO-Anmeldung ist bereits mit einem anderen Konto verknüpft.", + "error.sso_invalid_issuer": "Der Issuer muss eine https-URL ohne Query und Zugangsdaten sein.", + "error.sso_link_required": "Es gibt bereits ein Konto mit dieser E-Mail. Melde dich mit Passwort an und verknüpfe SSO unter Sicherheit.", + "error.sso_not_member": "Dein Konto ist kein Mitglied dieser Organisation.", + "error.sso_not_provisioned": "Für diese Anmeldung gibt es kein Konto. Bitte lass dich von einem Admin einladen.", + "error.sso_provider_error": "Der Identity Provider konnte die Anmeldung nicht abschließen.", + "error.sso_unavailable": "Für diese Organisation ist kein Single Sign-on verfügbar.", "error.totp_already_enabled": "TOTP ist bereits aktiv.", - "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", - "error.no_password": "Konto ohne Passwort.", - "error.unsupported_locale": "Sprache wird nicht unterstützt." + "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", + "error.unsupported_locale": "Sprache wird nicht unterstützt.", + "lang.de": "Deutsch", + "lang.en": "English", + "security.sso.heading": "Single Sign-on", + "security.sso.link": "SSO-Anmeldung verknüpfen", + "security.sso.linked": "SSO-Anmeldung verknüpft.", + "security.sso.none": "In dieser Organisation ist keine SSO-Anmeldung verknüpft.", + "security.title": "Sicherheit", + "security.totp.active": "aktiv", + "security.totp.app_code": "Code aus der App", + "security.totp.confirm": "Bestätigen", + "security.totp.current_code": "Aktueller Code", + "security.totp.disable": "Deaktivieren", + "security.totp.heading": "Zwei-Faktor (TOTP)", + "security.totp.inactive": "nicht eingerichtet", + "security.totp.qr_alt": "QR-Code für die Authenticator-App", + "security.totp.start": "Einrichten", + "sso.action.delete": "Provider löschen", + "sso.action.delete_confirm": "Diesen Provider löschen? Verknüpfte Anmeldungen funktionieren dann nicht mehr.", + "sso.action.edit": "Bearbeiten", + "sso.choose.title": "Anmeldung wählen", + "sso.field.allowed_domains": "Erlaubte E-Mail-Domains", + "sso.field.allowed_domains_hint": "Kommagetrennt. Gilt nur für automatisch angelegte Konten; leer erlaubt jede Domain.", + "sso.field.auto_provision": "Konten automatisch anlegen", + "sso.field.client_id": "Client-ID", + "sso.field.client_secret": "Client-Secret", + "sso.field.client_secret_keep": "unverändert", + "sso.field.enabled": "Aktiv", + "sso.field.issuer": "Issuer-URL", + "sso.field.name": "Name", + "sso.settings.add": "Provider hinzufügen", + "sso.settings.intro": "Mitglieder dieser Organisation können sich über euren eigenen OpenID-Connect-Identity-Provider anmelden. Tragt die Redirect-URL unten bei eurem Provider als erlaubten Callback ein.", + "sso.settings.login_url": "Anmelde-URL", + "sso.settings.redirect_url": "Redirect-URL", + "sso.settings.title": "Single Sign-on" } diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 8023c23..a480d22 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -1,57 +1,96 @@ { "app.network_error": "Connection failed.", - "lang.en": "English", - "lang.de": "Deutsch", - - "auth.login.title": "Sign in", - "auth.login.totp_hint": "Enter the code from your authenticator app.", - "auth.login.submit": "Continue", - "auth.login.no_account": "No account yet?", - "auth.login.to_signup": "Sign up", - "auth.signup.title": "Create account", - "auth.signup.submit": "Create", - "auth.signup.to_login": "Back to sign in", - "auth.field.name": "Name", + "auth.field.code": "Code", "auth.field.email": "Email", - "auth.field.password": "Password", + "auth.field.name": "Name", "auth.field.new_password": "Password (min. {{.Min}} characters)", "auth.field.org_name": "Organization", "auth.field.org_slug": "Short name (a–z, 0–9, -)", - "auth.field.code": "Code", - - "console.nav.security": "Security", + "auth.field.password": "Password", + "auth.login.no_account": "No account yet?", + "auth.login.submit": "Continue", + "auth.login.title": "Sign in", + "auth.login.to_signup": "Sign up", + "auth.login.totp_hint": "Enter the code from your authenticator app.", + "auth.signup.submit": "Create", + "auth.signup.title": "Create account", + "auth.signup.to_login": "Back to sign in", + "auth.sso.heading": "Single sign-on", + "auth.sso.org_placeholder": "Organization short name", + "auth.sso.submit": "Continue", + "common.no": "no", + "common.save": "Save", + "common.yes": "yes", + "console.monitors.empty": "No monitors yet.", + "console.monitors.title": "Monitors", "console.nav.logout": "Sign out", + "console.nav.security": "Security", + "console.nav.sso": "SSO", "console.totp_missing": "Your organization requires two-factor sign-in.", "console.totp_missing_action": "Set up now", - "console.monitors.title": "Monitors", - "console.monitors.empty": "No monitors yet.", - - "security.title": "Security", - "security.totp.heading": "Two-factor (TOTP)", - "security.totp.active": "active", - "security.totp.inactive": "not set up", - "security.totp.disable": "Disable", - "security.totp.current_code": "Current code", - "security.totp.start": "Set up", - "security.totp.qr_alt": "QR code for your authenticator app", - "security.totp.app_code": "Code from the app", - "security.totp.confirm": "Confirm", - + "error.email_taken": "This email address is already registered.", + "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", + "error.invalid_code": "Invalid code.", + "error.invalid_credentials": "Wrong email or password.", + "error.invalid_domain": "One of the domains is not valid.", "error.invalid_input": "Please check your input.", + "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.mfa_expired": "Sign-in expired, please start again.", + "error.no_password": "This account has no password.", + "error.not_found": "Not found.", + "error.org_not_found": "Organization not found.", + "error.password_too_short": "The password needs at least {{.Min}} characters.", "error.rate_limited": "Too many attempts, please try again later.", "error.signup_closed": "Sign-up is disabled.", - "error.password_too_short": "The password needs at least {{.Min}} characters.", - "error.email_taken": "This email address is already registered.", "error.slug_taken": "This short name is already taken.", - "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", - "error.invalid_credentials": "Wrong email or password.", - "error.mfa_expired": "Sign-in expired, please start again.", - "error.invalid_code": "Invalid code.", - "error.org_not_found": "Organization not found.", + "error.sso_denied": "Sign-in was cancelled at the identity provider.", + "error.sso_discovery_failed": "The identity provider could not be reached or returned no valid configuration.", + "error.sso_expired": "The sign-in attempt expired, please start again.", + "error.sso_forbidden_address": "The issuer points to a non-public address.", + "error.sso_identity_taken": "This SSO sign-in is already linked to another account.", + "error.sso_invalid_issuer": "The issuer must be an https URL without query or credentials.", + "error.sso_link_required": "An account with this email already exists. Sign in with your password and link SSO under Security.", + "error.sso_not_member": "Your account is not a member of this organization.", + "error.sso_not_provisioned": "No account exists for this sign-in. Ask an administrator to invite you.", + "error.sso_provider_error": "The identity provider could not complete the sign-in.", + "error.sso_unavailable": "Single sign-on is not available for this organization.", "error.totp_already_enabled": "TOTP is already active.", - "error.totp_setup_expired": "Setup expired, please start again.", "error.totp_required_by_org": "One of your organizations requires TOTP.", - "error.no_password": "This account has no password.", - "error.unsupported_locale": "Unsupported language." + "error.totp_setup_expired": "Setup expired, please start again.", + "error.unsupported_locale": "Unsupported language.", + "lang.de": "Deutsch", + "lang.en": "English", + "security.sso.heading": "Single sign-on", + "security.sso.link": "Link SSO sign-in", + "security.sso.linked": "SSO sign-in linked.", + "security.sso.none": "No SSO sign-in linked in this organization.", + "security.title": "Security", + "security.totp.active": "active", + "security.totp.app_code": "Code from the app", + "security.totp.confirm": "Confirm", + "security.totp.current_code": "Current code", + "security.totp.disable": "Disable", + "security.totp.heading": "Two-factor (TOTP)", + "security.totp.inactive": "not set up", + "security.totp.qr_alt": "QR code for your authenticator app", + "security.totp.start": "Set up", + "sso.action.delete": "Delete provider", + "sso.action.delete_confirm": "Delete this provider? Linked sign-ins stop working.", + "sso.action.edit": "Edit", + "sso.choose.title": "Choose sign-in", + "sso.field.allowed_domains": "Allowed email domains", + "sso.field.allowed_domains_hint": "Comma-separated. Only applies to automatically created accounts; empty allows any domain.", + "sso.field.auto_provision": "Create accounts automatically", + "sso.field.client_id": "Client ID", + "sso.field.client_secret": "Client secret", + "sso.field.client_secret_keep": "unchanged", + "sso.field.enabled": "Enabled", + "sso.field.issuer": "Issuer URL", + "sso.field.name": "Name", + "sso.settings.add": "Add provider", + "sso.settings.intro": "Members of this organization can sign in through your own OpenID Connect identity provider. Register the redirect URL below as an allowed callback at your provider.", + "sso.settings.login_url": "Sign-in URL", + "sso.settings.redirect_url": "Redirect URL", + "sso.settings.title": "Single sign-on" } diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index 9f8fb8b..6ad947f 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -17,24 +17,33 @@ el.classList.toggle("hidden", !text); }; + // Inputs inside a hidden [data-step] are skipped, checkboxes become + // booleans and [data-list] inputs become comma-separated arrays. + const serialize = (form) => { + const out = {}; + for (const el of form.elements) { + if (!el.name || el.disabled || el.closest("[data-step]")?.hidden) continue; + if (el.type === "checkbox") out[el.name] = el.checked; + else if (el.dataset.list !== undefined) + out[el.name] = el.value.split(",").map((v) => v.trim()).filter(Boolean); + else out[el.name] = el.value; + } + return out; + }; + document.addEventListener("submit", async (ev) => { const form = ev.target.closest("form[data-api]"); if (!form) return; ev.preventDefault(); const button = form.querySelector("button[type=submit]"); - const body = Object.fromEntries( - [...new FormData(form)].filter(([k]) => { - const step = form.querySelector(`[name="${k}"]`)?.closest("[data-step]"); - return !step || !step.hidden; - }), - ); + const body = serialize(form); const totpStep = form.querySelector('[data-step="totp"]'); const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api; showError(form, ""); button && (button.disabled = true); try { - const res = await api.post(url, body); + const res = await api.request({ method: form.dataset.method || "post", url, data: body }); if (res.data?.status === "totp_required" && totpStep) { form.querySelector('[data-step="password"]').hidden = true; totpStep.hidden = false; @@ -56,6 +65,17 @@ location.reload(); return; } + const del = ev.target.closest("[data-delete]"); + if (del) { + if (del.dataset.confirm && !confirm(del.dataset.confirm)) return; + try { + await api.delete(del.dataset.delete); + location.reload(); + } catch (err) { + alert(message(err)); + } + return; + } if (ev.target.closest("[data-logout]")) { await api.post("/auth/logout").catch(() => {}); location.assign("/login"); diff --git a/internal/web/auth.templ b/internal/web/auth.templ index c0f86d6..14d9f59 100644 --- a/internal/web/auth.templ +++ b/internal/web/auth.templ @@ -19,6 +19,20 @@ templ Login(p Page, signupAllowed bool) { @submit(i18n.T(ctx, "auth.login.submit")) +
+

{ i18n.T(ctx, "auth.sso.heading") }

+
+ + +
+
if signupAllowed {

{ i18n.T(ctx, "auth.login.no_account") } diff --git a/internal/web/auth_templ.go b/internal/web/auth_templ.go index 3e4ffba..6ed711c 100644 --- a/internal/web/auth_templ.go +++ b/internal/web/auth_templ.go @@ -92,38 +92,90 @@ func Login(p Page, signupAllowed bool) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.sso.heading")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 23, Col: 108} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if signupAllowed { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var4 string - templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.no_account")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 24, Col: 42} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 38, Col: 42} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var5 string - templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.login.to_signup")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 25, Col: 105} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 39, Col: 105} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -155,7 +207,7 @@ func Signup(p Page) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var7 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var11 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -167,7 +219,7 @@ func Signup(p Page) templ.Component { }() } ctx = templ.InitializeContext(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -187,7 +239,7 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -203,26 +255,26 @@ func Signup(p Page) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var8 string - templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "auth.signup.to_login")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 43, Col: 137} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 57, Col: 137} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var7), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = authShell(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var11), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/console.templ b/internal/web/console.templ index 4a7a5f0..fca2b8e 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -4,6 +4,9 @@ import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" // Me is the signed-in user as the console templates see it. type Me struct { + // IsOwner refers to the active organization. + IsOwner bool + ActiveSlug string Email string DisplayName string TOTP bool @@ -35,6 +38,9 @@ templ consoleShell(p Page, me Me) { { me.Orgs[0].Name } }

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var23 string - templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) + var templ_7745c5c3_Var28 string + templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.heading")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 108, Col: 113} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 127, Col: 113} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } if len(identities) == 0 { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var24 string - templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) + var templ_7745c5c3_Var29 string + templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.none")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 110, Col: 73} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 129, Col: 73} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 40, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } else { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "
      ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } for _, id := range identities { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "
    • ") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var25 string - templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) + var templ_7745c5c3_Var30 string + templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(id.Provider) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 114, Col: 69} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 69} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var26 string - templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) + var templ_7745c5c3_Var31 string + templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(id.Email) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 114, Col: 131} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 133, Col: 131} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, "
    • ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "
    ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } if canLink { - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 46, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, "\" class=\"inline-block border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - var templ_7745c5c3_Var28 string - templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) + var templ_7745c5c3_Var33 string + templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.sso.link")) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 119, Col: 190} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 138, Col: 190} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -611,4 +720,57 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen }) } +// recoveryOutput is filled by app.js with codes returned by the API; they +// are shown once and never rendered by the server. +func recoveryOutput() templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + var _ = templruntime.GeneratedTemplate -- 2.54.1