From d84a56b28df2e1f35dcd29c56df3bdacc5e7415b Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 07:25:22 -0500 Subject: [PATCH 1/6] =?UTF-8?q?reporting:=20traffic-light=20scorecard,=20h?= =?UTF-8?q?ealth=20overlay=20and=20exports=20(spec=20=C2=A78.1,=20=C2=A78.?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit internal/reporting builds one authorized dataset (admins see every account; others the accounts they own or whose current policy lists a principal enrolled with their own issuer and subject), classifies each active account Green / Yellow / Red by schedule plus release evidence, then current envelope, overlays one health value, and filters by class, health, pool, account attributes and owner attributes. GET /api/reports/scorecard serves the dashboard; format=json|csv serves the same rows and totals as an audited download. Percentages always sum to 100; CSV formula cells are neutralized. GET /api/jobs lists rotation runs and checkout leases for the jobs screen. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + docs/DECISIONS.md | 14 + docs/INTERFACES.md | 10 + internal/api/AGENTS.md | 4 + internal/api/report_handlers.go | 104 +++++++ internal/api/report_test.go | 259 +++++++++++++++++ internal/api/server.go | 1 + internal/reporting/AGENTS.md | 31 +++ internal/reporting/reporting.go | 401 +++++++++++++++++++++++++++ internal/reporting/reporting_test.go | 112 ++++++++ internal/store/AGENTS.md | 1 + internal/store/inventory.go | 6 + internal/store/inventory_reports.go | 115 ++++++++ 13 files changed, 1059 insertions(+) create mode 100644 internal/api/report_handlers.go create mode 100644 internal/api/report_test.go create mode 100644 internal/reporting/AGENTS.md create mode 100644 internal/reporting/reporting.go create mode 100644 internal/reporting/reporting_test.go create mode 100644 internal/store/inventory_reports.go diff --git a/AGENTS.md b/AGENTS.md index ea77efd..18a3d71 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -150,6 +150,7 @@ overlay merges with synthetic inputs and starts no containers. - [internal/backup/AGENTS.md](internal/backup/AGENTS.md): Product-side adapters over `ky-primitives/recoveryclient`: payload collection, drill checks, settings and sealer glue. - [internal/testdb/AGENTS.md](internal/testdb/AGENTS.md): Test-only isolated database provisioning (SQLite or PostgreSQL). - [internal/api/AGENTS.md](internal/api/AGENTS.md): HTTP REST API endpoints, routing, and middleware. +- [internal/reporting/AGENTS.md](internal/reporting/AGENTS.md): Traffic-light scorecard, health overlay, filters and CSV/JSON export (spec §8). - [web/AGENTS.md](web/AGENTS.md): React 19 + TypeScript + Vite PWA frontend and KySecurity design system. `docs/REPLICAS.md` owns topology, shared secrets, health/drain, the Compose replica overlay diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 24b82f8..062aaf6 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -240,3 +240,17 @@ contradicts itself. Each names its section. The most secure reading wins. strictly, is in the 1A slice and names the bundle's deployment and the account's own account and asset. It stores the canonical bytes, so the digest a Custodian sees is the digest of the stored row. +205. §8.1 (overdue). An account is `overdue` when the newest occurrence due at least one + `interval_seconds` ago came after its last `release` receipt (Control Plane time). +206. §8.1 (one health value). Health is a single value: a non-`healthy` broker report wins, + then `checkout_open`, `pending_first_rotation`, `overdue`, else `healthy`. It never + changes the class. +207. §8.3 (listed on in the policy). A non-admin is listed when a principal in any of the + current policy's principal lists has a verified `KeyEnrollmentManifest` whose issuer + and subject are the caller's own; a subject alone never matches. This build knows the + issuer only for KySignOn sign-ins (`KY_KYSIGNON_ISSUER`); every other caller sees only + accounts they own until `users.sso_issuer` (§7.2) is joined in. +208. §8.3 (what is audited). The dashboard view is not an export and is not audited; every + `format=json` or `format=csv` download is, before its body is sent. CSV cells that a + spreadsheet would run as a formula are prefixed with `'`. + diff --git a/docs/INTERFACES.md b/docs/INTERFACES.md index f133ab4..33ece90 100644 --- a/docs/INTERFACES.md +++ b/docs/INTERFACES.md @@ -559,6 +559,16 @@ carries `TODO(hawthorn §7.5)` until the route registry classifies it. | DELETE `/api/attributes/{id}` | Administrator | 204; the values go with it; 400 for a SCIM definition | | PUT `/api/attributes/{id}/values/{entity_id}` | Administrator; JSON `{"value"}` (≤256 printable characters, `""` clears) | 200; 400 for a SCIM attribute, an enum value outside the list or an unknown account or user; audited `attribute.value_set` | +### Scorecard and jobs (spec §8.1–§8.3, §10) + +Source: [report handlers](../internal/api/report_handlers.go), [reporting](../internal/reporting/reporting.go). + +| Route | Authentication and input | Success | +|---|---|---| +| GET `/api/reports/scorecard` | Any active session; filters `class`, `health`, `pool`, `attr.`, `owner.` (equality) | 200 `{generated_at, totals:{active, decommissioned, classes, percent, health}, account_attribute_keys, owner_attribute_keys, rows}`; admins see every account, others the accounts they own or are listed on in the current policy | +| GET `/api/reports/scorecard?format=json\|csv` | Same | 200 download (`Content-Disposition: attachment`, `no-store`) with the same rows and totals; CSV has the fixed columns, then `attr.` and `owner.`. Audited `report.exported` (format, row count, filter) before the body is sent; 500 and no body if the audit fails | +| GET `/api/jobs` | Administrator | 200 `{runs, leases}`: the 200 newest rotation runs and checkout leases, open leases first | + ## Replicas and database migration [Replication and migration](REPLICAS.md) owns deployment requirements and the cutover runbook. diff --git a/internal/api/AGENTS.md b/internal/api/AGENTS.md index 79879e0..2ff636d 100644 --- a/internal/api/AGENTS.md +++ b/internal/api/AGENTS.md @@ -18,6 +18,10 @@ Owns HTTP routing, request parsing, session cookie validation, CORS headers, and JSON (unknown fields refused), audited in the store transaction, `TODO(hawthorn §7.5)` until classified. Descriptor upload decodes with `pqcrypto.DecodeTargetDescriptor` and stores the canonical bytes. +- `report_handlers.go`: GET `/api/reports/scorecard` (session) serves the dashboard and, + with `format=json|csv`, an audited download from the same `reporting.Build` dataset and + filter; GET `/api/jobs` (admin). `callerIssuer` names the caller's issuer only for + KySignOn users until `users.sso_issuer` is joined in. - Update `docs/INTERFACES.md` when a route's inputs, outputs, permissions or errors change. - POST `/api/auth/change-password` accepts any local-account session (restricted or not; federated accounts get 409), current password and a different policy-valid new password. Browser CSRF and per-IP/account limits apply. Success revokes all sessions and requires sign-in again; flagged sessions get `password_change_required` on protected routes and public-only settings. - `GET|HEAD /livez` and `/readyz` (`health.go`) are unauthenticated, `Cache-Control: no-store`, diff --git a/internal/api/report_handlers.go b/internal/api/report_handlers.go new file mode 100644 index 0000000..d1dd904 --- /dev/null +++ b/internal/api/report_handlers.go @@ -0,0 +1,104 @@ +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "time" + + "github.com/Busnes-app/kyguard-server/internal/reporting" + "github.com/Busnes-app/kyguard-server/internal/store" +) + +func (s *Server) reportRoutes() { + // TODO(hawthorn §7.5): classify (session). The dataset is authorized per caller (§8.3). + s.mux.HandleFunc("GET /api/reports/scorecard", s.requireAuthenticated(s.handleScorecard)) + // TODO(hawthorn §7.5): classify (session). + s.mux.HandleFunc("GET /api/jobs", s.requireAdmin(s.handleJobs)) +} + +// callerIssuer is the issuer of the caller's SSO identity, or "" when this build cannot +// name it, so a principal can never be matched to them by subject alone. +// TODO(join): use users.sso_issuer from hawthorn's §7.2 stack. +func (s *Server) callerIssuer(u *store.User) string { + if u.SSOProvider == "kysignon" && u.SSOSubject != "" { + return s.config.SSO.KySignOnIssuer + } + return "" +} + +type scorecard struct { + GeneratedAt time.Time `json:"generated_at"` + Totals reporting.Totals `json:"totals"` + AccountKeys []string `json:"account_attribute_keys"` + OwnerKeys []string `json:"owner_attribute_keys"` + Rows []*reporting.Row `json:"rows"` +} + +// handleScorecard serves the dashboard (no format) and the exports (format=json|csv) from +// one dataset, one classifier and one filter (§8.3). Exports are downloads and audited. +func (s *Server) handleScorecard(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + u, _, err := s.sessions.AuthenticateRequest(r) + if err != nil { + s.writeError(w, http.StatusUnauthorized, "Authentication required") + return + } + q := r.URL.Query() + format := q.Get("format") + if format != "" && format != "json" && format != "csv" { + s.writeError(w, http.StatusBadRequest, "format is json or csv") + return + } + now := time.Now().UTC() + ds, err := reporting.Build(ctx, s.store, s.trust, reporting.Caller{UserID: u.ID, Admin: u.Role == "admin", Issuer: s.callerIssuer(u), Subject: u.SSOSubject}, now) + if err != nil { + s.writeError(w, http.StatusInternalServerError, "could not build the scorecard") + return + } + f := reporting.ParseFilter(q) + rows := f.Apply(ds.Rows) + card := scorecard{GeneratedAt: now, Totals: reporting.Summarize(rows, ds.Decommissioned), AccountKeys: ds.AccountKeys, OwnerKeys: ds.OwnerKeys, Rows: rows} + if format == "" { + s.writeJSON(w, http.StatusOK, card) + return + } + var body bytes.Buffer + ctype := "application/json" + if format == "csv" { + ctype = "text/csv; charset=utf-8" + err = reporting.WriteCSV(&body, ds, rows) + } else { + err = json.NewEncoder(&body).Encode(card) + } + if err != nil { + s.writeError(w, http.StatusInternalServerError, "could not write the export") + return + } + // The audit row lands before a byte of the export leaves (§8.3, §9.3). + if err := s.store.Audit().LogAudit(ctx, s.audit(r, "report.exported", "scorecard", + map[string]any{"format": format, "rows": len(rows), "filter": r.URL.Query().Encode()})); err != nil { + s.writeError(w, http.StatusInternalServerError, "could not audit the export") + return + } + w.Header().Set("Content-Type", ctype) + w.Header().Set("Content-Disposition", `attachment; filename="kyguard-scorecard-`+now.Format("20060102T150405Z")+`.`+format+`"`) + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body.Bytes()) +} + +// handleJobs lists recent rotation runs and checkout leases for the jobs screen (§10). +func (s *Server) handleJobs(w http.ResponseWriter, r *http.Request) { + runs, err := s.store.Inventory().RecentRuns(r.Context(), 200) + if err != nil { + s.writeError(w, http.StatusInternalServerError, "could not list rotation runs") + return + } + leases, err := s.store.Inventory().RecentLeases(r.Context(), 200) + if err != nil { + s.writeError(w, http.StatusInternalServerError, "could not list leases") + return + } + s.writeJSON(w, http.StatusOK, map[string]any{"runs": runs, "leases": leases}) +} diff --git a/internal/api/report_test.go b/internal/api/report_test.go new file mode 100644 index 0000000..d1568f0 --- /dev/null +++ b/internal/api/report_test.go @@ -0,0 +1,259 @@ +package api_test + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Busnes-app/ky-primitives/recoverykey" + + "github.com/Busnes-app/kyguard-server/internal/api" + "github.com/Busnes-app/kyguard-server/internal/auth" + "github.com/Busnes-app/kyguard-server/internal/brokerproto" + "github.com/Busnes-app/kyguard-server/internal/config" + "github.com/Busnes-app/kyguard-server/internal/pqcrypto" + "github.com/Busnes-app/kyguard-server/internal/pqcrypto/pqtest" + "github.com/Busnes-app/kyguard-server/internal/store" + "github.com/Busnes-app/kyguard-server/internal/testdb" +) + +type card struct { + Totals struct { + Active, Decommissioned int + Classes map[string]int + Percent map[string]int + Health map[string]int + } `json:"totals"` + Rows []struct { + AccountID string `json:"account_id"` + Class string `json:"class"` + Health string `json:"health"` + } `json:"rows"` +} + +func getCard(t *testing.T, srv *api.Server, c *http.Cookie, query string) (*httptest.ResponseRecorder, card) { + t.Helper() + w := sendJSON(srv, c, "GET", "/api/reports/scorecard"+query, "") + var out card + if w.Code == http.StatusOK && strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") { + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + } + return w, out +} + +// Acceptance 12 (§8.1–§8.3): classes sum to the active count; the dashboard, the JSON +// export and the CSV export agree for one filter; a department filter from SCIM reaches +// accounts through their owner; a non-admin sees only what they own or are listed on. +func TestScorecard(t *testing.T) { + dir := t.TempDir() + if _, err := brokerproto.CreateCA(dir); err != nil { + t.Fatal(err) + } + t.Setenv("KY_DATA_DIR", dir) + t.Setenv("KY_KYSIGNON_ISSUER", "https://idp.example.test") + cfg, err := config.LoadFromEnv() + if err != nil { + t.Fatal(err) + } + cfg.Database = testdb.Config(t) + cfg.Database.DataDir = dir + cfg.Captcha.Provider = "none" + st, err := store.Open(context.Background(), cfg.Database) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + d := pqtest.New(t) + ctx := context.Background() + if err := st.Guard().ImportBundle(ctx, &store.BootstrapBundle{DeploymentID: string(d.ID), Fingerprint: string(d.Fingerprint), Bundle: d.Bundle}, "host"); err != nil { + t.Fatal(err) + } + srv := api.NewServer(cfg, st) + admin := loginAs(t, srv, st, "admin1", "admin") + owner := loginAs(t, srv, st, "owner1", "user") + submit := func(raw []byte) { + t.Helper() + if w := postJSON(srv, admin, "/api/manifests", raw); w.Code != http.StatusCreated { + t.Fatalf("manifest: %d %s", w.Code, w.Body) + } + } + + // carol signs in through KySignOn and is enrolled as a principal with the same identity. + carolP := pqtest.NewPrincipal(t) + carol := &store.User{ID: "usr_carol", Username: "carol", Role: "user", Status: "active", SSOProvider: "kysignon", SSOSubject: "sub-" + string(carolP.ID)} + if err := st.Users().CreateUser(ctx, carol); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + if _, _, err := auth.NewSessionManager(st, cfg.Security).IssueSession(ctx, rec, httptest.NewRequest("GET", "/", nil), carol); err != nil { + t.Fatal(err) + } + carolCookie := rec.Result().Cookies()[0] + submit(d.Enrollment(t, carolP, 1)) + + pool := pqtest.UUID() + sig, _ := pqcrypto.GenerateSigningKey() + enc, _ := recoverykey.Generate() + b := &pqtest.Broker{ID: pqtest.UUID(), Sig: sig, Enc: enc, CertSHA256: pqcrypto.HexID(strings.Repeat("cd", 32))} + submit(d.Pool(t, pool, 1, []pqcrypto.BrokerMember{b.Member(pqcrypto.StatusActive)}, nil)) + if err := st.Guard().CreatePool(ctx, &store.BrokerPool{ID: string(pool), Name: "p", CreatedAt: time.Now().UTC()}, nil); err != nil { + t.Fatal(err) + } + var asset store.Asset + created(t, sendJSON(srv, admin, "POST", "/api/assets", `{"name":"dc1"}`), &asset) + account := func(name, kind, ownerID string) string { + t.Helper() + body := `{"asset_id":"` + asset.ID + `","name":"` + name + `","account_kind":"` + kind + `"` + if kind == "managed" { + body += `,"pool_id":"` + string(pool) + `"` + } + if ownerID != "" { + body += `,"owner_user_id":"` + ownerID + `"` + } + var a store.InventoryAccount + created(t, sendJSON(srv, admin, "POST", "/api/accounts", body+`}`), &a) + return a.ID + } + green := account("green", "managed", "usr_owner1") + yellow := account("yellow", "vaulted", "usr_owner1") + red := account("red", "managed", "") + listedRed := account("listed", "managed", "") + gone := account("gone", "vaulted", "usr_owner1") + + // green: a scheduled policy and a released rotation; listed: carol is an approver. + key := pqcrypto.HexID(strings.Repeat("ab", 32)) + for _, id := range []string{green, listedRed} { + raw, dg := d.SSHTarget(t, pqcrypto.UUID(id), pqcrypto.UUID(asset.ID), "h", 22, "root", key) + if w := sendJSON(srv, admin, "PUT", "/api/accounts/"+id+"/target-descriptor", string(raw)); w.Code != http.StatusOK { + t.Fatalf("descriptor: %d %s", w.Code, w.Body) + } + pol := d.ManagedPolicy(pqcrypto.UUID(id), pool, 1, dg) + if id == green { + pol.RotationSchedule = &pqcrypto.Schedule{AnchorUTC: pqcrypto.NewTime(time.Now().Add(-time.Hour)), IntervalSeconds: 86400} + } else { + pol.AllowedApproverPrincipalIDs = []pqcrypto.UUID{carolP.ID} + } + submit(d.Signed(t, pol)) + } + seal := func(acct, receipt string) { + t.Helper() + v := st.Vault() + op := "op-" + acct + ver, err := v.Reserve(ctx, acct, op, 0) + if err != nil { + t.Fatal(err) + } + env := "env-" + acct + if err := v.PutEnvelope(ctx, op, &store.StoredEnvelope{EnvelopeID: env, AccountID: acct, SecretVersion: ver, EnvelopeKind: "managed", Digest: "d-" + acct, Envelope: []byte("{}")}); err != nil { + t.Fatal(err) + } + rs := []*store.StoredReceipt{{EnvelopeID: env, ReceiptSeq: 1, ReceiptType: receipt, OperationID: op, Digest: "r1-" + acct, PrevReceiptHash: strings.Repeat("0", 64), Receipt: []byte("1")}} + if receipt == "commit_target" { + rs = append(rs, &store.StoredReceipt{EnvelopeID: env, ReceiptSeq: 2, ReceiptType: "release", OperationID: op, Digest: "r2-" + acct, PrevReceiptHash: "r1-" + acct, Receipt: []byte("2")}) + } + if err := v.Complete(ctx, op, acct, rs, env, "", store.LockDelete); err != nil { + t.Fatal(err) + } + } + seal(green, "commit_target") + seal(yellow, "vault_commit") + if w := sendJSON(srv, admin, "PATCH", "/api/accounts/"+gone, `{"status":"decommissioned"}`); w.Code != http.StatusOK { + t.Fatal(w.Code) + } + + // The owner's department comes from SCIM (§8.2). + dept, err := st.Inventory().EnsureDefinition(ctx, &store.AttributeDefinition{ID: string(pqtest.UUID()), Entity: store.EntityUser, Key: "department", Label: "Department", Type: store.AttrString, Source: store.SourceSCIM}, nil) + if err != nil { + t.Fatal(err) + } + if err := st.Inventory().SetValue(ctx, dept.ID, "usr_owner1", "Ops", store.SourceSCIM, nil); err != nil { + t.Fatal(err) + } + + _, all := getCard(t, srv, admin, "") + want := map[string]string{green: "green", yellow: "yellow", red: "red", listedRed: "red"} + if all.Totals.Active != 4 || all.Totals.Decommissioned != 1 || len(all.Rows) != 4 { + t.Fatalf("totals %+v", all.Totals) + } + for _, r := range all.Rows { + if want[r.AccountID] != r.Class { + t.Errorf("%s: class %s, want %s", r.AccountID, r.Class, want[r.AccountID]) + } + } + c := all.Totals.Classes + if c["green"]+c["yellow"]+c["red"] != all.Totals.Active || c["green"] != 1 || c["yellow"] != 1 || c["red"] != 2 { + t.Fatalf("classes %v", c) + } + if p := all.Totals.Percent; p["green"]+p["yellow"]+p["red"] != 100 { + t.Fatalf("percent %v", p) + } + + // One filter, three outputs, identical rows. + q := "?owner.department=Ops" + _, dash := getCard(t, srv, admin, q) + wj, exp := getCard(t, srv, admin, q+"&format=json") + if wj.Header().Get("Content-Disposition") == "" { + t.Fatal("JSON export is not a download") + } + wc := sendJSON(srv, admin, "GET", "/api/reports/scorecard"+q+"&format=csv", "") + recs, err := csv.NewReader(bytes.NewReader(wc.Body.Bytes())).ReadAll() + if err != nil || wc.Code != http.StatusOK { + t.Fatalf("csv %d %v", wc.Code, err) + } + if len(dash.Rows) != 2 || len(exp.Rows) != len(dash.Rows) || len(recs)-1 != len(dash.Rows) || dash.Totals.Active != exp.Totals.Active { + t.Fatalf("dashboard %d rows, json %d, csv %d", len(dash.Rows), len(exp.Rows), len(recs)-1) + } + col := map[string]int{} + for i, h := range recs[0] { + col[h] = i + } + for i, r := range dash.Rows { + if exp.Rows[i] != r || recs[i+1][col["account_id"]] != r.AccountID || recs[i+1][col["class"]] != r.Class || + recs[i+1][col["health"]] != r.Health || recs[i+1][col["owner.department"]] != "Ops" { + t.Fatalf("row %d differs: %+v %+v %v", i, r, exp.Rows[i], recs[i+1]) + } + } + audits, _, _ := st.Audit().ListAuditRecords(ctx, 0, 100) + exports := 0 + for _, a := range audits { + if a.Action == "report.exported" { + exports++ + } + } + if exports != 2 { + t.Fatalf("%d export audit records, want 2", exports) + } + + // The owner sees their two active accounts; carol sees only the one she approves. + _, mine := getCard(t, srv, owner, "") + if len(mine.Rows) != 2 || mine.Totals.Decommissioned != 1 { + t.Fatalf("owner sees %+v", mine) + } + _, hers := getCard(t, srv, carolCookie, "") + if len(hers.Rows) != 1 || hers.Rows[0].AccountID != listedRed { + t.Fatalf("carol sees %+v", hers.Rows) + } + // dave has carol's subject from another identity provider: not her principal. + dave := &store.User{ID: "usr_dave", Username: "dave", Role: "user", Status: "active", SSOProvider: "oidc", SSOSubject: carol.SSOSubject} + if err := st.Users().CreateUser(ctx, dave); err != nil { + t.Fatal(err) + } + rec = httptest.NewRecorder() + if _, _, err := auth.NewSessionManager(st, cfg.Security).IssueSession(ctx, rec, httptest.NewRequest("GET", "/", nil), dave); err != nil { + t.Fatal(err) + } + if _, his := getCard(t, srv, rec.Result().Cookies()[0], ""); len(his.Rows) != 0 { + t.Fatalf("dave sees %+v", his.Rows) + } + if w := sendJSON(srv, owner, "GET", "/api/jobs", ""); w.Code != http.StatusForbidden { + t.Fatalf("jobs for a user: %d", w.Code) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 00b0d71..20e4f65 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -351,6 +351,7 @@ func (s *Server) routes() { s.enrollRoutes() s.txRoutes() s.inventoryRoutes() + s.reportRoutes() s.mux.Handle("/saml/", http.NotFoundHandler()) diff --git a/internal/reporting/AGENTS.md b/internal/reporting/AGENTS.md new file mode 100644 index 0000000..31a80ce --- /dev/null +++ b/internal/reporting/AGENTS.md @@ -0,0 +1,31 @@ +# Reporting + +## Purpose +The traffic-light scorecard (spec §8.1–§8.3): one authorized dataset, one classifier, one +filter and one CSV writer, shared by the dashboard and the JSON and CSV exports. + +## Ownership +Owns `Build` (the dataset), `Classify` (class and health overlay), `Filter`, `Summarize` +and `WriteCSV`. The store owns the facts it reads (`Inventory().ReportFacts`); the API owns +the routes and the export audit. + +## Local Contracts +- Class order is fixed: Green needs a schedule in the current verified policy and at least + one `release` receipt; else Yellow needs a current envelope; else Red. Health never + changes the class. Decommissioned accounts are counted, never classified. +- Health is one value: a non-`healthy` broker report first, then `checkout_open`, then + `pending_first_rotation` (scheduled, never released), then `overdue` (the newest + occurrence due at least one interval ago came after the last release), else `healthy`. +- Visibility: admins see every account. Anyone else sees accounts they own, or whose + current policy lists a principal whose verified `KeyEnrollmentManifest` names the + caller's own non-empty issuer and subject (`sameIdentity`). A subject alone never + matches. The API passes `""` as the issuer whenever it cannot name it. +- Percentages are whole numbers by largest remainder, so they always sum to 100. +- CSV cells that start with `= + - @`, tab or CR are prefixed with `'`. + +## Verification +- `go test ./internal/reporting/` (classifier, percentages, filter, CSV); + `go test ./internal/api/ -run Scorecard` (acceptance 12 end to end). + +## Child DOX Index +None. diff --git a/internal/reporting/reporting.go b/internal/reporting/reporting.go new file mode 100644 index 0000000..4300d88 --- /dev/null +++ b/internal/reporting/reporting.go @@ -0,0 +1,401 @@ +// Package reporting builds the traffic-light scorecard (spec §8.1–§8.3): one authorized +// dataset, one classifier and one filter, shared by the dashboard and the CSV and JSON +// exports. +package reporting + +import ( + "context" + "encoding/csv" + "errors" + "io" + "maps" + "slices" + "strconv" + "strings" + "time" + + "github.com/Busnes-app/kyguard-server/internal/cptrust" + "github.com/Busnes-app/kyguard-server/internal/pqcrypto" + "github.com/Busnes-app/kyguard-server/internal/store" +) + +// Classes (§8.1). +const ( + Green = "green" // managed: active schedule and at least one release + Yellow = "yellow" // vaulted: a sealed current envelope + Red = "red" // listed, not controlled +) + +// Health values (§8.1). The broker reports the first five; the rest are derived here. +const ( + Healthy = "healthy" + PendingFirstRotation = "pending_first_rotation" + Overdue = "overdue" + RotationFailed = "rotation_failed" + AuthFailed = "auth_failed" + Quarantined = "quarantined" + NeedsEnrollment = "needs_enrollment" + CheckoutOpen = "checkout_open" +) + +// Caller is who asks. Admins see every account; anyone else sees the accounts they own or +// are listed on in the current policy (§8.3). Issuer and Subject name the caller's SSO +// identity; a principal counts as the caller only when its verified KeyEnrollmentManifest +// names that same non-empty pair. +type Caller struct { + UserID string + Admin bool + Issuer, Subject string +} + +// Facts are the stored inputs the classifier reads for one account. +type Facts struct { + Active bool + Kind string + Schedule *pqcrypto.Schedule // from the current verified policy; nil when none + LastRelease time.Time // newest release receipt; zero when none + CurrentSealed bool // a current envelope exists (§3.5) + BrokerHealth string // as the broker last reported it + CheckoutLeases int // non-closed leases +} + +// Classify returns the class and the health overlay (§8.1). Facts must be of an active +// account; decommissioned accounts are not classified. +func Classify(f Facts, now time.Time) (class, health string) { + switch { + case f.Schedule != nil && !f.LastRelease.IsZero(): + class = Green + case f.CurrentSealed: + class = Yellow + default: + class = Red + } + switch { + case f.BrokerHealth != "" && f.BrokerHealth != Healthy: + health = f.BrokerHealth + case f.CheckoutLeases > 0: + health = CheckoutOpen + case f.Schedule != nil && f.LastRelease.IsZero(): + health = PendingFirstRotation + case f.Schedule != nil && overdue(*f.Schedule, f.LastRelease, now): + health = Overdue + default: + health = Healthy + } + return class, health +} + +// overdue reports a due occurrence not run within one interval: the latest occurrence due +// at or before now - interval came after the last release. +func overdue(s pqcrypto.Schedule, last, now time.Time) bool { + if s.IntervalSeconds <= 0 { + return false + } + iv := time.Duration(s.IntervalSeconds) * time.Second + cutoff := now.Add(-iv) + if cutoff.Before(s.AnchorUTC.Time) { + return false + } + k := cutoff.Sub(s.AnchorUTC.Time) / iv + due := s.AnchorUTC.Add(k * iv) + return last.Before(due) +} + +// Row is one account in the scorecard. +type Row struct { + AccountID string `json:"account_id"` + Asset string `json:"asset"` + Name string `json:"name"` + Kind string `json:"account_kind"` + PoolID string `json:"pool_id"` + Class string `json:"class"` + Health string `json:"health"` + HealthReason string `json:"health_reason"` + OwnerUserID string `json:"owner_user_id"` + Owner string `json:"owner"` + MinPasswordAgeSeconds *int64 `json:"min_password_age_seconds"` + DescriptorDigest string `json:"target_descriptor_digest"` + LastRelease *time.Time `json:"last_release"` + Attributes map[string]string `json:"attributes"` + OwnerAttributes map[string]string `json:"owner_attributes"` +} + +// Dataset is the authorized scorecard dataset: active rows and the visible decommissioned +// count, which no class includes (§8.1). +type Dataset struct { + Rows []*Row + Decommissioned int + AccountKeys []string // account attribute keys, sorted + OwnerKeys []string // user attribute keys, sorted +} + +// Build reads the inventory and the verified policies once and returns what caller may see. +func Build(ctx context.Context, st store.Store, trust *cptrust.Trust, caller Caller, now time.Time) (*Dataset, error) { + inv := st.Inventory() + accounts, err := inv.ListAccounts(ctx) + if err != nil { + return nil, err + } + facts, err := inv.ReportFacts(ctx) + if err != nil { + return nil, err + } + acctVals, err := inv.Values(ctx, store.EntityAccount) + if err != nil { + return nil, err + } + userVals, err := inv.Values(ctx, store.EntityUser) + if err != nil { + return nil, err + } + policies := map[string]*pqcrypto.PolicyManifest{} + mine := map[pqcrypto.UUID]bool{} // the caller's principals + err = trust.View(ctx, func(tr *pqcrypto.Trust) error { + for _, a := range accounts { + if p, _ := tr.Policy(pqcrypto.UUID(a.ID)); p != nil { + policies[a.ID] = p + } + } + if caller.Admin || caller.Issuer == "" || caller.Subject == "" { + return nil + } + for _, r := range tr.Records() { + if r.Type != pqcrypto.TypeKeyEnrollment { + continue + } + if ke := tr.Enrollment(r.ScopeID); ke != nil && sameIdentity(ke, caller) { + mine[ke.PrincipalID] = true + } + } + return nil + }) + if err != nil && !errors.Is(err, cptrust.ErrNoBundle) { + return nil, err + } + + ds := &Dataset{Rows: []*Row{}} + owners := map[string]string{} + akeys, okeys := map[string]bool{}, map[string]bool{} + for _, a := range accounts { + p := policies[a.ID] + if !caller.Admin && a.OwnerUserID != caller.UserID && !listed(p, mine) { + continue + } + if a.Status != "active" { + ds.Decommissioned++ + continue + } + f := facts[a.ID] + if f == nil { + f = &store.ReportFacts{} + } + in := Facts{Active: true, Kind: a.AccountKind, LastRelease: f.LastRelease, CurrentSealed: a.CurrentEnvelopeID != "", + BrokerHealth: a.Health, CheckoutLeases: f.OpenLeases} + row := &Row{AccountID: a.ID, Asset: a.AssetName, Name: a.Name, Kind: a.AccountKind, PoolID: a.PoolID, HealthReason: a.HealthReason, + OwnerUserID: a.OwnerUserID, MinPasswordAgeSeconds: a.MinPasswordAgeSeconds, Attributes: nonNil(acctVals[a.ID]), OwnerAttributes: map[string]string{}} + if p != nil { + in.Schedule = p.RotationSchedule + row.DescriptorDigest = string(p.TargetDescriptorDigest) + } + if !f.LastRelease.IsZero() { + lr := f.LastRelease + row.LastRelease = &lr + } + row.Class, row.Health = Classify(in, now) + if a.OwnerUserID != "" { + row.OwnerAttributes = nonNil(userVals[a.OwnerUserID]) + name, ok := owners[a.OwnerUserID] + if !ok { + if u, err := st.Users().GetUserByID(ctx, a.OwnerUserID); err == nil { + name = u.Username + } else if !errors.Is(err, store.ErrNotFound) { + return nil, err + } + owners[a.OwnerUserID] = name + } + row.Owner = name + } + for k := range row.Attributes { + akeys[k] = true + } + for k := range row.OwnerAttributes { + okeys[k] = true + } + ds.Rows = append(ds.Rows, row) + } + ds.AccountKeys, ds.OwnerKeys = slices.Sorted(maps.Keys(akeys)), slices.Sorted(maps.Keys(okeys)) + return ds, nil +} + +func nonNil(m map[string]string) map[string]string { + if m == nil { + return map[string]string{} + } + return m +} + +// sameIdentity reports whether a verified key enrollment names the caller: the same +// non-empty issuer and subject, never the subject alone (§7.2). +func sameIdentity(ke *pqcrypto.KeyEnrollmentManifest, c Caller) bool { + return c.Issuer != "" && c.Subject != "" && ke.Issuer == c.Issuer && ke.Subject == c.Subject +} + +// listed reports whether one of the caller's principals is named anywhere in the policy. +func listed(p *pqcrypto.PolicyManifest, mine map[pqcrypto.UUID]bool) bool { + if p == nil || len(mine) == 0 { + return false + } + for _, l := range [][]pqcrypto.UUID{p.AllowedUserPrincipalIDs, p.AllowedApproverPrincipalIDs, p.EnrollerPrincipalIDs, p.StandingRecipientPrincipalIDs} { + for _, id := range l { + if mine[id] { + return true + } + } + } + return false +} + +// Filter is equality on class, health, pool and attributes (§8.3). Empty fields match all. +type Filter struct { + Class, Health, Pool string + Attributes map[string]string // account attribute key -> value + OwnerAttributes map[string]string // owner's user attribute key -> value +} + +// ParseFilter reads class, health, pool, attr. and owner. from a query. +func ParseFilter(q map[string][]string) Filter { + f := Filter{Attributes: map[string]string{}, OwnerAttributes: map[string]string{}} + for k, v := range q { + if len(v) == 0 { + continue + } + switch { + case k == "class": + f.Class = v[0] + case k == "health": + f.Health = v[0] + case k == "pool": + f.Pool = v[0] + case strings.HasPrefix(k, "attr."): + f.Attributes[strings.TrimPrefix(k, "attr.")] = v[0] + case strings.HasPrefix(k, "owner."): + f.OwnerAttributes[strings.TrimPrefix(k, "owner.")] = v[0] + } + } + return f +} + +// Match applies the filter to one row. +func (f Filter) Match(r *Row) bool { + if (f.Class != "" && r.Class != f.Class) || (f.Health != "" && r.Health != f.Health) || (f.Pool != "" && r.PoolID != f.Pool) { + return false + } + for k, v := range f.Attributes { + if r.Attributes[k] != v { + return false + } + } + for k, v := range f.OwnerAttributes { + if r.OwnerAttributes[k] != v { + return false + } + } + return true +} + +// Apply returns the rows the filter matches, in order. +func (f Filter) Apply(rows []*Row) []*Row { + out := []*Row{} + for _, r := range rows { + if f.Match(r) { + out = append(out, r) + } + } + return out +} + +// Totals are the dashboard numbers for a set of rows. Percent values are whole percents +// that sum to 100 whenever Active > 0. +type Totals struct { + Active int `json:"active"` + Decommissioned int `json:"decommissioned"` + Classes map[string]int `json:"classes"` + Percent map[string]int `json:"percent"` + Health map[string]int `json:"health"` +} + +// Summarize counts classes and health. Decommissioned is passed through from the dataset. +func Summarize(rows []*Row, decommissioned int) Totals { + t := Totals{Active: len(rows), Decommissioned: decommissioned, Classes: map[string]int{Green: 0, Yellow: 0, Red: 0}, + Percent: map[string]int{Green: 0, Yellow: 0, Red: 0}, Health: map[string]int{}} + for _, r := range rows { + t.Classes[r.Class]++ + t.Health[r.Health]++ + } + if t.Active > 0 { + // Largest remainder, so the three always add up to 100. + order := []string{Green, Yellow, Red} + used := 0 + rem := map[string]int{} + for _, c := range order { + t.Percent[c] = t.Classes[c] * 100 / t.Active + rem[c] = t.Classes[c] * 100 % t.Active + used += t.Percent[c] + } + slices.SortStableFunc(order, func(a, b string) int { return rem[b] - rem[a] }) + for i := 0; used < 100; i++ { + t.Percent[order[i%3]]++ + used++ + } + } + return t +} + +// WriteCSV writes rows with the fixed columns, then attr. and owner. columns. +// Cells that a spreadsheet would read as a formula are prefixed with a quote. +func WriteCSV(w io.Writer, ds *Dataset, rows []*Row) error { + cw := csv.NewWriter(w) + head := []string{"account_id", "asset", "account", "account_kind", "pool_id", "class", "health", "health_reason", + "owner", "owner_user_id", "min_password_age_seconds", "target_descriptor_digest", "last_release"} + for _, k := range ds.AccountKeys { + head = append(head, "attr."+k) + } + for _, k := range ds.OwnerKeys { + head = append(head, "owner."+k) + } + if err := cw.Write(head); err != nil { + return err + } + for _, r := range rows { + age, last := "", "" + if r.MinPasswordAgeSeconds != nil { + age = strconv.FormatInt(*r.MinPasswordAgeSeconds, 10) + } + if r.LastRelease != nil { + last = r.LastRelease.UTC().Format(time.RFC3339) + } + rec := []string{r.AccountID, r.Asset, r.Name, r.Kind, r.PoolID, r.Class, r.Health, r.HealthReason, + r.Owner, r.OwnerUserID, age, r.DescriptorDigest, last} + for _, k := range ds.AccountKeys { + rec = append(rec, r.Attributes[k]) + } + for _, k := range ds.OwnerKeys { + rec = append(rec, r.OwnerAttributes[k]) + } + for i, c := range rec { + rec[i] = cell(c) + } + if err := cw.Write(rec); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +func cell(s string) string { + if s != "" && strings.ContainsRune("=+-@\t\r", rune(s[0])) { + return "'" + s + } + return s +} diff --git a/internal/reporting/reporting_test.go b/internal/reporting/reporting_test.go new file mode 100644 index 0000000..85824ec --- /dev/null +++ b/internal/reporting/reporting_test.go @@ -0,0 +1,112 @@ +package reporting + +import ( + "bytes" + "strings" + "testing" + "time" + + "github.com/Busnes-app/kyguard-server/internal/pqcrypto" +) + +var t0 = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + +func day() *pqcrypto.Schedule { + return &pqcrypto.Schedule{AnchorUTC: pqcrypto.NewTime(t0), IntervalSeconds: 86400} +} + +// §8.1: the class is decided by schedule + release, then a current envelope; health is an +// overlay and never changes the class. +func TestClassify(t *testing.T) { + now := t0.Add(10 * 24 * time.Hour) + for _, c := range []struct { + name string + f Facts + class, health string + }{ + {"listed", Facts{}, Red, Healthy}, + {"vaulted", Facts{CurrentSealed: true}, Yellow, Healthy}, + {"scheduled, never released", Facts{Schedule: day(), CurrentSealed: true}, Yellow, PendingFirstRotation}, + {"released, no schedule", Facts{LastRelease: now.Add(-time.Hour), CurrentSealed: true}, Yellow, Healthy}, + {"managed", Facts{Schedule: day(), LastRelease: now.Add(-time.Hour), CurrentSealed: true}, Green, Healthy}, + {"managed, overdue", Facts{Schedule: day(), LastRelease: now.Add(-50 * time.Hour), CurrentSealed: true}, Green, Overdue}, + {"latest occurrence due under one interval ago", Facts{Schedule: day(), LastRelease: now.Add(-23 * time.Hour), CurrentSealed: true}, Green, Healthy}, + {"quarantined stays green", Facts{Schedule: day(), LastRelease: now.Add(-time.Hour), CurrentSealed: true, BrokerHealth: Quarantined}, Green, Quarantined}, + {"checkout open", Facts{Schedule: day(), LastRelease: now.Add(-time.Hour), CurrentSealed: true, CheckoutLeases: 1}, Green, CheckoutOpen}, + {"auth failed beats checkout", Facts{CurrentSealed: true, BrokerHealth: AuthFailed, CheckoutLeases: 1}, Yellow, AuthFailed}, + {"release without a current envelope", Facts{Schedule: day(), LastRelease: now.Add(-time.Hour)}, Green, Healthy}, + } { + class, health := Classify(c.f, now) + if class != c.class || health != c.health { + t.Errorf("%s: %s/%s, want %s/%s", c.name, class, health, c.class, c.health) + } + } +} + +func TestPercentagesAlwaysSumTo100(t *testing.T) { + for n := 1; n <= 40; n++ { + for g := 0; g <= n; g++ { + for y := 0; g+y <= n; y++ { + var rows []*Row + for i := 0; i < n; i++ { + c := Red + if i < g { + c = Green + } else if i < g+y { + c = Yellow + } + rows = append(rows, &Row{Class: c, Health: Healthy}) + } + s := Summarize(rows, 0) + if s.Classes[Green]+s.Classes[Yellow]+s.Classes[Red] != n || s.Percent[Green]+s.Percent[Yellow]+s.Percent[Red] != 100 { + t.Fatalf("n=%d g=%d y=%d: %+v", n, g, y, s) + } + } + } + } +} + +func TestFilterAndCSV(t *testing.T) { + rows := []*Row{ + {AccountID: "a", Name: "=cmd|' /C calc'!A0", Class: Green, Health: Healthy, PoolID: "p1", Attributes: map[string]string{"tier": "gold"}, OwnerAttributes: map[string]string{"department": "Ops"}}, + {AccountID: "b", Name: "svc", Class: Red, Health: Healthy, PoolID: "p2", Attributes: map[string]string{}, OwnerAttributes: map[string]string{"department": "Sales"}}, + } + f := ParseFilter(map[string][]string{"owner.department": {"Ops"}, "attr.tier": {"gold"}, "pool": {"p1"}}) + if got := f.Apply(rows); len(got) != 1 || got[0].AccountID != "a" { + t.Fatalf("filter %v", got) + } + if got := ParseFilter(map[string][]string{"class": {"red"}}).Apply(rows); len(got) != 1 || got[0].AccountID != "b" { + t.Fatalf("class filter %v", got) + } + var b bytes.Buffer + if err := WriteCSV(&b, &Dataset{AccountKeys: []string{"tier"}, OwnerKeys: []string{"department"}}, rows); err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimSpace(b.String()), "\n") + if len(lines) != 3 || !strings.HasSuffix(lines[0], ",attr.tier,owner.department") { + t.Fatalf("csv %q", b.String()) + } + if !strings.Contains(lines[1], `,'=cmd|' /C calc'!A0,`) || !strings.HasSuffix(lines[1], ",gold,Ops") { + t.Fatalf("formula cell not neutralized: %q", lines[1]) + } +} + +func TestSameIdentityNeedsIssuerAndSubject(t *testing.T) { + ke := &pqcrypto.KeyEnrollmentManifest{Issuer: "https://idp.example.test", Subject: "s1"} + for _, c := range []struct { + caller Caller + want bool + }{ + {Caller{Issuer: "https://idp.example.test", Subject: "s1"}, true}, + {Caller{Issuer: "https://other.example.test", Subject: "s1"}, false}, + {Caller{Subject: "s1"}, false}, + {Caller{Issuer: "https://idp.example.test", Subject: "s2"}, false}, + } { + if got := sameIdentity(ke, c.caller); got != c.want { + t.Errorf("%+v: %v", c.caller, got) + } + } + if sameIdentity(&pqcrypto.KeyEnrollmentManifest{}, Caller{}) { + t.Error("empty identities match") + } +} diff --git a/internal/store/AGENTS.md b/internal/store/AGENTS.md index 8cdd87e..edfca1a 100644 --- a/internal/store/AGENTS.md +++ b/internal/store/AGENTS.md @@ -81,6 +81,7 @@ Owns data models, store interfaces (`UserStore`, `SessionStore`, `GroupStore`, ` source differs from the definition's (`ErrInvalid`), an enum value outside the list and an unknown entity; `UpdateDefinition` refuses removing an enum value in use (`ErrConflict`). Both tables are in `migrationTables`; the migration seeds nothing. + `ReportFacts`, `RecentRuns` and `RecentLeases` are the reporting reads. ## Verification - `go test -v ./internal/store/...` diff --git a/internal/store/inventory.go b/internal/store/inventory.go index 603a642..d17ce21 100644 --- a/internal/store/inventory.go +++ b/internal/store/inventory.go @@ -53,6 +53,12 @@ type InventoryStore interface { SetValue(ctx context.Context, definitionID, entityID, value, source string, audit *AuditRecord) error // Values maps entity ID to attribute key to value for one entity type. Values(ctx context.Context, entity string) (map[string]map[string]string, error) + + // ReportFacts returns, per account, the newest release receipt and the open leases. + ReportFacts(ctx context.Context) (map[string]*ReportFacts, error) + // RecentRuns and RecentLeases feed the jobs screen, newest (and open leases) first. + RecentRuns(ctx context.Context, limit int) ([]*JobRun, error) + RecentLeases(ctx context.Context, limit int) ([]*JobLease, error) } // InventoryAccount is an account row with its inventory columns. diff --git a/internal/store/inventory_reports.go b/internal/store/inventory_reports.go new file mode 100644 index 0000000..7b17198 --- /dev/null +++ b/internal/store/inventory_reports.go @@ -0,0 +1,115 @@ +package store + +import ( + "context" + "time" +) + +// ReportFacts are the per-account rows the classifier reads (spec §8.1). +type ReportFacts struct { + LastRelease time.Time // newest release receipt; zero when none + OpenLeases int +} + +// JobRun is a rotation run as the jobs screen shows it (§10). +type JobRun struct { + OperationID string `json:"operation_id"` + AccountID string `json:"account_id"` + BrokerID string `json:"broker_id"` + SecretVersion uint64 `json:"secret_version"` + State string `json:"state"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (v inventoryStore) ReportFacts(ctx context.Context) (map[string]*ReportFacts, error) { + out := map[string]*ReportFacts{} + get := func(id string) *ReportFacts { + if out[id] == nil { + out[id] = &ReportFacts{} + } + return out[id] + } + // Rows, not MAX(): SQLite hands an aggregate timestamp back as text. + rows, err := v.s.db.QueryContext(ctx, `SELECT e.account_id, r.created_at FROM envelope_receipts r + JOIN secret_envelopes e ON e.envelope_id = r.envelope_id WHERE r.receipt_type = 'release'`) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var id string + var at time.Time + if err := rows.Scan(&id, &at); err != nil { + return nil, err + } + if f := get(id); at.After(f.LastRelease) { + f.LastRelease = at + } + } + if err := rows.Err(); err != nil { + return nil, err + } + leases, err := v.s.db.QueryContext(ctx, `SELECT account_id FROM checkout_leases WHERE state <> 'closed'`) + if err != nil { + return nil, err + } + defer leases.Close() + for leases.Next() { + var id string + if err := leases.Scan(&id); err != nil { + return nil, err + } + get(id).OpenLeases++ + } + return out, leases.Err() +} + +func (v inventoryStore) RecentRuns(ctx context.Context, limit int) ([]*JobRun, error) { + rows, err := v.s.db.QueryContext(ctx, v.s.rebind(`SELECT operation_id, account_id, broker_id, secret_version, state, created_at, updated_at + FROM rotation_runs ORDER BY updated_at DESC, operation_id LIMIT ?`), limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []*JobRun{} + for rows.Next() { + var j JobRun + var ver int64 + if err := rows.Scan(&j.OperationID, &j.AccountID, &j.BrokerID, &ver, &j.State, &j.CreatedAt, &j.UpdatedAt); err != nil { + return nil, err + } + j.SecretVersion = uint64(ver) + out = append(out, &j) + } + return out, rows.Err() +} + +// JobLease is a checkout lease as the jobs screen shows it. +type JobLease struct { + RequestID string `json:"request_id"` + AccountID string `json:"account_id"` + BrokerID string `json:"broker_id"` + State string `json:"state"` + CloseReason string `json:"close_reason"` + OpenedAt time.Time `json:"opened_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +func (v inventoryStore) RecentLeases(ctx context.Context, limit int) ([]*JobLease, error) { + rows, err := v.s.db.QueryContext(ctx, v.s.rebind(`SELECT request_id, account_id, broker_id, state, close_reason, opened_at, expires_at + FROM checkout_leases ORDER BY (state = 'closed'), opened_at DESC LIMIT ?`), limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []*JobLease{} + for rows.Next() { + var l JobLease + if err := rows.Scan(&l.RequestID, &l.AccountID, &l.BrokerID, &l.State, &l.CloseReason, &l.OpenedAt, &l.ExpiresAt); err != nil { + return nil, err + } + out = append(out, &l) + } + return out, rows.Err() +} From 7e9d8bd7f23376be8c67f9465f319fe525bc7a4e Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 07:48:35 -0500 Subject: [PATCH 2/6] notes: scorecard Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c8309d..18c1372 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,10 @@ History before the KyGuard import is `ky-server-base` at `fed0fb3` and its own ` account's owner and status, upload target descriptors (strictly decoded, 1A slice only, bound to this deployment, account and asset) and define account and user attributes (`string` or `enum`); SCIM-sourced attributes are read-only. +- Traffic-light scorecard (spec §8.1, §8.3): every active account is Green (scheduled and + released at least once), Yellow (sealed current envelope) or Red, with one health value + beside it; `GET /api/reports/scorecard` serves the dashboard and, with `format=json|csv`, + an audited download of the same rows. Non-admins see accounts they own or are listed on. ### Upgrade impact From 6edd7693820a502d65d92149dae115a13bea5c35 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 07:50:06 -0500 Subject: [PATCH 3/6] reporting: pick each account's newest release in SQL The scorecard read every release receipt and kept the newest in Go, so the work grew with rotation history. The query now returns only each account's newest release row. Co-Authored-By: Claude Opus 5.5 --- internal/store/inventory_reports.go | 9 ++++++-- internal/store/inventory_test.go | 34 +++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/internal/store/inventory_reports.go b/internal/store/inventory_reports.go index 7b17198..c53e07b 100644 --- a/internal/store/inventory_reports.go +++ b/internal/store/inventory_reports.go @@ -30,9 +30,14 @@ func (v inventoryStore) ReportFacts(ctx context.Context) (map[string]*ReportFact } return out[id] } - // Rows, not MAX(): SQLite hands an aggregate timestamp back as text. + // Only each account's newest release row, picked in SQL so the read grows with the + // accounts, not the rotation history. Not MAX(): SQLite returns an aggregate timestamp + // as text. Ties may return two rows; the loop keeps the later one. rows, err := v.s.db.QueryContext(ctx, `SELECT e.account_id, r.created_at FROM envelope_receipts r - JOIN secret_envelopes e ON e.envelope_id = r.envelope_id WHERE r.receipt_type = 'release'`) + JOIN secret_envelopes e ON e.envelope_id = r.envelope_id + WHERE r.receipt_type = 'release' AND NOT EXISTS ( + SELECT 1 FROM envelope_receipts r2 JOIN secret_envelopes e2 ON e2.envelope_id = r2.envelope_id + WHERE e2.account_id = e.account_id AND r2.receipt_type = 'release' AND r2.created_at > r.created_at)`) if err != nil { return nil, err } diff --git a/internal/store/inventory_test.go b/internal/store/inventory_test.go index 562abe4..c9c76e5 100644 --- a/internal/store/inventory_test.go +++ b/internal/store/inventory_test.go @@ -3,7 +3,9 @@ package store import ( "context" "errors" + "strconv" "testing" + "time" ) func inventoryFor(t *testing.T) (*SQLStore, InventoryStore) { @@ -104,3 +106,35 @@ func TestInventoryWriteRollsBackWithItsAudit(t *testing.T) { t.Fatalf("assets %v %v", assets, err) } } + +// ReportFacts returns each account's newest release, however many it has had. +func TestReportFactsNewestRelease(t *testing.T) { + s, inv := inventoryFor(t) + ctx := context.Background() + v := s.Vault() + var last time.Time + for i := 1; i <= 3; i++ { + n := strconv.Itoa(i) + op := "op" + n + ver, err := v.Reserve(ctx, "ac", op, 0) + if err != nil { + t.Fatal(err) + } + if err := v.PutEnvelope(ctx, op, &StoredEnvelope{EnvelopeID: "e" + n, AccountID: "ac", SecretVersion: ver, EnvelopeKind: "managed", Digest: "d" + n, Envelope: []byte("{}")}); err != nil { + t.Fatal(err) + } + rs := []*StoredReceipt{{EnvelopeID: "e" + n, ReceiptSeq: 1, ReceiptType: "commit_target", OperationID: op, Digest: "c" + n, PrevReceiptHash: zeroHash, Receipt: []byte("1")}, + {EnvelopeID: "e" + n, ReceiptSeq: 2, ReceiptType: "release", OperationID: op, Digest: "r" + n, PrevReceiptHash: "c" + n, Receipt: []byte("2")}} + if err := v.Complete(ctx, op, "ac", rs, "e"+n, "", LockDelete); err != nil { + t.Fatal(err) + } + if err := s.db.QueryRowContext(ctx, s.rebind(`SELECT created_at FROM envelope_receipts WHERE digest = ?`), "r"+n).Scan(&last); err != nil { + t.Fatal(err) + } + time.Sleep(2 * time.Millisecond) + } + f, err := inv.ReportFacts(ctx) + if err != nil || !f["ac"].LastRelease.Equal(last) { + t.Fatalf("facts %+v %v, want %v", f["ac"], err, last) + } +} From cc0079e342d5f5a9a1f2398331ee9adc19ce8ea6 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 08:05:16 -0500 Subject: [PATCH 4/6] reporting: filter the decommissioned count too A pool or attribute filter now applies to the decommissioned count; a class or health filter matches no decommissioned account, since they have neither. Co-Authored-By: Claude Opus 5.5 --- internal/api/report_handlers.go | 2 +- internal/api/report_test.go | 10 ++++++++++ internal/reporting/AGENTS.md | 3 ++- internal/reporting/reporting.go | 29 ++++++++++++++++++++--------- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/internal/api/report_handlers.go b/internal/api/report_handlers.go index d1dd904..7d823d0 100644 --- a/internal/api/report_handlers.go +++ b/internal/api/report_handlers.go @@ -58,7 +58,7 @@ func (s *Server) handleScorecard(w http.ResponseWriter, r *http.Request) { } f := reporting.ParseFilter(q) rows := f.Apply(ds.Rows) - card := scorecard{GeneratedAt: now, Totals: reporting.Summarize(rows, ds.Decommissioned), AccountKeys: ds.AccountKeys, OwnerKeys: ds.OwnerKeys, Rows: rows} + card := scorecard{GeneratedAt: now, Totals: reporting.Summarize(rows, f.Retired(ds.Retired)), AccountKeys: ds.AccountKeys, OwnerKeys: ds.OwnerKeys, Rows: rows} if format == "" { s.writeJSON(w, http.StatusOK, card) return diff --git a/internal/api/report_test.go b/internal/api/report_test.go index d1568f0..48a0d0b 100644 --- a/internal/api/report_test.go +++ b/internal/api/report_test.go @@ -232,6 +232,16 @@ func TestScorecard(t *testing.T) { t.Fatalf("%d export audit records, want 2", exports) } + // A filter applies to the decommissioned count too. + if _, c := getCard(t, srv, admin, "?owner.department=Sales"); c.Totals.Decommissioned != 0 { + t.Fatalf("decommissioned outside the filter counted: %+v", c.Totals) + } + if _, c := getCard(t, srv, admin, "?class=green"); c.Totals.Decommissioned != 0 { + t.Fatalf("decommissioned counted under a class filter: %+v", c.Totals) + } + if dash.Totals.Decommissioned != 1 { + t.Fatalf("decommissioned under the owner's department: %+v", dash.Totals) + } // The owner sees their two active accounts; carol sees only the one she approves. _, mine := getCard(t, srv, owner, "") if len(mine.Rows) != 2 || mine.Totals.Decommissioned != 1 { diff --git a/internal/reporting/AGENTS.md b/internal/reporting/AGENTS.md index 31a80ce..f043540 100644 --- a/internal/reporting/AGENTS.md +++ b/internal/reporting/AGENTS.md @@ -12,7 +12,8 @@ the routes and the export audit. ## Local Contracts - Class order is fixed: Green needs a schedule in the current verified policy and at least one `release` receipt; else Yellow needs a current envelope; else Red. Health never - changes the class. Decommissioned accounts are counted, never classified. + changes the class. Decommissioned accounts are counted (by the same pool and attribute filters; a class + or health filter excludes them), never classified. - Health is one value: a non-`healthy` broker report first, then `checkout_open`, then `pending_first_rotation` (scheduled, never released), then `overdue` (the newest occurrence due at least one interval ago came after the last release), else `healthy`. diff --git a/internal/reporting/reporting.go b/internal/reporting/reporting.go index 4300d88..c3d4cad 100644 --- a/internal/reporting/reporting.go +++ b/internal/reporting/reporting.go @@ -123,10 +123,10 @@ type Row struct { // Dataset is the authorized scorecard dataset: active rows and the visible decommissioned // count, which no class includes (§8.1). type Dataset struct { - Rows []*Row - Decommissioned int - AccountKeys []string // account attribute keys, sorted - OwnerKeys []string // user attribute keys, sorted + Rows []*Row + Retired []*Row // decommissioned: no class or health + AccountKeys []string // account attribute keys, sorted + OwnerKeys []string // user attribute keys, sorted } // Build reads the inventory and the verified policies once and returns what caller may see. @@ -181,10 +181,6 @@ func Build(ctx context.Context, st store.Store, trust *cptrust.Trust, caller Cal if !caller.Admin && a.OwnerUserID != caller.UserID && !listed(p, mine) { continue } - if a.Status != "active" { - ds.Decommissioned++ - continue - } f := facts[a.ID] if f == nil { f = &store.ReportFacts{} @@ -201,7 +197,9 @@ func Build(ctx context.Context, st store.Store, trust *cptrust.Trust, caller Cal lr := f.LastRelease row.LastRelease = &lr } - row.Class, row.Health = Classify(in, now) + if a.Status == "active" { + row.Class, row.Health = Classify(in, now) + } if a.OwnerUserID != "" { row.OwnerAttributes = nonNil(userVals[a.OwnerUserID]) name, ok := owners[a.OwnerUserID] @@ -215,6 +213,10 @@ func Build(ctx context.Context, st store.Store, trust *cptrust.Trust, caller Cal } row.Owner = name } + if a.Status != "active" { + ds.Retired = append(ds.Retired, row) // counted, never classified (§8.1) + continue + } for k := range row.Attributes { akeys[k] = true } @@ -303,6 +305,15 @@ func (f Filter) Match(r *Row) bool { return true } +// Retired counts the decommissioned rows the filter's pool and attribute terms match. They +// have no class or health, so a class or health term matches none of them. +func (f Filter) Retired(rows []*Row) int { + if f.Class != "" || f.Health != "" { + return 0 + } + return len(f.Apply(rows)) +} + // Apply returns the rows the filter matches, in order. func (f Filter) Apply(rows []*Row) []*Row { out := []*Row{} From a7db71be316f3a129b184d1f720323b16b3af7cb Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 16:55:46 -0500 Subject: [PATCH 5/6] reports: the scorecard waits for a break-glass session's reason A break-glass session counts as an admin, so before stating its reason it could read the deployment-wide scorecard and its exports. The route now uses requireSession (403 break_glass_reason_required). Co-Authored-By: Claude Opus 5.5 --- internal/api/report_handlers.go | 2 +- internal/api/reporting_breakglass_test.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/api/report_handlers.go b/internal/api/report_handlers.go index 7d823d0..a124a24 100644 --- a/internal/api/report_handlers.go +++ b/internal/api/report_handlers.go @@ -12,7 +12,7 @@ import ( func (s *Server) reportRoutes() { // TODO(hawthorn §7.5): classify (session). The dataset is authorized per caller (§8.3). - s.mux.HandleFunc("GET /api/reports/scorecard", s.requireAuthenticated(s.handleScorecard)) + s.mux.HandleFunc("GET /api/reports/scorecard", s.requireSession(s.handleScorecard)) // TODO(hawthorn §7.5): classify (session). s.mux.HandleFunc("GET /api/jobs", s.requireAdmin(s.handleJobs)) } diff --git a/internal/api/reporting_breakglass_test.go b/internal/api/reporting_breakglass_test.go index 3d9f645..e589bb6 100644 --- a/internal/api/reporting_breakglass_test.go +++ b/internal/api/reporting_breakglass_test.go @@ -7,7 +7,8 @@ import ( ) // reportingSessionRoutes are the reporting routes open to any session (method and path). -var reportingSessionRoutes = [][2]string{{"GET", "/api/attributes"}} +var reportingSessionRoutes = [][2]string{{"GET", "/api/attributes"}, + {"GET", "/api/reports/scorecard"}, {"GET", "/api/reports/scorecard?format=json"}, {"GET", "/api/reports/scorecard?format=csv"}} // Spec §7.4: a break-glass session reads no reporting data until it states its reason. func TestReportingRoutesWaitForBreakGlassReason(t *testing.T) { From ea1f07063f4ddb8abb4b2d3eb8d4c21e2a7223f2 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 19:50:38 -0500 Subject: [PATCH 6/6] reports: classify the report routes, match principals by users.sso_issuer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main's route registry (#18) refuses routes registered outside it, and main now stores the SSO issuer on the user (§7.2), so a principal is matched by the caller's stored issuer and subject, not only for KySignOn. Co-Authored-By: Claude Opus 5.5 --- docs/DECISIONS.md | 5 ++--- internal/api/AGENTS.md | 4 ++-- internal/api/report_handlers.go | 22 ++++++++++------------ internal/api/report_test.go | 4 ++-- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index dc74c3c..8dd1670 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -482,9 +482,8 @@ Numbered separately: these came from the parallel crypto stack. changes the class. 207. §8.3 (listed on in the policy). A non-admin is listed when a principal in any of the current policy's principal lists has a verified `KeyEnrollmentManifest` whose issuer - and subject are the caller's own; a subject alone never matches. This build knows the - issuer only for KySignOn sign-ins (`KY_KYSIGNON_ISSUER`); every other caller sees only - accounts they own until `users.sso_issuer` (§7.2) is joined in. + and subject are the caller's own (`users.sso_issuer`, §7.2); a subject alone never + matches, and a local account is never listed. 208. §8.3 (what is audited). The dashboard view is not an export and is not audited; every `format=json` or `format=csv` download is, before its body is sent. CSV cells that a spreadsheet would run as a formula are prefixed with `'`. diff --git a/internal/api/AGENTS.md b/internal/api/AGENTS.md index eeae8d9..6d2faf7 100644 --- a/internal/api/AGENTS.md +++ b/internal/api/AGENTS.md @@ -20,8 +20,8 @@ Owns HTTP routing, request parsing, session cookie validation, CORS headers, and stores the canonical bytes. - `report_handlers.go`: GET `/api/reports/scorecard` (session) serves the dashboard and, with `format=json|csv`, an audited download from the same `reporting.Build` dataset and - filter; GET `/api/jobs` (admin). `callerIssuer` names the caller's issuer only for - KySignOn users until `users.sso_issuer` is joined in. + filter; GET `/api/jobs` (admin). Both are session class with no step-up window. + `callerIssuer` is `users.sso_issuer`, empty for a local account. - Update `docs/INTERFACES.md` when a route's inputs, outputs, permissions or errors change. - POST `/api/auth/change-password` accepts a break-glass session (restricted or not; SSO accounts get 409), current password, a TOTP code (checked after the password) and a different policy-valid new password. Browser CSRF and per-IP/account limits apply. Success revokes all sessions and requires sign-in again; flagged sessions get `password_change_required` on protected routes and public-only settings. - `GET|HEAD /livez` and `/readyz` (`health.go`) are unauthenticated, `Cache-Control: no-store`, diff --git a/internal/api/report_handlers.go b/internal/api/report_handlers.go index a124a24..fd18f8b 100644 --- a/internal/api/report_handlers.go +++ b/internal/api/report_handlers.go @@ -11,20 +11,18 @@ import ( ) func (s *Server) reportRoutes() { - // TODO(hawthorn §7.5): classify (session). The dataset is authorized per caller (§8.3). - s.mux.HandleFunc("GET /api/reports/scorecard", s.requireSession(s.handleScorecard)) - // TODO(hawthorn §7.5): classify (session). - s.mux.HandleFunc("GET /api/jobs", s.requireAdmin(s.handleJobs)) + // Reads only, so no step-up window. The dataset is authorized per caller (§8.3). + s.route(ClassSession, "GET /api/reports/scorecard", http.HandlerFunc(s.requireSession(s.handleScorecard))) + s.route(ClassSession, "GET /api/jobs", http.HandlerFunc(s.requireAdmin(s.handleJobs))) } -// callerIssuer is the issuer of the caller's SSO identity, or "" when this build cannot -// name it, so a principal can never be matched to them by subject alone. -// TODO(join): use users.sso_issuer from hawthorn's §7.2 stack. -func (s *Server) callerIssuer(u *store.User) string { - if u.SSOProvider == "kysignon" && u.SSOSubject != "" { - return s.config.SSO.KySignOnIssuer +// callerIssuer is the issuer of the caller's SSO identity (users.sso_issuer, §7.2), or "" +// for a local account, so a principal can never be matched to them by subject alone. +func callerIssuer(u *store.User) string { + if u.SSOSubject == "" { + return "" } - return "" + return u.SSOIssuer } type scorecard struct { @@ -51,7 +49,7 @@ func (s *Server) handleScorecard(w http.ResponseWriter, r *http.Request) { return } now := time.Now().UTC() - ds, err := reporting.Build(ctx, s.store, s.trust, reporting.Caller{UserID: u.ID, Admin: u.Role == "admin", Issuer: s.callerIssuer(u), Subject: u.SSOSubject}, now) + ds, err := reporting.Build(ctx, s.store, s.trust, reporting.Caller{UserID: u.ID, Admin: u.Role == "admin", Issuer: callerIssuer(u), Subject: u.SSOSubject}, now) if err != nil { s.writeError(w, http.StatusInternalServerError, "could not build the scorecard") return diff --git a/internal/api/report_test.go b/internal/api/report_test.go index 48a0d0b..45b83f2 100644 --- a/internal/api/report_test.go +++ b/internal/api/report_test.go @@ -88,7 +88,7 @@ func TestScorecard(t *testing.T) { // carol signs in through KySignOn and is enrolled as a principal with the same identity. carolP := pqtest.NewPrincipal(t) - carol := &store.User{ID: "usr_carol", Username: "carol", Role: "user", Status: "active", SSOProvider: "kysignon", SSOSubject: "sub-" + string(carolP.ID)} + carol := &store.User{ID: "usr_carol", Username: "carol", Role: "user", Status: "active", SSOProvider: "kysignon", SSOSubject: "sub-" + string(carolP.ID), SSOIssuer: "https://idp.example.test"} if err := st.Users().CreateUser(ctx, carol); err != nil { t.Fatal(err) } @@ -252,7 +252,7 @@ func TestScorecard(t *testing.T) { t.Fatalf("carol sees %+v", hers.Rows) } // dave has carol's subject from another identity provider: not her principal. - dave := &store.User{ID: "usr_dave", Username: "dave", Role: "user", Status: "active", SSOProvider: "oidc", SSOSubject: carol.SSOSubject} + dave := &store.User{ID: "usr_dave", Username: "dave", Role: "user", Status: "active", SSOProvider: "oidc", SSOSubject: carol.SSOSubject, SSOIssuer: "https://other-idp.example.test"} if err := st.Users().CreateUser(ctx, dave); err != nil { t.Fatal(err) }