Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

25.6 KB
Raw Blame

This change lands after restore-console-command-database-access. Console commands started with docker exec cannot reach the metadata database of a container that generates its password at startup, which that change fixes; without it the --list-admins command in section 5 and the recovery path documented in sections 7 and 8 fail with an authentication error on a normal deployment.

1. Record the bootstrap administrator

  • 1.1 Create the migration with make migration-create under backend/: add users.is_root_admin boolean not null default false, add the partial unique index that allows at most one row to carry it, delete the seeded admin row when it has no password, no linked Google or GitHub identity and is the only row in users, and set the flag on the remaining admin row or, when none exists, on the oldest ADMIN-role account; write the down step that drops the index and the column. The "only row" condition is what keeps an instance that holds members while its seeded account was never claimed from losing its last administrator: registration answers on POST /users/signup whether or not the claim screen offers it, so that shape exists, and there the unclaimed row is kept and flagged instead of deleted. Verify with make migration-up then make migration-down on a scratch database, and check each shape by hand: a claimed admin row keeps its password and carries the flag, an unclaimed one alone on the instance is gone, an unclaimed one beside other accounts is kept and carries the flag, a renamed one leaves the flag on the oldest administrator, and an empty database backfills nothing. A test cannot stand in for this check - Goose has already run against the test databases before go test starts (backend/Makefile:11-16), so no test can observe an instance in the pre-migration shape.
  • 1.2 Add the field to the user model with json:"-", the way HashedPassword and the OAuth ids carry it (models/user.go:14-20), so a handler that ever returns the model cannot leak it; add a repository lookup that finds the recorded bootstrap administrator by flag. No response shape changes: GET /users/me and the user list both build UserProfileResponseDTO rather than serializing the model (user_controller.go:301, management_controller.go:91-101), so there is nothing to assert about response bodies here. Verify with make test in backend/ that the existing repository and controller suites still pass.
  • 1.3 Rebuild both bootstrap-account helpers in backend/internal/features/users/testing/user_utils.go on the flag. RecreateInitialAdmin (:67-79) retires the account currently holding the flag - found by flag, renamed and cleared in one statement - and creates a fresh flagged ADMIN account the way CreateTestUser (:19-48) does, panicking with a message that names what it could not find. RecreateInitAdminAndGetAccess (:50-65) returns the account that helper just created instead of reading it back with GetUserByEmail(ctx, "admin"), which would hand a nil user to GenerateAccessToken and panic. Selecting the outgoing account by address would no-op after any test that changes it (user_repository.go:147-157), leaving the next test without a bootstrap account. Verify with make test in backend/ that all 11 call sites across e2e_test.go, user_controller_test.go and management_controller_test.go - 9 of them through RecreateInitAdminAndGetAccess - still get a usable bootstrap account and a working token.
  • 1.4 Add a test that pins the helpers against that failure: change the bootstrap address to a real one, call the helper, and confirm the fresh account carries the flag while the retired one holds neither the flag nor the old address; verify with make test in backend/.
  • 1.5 Add a test that the database refuses a second flagged account, by inserting one directly against an instance that already has a bootstrap administrator; verify with make test in backend/.
  • 1.6 Add an audit-log writer to backend/internal/features/users/testing that records the entries it receives, and use it in place of AuditLogWriterStub in all four test routers (controllers/e2e_test.go:177, :196, :214, :232), installing a fresh recorder per router so one test cannot read another's entries; delete the stub (:255-258). The services are package-level singletons and SetAuditLogWriter mutates them (services/di.go:10-28), and the four builders are called from about ninety sites, so keep their signatures and let a test reach the current recorder through users/testing. Verify with make test in backend/ that the existing suites still pass with the recording writer installed.
  • 1.7 Add a helper to backend/internal/features/users/testing that empties the users table, so a test can put the instance in the state the new account-creation rule is keyed on. No test can assume that state: cleanup_test_db recreates the per-slot databases once per run (backend/cmd/cleanup_test_db/main.go:64-97), each binary claims a slot and releases it on exit (internal/config/config.go:259-277) so later packages inherit what earlier ones left, and around twenty packages outside features/users create accounts through CreateTestUser. Verify with make test in backend/ that the suites still pass, and that a test calling the helper sees GET /users/is-any-user-exist answer false right afterwards (once task 2.6 lands).

