Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<role>/_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:
Expand Down
35 changes: 35 additions & 0 deletions internal/dashboard/access.go
Original file line number Diff line number Diff line change
Expand Up @@ -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".
Expand Down Expand Up @@ -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")) {
Expand Down
130 changes: 9 additions & 121 deletions internal/dashboard/activity.go
Original file line number Diff line number Diff line change
@@ -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
}
28 changes: 28 additions & 0 deletions internal/dashboard/activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
5 changes: 5 additions & 0 deletions internal/dashboard/pages.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,11 @@ Sign in with Apple: <code>{"service":"NAME","auth":"sign-in-with-apple-sign","si
<ul class="grants">{{range .Services}}<li><a class="grant" href="/access/{{$.Role}}/{{.Service}}"><span class="svc">{{.Service}}</span><span class="what">{{.Label}}{{with .Via}} · through project {{.}}{{end}}</span></a></li>{{else}}<li class="mute">None yet.</li>{{end}}</ul>
{{if .Off}}<form method="get" action="/access/{{.Role}}/-" class="add" data-pathpick><select name="service" aria-label="Add a service"><option value="">Add a service…</option>{{range .Off}}<option>{{.}}</option>{{end}}</select><noscript><button class="ghost">Open</button></noscript></form>{{end}}
</div>
<div class="card"><h2>Activity log</h2>{{if .AuditSaved}}<p class="notice">Saved.</p>{{end}}
<p>{{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}}</p>
<form method="post" action="/agents/{{.Role}}/audit"><input type="hidden" name="csrf" value="{{.CSRF}}"><input type="hidden" name="allow" value="{{if .AuditRead}}no{{else}}yes{{end}}">
{{template "password" .}}<div class="actions"><button{{if .AuditRead}} class="ghost"{{end}}>{{if .AuditRead}}Stop audit access{{else}}Allow audit search{{end}}</button></div></form>
<p class="hint">Through its relay: <code>GET /{{.Role}}/_keyring/audit?from=2026-11-15T16:39&amp;to=2026-11-15T16:39&amp;service=&amp;role=&amp;path=</code>, the same search as the Activity page.</p></div>
<div class="card"><dl><dt>Ends</dt><dd>{{with .Expires}}{{.}}{{else}}never{{end}}</dd><dt>Token file</dt><dd><code>{{.File}}</code></dd></dl></div>
<details class="card"><summary>Make a new token</summary><form method="post" action="/agents/{{.Role}}/token"><input type="hidden" name="csrf" value="{{.CSRF}}"><input type="hidden" name="current" value="{{.Current}}">
<p class="mute">Shown once. The old token stops working at once.</p>{{template "password" .}}<div class="actions"><button>Make a new token</button></div></form></details>
Expand Down
4 changes: 4 additions & 0 deletions internal/policy/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading