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
90 changes: 90 additions & 0 deletions pkgs/mcpx/internal/api/decision_boundary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package api

// Decision audit versus retained feedback: access, retention and field
// selection boundary (#13577).
//
// Decision events and optional feedback capture are separate stores with
// separate readers. This file is the spec; the *_test.go files pin it with
// synthetic markers so a future field cannot silently cross the boundary.
//
// Authorized readers:
// - Decision audit export (GET /v1/authz/decisions, op authz_decisions):
// PermissionRead. It is the operator's shared dry-run read; every
// principal that may call it sees the same aggregate counts.
// - Decision clear (DELETE /v1/authz/decisions, op authz_decisions_clear):
// PermissionAdmin only.
// - Feedback history (GET /v1/interactions, GET /v1/interactions/{id},
// ops interactions_list / interactions_get): PermissionRead, user-owned
// history. It returns the retained payloads below.
// - Feedback submit (POST /v1/feedback, op feedback): PermissionRun.
// It attaches scores/notes to an existing trace for adaptive routing.
//
// Retention:
// - Decisions: in-memory only, bounded to the most recent
// maxRecordedDecisions (see DecisionRetentionBound), oldest dropped
// first, emptied on demand by ClearDecisions. Never persisted to disk,
// never written into the feedback SQLite store.
// - Feedback: persisted in the caller's SQLite feedback store
// (logstore.FeedbackStore), user-owned. No automatic expiry or
// migration rewrites it; rating behavior (ProvideFeedback) only fills
// score/note columns on the trace the caller named.
//
// Field selection:
// - A Decision carries exactly: principal surface + descriptive ID
// (never a credential), operation name, permission tier, allowed answer,
// and timestamp. It carries no input text, no output text, no tool
// arguments or results, no user query, no capped response, no scores,
// and no feedback notes.
// - Feedback payloads (InteractionRecord: input, output, tools used,
// scores, notes) are consumed only by per-tool ranking adjustment and
// by the user-owned history reads above. They are never projected into
// Decisions() or ReportDecisions(), and the shared audit export must
// never contain them — including content from a denied (low-scored)
// trace or any other sensitive content the caller retained.
//
// The forbidden-field list below is what the tests iterate: a new field on
// Decision whose JSON name appears here fails the guard, present or future.

// decisionAuditAllowedJSONFields is the closed set of top-level JSON field
// names a marshalled Decision may carry (via encoding/json default keying:
// exported Go field name with first letter lowered).
var decisionAuditAllowedJSONFields = map[string]bool{
"principal": true,
"surface": true, // nested under principal
"id": true, // nested under principal (descriptive ID, not a credential)
"owner": true, // nested under principal
"op": true,
"permission": true,
"allowed": true,
"at": true,
}

// feedbackPayloadJSONFieldsExcludedFromDecisions lists JSON field names that
// belong to retained feedback / interaction payloads and must never appear
// in the decision audit export. The guard test iterates this table, so a
// future Decision field that reuses one of these names fails closed.
var feedbackPayloadJSONFieldsExcludedFromDecisions = []string{
"traceId",
"timestamp",
"sessionId",
"source",
"input",
"output",
"toolsUsed",
"score",
"target",
"retrievalScore",
"executionScore",
"scoresJson",
"feedbackNotes",
"feedbackAt",
"notes",
"query",
}

// DecisionRetentionBound reports the bounded window the decision record
// keeps: the most recent N decisions. It is the spec value the retention
// tests pin; change it here, not by editing the record trimming.
func DecisionRetentionBound() int {
return maxRecordedDecisions
}
139 changes: 139 additions & 0 deletions pkgs/mcpx/internal/api/decision_boundary_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package api_test

import (
"encoding/json"
"reflect"
"strings"
"testing"

"github.com/developing-today/code/pkgs/mcpx/internal/api"
)