2. Create the administrator from the first account

  • 2.1 Delete the seeding: CreateInitialAdmin in the service (user_services.go:291-293) and the repository (user_repository.go:65-86), and its call in backend/cmd/main.go:109; verify with make test in backend/ that nothing else referenced them.
  • 2.2 Grant the administrator role and the flag to an account created while the instance holds no user, on the path of each entry point that inserts a new row - SignUp (user_services.go:114-127) and getOrCreateUserFromOAuth (:963-976) - and not on the branches that complete an invitation or link an identity to an account that already exists (:66-101, :896-944). Ask the account count before the refusal external registration is disabled (:110-111 for registration, :951-952 for a first external sign-in), and let an empty instance skip that refusal: asking inside the insert branch is too late, because an empty instance whose setting is off would never reach it and could never gain an administrator. Write the audit entry recording that this account now administers the instance, beside the entry SignUp already writes (:130). Verify with controller tests, each starting from the empty-table helper, that the first registration on an empty instance comes back as an administrator, is the recorded bootstrap administrator and leaves that audit entry; that a first GitHub sign-in does the same; that a first Google sign-in does the same; that an empty instance grants it even with external registration disabled; and that a second account created afterwards is an ordinary member.
  • 2.3 Handle the lost race: when the insert is refused, unwrap the driver error with errors.As into *pgconn.PgError the way internal/features/databases/service.go:335 does, and retry as an ordinary account under the open-registration policy only when ConstraintName names the bootstrap index - a violation of users_email_idx must keep returning the duplicate-address error it returns today. Verify with a test that creates the bootstrap administrator first and then registers again, expecting a member account and an unchanged bootstrap administrator, and with a test that registering on an address another account already holds is still refused as a duplicate.
  • 2.4 Add email to the binding tag of SignUpRequestDTO.Email (backend/internal/features/users/dto/dto.go:12); verify with a controller test that a registration whose email is not an address is refused and creates no account, and that a valid one still succeeds.
  • 2.5 Pin the check the previous tasks deliberately bypass, which has no test today: on an instance that already holds an account, a password registration is refused while external registration is disabled. Use users_testing.DisableExternalRegistrations (testing/settings_utils.go:21) and restore the setting with ResetSettingsToDefaults; the GitHub path already has its counterpart (user_controller_test.go:1007). Verify with make test in backend/.
  • 2.6 Replace GET /users/admin/has-password and POST /users/admin/set-password with GET /users/is-any-user-exist, answering { "isExist": boolean } - the shape and the method the client already uses (frontend/src/entity/users/api/userApi.ts:62-74) - and delete IsRootAdminHasPassword (user_services.go:299), SetRootAdminPassword (:312), their controller handlers and the two DTOs that exist only for them (dto.go:30-36). Verify with controller tests that the new endpoint answers false on an empty instance - emptied through the helper from task 1.7 - and true once an account exists, and that both removed routes now answer 404, which is also what closes the unauthenticated password-setting path the spec refuses.
  • 2.7 Retire the tests that pin the removed claim path, once the tests above cover what replaces them. Test_CheckAdminHasPassword_WhenAdminHasNoPassword_ReturnsFalse and the three Test_SetAdminPassword_* tests (user_controller_test.go:278-374) are deleted outright. Test_AdminLifecycleE2E_CompletesSuccessfully (controllers/e2e_test.go:21-119) is rewritten rather than deleted: it opens by posting to the deleted /users/admin/set-password, and it is the walk this change makes canonical - an empty instance from the helper in task 1.7, a first registration that comes back as the bootstrap administrator, a sign-out and sign-in with that address, an address change, and a sign-in with the new address. Verify with make test in backend/.
  • 2.8 Give Test_UserLifecycleE2E_CompletesSuccessfully (controllers/e2e_test.go:120) its own precondition: it registers and asserts the member role (:172), which from now on only holds when the instance already has an account, and today it holds only because the test above it happens to seed one. Create that account in the test. Verify with make test in backend/ and with go test ./internal/features/users/... -run Test_UserLifecycleE2E_CompletesSuccessfully, which must pass on its own.
  • 2.9 Run make lint in backend/.

