Stop an owner deleting the account they are signed in as

Deleting your own user succeeded, and logged you out doing it:
local_sessions.user_id is ON DELETE CASCADE, so the delete took the
caller's own live session with it. Nothing refused this. The
last-owner guard is the only thing in the path, and it passes cleanly
as soon as a second owner exists -- which is exactly the state you are
in just after creating one.

The way back in was then whatever other account happened to exist, and
-seed-admin could not help: it skipped whenever *any* local user was
present, so the command documented as the way to create an
administrator refused precisely when there was no usable one, because
some other account still existed. It now asks whether the admin
account itself is missing, which is what its own help text always
claimed, and what makes it useful as recovery rather than only as
first-run bootstrap.

TestCanDeleteAnOwnerWhenAnotherRemains signed in as admin1 and deleted
admin1, asserting 204 -- it encoded the lockout as intended behaviour.
It now deletes the other owner, which is what it meant to cover, and a
new test holds the refusal in place.

runSeedAdmin takes a small interface so the bootstrap path is tested
without a Postgres pool; it had no tests before.

Signed-off-by: John Coffey <[email protected]>
This commit is contained in:
2026-09-04 17:39:22 -07:00
parent 5374c1946a
commit 7becb7344d
6 changed files with 185 additions and 24 deletions
+12 -7
View File
@@ -314,13 +314,18 @@ func (s *Store) GetPasswordHashByID(ctx context.Context, id string) (string, err
return hash, nil
}
// CountLocalUsers backs -seed-admin's idempotency check (see
// cmd/api/main.go's runSeedAdmin): a deployment that already has at
// least one local user never gets a second auto-created admin account.
func (s *Store) CountLocalUsers(ctx context.Context) (int, error) {
var n int
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username IS NOT NULL`).Scan(&n)
return n, err
// UsernameExists backs -seed-admin's idempotency check (see
// cmd/api/main.go's runSeedAdmin). It asks whether the account that
// command would create is already provisioned -- deliberately not
// whether the deployment has any local user at all, which is the
// question it used to ask: an operator who deleted the seeded admin
// account was then refused by the very command documented as the way
// to create one, because some *other* account still existed.
func (s *Store) UsernameExists(ctx context.Context, username string) (bool, error) {
var exists bool
err := s.pool.QueryRow(ctx,
`SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)`, username).Scan(&exists)
return exists, err
}
// CreateSession mints a fresh opaque token for an already-authenticated