server: admin-credentials REST + Slot:admin push helper

Adds GET/PUT/DELETE /api/hosts/{id}/admin-credentials handlers that
mirror the existing repo-credentials endpoints but write to
store.CredKindAdmin with AEAD additional-data "host:<id>:admin" (scoped
away from the repo slot to prevent cross-binding). PUT immediately pushes
a config.update(Slot:"admin") to the agent when it is connected, and the
new pushAdminCredsToAgent helper is wired for use by the upcoming prune
run-now endpoint (D2) to push on-demand before dispatch.
This commit is contained in:
2026-05-03 22:55:09 +01:00
parent ee8538c928
commit b66eb10524
3 changed files with 412 additions and 0 deletions
@@ -6,6 +6,7 @@ import (
"testing"
"time"
"gitea.dcglab.co.uk/steve/restic-manager/internal/api"
"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
)
@@ -107,3 +108,207 @@ func TestEnrollmentTokenWithoutCreds(t *testing.T) {
t.Errorf("token without creds should return empty blob; got %q", att.EncRepoCreds)
}
}
// ----- admin credentials tests ----------------------------------------
// TestAdminCredentialsRoundTrip verifies set→get→delete→get (404).
func TestAdminCredentialsRoundTrip(t *testing.T) {
t.Parallel()
srv, url, st := newTestServerWithHub(t)
cookie := loginAsAdmin(t, st)
hostID := makeHost(t, st, "admin-creds-host")
// Mark init done so auto-init doesn't interfere.
_ = st.CreateJob(context.Background(), store.Job{
ID: "init-" + hostID,
HostID: hostID,
Kind: string(api.JobInit),
ActorKind: "system",
CreatedAt: time.Now().UTC(),
})
// GET before set → 404.
status, body := doJSON(t, url, "GET", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 404 {
t.Fatalf("before set: want 404, got %d body=%+v", status, body)
}
// PUT — set admin creds.
status, body = doJSON(t, url, "PUT", "/api/hosts/"+hostID+"/admin-credentials",
map[string]any{
"repo_url": "rest:http://admin.example/host",
"repo_username": "admin",
"repo_password": "s3cur3",
}, cookie)
if status != 204 {
t.Fatalf("set: want 204, got %d body=%+v", status, body)
}
// GET — should return redacted view.
status, body = doJSON(t, url, "GET", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 200 {
t.Fatalf("get after set: want 200, got %d body=%+v", status, body)
}
if body["repo_url"] != "rest:http://admin.example/host" {
t.Errorf("repo_url: %+v", body)
}
if body["repo_username"] != "admin" {
t.Errorf("repo_username: %+v", body)
}
if body["has_password"] != true {
t.Errorf("has_password: %+v", body)
}
// DELETE.
status, _ = doJSON(t, url, "DELETE", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 204 {
t.Fatalf("delete: want 204, got %d", status)
}
// GET after delete → 404.
status, _ = doJSON(t, url, "GET", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 404 {
t.Fatalf("after delete: want 404, got %d", status)
}
// Extra: suppress unused import warning by actually using srv in assertion.
_ = srv
}
// TestAdminCredsAADIsolatedFromRepo writes a blob encrypted with the repo
// AAD ("host:<id>") into the admin kind slot, then GETs it — the handler
// should fail to decrypt and return 500 decrypt_failed. This proves the
// AAD scoping is real.
func TestAdminCredsAADIsolatedFromRepo(t *testing.T) {
t.Parallel()
srv, url, st := newTestServerWithHub(t)
cookie := loginAsAdmin(t, st)
hostID := makeHost(t, st, "aad-isolation-host")
ctx := context.Background()
// Encrypt with the REPO AAD (wrong for admin slot).
enc, err := srv.encryptRepoCreds(repoCredsBlob{
RepoURL: "rest:http://r/x",
RepoPassword: "p",
}, []byte("host:"+hostID)) // wrong AAD — repo, not admin
if err != nil {
t.Fatalf("encrypt: %v", err)
}
// Write it directly into the admin kind slot.
if err := st.SetHostCredentials(ctx, hostID, store.CredKindAdmin, enc); err != nil {
t.Fatalf("set host credentials: %v", err)
}
// GET admin-credentials — handler decrypts with admin AAD, which
// is different, so decrypt must fail → 500.
status, body := doJSON(t, url, "GET", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 500 {
t.Fatalf("want 500 (decrypt_failed), got %d body=%+v", status, body)
}
if code, _ := body["code"].(string); code != "decrypt_failed" {
t.Errorf("want code=decrypt_failed, got %+v", body)
}
}
// TestAdminCredsPushOnSet connects a fake WS host, sets admin creds via
// PUT, drains the conn, and asserts a config.update with Slot:"admin"
// was shipped.
func TestAdminCredsPushOnSet(t *testing.T) {
t.Parallel()
srv, ts, st := rawTestServer(t)
hostID, token := enrolHostForWS(t, srv, st, "admin-push-host")
cookie := loginAsAdmin(t, st)
c := agentDial(t, srv, ts, hostID, token)
sendHello(t, c, "admin-push-host")
// Drain the on-hello burst (config.update for repo + schedule.set
// + possibly command.run(init)).
_ = drainUntil(t, c, api.MsgScheduleSet)
// Now PUT admin creds — should trigger an immediate push.
status, body := doJSON(t, ts.URL, "PUT", "/api/hosts/"+hostID+"/admin-credentials",
map[string]any{
"repo_url": "rest:http://admin.example/h",
"repo_username": "admin",
"repo_password": "prune-pass",
}, cookie)
if status != 204 {
t.Fatalf("set admin creds: want 204, got %d body=%+v", status, body)
}
// Drain until we see a config.update with Slot=admin.
deadline := time.Now().Add(3 * time.Second)
found := false
for !found && time.Now().Before(deadline) {
env := readEnvelope(t, c)
if env.Type != api.MsgConfigUpdate {
continue
}
var p api.ConfigUpdatePayload
if err := env.UnmarshalPayload(&p); err != nil {
t.Fatalf("unmarshal config.update: %v", err)
}
if p.Slot == "admin" {
found = true
if p.RepoURL != "rest:http://admin.example/h" {
t.Errorf("admin push: wrong URL %q", p.RepoURL)
}
}
}
if !found {
t.Fatal("timed out waiting for config.update(slot=admin)")
}
}
// TestDeleteAdminCredentialsAuditLogged checks that DELETE appends an
// audit row with action='host.admin_credentials_deleted'.
func TestDeleteAdminCredentialsAuditLogged(t *testing.T) {
t.Parallel()
_, url, st := newTestServerWithHub(t)
cookie := loginAsAdmin(t, st)
hostID := makeHost(t, st, "audit-del-host")
ctx := context.Background()
// Set admin creds first so there is something to delete.
status, body := doJSON(t, url, "PUT", "/api/hosts/"+hostID+"/admin-credentials",
map[string]any{
"repo_url": "rest:http://x/h",
"repo_password": "p",
}, cookie)
if status != 204 {
t.Fatalf("set: want 204, got %d body=%+v", status, body)
}
// Delete.
status, _ = doJSON(t, url, "DELETE", "/api/hosts/"+hostID+"/admin-credentials", nil, cookie)
if status != 204 {
t.Fatalf("delete: want 204, got %d", status)
}
// Query audit_log for the host.
rows, err := st.DB().QueryContext(ctx,
`SELECT action FROM audit_log WHERE target_id = ? AND target_kind = 'host'`, hostID)
if err != nil {
t.Fatalf("query audit: %v", err)
}
defer rows.Close()
found := false
for rows.Next() {
var action string
if err := rows.Scan(&action); err != nil {
t.Fatalf("scan: %v", err)
}
if action == "host.admin_credentials_deleted" {
found = true
}
}
if err := rows.Err(); err != nil {
t.Fatalf("rows: %v", err)
}
if !found {
t.Error("audit row with action='host.admin_credentials_deleted' not found")
}
}