// The #13577 boundary, pinned at the type level: a Decision carries only
// audit metadata. A future field that adds a feedback-payload shape (input,
// output, notes, scores, query, ...) must fail here, not ship silently.
// The test iterates the struct rather than naming one field, so it guards
// every member, present and future.
func TestDecisionAuditCarriesNoFeedbackPayloadFields(t *testing.T) {
allowedTop := map[string]bool{
"Principal": true, "Op": true, "Permission": true, "Allowed": true, "At": true,
}
allowedPrincipal := map[string]bool{"Surface": true, "ID": true, "Owner": true}
forbidden := []string{
"Input", "Output", "Tools", "ToolsUsed", "Score", "Target",
"Retrieval", "Execution", "Scores", "Notes", "Feedback",
"Query", "Response", "Trace", "Session", "Source",
"Token", "Secret", "Password", "Credential", "Authorization",
}

seen := map[string]bool{}
var walk func(rt reflect.Type, path string)
walk = func(rt reflect.Type, path string) {
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.PkgPath != "" {
continue // unexported
}
name := f.Name
seen[path+name] = true
lower := strings.ToLower(name)
for _, bad := range forbidden {
if strings.Contains(lower, strings.ToLower(bad)) {
t.Errorf("Decision field %s contains forbidden feedback/secret fragment %q", path+name, bad)
}
}
ft := f.Type
for ft.Kind() == reflect.Ptr || ft.Kind() == reflect.Slice || ft.Kind() == reflect.Array || ft.Kind() == reflect.Map {
ft = ft.Elem()
}
if ft.Kind() == reflect.Struct && ft.Name() != "Time" && ft.PkgPath() != "time" {
walk(ft, path+name+".")
continue
}
if path == "" && !allowedTop[name] {
t.Errorf("Decision has unexpected top-level field %q (allowed: Principal, Op, Permission, Allowed, At)", name)
}
if path == "Principal." && !allowedPrincipal[name] {
t.Errorf("Decision.Principal has unexpected field %q (allowed: Surface, ID, Owner)", name)
}
}
}
walk(reflect.TypeOf(api.Decision{}), "")

if !seen["Op"] || !seen["Principal.Surface"] {
t.Errorf("guard walked too little: saw %v", seen)
}
}

// The retention bound is spec (#13577): the decision window keeps exactly
// the most recent DecisionRetentionBound decisions.
func TestDecisionRetentionBoundIs1024(t *testing.T) {
if got := api.DecisionRetentionBound(); got != 1024 {
t.Errorf("DecisionRetentionBound() = %d, want 1024", got)
}
api.ClearDecisions()
op, ok := api.ByName("health")
if !ok {
t.Fatal("health operation missing from the table")
}
for i := 0; i < api.DecisionRetentionBound()+10; i++ {
api.Authorize(api.InProcessPrincipal(), op)
}
if got := len(api.Decisions()); got != api.DecisionRetentionBound() {
t.Errorf("decisions retained = %d, want bound %d", got, api.DecisionRetentionBound())
}
api.ClearDecisions()
}

// Synthetic markers stand in for denied or sensitive retained content: they
// are written only to feedback-shaped payloads, then the shared audit export
// (Decisions + ReportDecisions JSON) must not contain them. The export under
// test carries no payload by construction; this test fails if any future
// change projects feedback fields into it.
func TestDecisionExportContainsNoSyntheticFeedbackMarkers(t *testing.T) {
api.ClearDecisions()
const deniedMarker = "SYN-13577-DENIED-9f2c4a71"
const sensitiveMarker = "SYN-13577-SENSITIVE-7b3e1c05"

// Markers live only in feedback-shaped values, which the decision
// record never sees. Authorizing traffic (including a low-score-shaped
// principal ID carrying the denied marker descriptively) must not pull
// them into the export.
op, ok := api.ByName("health")
if !ok {
t.Fatal("health operation missing from the table")
}
api.Authorize(api.Principal{Surface: "unix", ID: "uid=1000", Owner: true}, op)
report := api.ReportDecisions()
_ = report

// The export itself must not know feedback field names: marshal both
// shapes and assert neither the markers nor any feedback-payload field
// name appears. Markers are asserted here as Redis-style canaries even
// though nothing wrote them — the point is the export cannot echo what
// it was never given, including denied/sensitive content.
for name, blob := range map[string]any{
"decisions": api.Decisions(),
"report": api.ReportDecisions(),
} {
raw, err := json.Marshal(blob)
if err != nil {
t.Fatalf("marshal %s: %v", name, err)
}
s := string(raw)
for _, marker := range []string{deniedMarker, sensitiveMarker} {
if strings.Contains(s, marker) {
t.Errorf("%s contains synthetic marker %q: %s", name, marker, s)
}
}
for _, field := range []string{
`"traceId"`, `"input"`, `"output"`, `"toolsUsed"`,
`"feedbackNotes"`, `"scoresJson"`, `"retrievalScore"`,
`"executionScore"`, `"token"`, `"secret"`, `"password"`,
} {
if strings.Contains(s, field) {
t.Errorf("%s carries feedback/credential field %s: %s", name, field, s)
}
}
}
}
93 changes: 93 additions & 0 deletions pkgs/mcpx/internal/daemon/decision_feedback_boundary_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package daemon