3. Free the administrator address

  • 3.1 Delete the refusal at user_services.go:468, and rewrite Test_UpdateUserInfo_WhenAdminTriesToChangeEmail_ReturnsBadRequest (user_controller_test.go:761), which pins the behavior being deleted, into a test that the change succeeds: the address becomes the new one, a sign-in with it works, and a sign-in with the previous value is rejected. Verify with make test in backend/.
  • 3.2 Assert with the recording audit writer that the recorded entries contain the one user_services.go:486-506 builds for the address change, naming the old and the new address. Look for that entry among the recorded ones rather than expecting it to be the only one - the sign-in and account creation the test needs first write their own. Verify with make test in backend/.
  • 3.3 Verify that an invalid address is still rejected and that taking another user's address is still refused, by extending the same test with both cases; no new validation code is expected, since UpdateUserInfoRequestDTO already binds omitempty,email (dto.go:42) and user_services.go:471-479 already checks uniqueness.
  • 3.4 Confirm with a test that the token issued before the address change still authenticates afterwards; GenerateAccessToken carries the user id and the password creation time and no email (user_services.go:271-276), so this is a check rather than a change.
  • 3.5 Add a test that the bootstrap administrator can request a password reset for their address and complete it with the emailed code.
  • 3.6 Delete the single-user sign-in hint branch at user_services.go:157-161; verify with a controller test that a sign-in attempt with an unknown address on a single-user instance returns a response whose text contains neither admin nor a user count. Confirm GetUsersCount stays, since telemetry calls it (backend/internal/features/telemetry/service.go:102) and the new account-creation rule asks it the same question.
  • 3.7 Guard the password comparison in SignIn (user_services.go:181) with HasPassword() (models/user.go:56-58) so an account with no password hash is refused the way a wrong password is, instead of dereferencing nil; verify with a controller test that submits the password form for an account created through Google or GitHub and expects the refusal rather than a 500.
  • 3.8 Pin the two refusals the new guard sits below, neither of which has a test today: signing in to an account still in the invited state and to a deactivated one (user_services.go:168-179). Both accounts are reachable through existing helpers - an invitation through POST /users/invite, a deactivation through the management endpoint. Verify with make test in backend/.
  • 3.9 Pin the half of the upgrade scenario (spec.md - Upgrading an instance in use) that a test can reach: create a flagged ADMIN account whose address is the placeholder admin, and confirm a sign-in with that address and its password succeeds. The migration itself cannot be observed from a test, but this can, and it guards a specific regression: SignInRequestDTO.Email binds required alone (dto.go:19), so the day somebody adds email beside it for symmetry with the registration DTO task 2.4 changes, every upgraded instance that has not yet moved off the placeholder is locked out with a binding error. This test is what makes that edit fail instead of shipping. Verify with make test in backend/.

4. Keep the root administrator's powers

  • 4.1 Switch the three root-administrator checks in backend/internal/features/users/services/management_service.go from comparing the caller's email to reading the flag: deactivation (:74), reactivation (:108) and the ADMIN-role grant or revoke (:154). Update the three comments above them so they describe the rule rather than the address.
  • 4.2 Confirm the existing privilege matrix still passes and now proves more than it did. management_controller_test.go already covers the bootstrap administrator succeeding at all three actions (:574, :596, :618, :636) and an ordinary ADMIN account being refused all three (:486, :512, :538, :556), and after task 1.3 those tests run against a bootstrap account whose address is an ordinary one. Add the case they cannot reach: change the bootstrap administrator's address first, then exercise all three actions through the API and expect them to succeed. Verify with make test in backend/.
  • 4.3 Add the test the spec requirement rests on and no existing test names: an ordinary ADMIN account cannot revoke the role of the flagged account or deactivate it, and the flagged account cannot do either to itself. The self-action refusals exist (:665, :686) but target whichever account the helper returns; assert here that the account they protect is the one holding the flag, so the instance is never left without a recognized bootstrap administrator. Verify with make test in backend/.
  • 4.4 Assert with the recording audit writer that the recorded entries contain the ones a role grant and a deactivation performed by the bootstrap administrator write (management_service.go:165 and :83), again matching an entry rather than expecting a single one; verify with make test in backend/.
  • 4.5 Grep production code under backend/ for the literal "admin" and confirm the only remaining occurrences are in the MongoDB feature, which means a database by it; anything else is a site this change missed.

