Guard app HTTP response emission with current delegated authority

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4b94ff9e8a8df96fc1dc90901e7aec5dbbe511c4 parent 8ed8ba8
3 files changed, +490 −0
  • docs/guarded-http-responses.md +11 −0
  • http_guarded.go +163 −0
  • http_guarded_test.go +316 −0

CI passed — run details

diff --git a/docs/guarded-http-responses.md b/docs/guarded-http-responses.md
new file mode 100644
index 0000000..af4d2d5
--- /dev/null
+++ b/docs/guarded-http-responses.md
@@ -0,0 +1,11 @@
+# Guarded app HTTP responses
+
+Status: bounded design approved by GPT-6 Astra with the explicit continuity and fail-closed requirements below; implementation/evidence review pending. Follow-up to close the legacy adapters' response-emission gap. Docs, Sheets and Slides already have app-owned guarded emission; Calendar, Calls and Memoria still use direct Registry.HTTP output.
+
+Add a separate Registry.HTTPGuarded(initial Verifier, recheck Verifier, guard ResponseGuard) entry point. Existing HTTP behavior stays for the connection gateway and compatibility. A nonnil app guard is mandatory. Initial verification may include local admission and one rate-limit charge. Rechecks use the original underlying credential verifier, never the rate-limiting wrapper. Preserve the exact bearer and Subject/Client/Grant; require the original operation's scope and input team on each check. Discovery must retain the originally disclosed team/scope set (revoked facts cannot be emitted). Registry.Call and schemas remain the single invocation path, executed exactly once.
+
+Before serializing success, bound it to MaxPayload. The app callback receives the request context, original principal, operation name, input and result, and revalidates current local identity plus permissions for every returned resource. It must not execute a write, refresh a token or replay the operation. Call original-verifier plus app guard immediately before headers and each at-most-64-KiB write with a five-second context/write deadline (shortened to caller deadline). Fail safely before headers; abort partial HTTP bodies with ErrAbortHandler and exact Content-Length. Do not silently tolerate a transport without write-deadline support. Failure bodies contain no app result. Check the elapsed context deadline after every verifier and guard callback, including callbacks that return nil.
+
+Adapter state is per request, captured before domain execution, and retains stable local person ID/address plus the returned resource set. Calendar rechecks current calendar readability and archive state; event reads/creation capture the event and calendar IDs, then re-read the live event and reject deletion or any change to its captured calendar coordinate, and free/busy must carry calendar provenance from the same range expansion that produced its spans. Calls rechecks local membership and meeting existence; invitation responses additionally require the exact originally returned invitation to remain live and its meeting unended. Memoria checks current Home/local admission, exact live chunk/document pairs, and current sibling custody for the returned revisions. Sibling checks use the existing custody interface without replaying search or recording duplicate breaker statistics. Locally owned created notes require the same current document/receipt identity. Missing or incomplete resource provenance fails closed. Memoria freezes the original sibling item/revision coordinates; current coordinates must still match, and every original candidate must receive an explicit VISIBLE/renderable custody disposition. Missing, short, or non-renderable dispositions fail closed. Never filter a selected response midway through emission. No second model call and no repeated mutation.
+
+Tests use actual HTTP transport to prove revocation/permission loss after the first chunk truncates the body, plus preheader rejection, successful-principal continuity, metadata revocation, deadline failure/timeout, single domain invocation, and one Calls rate charge. App tests distinguish loss of local identity, item permission, invitation revocation, missing/stale chunks and changed sibling visibility. Writer-boundary regression tests must remain discriminating now that a later response guard could mask a missing transaction guard. Effective mutants omit preheader versus chunk checks independently and each app's resource guard. Run full shared and affected app CI/race checks, independent source/evidence review, then exact module pins.
diff --git a/http_guarded.go b/http_guarded.go
new file mode 100644
index 0000000..ee41b39
--- /dev/null
+++ b/http_guarded.go
@@ -0,0 +1,163 @@
+package agentaccess
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "mime"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// ResponseGuard revalidates local identity and every resource selected by the
+// operation. It must never replay the operation or mutate application state.
+// Discovery uses an empty name/input. Captured provenance belongs to the request.
+type ResponseGuard func(context.Context, Principal, string, json.RawMessage, any) error
+
+// HTTPGuarded retains HTTP's contracts while authorizing bounded response
+// emission. initial may charge a quota; recheck must be a pure credential check.
+func (registry *Registry) HTTPGuarded(initial, recheck Verifier, guard ResponseGuard) http.Handler {
+ if initial == nil || recheck == nil || guard == nil {
+ panic("agentaccess: guarded HTTP requires both verifiers and an app guard")
+ }
+ mux := http.NewServeMux()
+ emit := func(w http.ResponseWriter, r *http.Request, name string, raw json.RawMessage, result any) {
+ p := principalFrom(r.Context())
+ token := strings.Fields(r.Header.Get("Authorization"))[1] // Authenticate validated the header.
+ var disclosed []Operation
+ if metadata, ok := result.(map[string]any); ok && name == "" {
+ disclosed, _ = metadata["operations"].([]Operation)
+ }
+ var team string
+ if name != "" {
+ var input map[string]any
+ _ = DecodeJSON(raw, &input)
+ team, _ = input["team"].(string)
+ }
+ check := func(ctx context.Context) error {
+ fresh, err := recheck.Verify(ctx, token)
+ if err != nil {
+ return err
+ }
+ if err = ctx.Err(); err != nil {
+ return err
+ }
+ if fresh.Subject != p.Subject || fresh.Client != p.Client || fresh.Grant != p.Grant {
+ return Fail("unauthenticated", "Reconnect to Oficina.")
+ }
+ if name == "" {
+ for _, t := range p.Teams {
+ if !contains(fresh.Teams, t) {
+ return Fail("forbidden", "Connection access changed.")
+ }
+ }
+ for _, s := range p.Scopes {
+ if !contains(fresh.Scopes, s) {
+ return Fail("forbidden", "Connection access changed.")
+ }
+ }
+ for _, op := range disclosed {
+ entry := registry.operations[op.Name]
+ if entry.op.Available != nil && !entry.op.Available(fresh) {
+ return Fail("forbidden", "Connection access changed.")
+ }
+ }
+ } else {
+ entry := registry.operations[name]
+ if !fresh.Allows(team, entry.op.Scope) || entry.op.Available != nil && !entry.op.Available(fresh) {
+ return Fail("forbidden", "Connection access changed.")
+ }
+ }
+ if err = guard(ctx, p, name, raw, result); err != nil {
+ return err
+ }
+ return ctx.Err()
+ }
+ guardedJSON(w, r, result, check)
+ }
+ mux.HandleFunc("GET /api/v1/connection", func(w http.ResponseWriter, r *http.Request) {
+ emit(w, r, "", nil, ConnectionFrom(principalFrom(r.Context())))
+ })
+ mux.HandleFunc("GET /api/v1/operations", func(w http.ResponseWriter, r *http.Request) {
+ emit(w, r, "", nil, map[string]any{"operations": registry.List(principalFrom(r.Context()))})
+ })
+ mux.HandleFunc("POST /api/v1/operations/{name}", func(w http.ResponseWriter, r *http.Request) {
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || media != "application/json" {
+ writeFailure(w, Fail("unsupported_media_type", "Send application/json."))
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(r.Body, MaxPayload+1))
+ if err != nil {
+ writeFailure(w, Fail("invalid", "Could not read the request."))
+ return
+ }
+ result, err := registry.Call(r.Context(), principalFrom(r.Context()), r.PathValue("name"), raw)
+ if err != nil {
+ writeFailure(w, err)
+ return
+ }
+ emit(w, r, r.PathValue("name"), raw, result)
+ })
+ return Authenticate(initial, mux)
+}
+
+func guardedJSON(w http.ResponseWriter, r *http.Request, result any, check func(context.Context) error) {
+ body, err := json.Marshal(result)
+ if err != nil || len(body) > MaxPayload {
+ writeFailure(w, Fail("too_large", "The response is too large."))
+ return
+ }
+ body = append(body, '\n')
+ controller := http.NewResponseController(w)
+ // Refuse unsupported transports before emitting any application data.
+ deadline := time.Now().Add(5 * time.Second)
+ if d, ok := r.Context().Deadline(); ok && d.Before(deadline) {
+ deadline = d
+ }
+ if err = controller.SetWriteDeadline(deadline); err != nil {
+ writeFailure(w, Fail("unavailable", "This transport cannot safely send the response."))
+ return
+ }
+ defer func() { _ = controller.SetWriteDeadline(time.Time{}) }()
+ verify := func() error {
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+ if err := check(ctx); err != nil {
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ d, _ := ctx.Deadline()
+ return controller.SetWriteDeadline(d)
+ }
+ if err = verify(); err != nil {
+ writeFailure(w, err)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ // Do not commit headers until the first chunk check has also passed.
+ for offset := 0; offset < len(body); {
+ if err = verify(); err != nil {
+ if offset == 0 {
+ w.Header().Del("Content-Length")
+ writeFailure(w, err)
+ return
+ }
+ panic(http.ErrAbortHandler)
+ }
+ end := min(offset+(64<<10), len(body))
+ n, err := w.Write(body[offset:end])
+ if err != nil || n != end-offset {
+ panic(http.ErrAbortHandler)
+ }
+ if err = controller.Flush(); err != nil {
+ panic(http.ErrAbortHandler)
+ }
+ offset = end
+ }
+}
diff --git a/http_guarded_test.go b/http_guarded_test.go
new file mode 100644
index 0000000..bfd087f
--- /dev/null
+++ b/http_guarded_test.go
@@ -0,0 +1,316 @@
+package agentaccess
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type guardedWriter struct {
+ http.ResponseWriter
+ after func()
+ deadline func(time.Time) error
+}
+
+func (w guardedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w guardedWriter) Write(b []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(b)
+ if w.after != nil {
+ w.after()
+ }
+ return n, e
+}
+func (w guardedWriter) SetWriteDeadline(d time.Time) error {
+ if w.deadline != nil {
+ return w.deadline(d)
+ }
+ return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(d)
+}
+
+func TestGuardedHTTPResponseBoundaries(t *testing.T) {
+ for _, phase := range []string{"success", "preheader", "chunk", "chunk-verifier", "unrelated", "identity", "client", "grant", "scope", "team", "expired"} {
+ t.Run(phase, func(t *testing.T) {
+ var invokes, initialCalls, checks, guards atomic.Int32
+ var written atomic.Bool
+ r, e := NewRegistry(Operation{Name: "notes_read", Description: "Read", Scope: "notes:read", Input: json.RawMessage(`{"type":"object","properties":{"team":{"type":"string"}},"required":["team"]}`), Output: json.RawMessage(`{"type":"object"}`), Invoke: func(context.Context, Principal, json.RawMessage) (any, error) {
+ invokes.Add(1)
+ return map[string]string{"body": strings.Repeat("private", 24000)}, nil
+ }})
+ if e != nil {
+ t.Fatal(e)
+ }
+ p := principal()
+ p.Scopes = []string{"notes:read"}
+ if phase == "unrelated" {
+ p.Scopes = append(p.Scopes, "extra:read")
+ p.Teams = append(p.Teams, "extra")
+ }
+ initial := VerifyFunc(func(context.Context, string) (Principal, error) { initialCalls.Add(1); return p, nil })
+ recheck := VerifyFunc(func(ctx context.Context, token string) (Principal, error) {
+ checks.Add(1)
+ if token != "original" {
+ t.Error("credential changed")
+ }
+ fresh := p
+ if phase == "chunk-verifier" && written.Load() {
+ return Principal{}, Fail("unauthenticated", "Revoked.")
+ }
+ if phase == "unrelated" {
+ fresh.Scopes = fresh.Scopes[:1]
+ fresh.Teams = fresh.Teams[:1]
+ }
+ switch phase {
+ case "identity":
+ fresh.Subject = "other"
+ case "client":
+ fresh.Client = "other"
+ case "grant":
+ fresh.Grant = "other"
+ case "scope":
+ fresh.Scopes = nil
+ case "team":
+ fresh.Teams = nil
+ }
+ return fresh, nil
+ })
+ guard := func(ctx context.Context, original Principal, name string, raw json.RawMessage, result any) error {
+ if strings.Join(original.Teams, ",") != strings.Join(p.Teams, ",") || strings.Join(original.Scopes, ",") != strings.Join(p.Scopes, ",") || original.Subject != p.Subject || original.Client != p.Client || original.Grant != p.Grant || string(raw) != `{"team":"acme"}` {
+ t.Error("lost original coordinates")
+ }
+ value, ok := result.(map[string]any)
+ if !ok || value["body"] != strings.Repeat("private", 24000) {
+ t.Error("lost result")
+ }
+ guards.Add(1)
+ if name != "notes_read" {
+ t.Error("lost operation")
+ }
+ if phase == "preheader" || phase == "chunk" && written.Load() {
+ return Fail("forbidden", "Access changed.")
+ }
+ if phase == "expired" {
+ <-ctx.Done()
+ return nil
+ }
+ return nil
+ }
+ h := r.HTTPGuarded(initial, recheck, guard)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if phase == "expired" {
+ ctx, cancel := context.WithTimeout(req.Context(), 20*time.Millisecond)
+ defer cancel()
+ req = req.WithContext(ctx)
+ }
+ // Ignore the elapsed network deadline only in the expiry test, so the safe
+ // failure can be inspected even though the callback consumed its budget.
+ var deadline func(time.Time) error
+ if phase == "expired" {
+ deadline = func(time.Time) error { return nil }
+ }
+ h.ServeHTTP(guardedWriter{w, func() { written.Store(true) }, deadline}, req)
+ }))
+ defer server.Close()
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/notes_read", strings.NewReader(`{"team":"acme"}`))
+ req.Header.Set("Authorization", "Bearer original")
+ req.Header.Set("Content-Type", "application/json")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ body, e := io.ReadAll(resp.Body)
+ if invokes.Load() != 1 || initialCalls.Load() != 1 {
+ t.Fatalf("invokes=%d initial=%d", invokes.Load(), initialCalls.Load())
+ }
+ switch phase {
+ case "success", "unrelated":
+ if checks.Load() != 4 || guards.Load() != 4 {
+ t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load())
+ }
+ if e != nil || resp.StatusCode != 200 || len(body) < 130000 {
+ t.Fatalf("%d %d %v", resp.StatusCode, len(body), e)
+ }
+ case "chunk", "chunk-verifier":
+ wantGuards := int32(3)
+ if phase == "chunk-verifier" {
+ wantGuards = 2
+ }
+ if checks.Load() != 3 || guards.Load() != wantGuards {
+ t.Fatalf("checks=%d guards=%d", checks.Load(), guards.Load())
+ }
+ if resp.StatusCode != 200 || e == nil || len(body) != 64<<10 {
+ t.Fatalf("chunk %d %d %v", resp.StatusCode, len(body), e)
+ }
+ default:
+ if resp.StatusCode == 200 || strings.Contains(string(body), "private") {
+ t.Fatalf("leaked %d %d %v", resp.StatusCode, len(body), e)
+ }
+ }
+ })
+ }
+}
+func TestGuardedDiscoveryRetainsDisclosedAuthority(t *testing.T) {
+ for _, path := range []string{"connection", "operations"} {
+ for _, lost := range []string{"scope", "team"} {
+ t.Run(path+lost, func(t *testing.T) {
+ var count atomic.Int32
+ r := testRegistry(t, &count)
+ p := principal()
+ p.Scopes = append(p.Scopes, "unrelated:read")
+ p.Teams = append(p.Teams, "other")
+ initial := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil })
+ fresh := p
+ if lost == "scope" {
+ fresh.Scopes = fresh.Scopes[:1]
+ } else {
+ fresh.Teams = fresh.Teams[:1]
+ }
+ recheck := VerifyFunc(func(context.Context, string) (Principal, error) { return fresh, nil })
+ server := httptest.NewServer(r.HTTPGuarded(initial, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { return nil }))
+ defer server.Close()
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil)
+ req.Header.Set("Authorization", "Bearer token")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 403 || strings.Contains(string(b), "unrelated") || count.Load() != 0 {
+ t.Fatalf("%d %s invokes %d", resp.StatusCode, b, count.Load())
+ }
+ })
+ }
+ }
+}
+func TestGuardedTransportAndCallbacksRequired(t *testing.T) {
+ var calls atomic.Int32
+ r := testRegistry(t, &calls)
+ v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil })
+ guard := func(context.Context, Principal, string, json.RawMessage, any) error { return nil }
+ for _, f := range []func(){func() { r.HTTPGuarded(nil, v, guard) }, func() { r.HTTPGuarded(v, nil, guard) }, func() { r.HTTPGuarded(v, v, nil) }} {
+ func() {
+ defer func() {
+ if recover() == nil {
+ t.Error("missing callback accepted")
+ }
+ }()
+ f()
+ }()
+ }
+ req := httptest.NewRequest("GET", "/api/v1/connection", nil)
+ req.Header.Set("Authorization", "Bearer t")
+ w := httptest.NewRecorder()
+ r.HTTPGuarded(v, v, guard).ServeHTTP(w, req)
+ if w.Code != 503 || strings.Contains(w.Body.String(), "acme") {
+ t.Fatalf("unsupported writer: %d %s", w.Code, w.Body.String())
+ }
+}
+
+func TestGuardedAvailableUsesCapturedDiscovery(t *testing.T) {
+ for _, path := range []string{"operations", "operations/notes_create"} {
+ t.Run(path, func(t *testing.T) {
+ var count atomic.Int32
+ r := testRegistry(t, &count)
+ entry := r.operations["notes_create"]
+ var available atomic.Int32
+ // The first evaluation selects the operation; all later checks revoke it.
+ entry.op.Available = func(Principal) bool { return available.Add(1) == 1 }
+ r.operations["notes_create"] = entry
+ v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil })
+ server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil }))
+ defer server.Close()
+ method := "GET"
+ var body io.Reader
+ if strings.Contains(path, "/") {
+ method = "POST"
+ body = strings.NewReader(`{"team":"acme","title":"x"}`)
+ }
+ req, _ := http.NewRequest(method, server.URL+"/api/v1/"+path, body)
+ req.Header.Set("Authorization", "Bearer t")
+ req.Header.Set("Content-Type", "application/json")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ data, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 403 || strings.Contains(string(data), "notes_create") {
+ t.Fatalf("stale operation: %d %s", resp.StatusCode, data)
+ }
+ })
+ }
+}
+func TestGuardedDiscoveryCallsAppGuard(t *testing.T) {
+ var count, guards atomic.Int32
+ r := testRegistry(t, &count)
+ v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil })
+ h := r.HTTPGuarded(v, v, func(_ context.Context, p Principal, name string, raw json.RawMessage, result any) error {
+ guards.Add(1)
+ if p.Subject != principal().Subject || name != "" || raw != nil || result == nil {
+ t.Error("discovery coordinates")
+ }
+ return Fail("forbidden", "Local identity revoked.")
+ })
+ server := httptest.NewServer(h)
+ defer server.Close()
+ for _, path := range []string{"connection", "operations"} {
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil)
+ req.Header.Set("Authorization", "Bearer t")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != 403 {
+ t.Fatal(resp.StatusCode)
+ }
+ }
+ if guards.Load() != 2 || count.Load() != 0 {
+ t.Fatal(guards.Load(), count.Load())
+ }
+}
+func TestGuardedExpiredVerifierCannotReachAppGuard(t *testing.T) {
+ var count, guards atomic.Int32
+ r := testRegistry(t, &count)
+ v := VerifyFunc(func(context.Context, string) (Principal, error) { return principal(), nil })
+ recheck := VerifyFunc(func(ctx context.Context, _ string) (Principal, error) { <-ctx.Done(); return principal(), nil })
+ h := r.HTTPGuarded(v, recheck, func(context.Context, Principal, string, json.RawMessage, any) error { guards.Add(1); return nil })
+ req := httptest.NewRequest("GET", "/api/v1/connection", nil)
+ req.Header.Set("Authorization", "Bearer t")
+ ctx, cancel := context.WithTimeout(req.Context(), 10*time.Millisecond)
+ defer cancel()
+ w := httptest.NewRecorder()
+ h.ServeHTTP(guardedWriter{w, nil, func(time.Time) error { return nil }}, req.WithContext(ctx))
+ if w.Code == 200 || guards.Load() != 0 {
+ t.Fatalf("%d guards=%d", w.Code, guards.Load())
+ }
+}
+
+func TestGuardedDiscoveryPayloadBound(t *testing.T) {
+ var count atomic.Int32
+ r := testRegistry(t, &count)
+ p := principal()
+ p.Teams = []string{strings.Repeat("private-canary", MaxPayload/10)}
+ v := VerifyFunc(func(context.Context, string) (Principal, error) { return p, nil })
+ server := httptest.NewServer(r.HTTPGuarded(v, v, func(context.Context, Principal, string, json.RawMessage, any) error { return nil }))
+ defer server.Close()
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/connection", nil)
+ req.Header.Set("Authorization", "Bearer t")
+ resp, e := server.Client().Do(req)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer resp.Body.Close()
+ b, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 413 || strings.Contains(string(b), "private-canary") {
+ t.Fatalf("%d %d", resp.StatusCode, len(b))
+ }
+}