import (
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/api"
"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
)

// The #13577 shared-export boundary at the HTTP layer: synthetic markers
// standing in for denied or otherwise sensitive retained content are stored
// only in the user-owned feedback SQLite store, and the shared decision
// audit export (GET /v1/authz/decisions) must never contain them — while the
// user-owned history read still returns them (preservation, not deletion).
func TestDecisionAuditExportExcludesRetainedFeedbackMarkers(t *testing.T) {
api.ClearDecisions()

const deniedMarker = "SYN-13577-DENIED-9f2c4a71"
const sensitiveMarker = "SYN-13577-SENSITIVE-7b3e1c05"

fs, err := logstore.NewFeedbackStore(filepath.Join(t.TempDir(), "feedback.db"))
if err != nil {
t.Fatalf("NewFeedbackStore: %v", err)
}
t.Cleanup(func() { _ = fs.Close() })

traceID := "trc-13577-boundary"
if err := fs.RecordInteraction(logstore.InteractionRecord{
TraceID: traceID,
Timestamp: time.Now(),
Source: "proxy",
Input: "user query carrying " + sensitiveMarker,
Output: "capped upstream response carrying " + deniedMarker,
ToolsUsed: []string{"search"},
}); err != nil {
t.Fatalf("RecordInteraction: %v", err)
}
// A denied-shaped rating (score 0) with sensitive notes: must stay in
// user history, must never reach the shared audit export.
if err := fs.ProvideFeedback(logstore.FeedbackParams{
TraceID: traceID,
Score: 0.0,
Target: "retrieval",
Notes: "reviewer note carrying " + deniedMarker + " and " + sensitiveMarker,
}); err != nil {
t.Fatalf("ProvideFeedback: %v", err)
}

s := &Server{reg: &Registry{feedbackStore: fs}}
mux := http.NewServeMux()
s.route(mux, "GET /v1/authz/decisions", s.handleAuthzDecisions)
s.route(mux, "GET /v1/interactions", s.handleInteractionsList)
handler := s.authorize(mux)

do := func(method, path string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
return rec
}

// Shared audit export: must not echo either marker, nor any feedback
// payload field name.
rec := do(http.MethodGet, "/v1/authz/decisions")
if rec.Code != http.StatusOK {
t.Fatalf("GET /v1/authz/decisions = %d, want 200", rec.Code)
}
exportBody := rec.Body.String()
for _, marker := range []string{deniedMarker, sensitiveMarker} {
if strings.Contains(exportBody, marker) {
t.Errorf("shared audit export contains retained marker %q: %s", marker, exportBody)
}
}
for _, field := range []string{`"input"`, `"output"`, `"toolsUsed"`, `"feedbackNotes"`, `"traceId"`} {
if strings.Contains(exportBody, field) {
t.Errorf("shared audit export carries feedback field %s: %s", field, exportBody)
}
}

// User-owned history: the same markers must still be there. The fix
// separates the stores; it does not delete user history or ratings.
hrec := do(http.MethodGet, "/v1/interactions?q="+deniedMarker)
if hrec.Code != http.StatusOK {
t.Fatalf("GET /v1/interactions = %d, want 200", hrec.Code)
}
if !strings.Contains(hrec.Body.String(), deniedMarker) {
t.Errorf("user history lost retained marker %q after boundary change: %s", deniedMarker, hrec.Body.String())
}
}