5. Console recovery

  • 5.1 Add the administrator listing to the users feature under backend/internal/features/users/: select every ADMIN-role account, order it, mark the one holding the flag, and render the lines carrying the address, display name, creation date and active state and nothing else. The active state is part of the answer because a deactivated administrator otherwise reads as an address that should work. The listing writes no audit entry: UserService dereferences its audit writer without a nil check (user_services.go:128) and that writer only exists after audit_logs.SetupDependencies(), which the console path calls only for the password reset (main.go:167-190). It goes here rather than in backend/cmd/ because make test and CI run go test ./internal/... only (backend/Makefile:16, .github/workflows/ci-release.yml:221,345), so logic living in cmd/ ships untested. This is the one place the change tests a service directly instead of through HTTP, which backend/AGENTS.md allows for logic with no API surface.
  • 5.2 Add tests covering the listing on an instance with several administrators, where the flagged one is marked, a deactivated administrator is shown as inactive and members do not appear, and on one where no account exists yet - emptied through the helper from task 1.7 - where it reports that the instance has no administrator; assert the rendered output carries no password hash. Verify with make test in backend/.
  • 5.3 Add the --list-admins flag to parseCommandLineOptions (backend/cmd/main.go:154) and a handler invoked from the same startup point as resetPasswordIfRequested (main.go:115) that calls the listing, prints it to the process log and exits; verify with docker exec -it databasus ./main --list-admins against a running container, not against a local database, and confirm the output lists the administrators and contains no password material. Running it through docker exec is the point: that is how an owner reaches it, and it is the path restore-console-command-database-access repairs.
  • 5.4 Run make test and make lint in backend/ and fix what they report.

6. Frontend

  • 6.1 Change AuthPageComponent (frontend/src/pages/AuthPageComponent.tsx:21-41) to ask whether any account exists instead of whether the administrator has a password, to open on registration when none does, and to drop the AdminPasswordComponent branch; delete that component, its barrel export (frontend/src/features/users/index.ts:1), and everything only it used: userApi.isAdminHasPassword and userApi.setAdminPassword (entity/users/api/userApi.ts:76-95) with the two types they are the only users of (entity/users/model/IsAdminHasPasswordResponse.ts and entity/users/model/SetAdminPasswordRequest.ts, exported at entity/users/index.ts:10-11). An instance that already holds accounts keeps the screen it opens on today - registration, with sign-in one click away - so the only branch that changes is the empty one. Verify in the running application against an empty instance and against one that already has accounts - the repository has no component or page tests, so this is a manual check rather than a missing one.
  • 6.2 Add the copy that tells the first visitor the account they are creating administers the instance, and delete the keys users.adminPassword.* and app.auth.adminPasswordCheckFailed from frontend/src/shared/i18n/locales/{en,ru,es,pt,zh,fr}.ts; verify the removed keys appear nowhere under frontend/src, and run pnpm test so the dictionary parity suite (shared/i18n/dictionaries.test.ts) confirms the six files still hold the same key set.
  • 6.3 Remove the four places in frontend/src/features/users/ui/ProfileComponent.tsx that treat the address admin as read-only: the skipped validation (:138), the omitted request field (:157), the disabled prop (:234) and the explanatory line (:236-238), and delete users.profile.adminEmailReadOnly from the six locale files; verify by changing the address on the profile screen of an upgraded instance.
  • 6.4 Confirm the sign-in form still accepts admin as a login value (SignInComponent.tsx:50), since an upgraded instance that has not changed the address still uses it; verify by signing in as admin against such an instance.
  • 6.5 Run pnpm lint, pnpm format, pnpm test and pnpm build in frontend/ and fix what they report.

