Files
ilkerandClaude Opus 5 262921f5df hpcod: delete an account, for the ones that were never a person
Disabling is the right answer for somebody who has left: it keeps the
record of who registered, who decided and when, which is the point of
having the trail. It is the wrong answer for an account opened to
check that a page works. Ten of those had accumulated on this estate,
each one disabled and each one still in the list.

Two refusals, both in the same transaction as the delete so two
administrators racing cannot step through the gap.

The last active administrator, because nothing else in the system can
grant admin and removing the last one locks everybody out of the
accounts page for good.

An account whose tenant still holds a cluster. The cluster would go
on running, owned by a name nobody can sign in as and reachable by
administrators alone, and the person it belongs to could not release
it. The message says how many and to release them first.

The page keeps the rule the other actions keep - you cannot decide on
your own account - and says in one line when to disable and when to
delete, because the difference is not obvious from two buttons side
by side. The command line takes -delete, and deliberately does not
ask for -by: there is nothing left to attribute the decision to.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 09:24:06 +02:00

209 lines
6.7 KiB
Go

package store
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
)
var (
// ErrAccountExists is returned rather than a constraint error so the
// signup page can say something a person can act on.
ErrAccountExists = errors.New("that username is taken")
ErrNoAccount = errors.New("no such account")
)
// Account is a portal login.
//
// The password hash is deliberately not a field. Everything that renders an
// account - the admin list, a log line, a JSON response - would carry it
// along, and the only code that needs it is the one comparing a password.
// It is returned separately, by the one call that has a reason to see it.
type Account struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email,omitempty"`
Reason string `json:"reason,omitempty"`
State string `json:"state"`
IsAdmin bool `json:"is_admin"`
CreatedAt time.Time `json:"created_at"`
DecidedAt *time.Time `json:"decided_at,omitempty"`
DecidedBy string `json:"decided_by,omitempty"`
}
func (a Account) Pending() bool { return a.State == "pending" }
func (a Account) Active() bool { return a.State == "active" }
const accountColumns = `id, username, coalesce(email,''), coalesce(reason,''),
state, is_admin, created_at, decided_at, coalesce(decided_by,'')`
func scanAccount(row pgx.Row) (*Account, error) {
var a Account
err := row.Scan(&a.ID, &a.Username, &a.Email, &a.Reason,
&a.State, &a.IsAdmin, &a.CreatedAt, &a.DecidedAt, &a.DecidedBy)
return &a, err
}
// CreateAccount registers someone. The result is never usable: state comes
// from the column default and is_admin is not named, so no mistake in a
// handler can produce a live account or an administrator.
func (s *Store) CreateAccount(ctx context.Context, username, passwordHash, email, reason string) (*Account, error) {
a, err := scanAccount(s.pool.QueryRow(ctx, `
INSERT INTO account (username, password_hash, email, reason)
VALUES ($1, $2, nullif($3,''), nullif($4,''))
RETURNING `+accountColumns, username, passwordHash, email, reason))
if isUniqueViolationOn(err, "account_username_key") {
return nil, ErrAccountExists
}
if err != nil {
return nil, err
}
return a, nil
}
// AccountWithHash returns the account and its password hash. The only
// caller with a reason to ask is the one checking a password.
func (s *Store) AccountWithHash(ctx context.Context, username string) (*Account, string, error) {
var a Account
var hash string
err := s.pool.QueryRow(ctx, `
SELECT `+accountColumns+`, password_hash
FROM account WHERE username = $1`, username).Scan(
&a.ID, &a.Username, &a.Email, &a.Reason, &a.State, &a.IsAdmin,
&a.CreatedAt, &a.DecidedAt, &a.DecidedBy, &hash)
if errors.Is(err, pgx.ErrNoRows) {
return nil, "", ErrNoAccount
}
if err != nil {
return nil, "", err
}
return &a, hash, nil
}
// Accounts lists everyone, pending first: that is the list an approver came
// to look at, and it should not be buried under the accounts they have
// already dealt with.
func (s *Store) Accounts(ctx context.Context) ([]Account, error) {
rows, err := s.pool.Query(ctx, `
SELECT `+accountColumns+`
FROM account
ORDER BY state = 'pending' DESC, created_at DESC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Account
for rows.Next() {
a, err := scanAccount(rows)
if err != nil {
return nil, err
}
out = append(out, *a)
}
return out, rows.Err()
}
// DecideAccount approves or refuses one. "by" is required; the database
// will not record a decision nobody owns.
func (s *Store) DecideAccount(ctx context.Context, username, state, by string) (*Account, error) {
if state != "active" && state != "disabled" {
return nil, fmt.Errorf("a decision is active or disabled, not %q", state)
}
if by == "" {
return nil, errors.New("a decision has to say who made it")
}
a, err := scanAccount(s.pool.QueryRow(ctx, `
UPDATE account
SET state = $2, decided_at = now(), decided_by = $3
WHERE username = $1
RETURNING `+accountColumns, username, state, by))
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNoAccount
}
if err != nil {
return nil, err
}
return a, nil
}
// SetAdmin grants or removes administrator rights. Separate from approving,
// because they are different decisions and conflating them is how someone
// gets more than was intended.
// DeleteAccount removes an account outright.
//
// Disabling is the usual answer and keeps the audit trail: who registered,
// who decided, when. Deleting is for the accounts that should not be in
// the trail at all - the ones opened to verify something and never used by
// a person.
//
// Two things it refuses, both in the same transaction as the delete so
// that two administrators racing cannot step through the gap:
//
// The last active administrator. Nothing else in the system can grant
// admin, so removing the last one locks everybody out of the accounts
// page permanently.
//
// An account whose tenant still holds a cluster. The cluster would go on
// running, owned by a name nobody can sign in as, reachable by
// administrators alone - and the person it belongs to would not be able
// to release it.
func (s *Store) DeleteAccount(ctx context.Context, username string) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
var held int
if err := tx.QueryRow(ctx, `
SELECT count(*) FROM cluster c JOIN tenant t ON t.id = c.tenant_id
WHERE t.name = $1 AND c.destroyed_at IS NULL`, username).Scan(&held); err != nil {
return err
}
if held > 0 {
return fmt.Errorf("%s still holds %d cluster(s); release them first", username, held)
}
tag, err := tx.Exec(ctx, `DELETE FROM account WHERE username = $1`, username)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("no account %q", username)
}
var admins int
if err := tx.QueryRow(ctx,
`SELECT count(*) FROM account WHERE is_admin AND state = 'active'`).Scan(&admins); err != nil {
return err
}
if admins == 0 {
return fmt.Errorf("%s is the last active administrator; grant it to somebody else first", username)
}
return tx.Commit(ctx)
}
func (s *Store) SetAdmin(ctx context.Context, username string, admin bool) (*Account, error) {
a, err := scanAccount(s.pool.QueryRow(ctx, `
UPDATE account SET is_admin = $2 WHERE username = $1
RETURNING `+accountColumns, username, admin))
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNoAccount
}
if err != nil {
return nil, err
}
return a, nil
}
// PendingCount is what the admin navigation shows a badge for.
func (s *Store) PendingCount(ctx context.Context) (int, error) {
var n int
err := s.pool.QueryRow(ctx, `SELECT count(*) FROM account WHERE state = 'pending'`).Scan(&n)
return n, err
}