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
+28 -9
View File
@@ -79,7 +79,7 @@ func main() {
// startup path -- mirrors enterprise-api's -provision-tenant shape
// (declare, flag.Parse(), short-circuit before the rest of main's
// dependencies matter to it). See runSeedAdmin's doc comment.
seedAdmin := flag.Bool("seed-admin", false, "create the default local-auth admin user with a random password if none exists, print it once, and exit")
seedAdmin := flag.Bool("seed-admin", false, "create the default local-auth admin user with a random password if that account does not exist, print it once, and exit")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
@@ -259,21 +259,40 @@ func main() {
}
}
// seedAdminUsername is the account -seed-admin creates, and the one it
// checks for before deciding it has nothing to do.
const seedAdminUsername = "admin"
// seedStore is the slice of *localauth.Store that runSeedAdmin uses,
// named here so the bootstrap path can be tested without a Postgres
// pool behind it.
type seedStore interface {
UsernameExists(ctx context.Context, username string) (bool, error)
CreateUser(ctx context.Context, username, passwordHash string, role authz.Role) (*localauth.User, error)
}
// runSeedAdmin is the operator action that bootstraps local login on a
// fresh deployment: idempotent (a no-op if any local user already
// fresh deployment: idempotent (a no-op if the admin account already
// exists, safe to run on every deploy per the runbook), so there's no
// separate "has this already run" flag to track. The generated
// password is printed to stdout exactly once and never stored in
// plaintext anywhere -- losing it means resetting it
// (POST /auth/users/{id}/reset-password), not recovering it.
func runSeedAdmin(ctx context.Context, logger *slog.Logger, stdout io.Writer, store *localauth.Store) int {
n, err := store.CountLocalUsers(ctx)
//
// The check is specifically for the admin account rather than for any
// local user, which is what it used to be. That older test made this
// command useless in the situation it is most needed: an operator who
// no longer has a working administrator account, but whose deployment
// still contains other users, was told "already provisioned" and left
// with nothing to do.
func runSeedAdmin(ctx context.Context, logger *slog.Logger, stdout io.Writer, store seedStore) int {
exists, err := store.UsernameExists(ctx, seedAdminUsername)
if err != nil {
logger.Error("counting local users", "error", err)
logger.Error("checking for an existing admin user", "error", err)
return 1
}
if n > 0 {
fmt.Fprintln(stdout, "admin already provisioned, skipping")
if exists {
fmt.Fprintf(stdout, "%q user already exists, skipping\n", seedAdminUsername)
return 0
}
@@ -289,13 +308,13 @@ func runSeedAdmin(ctx context.Context, logger *slog.Logger, stdout io.Writer, st
logger.Error("hashing password", "error", err)
return 1
}
if _, err := store.CreateUser(ctx, "admin", hash, authz.RoleOwner); err != nil {
if _, err := store.CreateUser(ctx, seedAdminUsername, hash, authz.RoleOwner); err != nil {
logger.Error("creating admin user", "error", err)
return 1
}
fmt.Fprintln(stdout, "created default admin user:")
fmt.Fprintln(stdout, " username: admin")
fmt.Fprintf(stdout, " username: %s\n", seedAdminUsername)
fmt.Fprintf(stdout, " password: %s\n", password)
fmt.Fprintln(stdout, "this password will not be shown again -- save it now.")
return 0
+96
View File
@@ -0,0 +1,96 @@
package main
import (
"bytes"
"context"
"io"
"log/slog"
"strings"
"testing"
"github.com/cairnobs/cairnobs/api/authz"
"github.com/cairnobs/cairnobs/api/localauth"
)
type fakeSeedStore struct {
usernames map[string]bool
created []createdUser
}
type createdUser struct {
username string
role authz.Role
}
func newFakeSeedStore(existing ...string) *fakeSeedStore {
f := &fakeSeedStore{usernames: map[string]bool{}}
for _, u := range existing {
f.usernames[u] = true
}
return f
}
func (f *fakeSeedStore) UsernameExists(_ context.Context, username string) (bool, error) {
return f.usernames[username], nil
}
func (f *fakeSeedStore) CreateUser(_ context.Context, username, _ string, role authz.Role) (*localauth.User, error) {
f.usernames[username] = true
f.created = append(f.created, createdUser{username: username, role: role})
return &localauth.User{ID: "id-" + username, Username: username, Role: role}, nil
}
func discardLogger() *slog.Logger {
return slog.New(slog.NewTextHandler(io.Discard, nil))
}
func TestSeedAdminCreatesTheAdminOnAFreshDeployment(t *testing.T) {
fs := newFakeSeedStore()
var out bytes.Buffer
if code := runSeedAdmin(context.Background(), discardLogger(), &out, fs); code != 0 {
t.Fatalf("runSeedAdmin: exit code = %d, want 0", code)
}
if len(fs.created) != 1 || fs.created[0].username != seedAdminUsername {
t.Fatalf("created = %+v, want one %q", fs.created, seedAdminUsername)
}
if fs.created[0].role != authz.RoleOwner {
t.Fatalf("created role = %q, want %q", fs.created[0].role, authz.RoleOwner)
}
if !strings.Contains(out.String(), "password:") {
t.Fatalf("output does not print the generated password: %q", out.String())
}
}
func TestSeedAdminSkipsWhenTheAdminAlreadyExists(t *testing.T) {
fs := newFakeSeedStore(seedAdminUsername)
var out bytes.Buffer
if code := runSeedAdmin(context.Background(), discardLogger(), &out, fs); code != 0 {
t.Fatalf("runSeedAdmin: exit code = %d, want 0", code)
}
if len(fs.created) != 0 {
t.Fatalf("created = %+v, want none -- a second admin must never be minted", fs.created)
}
if !strings.Contains(out.String(), "skipping") {
t.Fatalf("output does not say it skipped: %q", out.String())
}
}
// The recovery case this command exists for. It used to refuse here,
// because it asked whether the deployment had *any* local user rather
// than whether the admin account it creates was missing -- so an
// operator whose administrator account was gone, but whose deployment
// still held other accounts, was told "already provisioned" and left
// with no supported way back in.
func TestSeedAdminStillSeedsWhenOtherUsersExist(t *testing.T) {
fs := newFakeSeedStore("someone-else")
var out bytes.Buffer
if code := runSeedAdmin(context.Background(), discardLogger(), &out, fs); code != 0 {
t.Fatalf("runSeedAdmin: exit code = %d, want 0", code)
}
if len(fs.created) != 1 || fs.created[0].username != seedAdminUsername {
t.Fatalf("created = %+v, want one %q", fs.created, seedAdminUsername)
}
}