diff --git a/README.md b/README.md index 46b9231..e8571bd 100644 --- a/README.md +++ b/README.md @@ -841,6 +841,8 @@ The Keys and Agents pages are sortable tables (click a column); forms are one co The **Activity** page (`/activity`) searches the audit log, read-only, so the owner can see who did what without a terminal or `sudo`: a UTC time window by the minute (default: the last hour; the end minute is included), and optionally a service, an agent and text the path contains. It lists each matching call (time, agent, service, method and path, status, source address, note) and dashboard event, newest first, at most 500 (narrow the search for more). It shows only what the audit log holds: no key values, no query strings. The log is streamed, never loaded whole. +**Agents searching the audit log.** The owner can allow an agent to run the same search (off by default; agent's page, "Allow audit search", with the password; stored as `"audit_read": true` on the role). The agent calls `GET /_keyring/audit` on the keyring with its role token (through a relay: `http://127.0.0.1:7700//_keyring/audit`) with `from` and `to` (UTC minutes such as `2026-11-15T16:39`, the end minute included, or RFC 3339; default the last hour), and optionally `service`, `role` and `path` (contains). It gets JSON `{"from","to","rows":[...],"more","limit"}`. It sees every agent's calls and dashboard events, never key values or query strings. One search runs at a time (another gets 429); each search is itself audited. Without the grant the answer is 403. + The **Keys** page (`/keys`) is a table of every key the access file names or the store holds: key, API, status, the agents with access (with a dot: full or limited access), last use, calls today, calls over the last 7 days, and when the value was last added or replaced here. Filters above it show only working, failing, untested, leaked, missing or unused keys. Values are not shown in the table; a key's page can show its value on request (below). - **Show value** (a key's page) shows the stored value, or each named value, after the dashboard password, with a Copy button. It is the answer to that one request: diff --git a/internal/dashboard/access.go b/internal/dashboard/access.go index 0a2b48e..06a67b1 100644 --- a/internal/dashboard/access.go +++ b/internal/dashboard/access.go @@ -38,6 +38,7 @@ func registerAccess(b *Backend) { a.Handle("GET /agents/{role}", b.agentPage) a.Handle("POST /agents/{role}/token", b.newAgentToken) a.Handle("POST /agents/{role}/revoke", b.revokeAgent) + a.Handle("POST /agents/{role}/audit", b.setAuditRead) } // maxChips is how many APIs an agent's row lists before "+N more". @@ -570,9 +571,43 @@ func (b *Backend) agentPage(w http.ResponseWriter, r *http.Request, sid string) "ProjectGrants": sortedNames(rl.Projects), "File": tokenDir + "/" + role + ".token", "Current": rl.TokenSHA256[:12], "Error": agentErrors[r.URL.Query().Get("error")], "Added": r.URL.Query().Get("done") == "added", + "AuditRead": rl.AuditRead, "AuditSaved": r.URL.Query().Get("done") == "audit", }) } +// setAuditRead allows or stops the agent's audit search (owner, 2026-11-15: +// per agent, off by default). +func (b *Backend) setAuditRead(w http.ResponseWriter, r *http.Request, sid string) { + role := r.PathValue("role") + if !b.Admin.Confirm(sid, r.PostFormValue("password")) { + http.Redirect(w, r, "/agents/"+role+"?error=password", http.StatusSeeOther) + return + } + allow := r.PostFormValue("allow") == "yes" + b.Mu.Lock() + defer b.Mu.Unlock() + next, err := policy.LoadAccess(b.rules().AccessFile) + if err != nil { + b.fail(w, sid, err) + return + } + rl, ok := next.Roles[role] + if !ok { + b.notFound(w, sid) + return + } + if rl.AuditRead != allow { + rl.AuditRead = allow + next.Roles[role] = rl + if err := b.saveAndApply(next); err != nil { + b.fail(w, sid, err) + return + } + b.Admin.Audit("agent_audit_read", sid, map[string]any{"role": role, "allowed": allow}) + } + http.Redirect(w, r, "/agents/"+role+"?done=audit", http.StatusSeeOther) +} + func (b *Backend) newAgentToken(w http.ResponseWriter, r *http.Request, sid string) { role := r.PathValue("role") if !b.Admin.Confirm(sid, r.PostFormValue("password")) { diff --git a/internal/dashboard/activity.go b/internal/dashboard/activity.go index 5c45021..3790bf5 100644 --- a/internal/dashboard/activity.go +++ b/internal/dashboard/activity.go @@ -1,157 +1,45 @@ package dashboard import ( - "bufio" - "encoding/json" "errors" - "io" "net/http" "os" - "slices" "strings" "time" + + "github.com/gitmoot/keyring/internal/server" ) // Activity (Jarvis 488255): the owner looks up who called what, and when, -// from the audit log, without a terminal or sudo. Read-only. +// from the audit log, without a terminal or sudo. Read-only. The search is +// server.SearchAudit, which agents allowed to read the log also use. func registerActivity(b *Backend) { b.Admin.Handle("GET /activity", b.activityPage) } -// activityLimit caps the rows shown; the newest matches are kept. -const activityLimit = 500 - -// activityFormat is the form's time format, as a datetime-local input sends it. -const activityFormat = "2006-01-02T15:04" - -type activityRow struct { - Time string `json:"time"` - Source string `json:"source"` - Role string `json:"role"` - Service string `json:"service"` - Method string `json:"method"` - Path string `json:"path"` - Status int `json:"status"` - Note string `json:"note"` - // Admin is a dashboard event (login, key added, ...). - Admin string `json:"admin"` -} - type activityQuery struct { From, To, Service, Role, Path string } func (b *Backend) activityPage(w http.ResponseWriter, r *http.Request, sid string) { - now := b.Now().UTC() q := activityQuery{From: r.FormValue("from"), To: r.FormValue("to"), Service: strings.TrimSpace(r.FormValue("service")), Role: strings.TrimSpace(r.FormValue("role")), Path: strings.TrimSpace(r.FormValue("path"))} data := map[string]any{"Q": &q} - from, to, err := activityWindow(q.From, q.To, now) + from, to, err := server.AuditWindow(q.From, q.To, b.Now()) if err != nil { - data["ActivityError"] = err.Error() + data["ActivityError"] = strings.ToUpper(err.Error()[:1]) + err.Error()[1:] + "." b.render(w, http.StatusBadRequest, "activity", sid, data) return } - q.From, q.To = from.Format(activityFormat), to.Add(-time.Minute).Format(activityFormat) - rows, more, err := readActivity(b.rules().AuditLog, from, to, q) + q.From, q.To = from.Format(server.AuditMinute), to.Add(-time.Minute).Format(server.AuditMinute) + rows, more, err := server.SearchAudit(b.rules().AuditLog, from, to, server.AuditFilter{Service: q.Service, Role: q.Role, Path: q.Path}) switch { case errors.Is(err, os.ErrNotExist) || b.rules().AuditLog == "": data["ActivityError"] = "There is no audit log yet." case err != nil: data["ActivityError"] = "The audit log could not be read." } - data["Rows"], data["More"], data["Limit"] = rows, more, activityLimit + data["Rows"], data["More"], data["Limit"] = rows, more, server.AuditLimit b.render(w, http.StatusOK, "activity", sid, data) } - -// activityWindow reads the form's UTC minutes; the end minute is included. -// The default is the last hour. -func activityWindow(fromText, toText string, now time.Time) (time.Time, time.Time, error) { - to := now.Truncate(time.Minute).Add(time.Minute) - from := to.Add(-time.Hour) - if toText != "" { - t, err := time.Parse(activityFormat, toText) - if err != nil { - return from, to, errors.New("Write the times as 2026-11-15T16:39 (UTC).") - } - to = t.Add(time.Minute) - if fromText == "" { - from = to.Add(-time.Hour) - } - } - if fromText != "" { - t, err := time.Parse(activityFormat, fromText) - if err != nil { - return from, to, errors.New("Write the times as 2026-11-15T16:39 (UTC).") - } - from = t - } - if !from.Before(to) { - return from, to, errors.New("The start must be before the end.") - } - return from, to, nil -} - -// readActivity scans the audit log for lines in [from, to) matching q, -// newest first; past activityLimit it keeps the last ones written. The log is append-only and never rotated, so it is streamed: -// a line's time is compared as text before it is decoded. -func readActivity(path string, from, to time.Time, q activityQuery) ([]activityRow, bool, error) { - f, err := os.Open(path) - if err != nil { - return nil, false, err - } - defer f.Close() - lo, hi := from.UTC().Format(time.RFC3339), to.UTC().Format(time.RFC3339) - var kept []activityRow - more := false - rd := bufio.NewReaderSize(f, 64<<10) - for { - line, err := rd.ReadSlice('\n') - if errors.Is(err, bufio.ErrBufferFull) { - // A line this long is not an audit record worth showing; skip it. - for errors.Is(err, bufio.ErrBufferFull) { - _, err = rd.ReadSlice('\n') - } - continue - } - if len(line) > 0 { - if row, ok := activityMatch(line, lo, hi, q); ok { - if len(kept) == activityLimit { - kept, more = kept[1:], true - } - kept = append(kept, row) - } - } - if err == io.EOF { - break - } - if err != nil { - return nil, false, err - } - } - // A line is written when the call ends but stamped with its start, so - // file order is not time order. - slices.SortStableFunc(kept, func(a, b activityRow) int { return strings.Compare(b.Time, a.Time) }) - return kept, more, nil -} - -func activityMatch(line []byte, lo, hi string, q activityQuery) (activityRow, bool) { - var row activityRow - s := string(line) - i := strings.Index(s, `"time":"`) - if i < 0 || len(s) < i+8+len(lo) { - return row, false - } - if t := s[i+8 : i+8+len(lo)]; t < lo || t >= hi { - return row, false - } - if json.Unmarshal(line, &row) != nil { - return row, false - } - if q.Service != "" && row.Service != q.Service || q.Role != "" && row.Role != q.Role || - q.Path != "" && !strings.Contains(row.Path, q.Path) { - return row, false - } - return row, true -} diff --git a/internal/dashboard/activity_test.go b/internal/dashboard/activity_test.go index 41470f7..7613d0f 100644 --- a/internal/dashboard/activity_test.go +++ b/internal/dashboard/activity_test.go @@ -52,3 +52,31 @@ func TestActivityFindsTheCallerByMinuteAndPath(t *testing.T) { t.Errorf("bad time: %d", w.Code) } } + +// Owner, 2026-11-15: audit search is allowed per agent on its page, with the +// password, off by default, and the change is audited. +func TestAllowAndStopAgentAuditSearch(t *testing.T) { + e := newEnv(t) + if e.proxy.Config().Roles["phobos"].AuditRead { + t.Fatal("audit search is on by default") + } + if !strings.Contains(e.request("GET", "/agents/phobos", nil).Body.String(), "Allow audit search") { + t.Fatal("agent page has no audit-search control") + } + if w := e.request("POST", "/agents/phobos/audit", url.Values{"allow": {"yes"}, "password": {"wrong-password-123"}}); w.Header().Get("Location") != "/agents/phobos?error=password" || e.proxy.Config().Roles["phobos"].AuditRead { + t.Fatalf("wrong password allowed it: %d %s", w.Code, w.Header().Get("Location")) + } + if w := e.request("POST", "/agents/phobos/audit", url.Values{"allow": {"yes"}, "password": {password}}); w.Header().Get("Location") != "/agents/phobos?done=audit" || !e.proxy.Config().Roles["phobos"].AuditRead { + t.Fatalf("allow: %d %s", w.Code, w.Header().Get("Location")) + } + if !strings.Contains(e.audit.String(), `"agent_audit_read"`) || !strings.Contains(string(e.accessBytes()), `"audit_read": true`) { + t.Fatal("not audited or not saved to the access file") + } + if !strings.Contains(e.request("GET", "/agents/phobos", nil).Body.String(), "Stop audit access") { + t.Fatal("page does not offer to stop it") + } + e.request("POST", "/agents/phobos/audit", url.Values{"allow": {"no"}, "password": {password}}) + if e.proxy.Config().Roles["phobos"].AuditRead { + t.Fatal("stop did not take effect") + } +} diff --git a/internal/dashboard/pages.go b/internal/dashboard/pages.go index 4f5594b..23f0cf6 100644 --- a/internal/dashboard/pages.go +++ b/internal/dashboard/pages.go @@ -261,6 +261,11 @@ Sign in with Apple: {"service":"NAME","auth":"sign-in-with-apple-sign","si {{if .Off}}
{{end}} +