7. English documentation

  • 7.1 Update the password section of the root README.md (lines 261-269): document --list-admins beside the existing reset command, and change the reset example so it no longer presents --email="admin" as the expected address, explaining that an instance created before this change still uses admin until its owner replaces it; verify by reading the rendered section as a reader who cannot sign in and can only reach the host.
  • 7.2 Add to the usage section of the root README.md (lines 251-259) the step that comes before everything else: open the instance and create the first account, which administers it; verify the section reads correctly for a reader who has just started the container.
  • 7.3 Add a section to website/app/(en)/password/page.tsx covering the administrator listing, with its own heading id so it can be linked, and correct the example command (:41) and the illustration of a valid address (:141) the same way; verify with npm run build in website/ and by loading the page.
  • 7.4 Rewrite the sentence at website/app/(en)/access-management/page.tsx:220-221 so it describes the first account created on the instance as its administrator rather than naming its address admin; verify with npm run build in website/.
  • 7.5 Add the FAQ entry "I forgot my admin email or password" to website/app/(en)/page.tsx, in both the visible FAQ list and the structured-data block that mirrors it, linking to the password page; verify with npm run build in website/ and by confirming both copies carry the same answer text.
  • 7.6 Run npm run lint in website/ and fix what it reports.

8. Translations

  • 8.1 Translate the new password-page section into Russian in website/app/[lang]/password/content/ru.tsx, mirror the access-management correction in website/app/[lang]/access-management/content/ru.tsx, and add the FAQ entry to the Russian home-page content; verify with npm run build in website/ and by reading all three pages under /ru/.
  • 8.2 Repeat for Spanish (es).
  • 8.3 Repeat for Portuguese (pt).
  • 8.4 Repeat for Chinese (zh).
  • 8.5 Repeat for French (fr).
  • 8.6 Mirror the README changes into assets/readme/README.{ru,es,pt,zh,fr}.md, following the translation rules in assets/readme/AGENTS.md; verify each file keeps the command lines byte-identical to the English ones.

9. Verification and review

  • 9.1 Run make test and make lint in backend/, pnpm lint, pnpm format, pnpm test and pnpm build in frontend/, and npm run lint and npm run build in website/; fix every failure.
  • 9.2 Confirm every behavior in specs/root-admin-account/spec.md has a test or a documented manual check, and that no scenario is left unexercised. Three rest on manual checks: the migration shapes (task 1.1), the two screens (tasks 6.1 and 6.3) and the restart scenario (task 9.3, which restarts the instance rather than asserting it in Go). Everything else names a test.
  • 9.3 Walk a fresh install end to end: start an empty instance, register the first account, confirm it is an administrator, restart the container and confirm no account was created and the administrator is unchanged, invite a second user, confirm that user is a member and cannot manage administrators, and recover the address with docker exec -it databasus ./main --list-admins.
  • 9.4 Walk all three upgrade paths on databases seeded from the previous version: a claimed instance, where the owner signs in as admin, changes the address from the profile screen, signs out, signs in with the new address and confirms admin is no longer accepted for that account; an instance that was never claimed and holds nothing else, where the seeded account is gone and the first registration becomes the administrator; and an instance that was never claimed but holds a member registered through the API, where the seeded account is kept as the bootstrap administrator and a password set with --new-password --email="admin" gets the owner in.
  • 9.5 Record in the change's completion notes that the rollback window closes once an administrator address has been changed, and that the down step cannot restore the unclaimed account the up step deleted, as described in design.md - Migration Plan.
  • 9.6 Complete the mandatory compliance review for the finished diff and resolve every CHANGES REQUIRED finding.

Completion notes

  • The rollback window closes once an administrator address has been changed. Rolling the binary back on an instance whose owner still signs in as admin leaves an unused column behind and works. Rolling it back after the owner has moved to a real address does not: the old code looks the bootstrap account up by the text admin, finds nothing, IsRootAdminHasPassword fails, and the authentication screen alerts without clearing its loading state, so nobody reaches the sign-in form. The restored Email != "admin" privilege checks would freeze administrator management even if sign-in worked. It is a lockout rather than a takeover, and it is recovered by rolling forward again or by setting the address back to admin in the database. See design.md - Migration Plan.
  • The down step cannot restore the account the up step deleted. The up step removes the seeded admin row when it was never claimed and is the only row in users. The down step drops the index and the column and does not try to bring that row back: on such an instance the old binary seeds the account again at startup, which is exactly where it was.