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

431 lines
15 KiB
Go

package httpapi
import (
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
"github.com/ilkermanap/hpcod/internal/store"
)
func postForm(t *testing.T, h func(http.ResponseWriter, *http.Request), path string, form url.Values) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
h(w, r)
return w
}
func goodSignup() url.Values {
return url.Values{
"username": {"newcomer"},
"password": {"correct-horse-battery"},
"email": {"n@example.invalid"},
"reason": {"molecular dynamics for a term project"},
}
}
// The whole point: registering gets you a row, not an account.
func TestSignupCreatesSomethingUnusable(t *testing.T) {
f := &fakeStore{}
s := testServerWithPages(t, f)
w := postForm(t, s.pageSignup, "/signup", goodSignup())
if w.Code != http.StatusOK {
t.Fatalf("status %d", w.Code)
}
if !strings.Contains(w.Body.String(), "Registered") {
t.Fatalf("no confirmation shown: %s", w.Body)
}
a := f.accounts["newcomer"]
if a == nil {
t.Fatal("no account was created")
}
if a.State != "pending" {
t.Errorf("state = %q, want pending", a.State)
}
if a.IsAdmin {
t.Error("signup produced an administrator")
}
// And the password was hashed on the way in.
if len(f.hashes) != 1 || !strings.HasPrefix(f.hashes[0], "$2") {
t.Errorf("stored credential is not a bcrypt hash: %q", f.hashes)
}
if strings.Contains(strings.Join(f.hashes, ""), "correct-horse-battery") {
t.Error("the password was stored in the clear")
}
}
// If the database ever stops defaulting to pending, the handler must not
// quietly hand out the account.
func TestSignupRefusesAnAccountThatCameBackUsable(t *testing.T) {
for _, bad := range []func(*store.Account) *store.Account{
func(a *store.Account) *store.Account { a.State = "active"; return a },
func(a *store.Account) *store.Account { a.IsAdmin = true; return a },
} {
f := &fakeStore{createOverride: bad}
s := testServerWithPages(t, f)
w := postForm(t, s.pageSignup, "/signup", goodSignup())
if strings.Contains(w.Body.String(), "Registered") {
t.Error("a usable account was accepted as a normal registration")
}
if a := f.accounts["newcomer"]; a == nil || a.State != "disabled" {
t.Errorf("the account was not disabled: %+v", a)
}
}
}
func TestSignupValidation(t *testing.T) {
cases := map[string]url.Values{
"short username": {"username": {"ab"}, "password": {"correct-horse-battery"}, "reason": {"x"}},
"bad characters": {"username": {"new comer"}, "password": {"correct-horse-battery"}, "reason": {"x"}},
"short password": {"username": {"newcomer"}, "password": {"short"}, "reason": {"x"}},
"no reason": {"username": {"newcomer"}, "password": {"correct-horse-battery"}, "reason": {""}},
"bad email": {"username": {"newcomer"}, "password": {"correct-horse-battery"}, "reason": {"x"}, "email": {"nope"}},
}
for name, form := range cases {
t.Run(name, func(t *testing.T) {
f := &fakeStore{}
s := testServerWithPages(t, f)
w := postForm(t, s.pageSignup, "/signup", form)
if strings.Contains(w.Body.String(), "Registered") {
t.Error("accepted")
}
if len(f.accounts) != 0 {
t.Errorf("an account was created anyway: %v", f.accounts)
}
})
}
}
func TestSignupKeepsWhatWasTypedOnError(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
form := goodSignup()
form.Set("password", "short")
w := postForm(t, s.pageSignup, "/signup", form)
body := w.Body.String()
if !strings.Contains(body, "molecular dynamics") || !strings.Contains(body, "newcomer") {
t.Error("the form was cleared, so the person has to start over")
}
if strings.Contains(body, "short") {
t.Error("the password was echoed back into the page")
}
}
// ---------- who may sign in ----------
func TestPendingAndDisabledAccountsCannotSignIn(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse-battery"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
f := &fakeStore{
accounts: map[string]*store.Account{
"waiting": {Username: "waiting", State: "pending"},
"blocked": {Username: "blocked", State: "disabled"},
"welcome": {Username: "welcome", State: "active"},
"theboss": {Username: "theboss", State: "active", IsAdmin: true},
},
hashFor: map[string]string{
"waiting": string(hash), "blocked": string(hash),
"welcome": string(hash), "theboss": string(hash),
},
}
a := &authStore{
accounts: f, users: map[string]string{}, sessions: map[string]*session{},
fails: map[string]*failure{}, idleTTL: time.Hour, absTTL: time.Hour,
}
for _, c := range []struct {
user string
ok bool
admin bool
reason string
}{
{"waiting", false, false, "approve"},
{"blocked", false, false, "disabled"},
{"welcome", true, false, ""},
{"theboss", true, true, ""},
} {
got := a.authenticate(t.Context(), c.user, "correct-horse-battery", "10.0.0.1")
if got.OK != c.ok {
t.Errorf("%s: OK = %v, want %v (%s)", c.user, got.OK, c.ok, got.Reason)
}
if got.Admin != c.admin {
t.Errorf("%s: Admin = %v, want %v", c.user, got.Admin, c.admin)
}
if c.reason != "" && !strings.Contains(got.Reason, c.reason) {
t.Errorf("%s: reason %q does not mention %q", c.user, got.Reason, c.reason)
}
}
}
// The reason must never be more specific than "no" for a wrong password -
// otherwise it says which usernames exist.
func TestAWrongPasswordNeverExplainsItself(t *testing.T) {
hash, _ := bcrypt.GenerateFromPassword([]byte("correct-horse-battery"), bcrypt.MinCost)
f := &fakeStore{
accounts: map[string]*store.Account{"waiting": {Username: "waiting", State: "pending"}},
hashFor: map[string]string{"waiting": string(hash)},
}
a := &authStore{
accounts: f, users: map[string]string{}, sessions: map[string]*session{},
fails: map[string]*failure{}, idleTTL: time.Hour, absTTL: time.Hour,
}
withPassword := a.authenticate(t.Context(), "waiting", "wrong-password-here", "10.0.0.1")
noSuchUser := a.authenticate(t.Context(), "nobody", "wrong-password-here", "10.0.0.2")
if withPassword.Reason != noSuchUser.Reason {
t.Errorf("a pending account with the wrong password says %q, an unknown user says %q;"+
" the difference tells an attacker the account exists",
withPassword.Reason, noSuchUser.Reason)
}
}
// ---------- approval ----------
func adminRequest(method, path string, form url.Values) *http.Request {
var r *http.Request
if form == nil {
r = httptest.NewRequest(method, path, nil)
} else {
r = httptest.NewRequest(method, path, strings.NewReader(form.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return r.WithContext(withUser(r.Context(), "theboss", true))
}
func TestOnlyAnAdministratorSeesAccounts(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
// A signed-in operator who is not an administrator gets nothing - not a
// 403, which would confirm the page exists.
r := httptest.NewRequest(http.MethodGet, "/admin/accounts", nil)
r = r.WithContext(withUser(r.Context(), "someone", false))
w := httptest.NewRecorder()
s.pageAccounts(w, r)
if w.Code != http.StatusNotFound {
t.Errorf("non-admin got %d, want 404", w.Code)
}
w = httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodGet, "/admin/accounts", nil))
if w.Code != http.StatusOK {
t.Errorf("admin got %d, want 200", w.Code)
}
}
func TestApprovalMakesAnAccountUsable(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{
"newcomer": {Username: "newcomer", State: "pending"},
}}
s := testServerWithPages(t, f)
w := httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodPost, "/admin/accounts",
url.Values{"username": {"newcomer"}, "do": {"approve"}}))
if w.Code != http.StatusSeeOther {
t.Fatalf("status %d", w.Code)
}
a := f.accounts["newcomer"]
if a.State != "active" {
t.Errorf("state = %q, want active", a.State)
}
if a.DecidedBy != "theboss" {
t.Errorf("decided by %q; a decision has to be attributed", a.DecidedBy)
}
if a.IsAdmin {
t.Error("approving also made them an administrator")
}
}
// Deciding on yourself is either pointless or a way to lock the last
// administrator out of their own portal.
func TestAnAdminCannotDecideOnThemselves(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{
"theboss": {Username: "theboss", State: "active", IsAdmin: true},
}}
s := testServerWithPages(t, f)
for _, do := range []string{"disable", "revoke-admin", "approve"} {
w := httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodPost, "/admin/accounts",
url.Values{"username": {"theboss"}, "do": {do}}))
if w.Code != http.StatusBadRequest {
t.Errorf("%s on self gave %d, want 400", do, w.Code)
}
}
if a := f.accounts["theboss"]; a.State != "active" || !a.IsAdmin {
t.Errorf("the administrator changed anyway: %+v", a)
}
}
func TestSignupIsRateLimited(t *testing.T) {
var l signupLimiter // the zero value has to work
if !l.allow("10.0.0.1") {
t.Fatal("the first attempt was refused")
}
if l.allow("10.0.0.1") {
t.Error("a second attempt from the same address was allowed straight away")
}
if !l.allow("10.0.0.2") {
t.Error("a different address was caught by another address's limit")
}
}
// An admin-only route must not be advertised to people who cannot use it.
func TestTheAccountsLinkIsOnlyShownToAdministrators(t *testing.T) {
s := testServerWithPages(t, &fakeStore{})
r := httptest.NewRequest(http.MethodGet, "/clusters", nil)
r = r.WithContext(withUser(r.Context(), "someone", false))
w := httptest.NewRecorder()
s.pageClusters(w, r)
if strings.Contains(w.Body.String(), "/admin/accounts") {
t.Error("a non-admin was shown the Accounts link")
}
w = httptest.NewRecorder()
s.pageClusters(w, adminRequest(http.MethodGet, "/clusters", nil))
if !strings.Contains(w.Body.String(), "/admin/accounts") {
t.Error("an administrator was not shown the Accounts link")
}
}
// Rights and access are re-read per request. If they were not, disabling
// an account would take up to twelve hours to mean anything.
func TestRevokingTakesEffectWithoutWaitingForTheSession(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{
"someone": {Username: "someone", State: "active", IsAdmin: true},
}}
s := testServerWithPages(t, f)
a := &authStore{
accounts: f, users: map[string]string{}, sessions: map[string]*session{},
fails: map[string]*failure{}, idleTTL: time.Hour, absTTL: time.Hour,
}
s.auth = a
tok := a.newSession("someone", true, "10.0.0.1")
h := a.middleware(http.HandlerFunc(s.pageAccounts), []byte("login"), "")
get := func() int {
r := httptest.NewRequest(http.MethodGet, "/admin/accounts", nil)
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: tok})
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code
}
if code := get(); code != http.StatusOK {
t.Fatalf("the administrator got %d", code)
}
// Revoked mid-session: the very next request must not be an admin.
f.accounts["someone"].IsAdmin = false
if code := get(); code != http.StatusNotFound {
t.Errorf("after revoking, got %d; the old session kept its rights", code)
}
// Disabled mid-session: the session itself has to end.
f.accounts["someone"].IsAdmin = true
f.accounts["someone"].State = "disabled"
if code := get(); code != http.StatusSeeOther {
t.Errorf("a disabled account got %d, want a redirect to the login", code)
}
if a.lookup(tok) != nil {
t.Error("the session survived the account being disabled")
}
}
// The bootstrap account lives only in the file and must keep working, or a
// database problem locks the operator out of the machine that fixes it.
func TestTheFileAccountSurvivesAnEmptyDatabase(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{}}
a := &authStore{
accounts: f, users: map[string]string{"bootstrap": aBcryptHash},
sessions: map[string]*session{}, fails: map[string]*failure{},
idleTTL: time.Hour, absTTL: time.Hour,
}
admin, ok := a.stillAllowed(t.Context(), "bootstrap")
if !ok || !admin {
t.Errorf("the file account: admin=%v ok=%v, want both true", admin, ok)
}
// Someone who is in neither place is not allowed.
if _, ok := a.stillAllowed(t.Context(), "ghost"); ok {
t.Error("an account in neither the file nor the database was allowed")
}
}
const aBcryptHash = "$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"
// Deleting is for the accounts opened to verify something and never used
// by a person. Disabling is the answer for anyone else, and the page says
// so - but the endpoint has to hold the same lines the other actions do.
func TestDeletingAnAccount(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{
"throwaway": {Username: "throwaway", State: "disabled"},
"theboss": {Username: "theboss", State: "active", IsAdmin: true},
}}
s := testServerWithPages(t, f)
w := httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodPost, "/admin/accounts",
url.Values{"username": {"throwaway"}, "do": {"delete"}}))
if w.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want 303: %s", w.Code, w.Body)
}
if len(f.deleted) != 1 || f.deleted[0] != "throwaway" {
t.Errorf("deleted = %v", f.deleted)
}
}
// The same rule the other actions keep: you cannot decide on your own
// account, and deleting yourself is the most final way to get it wrong.
func TestYouCannotDeleteYourself(t *testing.T) {
f := &fakeStore{accounts: map[string]*store.Account{
"theboss": {Username: "theboss", State: "active", IsAdmin: true},
}}
s := testServerWithPages(t, f)
w := httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodPost, "/admin/accounts",
url.Values{"username": {"theboss"}, "do": {"delete"}}))
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
if len(f.deleted) != 0 {
t.Errorf("deleted anyway: %v", f.deleted)
}
}
// A refusal from the store - the last administrator, or an account still
// holding a cluster - has to reach the page rather than being swallowed.
func TestARefusedDeleteSaysWhy(t *testing.T) {
f := &fakeStore{
accounts: map[string]*store.Account{"acme": {Username: "acme", State: "active"}},
deleteErr: errors.New("acme still holds 2 cluster(s); release them first"),
}
s := testServerWithPages(t, f)
w := httptest.NewRecorder()
s.pageAccounts(w, adminRequest(http.MethodPost, "/admin/accounts",
url.Values{"username": {"acme"}, "do": {"delete"}}))
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", w.Code)
}
if !strings.Contains(w.Body.String(), "still holds 2 cluster") {
t.Errorf("the reason was not passed on: %s", w.Body)
}
}