Activity log

{{if .AuditSaved}}

Saved.

{{end}} +

{{if .AuditRead}}{{.Role}} may search the audit log: every agent's calls (time, service, path, status) and dashboard events, never key values.{{else}}{{.Role}} may not search the audit log.{{end}}

+
+{{template "password" .}}
{{if .AuditRead}}Stop audit access{{else}}Allow audit search{{end}}
+

Through its relay: GET /{{.Role}}/_keyring/audit?from=2026-11-15T16:39&to=2026-11-15T16:39&service=&role=&path=, the same search as the Activity page.

Ends
{{with .Expires}}{{.}}{{else}}never{{end}}
Token file
{{.File}}
Make a new token

Shown once. The old token stops working at once.

{{template "password" .}}
diff --git a/internal/policy/policy.go b/internal/policy/policy.go index 8bc57aa..81fd0e1 100644 --- a/internal/policy/policy.go +++ b/internal/policy/policy.go @@ -666,6 +666,10 @@ type Role struct { // services added to it later, with the same limits (#111). A grant in // Access for a single service takes precedence over its project's grant. Projects map[string]Access `json:"projects,omitempty"` + // AuditRead lets the role search the audit log (every agent's calls and + // dashboard events, never values) at the keyring's /_keyring/audit. Off + // unless the owner allows it on the agent's page (owner, 2026-11-15). + AuditRead bool `json:"audit_read,omitempty"` } type Access struct { diff --git a/internal/server/auditsearch.go b/internal/server/auditsearch.go new file mode 100644 index 0000000..8380137 --- /dev/null +++ b/internal/server/auditsearch.go @@ -0,0 +1,225 @@ +package server + +import ( + "bufio" + "container/heap" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "slices" + "strings" + "time" +) + +// AuditPath answers an agent the owner allowed to read the audit log +// (policy.Role.AuditRead; Jarvis 488255): GET with from, to, service, role +// and path, the same search as the dashboard's Activity page, as JSON. +const AuditPath = "/_keyring/audit" + +// AuditLimit caps the rows a search returns; the newest written are kept. +const AuditLimit = 500 + +// AuditMinute is the minute format a search takes (a datetime-local input); +// RFC 3339 times are accepted too. +const AuditMinute = "2006-01-02T15:04" + +// AuditRow is one audit record as a search shows it. +type AuditRow struct { + Time string `json:"time"` + Source string `json:"source,omitempty"` + Role string `json:"role,omitempty"` + Service string `json:"service,omitempty"` + Method string `json:"method,omitempty"` + Path string `json:"path,omitempty"` + Status int `json:"status,omitempty"` + Note string `json:"note,omitempty"` + // Admin is a dashboard event (login, key added, ...). + Admin string `json:"admin,omitempty"` +} + +// AuditFilter narrows a search: exact service and role, path substring. +type AuditFilter struct { + Service, Role, Path string +} + +var errAuditTime = errors.New("write the times as 2026-11-15T16:39 (UTC) or RFC 3339") + +func parseAuditTime(s string) (time.Time, bool, error) { + if t, err := time.Parse(AuditMinute, s); err == nil { + return t, true, nil + } + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return t, false, errAuditTime + } + return t.UTC(), false, nil +} + +// AuditWindow reads a search window: from and to in UTC; a to given as a +// minute includes that minute. Either may be empty: the default is the hour +// up to now, or the hour before to. +func AuditWindow(fromText, toText string, now time.Time) (time.Time, time.Time, error) { + to := now.UTC().Truncate(time.Minute).Add(time.Minute) + from := to.Add(-time.Hour) + if toText != "" { + t, minute, err := parseAuditTime(toText) + if err != nil { + return from, to, err + } + if to = t; minute { + to = t.Add(time.Minute) + } + from = to.Add(-time.Hour) + } + if fromText != "" { + t, _, err := parseAuditTime(fromText) + if err != nil { + return from, to, err + } + from = t + } + if !from.Before(to) { + return from, to, errors.New("the start must be before the end") + } + return from, to, nil +} + +func ceilSecond(t time.Time) time.Time { + if s := t.Truncate(time.Second); !s.Equal(t) { + return s.Add(time.Second) + } + return t +} + +// SearchAudit scans the audit log at path for records in [from, to) +// matching f, newest first; past AuditLimit it keeps the newest by time and +// reports more. A record is written when its call ends but stamped with its +// start, so the last written are not the newest (#153 review). The log is append-only and never rotated, so it is streamed: +// a line's time is compared as text before it is decoded. +func SearchAudit(path string, from, to time.Time, f AuditFilter) ([]AuditRow, bool, error) { + file, err := os.Open(path) + if err != nil { + return nil, false, err + } + defer file.Close() + // Records are stamped to the second and compared as text, so compare + // against whole seconds: for a whole-second t, t >= x and t < y exactly + // when t >= ceil(x) and t < ceil(y) (#155 review). The caller's window + // itself is not changed. + lo, hi := ceilSecond(from).UTC().Format(time.RFC3339), ceilSecond(to).UTC().Format(time.RFC3339) + kept := &newestRows{} + more := false + rd := bufio.NewReaderSize(file, 64<<10) + for { + line, err := rd.ReadSlice('\n') + if errors.Is(err, bufio.ErrBufferFull) { + // A line this long is not an audit record worth showing; skip it. + for errors.Is(err, bufio.ErrBufferFull) { + _, err = rd.ReadSlice('\n') + } + continue + } + if len(line) > 0 { + if row, ok := auditMatch(line, lo, hi, f); ok { + if kept.Len() < AuditLimit { + heap.Push(kept, row) + } else { + more = true + if row.Time > (*kept)[0].Time { + (*kept)[0] = row + heap.Fix(kept, 0) + } + } + } + } + if err == io.EOF { + break + } + if err != nil { + return nil, false, err + } + } + rows := []AuditRow(*kept) + slices.SortStableFunc(rows, func(a, b AuditRow) int { return strings.Compare(b.Time, a.Time) }) + return rows, more, nil +} + +// newestRows is a min-heap by time: its root is the oldest row kept. +type newestRows []AuditRow + +func (h newestRows) Len() int { return len(h) } +func (h newestRows) Less(i, j int) bool { return h[i].Time < h[j].Time } +func (h newestRows) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *newestRows) Push(x any) { *h = append(*h, x.(AuditRow)) } +func (h *newestRows) Pop() any { + old := *h + x := old[len(old)-1] + *h = old[:len(old)-1] + return x +} + +func auditMatch(line []byte, lo, hi string, f AuditFilter) (AuditRow, bool) { + var row AuditRow + s := string(line) + i := strings.Index(s, `"time":"`) + if i < 0 || len(s) < i+8+len(lo) { + return row, false + } + if t := s[i+8 : i+8+len(lo)]; t < lo || t >= hi { + return row, false + } + if json.Unmarshal(line, &row) != nil { + return row, false + } + if f.Service != "" && row.Service != f.Service || f.Role != "" && row.Role != f.Role || + f.Path != "" && !strings.Contains(row.Path, f.Path) { + return row, false + } + return row, true +} + +// serveAuditSearch answers AuditPath for a role with AuditRead. One search +// runs at a time: each one reads the whole log. +func (h *Handler) serveAuditSearch(w http.ResponseWriter, r *http.Request, snap *snapshot, allowed bool, rec *auditRecord, fail func(int, string)) { + rec.Path = AuditPath + switch { + case r.Method != http.MethodGet: + fail(http.StatusMethodNotAllowed, "the audit search is GET only") + return + case !allowed: + fail(http.StatusForbidden, "this agent may not read the audit log; the owner allows it on the agent's page in the dashboard") + return + } + q := r.URL.Query() + from, to, err := AuditWindow(q.Get("from"), q.Get("to"), h.now()) + if err != nil { + fail(http.StatusBadRequest, err.Error()) + return + } + if !h.auditSearch.TryLock() { + fail(http.StatusTooManyRequests, "another audit search is running; try again shortly") + return + } + defer h.auditSearch.Unlock() + rows, more, err := SearchAudit(snap.config.AuditLog, from, to, + AuditFilter{Service: q.Get("service"), Role: q.Get("role"), Path: q.Get("path")}) + if errors.Is(err, os.ErrNotExist) { + rows, err = nil, nil + } + if err != nil { + fail(http.StatusInternalServerError, "the audit log could not be read") + return + } + if rows == nil { + rows = []AuditRow{} + } + rec.Status = http.StatusOK + rec.Note = "audit search" + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(map[string]any{ + "from": from.Format(time.RFC3339Nano), "to": to.Format(time.RFC3339Nano), "rows": rows, "more": more, "limit": AuditLimit, + }) +} diff --git a/internal/server/auditsearch_test.go b/internal/server/auditsearch_test.go new file mode 100644 index 0000000..6c98e3d --- /dev/null +++ b/internal/server/auditsearch_test.go @@ -0,0 +1,139 @@ +package server + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gitmoot/keyring/internal/policy" +) + +// Owner, 2026-11-15: an agent the owner allows (audit_read) searches the +// audit log through the keyring; any other agent gets 403; the search is +// audited. +func TestAuditSearchOnlyForAllowedAgents(t *testing.T) { + dir := t.TempDir() + log := filepath.Join(dir, "audit.log") + lines := `{"time":"2026-11-15T16:39:53Z","role":"phobos","service":"macserve","method":"POST","path":"/v1/jobs/j_ce4ce15b/cancel","status":202} +{"time":"2026-11-15T16:39:20Z","role":"tandem","service":"macserve","method":"GET","path":"/v1/jobs/j_ce4ce15b","status":200} +{"time":"2026-11-15T16:41:00Z","role":"phobos","service":"macserve","method":"POST","path":"/v1/jobs/j_ce4ce15b/cancel","status":202} +` + if err := os.WriteFile(log, []byte(lines), 0o600); err != nil { + t.Fatal(err) + } + const reader, other = "reader-token-0123456789abcdef", "other-token-0123456789abcdef" + cfg := &policy.Config{ + Rules: policy.Rules{Listen: "127.0.0.1:7701", AllowSources: []string{caller}, AuditLog: log}, + AccessList: policy.AccessList{ + Services: map[string]policy.Service{"api": {Base: "https://api.example.com", Key: "API_KEY", Auth: policy.AuthBearer}}, + Roles: map[string]policy.Role{ + "jarvis": {TokenSHA256: tokenHash(reader), Access: map[string]policy.Access{}, AuditRead: true}, + "tandem": {TokenSHA256: tokenHash(other), Access: map[string]policy.Access{"api": allowAll}}, + }, + }, + } + if err := cfg.Validate(); err != nil { + t.Fatal(err) + } + audit := &bytes.Buffer{} + h := New(cfg, map[string]string{"API_KEY": testKey}, audit) + + w := call(h, "GET", AuditPath+"?from=2026-11-15T16:39&to=2026-11-15T16:39&path=/cancel", reader, nil) + var got struct { + Rows []AuditRow `json:"rows"` + More bool `json:"more"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); w.Code != http.StatusOK || err != nil { + t.Fatalf("allowed agent: %d %s", w.Code, w.Body) + } + if len(got.Rows) != 1 || got.Rows[0].Role != "phobos" || got.Rows[0].Time != "2026-11-15T16:39:53Z" { + t.Fatalf("rows = %+v, want only phobos's 16:39:53 cancel", got.Rows) + } + if w := call(h, "GET", AuditPath+"?from=2026-11-15T16:39&to=2026-11-15T16:39", other, nil); w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "j_ce4ce15b") { + t.Fatalf("agent without audit_read: %d %s", w.Code, w.Body) + } + if w := call(h, "POST", AuditPath, reader, nil); w.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST: %d", w.Code) + } + if w := call(h, "GET", AuditPath+"?to=yesterday", reader, nil); w.Code != http.StatusBadRequest { + t.Fatalf("bad time: %d", w.Code) + } + if w := call(h, "GET", AuditPath, "", nil); w.Code != http.StatusUnauthorized { + t.Fatalf("no token: %d", w.Code) + } + // The answer names the window as asked, fractions included, so it can be + // sent again (#155 review). + w = call(h, "GET", AuditPath+"?from=2026-11-15T16:39:53.1Z&to=2026-11-15T16:39:53.2Z", reader, nil) + var win struct{ From, To string } + if err := json.Unmarshal(w.Body.Bytes(), &win); w.Code != http.StatusOK || err != nil || win.From != "2026-11-15T16:39:53.1Z" || win.To != "2026-11-15T16:39:53.2Z" { + t.Fatalf("window echoed as %+v (%d)", win, w.Code) + } + if w := call(h, "GET", AuditPath+"?from="+win.From+"&to="+win.To, reader, nil); w.Code != http.StatusOK { + t.Fatalf("replaying the echoed window: %d", w.Code) + } + if !strings.Contains(audit.String(), `"role":"jarvis"`) || !strings.Contains(audit.String(), `"note":"audit search"`) || + !strings.Contains(audit.String(), `"role":"tandem","method":"GET","path":"/_keyring/audit","status":403`) { + t.Fatalf("searches not audited:\n%s", audit) + } +} + +// #153 review: past the limit the newest by time are kept, even when an +// older, slow call was written last. +func TestSearchAuditKeepsNewestPastTheLimit(t *testing.T) { + log := filepath.Join(t.TempDir(), "audit.log") + var b strings.Builder + base := time.Date(2026, 11, 15, 16, 0, 0, 0, time.UTC) + for i := 1; i <= AuditLimit; i++ { + fmt.Fprintf(&b, `{"time":%q,"role":"r","service":"s","method":"GET","path":"/x"}`+"\n", base.Add(time.Duration(i)*time.Second).Format(time.RFC3339)) + } + // The oldest call, slow, is written last. + fmt.Fprintf(&b, `{"time":%q,"role":"slow","service":"s","method":"GET","path":"/x"}`+"\n", base.Format(time.RFC3339)) + if err := os.WriteFile(log, []byte(b.String()), 0o600); err != nil { + t.Fatal(err) + } + rows, more, err := SearchAudit(log, base, base.Add(time.Hour), AuditFilter{}) + if err != nil || !more || len(rows) != AuditLimit { + t.Fatalf("rows %d more %v err %v", len(rows), more, err) + } + if want := base.Add(AuditLimit * time.Second).Format(time.RFC3339); rows[0].Time != want { + t.Errorf("newest row %s, want %s", rows[0].Time, want) + } + for _, r := range rows { + if r.Role == "slow" { + t.Fatal("kept the oldest (slow, last-written) call over a newer one") + } + } +} + +// #155 review: a window with fractional seconds matches exactly the +// whole-second records inside it. +func TestAuditWindowFractionalSeconds(t *testing.T) { + log := filepath.Join(t.TempDir(), "audit.log") + if err := os.WriteFile(log, []byte(`{"time":"2026-11-15T16:39:20Z","role":"r","service":"s","method":"GET","path":"/x"}`+"\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + from, to string + want int + }{ + {"2026-11-15T16:39:19.5Z", "2026-11-15T16:39:20.5Z", 1}, + {"2026-11-15T16:39:20.5Z", "2026-11-15T16:39:21.5Z", 0}, + {"2026-11-15T16:39:19Z", "2026-11-15T16:39:20Z", 0}, + {"2026-11-15T16:39:20Z", "2026-11-15T16:39:20.001Z", 1}, + } { + from, to, err := AuditWindow(c.from, c.to, time.Now()) + if err != nil { + t.Fatal(err) + } + rows, _, err := SearchAudit(log, from, to, AuditFilter{}) + if err != nil || len(rows) != c.want { + t.Errorf("[%s, %s): %d rows, want %d (%v)", c.from, c.to, len(rows), c.want, err) + } + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 011a54f..08fad47 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -48,8 +48,10 @@ type Handler struct { snap atomic.Pointer[snapshot] // requests, when set, takes access requests at RequestsPath. requests *requests.Store - audit io.Writer - client *http.Client + // auditSearch lets one audit search (AuditPath) run at a time. + auditSearch sync.Mutex + audit io.Writer + client *http.Client // pinned holds one client per tls_pin_sha256 value (see clientFor). pinned sync.Map now func() time.Time @@ -292,6 +294,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fail(http.StatusUnauthorized, "role expired") return } + if r.URL.Path == AuditPath { + h.serveAuditSearch(w, r, snap, role.AuditRead, &rec, fail) + return + } var accountID string var accountErr error r, accountID, accountErr = workspaceRequest(r)