From 6b4ff8101a14a6ecc7e3224cacf2c038de68cd53 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 27 Nov 2026 02:33:15 +1100 Subject: [PATCH] fix(governance): ask for the public URL during owner setup (#2076) --- api/openapi.yaml | 26 +++-- e2e/checks/org-selector.cjs | 2 +- e2e/seed.sh | 2 +- internal/infrastructure/postgres/accounts.go | 33 +----- .../pg/migrations/00016_default_workspace.sql | 10 ++ modules/governance/accounts_api.go | 23 ++-- modules/governance/bootstrap_test.go | 27 +++++ modules/governance/identity.go | 12 +- modules/governance/internal/store/accounts.go | 43 +++---- modules/governance/store_identities.go | 10 +- ui/src/accounts/AccountEntry.vue | 106 +++++++++--------- 11 files changed, 147 insertions(+), 147 deletions(-) create mode 100644 internal/platform/pg/migrations/00016_default_workspace.sql create mode 100644 modules/governance/bootstrap_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 9b0f9b2fc..f6d518b48 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -2756,16 +2756,10 @@ components: type: string email: type: string - organisation_name: - type: string password: type: string - public_url: - type: string role: type: string - workspace_name: - type: string required: - email - display_name @@ -4672,6 +4666,24 @@ components: required: - role type: object + SetUpInputBody: + additionalProperties: false + properties: + display_name: + type: string + email: + type: string + password: + type: string + public_url: + description: The public origin of this Archie instance + type: string + required: + - public_url + - email + - display_name + - password + type: object SignInInputBody: additionalProperties: false properties: @@ -5690,7 +5702,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/GovernanceRegistration" + $ref: "#/components/schemas/SetUpInputBody" required: true responses: "200": diff --git a/e2e/checks/org-selector.cjs b/e2e/checks/org-selector.cjs index c75fd4cfe..30d064f5c 100644 --- a/e2e/checks/org-selector.cjs +++ b/e2e/checks/org-selector.cjs @@ -17,7 +17,7 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => { await page.keyboard.press('Escape'); return names; })(); - assert.deepEqual(offered.sort(), ['Beta', 'E2E'], 'selector must offer exactly the orgs the caller belongs to'); + assert.deepEqual(offered.sort(), ['Beta', 'System'], 'selector must offer exactly the orgs the caller belongs to'); await go('/workflows'); await page.getByText('Parked', { exact: true }).first().waitFor(); await shot('home-org-workflows'); diff --git a/e2e/seed.sh b/e2e/seed.sh index 2c783aa35..f62c7f5aa 100755 --- a/e2e/seed.sh +++ b/e2e/seed.sh @@ -18,7 +18,7 @@ py() { python3 -c "import sys, json; d = json.load(sys.stdin); print($1)"; } # This account belongs only to the isolated local test stack. email=${ARCHIE_E2E_EMAIL:-operator@example.test} password=${ARCHIE_E2E_PASSWORD:-archie-local-e2e-password} -account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", organisation_name="E2E", workspace_name="Local test", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}") +account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}") if [ "$(get /api/auth/status | py 'd["setup_required"]')" = "True" ]; then post /api/auth/setup "$account" >/dev/null else diff --git a/internal/infrastructure/postgres/accounts.go b/internal/infrastructure/postgres/accounts.go index 931a04c3f..789ed33f1 100644 --- a/internal/infrastructure/postgres/accounts.go +++ b/internal/infrastructure/postgres/accounts.go @@ -6,7 +6,6 @@ import ( "crypto/sha256" "encoding/hex" "errors" - "fmt" "strings" "time" @@ -75,7 +74,7 @@ func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration now := time.Now().UTC() value.CreatedAt, value.UpdatedAt = now, now if bootstrap { - if err := setupAccountOrganisation(ctx, tx, r, orgID, now); err != nil { + if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil { return identity.Identity{}, err } } @@ -229,7 +228,8 @@ func accountRegistrationScope(ctx context.Context, r *identity.AccountRegistrati role := org.Role(r.Role) orgID := org.OrgFromContext(ctx) if bootstrap { - if err := validateAccountSetup(r); err != nil { + r.PublicURL = strings.TrimRight(strings.TrimSpace(r.PublicURL), "/") + if err := (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate(); err != nil { return "", "", err } return org.RoleOwner, org.DefaultOrgID, nil @@ -257,30 +257,3 @@ func recordFailedAccountLogin(ctx context.Context, tx pgx.Tx, id string, attempt } return identity.ErrCredentialRejected } - -func setupAccountOrganisation(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, orgID org.OrgID, now time.Time) error { - _, err := tx.Exec(ctx, `UPDATE orgs SET name=$1, updated_at=$2 WHERE id=$3`, r.OrganisationName, now, string(orgID)) - if err != nil { - return err - } - if _, err := tx.Exec(ctx, `UPDATE workspaces SET name=$1,updated_at=$2 WHERE org_id=$3 AND id=$4`, r.WorkspaceName, now, string(orgID), string(org.DefaultWorkspaceID)); err != nil { - return err - } - if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil { - return err - } - return nil -} - -func validateAccountSetup(r *identity.AccountRegistration) error { - r.OrganisationName = strings.TrimSpace(r.OrganisationName) - r.WorkspaceName = strings.TrimSpace(r.WorkspaceName) - r.PublicURL = strings.TrimRight(r.PublicURL, "/") - if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 { - return identity.ErrInvalid - } - if r.OrganisationName == "" || len(r.OrganisationName) > 200 { - return fmt.Errorf("%w: organisation name is required", identity.ErrInvalid) - } - return (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate() -} diff --git a/internal/platform/pg/migrations/00016_default_workspace.sql b/internal/platform/pg/migrations/00016_default_workspace.sql new file mode 100644 index 000000000..8139d594f --- /dev/null +++ b/internal/platform/pg/migrations/00016_default_workspace.sql @@ -0,0 +1,10 @@ +-- +goose Up +INSERT INTO governance.orgs (id, name) VALUES ('org-sys', 'System') +ON CONFLICT (id) DO NOTHING; + +INSERT INTO governance.workspaces (id, org_id, name) VALUES ('default', 'org-sys', 'Default') +ON CONFLICT (org_id, id) DO NOTHING; + +-- +goose Down +-- The built-in rows may own user data. Keep them on downgrade. +SELECT 1; diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index 378b94cab..357a0fa21 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -193,26 +193,29 @@ func (m *Module) authStatus(ctx context.Context, in *sessionInput) (*authStatusR } type registration struct { - PublicURL string `json:"public_url,omitempty"` - WorkspaceName string `json:"workspace_name,omitempty"` - OrganisationName string `json:"organisation_name,omitempty"` - Email string `json:"email"` - DisplayName string `json:"display_name"` - Password string `json:"password"` - Role string `json:"role,omitempty"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + Role string `json:"role,omitempty"` } func (r registration) account() AccountRegistration { - return AccountRegistration(r) + return AccountRegistration{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role} } type setUpInput struct { Client client - Body registration + Body struct { + PublicURL string `json:"public_url" doc:"The public origin of this Archie instance"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + } } func (m *Module) setUpAccount(ctx context.Context, in *setUpInput) (*userReply, error) { - if _, err := m.RegisterAccount(ctx, in.Body.account(), true); err != nil { + r := in.Body + if _, err := m.RegisterAccount(ctx, AccountRegistration{PublicURL: r.PublicURL, Email: r.Email, DisplayName: r.DisplayName, Password: r.Password}, true); err != nil { return nil, m.accountError(ctx, err) } return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password) diff --git a/modules/governance/bootstrap_test.go b/modules/governance/bootstrap_test.go new file mode 100644 index 000000000..bccc694dc --- /dev/null +++ b/modules/governance/bootstrap_test.go @@ -0,0 +1,27 @@ +package governance + +import ( + "errors" + "testing" +) + +// TestBootstrapRequiresThePublicOrigin guards the WebAuthn origin without requiring names for built-in rows. +func TestBootstrapRequiresThePublicOrigin(t *testing.T) { + for _, tc := range []struct { + url string + wantErr error + }{ + {"https://archie.example.test/", nil}, + {"", ErrInvalidIdentity}, + {"https://archie.example.test/some/path", ErrInvalidIdentity}, + } { + r := AccountRegistration{PublicURL: tc.url, Email: "owner@example.test", DisplayName: "Owner"} + role, org, err := registrationScope(t.Context(), &r, true) + if !errors.Is(err, tc.wantErr) { + t.Errorf("register with origin %q: %v, want %v", tc.url, err, tc.wantErr) + } + if err == nil && (r.PublicURL != "https://archie.example.test" || role != RoleOwner || org != DefaultOrgID) { + t.Errorf("bootstrap scope = %s/%s, origin = %q", org, role, r.PublicURL) + } + } +} diff --git a/modules/governance/identity.go b/modules/governance/identity.go index 300105705..9ad81417c 100644 --- a/modules/governance/identity.go +++ b/modules/governance/identity.go @@ -387,13 +387,11 @@ const AccountSessionLifetime = 7 * 24 * time.Hour // AccountRegistration carries the fields needed to register an account or // bootstrap the instance owner. type AccountRegistration struct { - PublicURL string `json:"public_url"` - WorkspaceName string `json:"workspace_name"` - OrganisationName string `json:"organisation_name"` - Email string `json:"email"` - DisplayName string `json:"display_name"` - Password string `json:"password"` - Role string `json:"role"` + PublicURL string `json:"public_url"` + Email string `json:"email"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + Role string `json:"role"` } // Validate normalises email and display name and checks their bounds. diff --git a/modules/governance/internal/store/accounts.go b/modules/governance/internal/store/accounts.go index 39ea215ca..f4b4494d8 100644 --- a/modules/governance/internal/store/accounts.go +++ b/modules/governance/internal/store/accounts.go @@ -35,20 +35,17 @@ type AuthSettingsRow struct { // RegisterAccountParams carries the validated inputs to create a user account. type RegisterAccountParams struct { - IdentityID string - Email string - DisplayName string - PasswordHash string - OrgID string - OrgName string - WorkspaceID string - WorkspaceName string - PublicURL string - Role string - ActorID string - RequestID string - Bootstrap bool - Now time.Time + IdentityID string + Email string + DisplayName string + PasswordHash string + OrgID string + PublicURL string + Role string + ActorID string + RequestID string + Bootstrap bool + Now time.Time } // AccountSetupRequired reports whether no local accounts exist yet. @@ -76,7 +73,7 @@ func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (I return ErrCredentialRejected } if p.Bootstrap { - if err := bootstrapOrgAndSettings(ctx, tx, p); err != nil { + if err := saveBootstrapOrigin(ctx, tx, p.PublicURL); err != nil { return err } } @@ -85,22 +82,10 @@ func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (I return out, err } -func bootstrapOrgAndSettings(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams) error { - if _, err := tx.ExecContext(ctx, ` - INSERT INTO governance.orgs (id, name, created_at, updated_at) VALUES ($1, $2, $3, $3) - ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`, - p.OrgID, p.OrgName, p.Now); err != nil { - return err - } - if _, err := tx.ExecContext(ctx, ` - INSERT INTO governance.workspaces (id, org_id, name, created_at, updated_at) VALUES ($1, $2, $3, $4, $4) - ON CONFLICT (org_id, id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`, - p.WorkspaceID, p.OrgID, p.WorkspaceName, p.Now); err != nil { - return err - } +func saveBootstrapOrigin(ctx context.Context, tx *sqlx.Tx, origin string) error { _, err := tx.ExecContext(ctx, ` INSERT INTO governance.authentication_settings (singleton, public_url) VALUES (true, $1) - ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, p.PublicURL) + ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, origin) return err } diff --git a/modules/governance/store_identities.go b/modules/governance/store_identities.go index 886954991..ba07fddf5 100644 --- a/modules/governance/store_identities.go +++ b/modules/governance/store_identities.go @@ -386,8 +386,7 @@ func (m *Module) RegisterAccount(ctx context.Context, r AccountRegistration, boo } row, err := m.store.RegisterAccount(ctx, store.RegisterAccountParams{ IdentityID: string(id), Email: r.Email, DisplayName: r.DisplayName, - PasswordHash: hash, OrgID: string(orgID), OrgName: r.OrganisationName, - WorkspaceID: string(DefaultWorkspaceID), WorkspaceName: r.WorkspaceName, + PasswordHash: hash, OrgID: string(orgID), PublicURL: r.PublicURL, Role: string(role), ActorID: string(actor), RequestID: "account:" + rand.Text(), Bootstrap: bootstrap, Now: time.Now().UTC(), }) @@ -408,12 +407,7 @@ func registrationScope(ctx context.Context, r *AccountRegistration, bootstrap bo return "", "", err } if bootstrap { - r.OrganisationName = strings.TrimSpace(r.OrganisationName) - r.WorkspaceName = strings.TrimSpace(r.WorkspaceName) - r.PublicURL = strings.TrimRight(r.PublicURL, "/") - if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 || r.OrganisationName == "" || len(r.OrganisationName) > 200 { - return "", "", ErrInvalidIdentity - } + r.PublicURL = strings.TrimRight(strings.TrimSpace(r.PublicURL), "/") if err := (AuthenticationSettings{PublicURL: r.PublicURL}).Validate(); err != nil { return "", "", err } diff --git a/ui/src/accounts/AccountEntry.vue b/ui/src/accounts/AccountEntry.vue index a3b8126f8..8c092daa1 100644 --- a/ui/src/accounts/AccountEntry.vue +++ b/ui/src/accounts/AccountEntry.vue @@ -6,38 +6,34 @@ import { computed, ref } from "vue"; import { Card } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { api, describeError } from "@/lib/api"; +import { api, ApiError, describeError } from "@/lib/api"; import { errors } from "@/copy/errors"; import { passkeysAvailable, useAccountsStore, usePasskey } from "./accounts"; const accounts = useAccountsStore(); const recovery = ref(false); const recoveryCode = ref(""); -const organisation = ref(""); -const workspace = ref("Default"); +const publicURL = ref(""); +const currentOrigin = window.location.origin; const name = ref(""); const email = ref(""); const password = ref(""); const busy = ref(false); const error = ref(""); const notice = ref(""); +const ownerCreated = ref(false); const setup = computed(() => accounts.status?.setup_required === true); const passkey = computed(() => passkeysAvailable(accounts.status?.public_url ?? "")); -// Setup asks one thing at a time: the organisation, then its first workspace, -// then the account that owns it. -const ACCOUNT_STEP = 3; -const step = ref(1); - async function submit() { - if (setup.value && !recovery.value && step.value < ACCOUNT_STEP) { - step.value += 1; - return; - } busy.value = true; error.value = ""; notice.value = ""; try { + if (ownerCreated.value) { + await openAccountWhenReady(); + return; + } if (recovery.value) { await api.recoverAccount(email.value, recoveryCode.value, password.value); recovery.value = false; @@ -46,35 +42,46 @@ async function submit() { return; } if (setup.value) { - // The instance URL is the address the operator already reached, and it - // stays editable under Settings, authentication once passkeys exist. await api.setupAccount({ - organisation_name: organisation.value, - workspace_name: workspace.value, - public_url: window.location.origin, + public_url: publicURL.value.trim(), display_name: name.value, email: email.value, password: password.value, }); - } else { - await api.signIn(email.value, password.value); + password.value = ""; + ownerCreated.value = true; + await openAccountWhenReady(); + return; } + await api.signIn(email.value, password.value); password.value = ""; - window.location.assign( - setup.value - ? "/account?welcome=1" - : new URLSearchParams(window.location.search).has("reauth") - ? "/account" - : "/", - ); + window.location.assign(new URLSearchParams(window.location.search).has("reauth") ? "/account" : "/"); } catch (cause) { error.value = describeError(cause, errors.common.unknown); - await accounts.load(); + if (!ownerCreated.value) await accounts.load(); } finally { busy.value = false; } } +async function openAccountWhenReady(): Promise { + const deadline = Date.now() + 15_000; + // Setup creates the owner before Archie opens its operational routes. + for (;;) { + try { + await api.passkeys(); + window.location.assign("/account?welcome=1"); + return; + } catch (cause) { + if (!(cause instanceof ApiError) || cause.status !== 404) throw cause; + if (Date.now() >= deadline) { + throw new Error("Archie hasn't finished starting. Try opening your account again."); + } + await new Promise((resolve) => window.setTimeout(resolve, 500)); + } + } +} + async function signInPasskey() { busy.value = true; error.value = ""; @@ -95,37 +102,28 @@ async function signInPasskey() {

{{ - setup - ? step === 1 - ? "Set up your organisation" - : step === 2 - ? "Create your first workspace" - : "Create your account" - : recovery - ? "Recover your account" - : "Sign in" + setup ? "Set up Archie" : recovery ? "Recover your account" : "Sign in" }}

-
- - - +
+

Your account is ready. Archie is starting.

+ {{ error }} + +
+ +
+ + +

Use the public address people will sign in at. You can't change it after adding a passkey.

+
+ + + + +

At least 15 characters.

{{ error }} {{ notice }} -
- - -
+