oficina / calendar Public

Recheck Calendar identity and selected resources during response emission

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 61c4ded64f87455fd4e1a3b72094f831417e6b29 parent 1d3b999
14 files changed, +379 −13
  • docs/superpowers/specs/2026-10-25-agent-response-authorization.md +13 −0
  • go.mod +1 −1
  • go.sum +2 −0
  • internal/calendar/agent_access.go +13 −2
  • internal/calendar/agent_access_test.go +2 −2
  • internal/calendar/agent_authority.go +2 −1
  • internal/calendar/agent_authority_test.go +1 −1
  • internal/calendar/agent_boundaries_test.go +1 −1
  • internal/calendar/agent_create.go +1 −0
  • internal/calendar/agent_read.go +6 −1
  • internal/calendar/agent_recorder_test.go +12 −0
  • internal/calendar/agent_response.go +89 −0
  • internal/calendar/agent_response_test.go +224 −0
  • internal/calendar/store_slots.go +12 −4

CI passed — run details

diff --git a/docs/superpowers/specs/2026-10-25-agent-response-authorization.md b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
new file mode 100644
index 0000000..2b0364f
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-25-agent-response-authorization.md
@@ -0,0 +1,13 @@
+# 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.
+
+Consumer pins shared module 4b94ff9. Design approval: GPT-6 Astra. App implementation/evidence review is recorded in the existing agent-access branch discussion. Source and tests are additive to the already reviewed create/retry authority boundary; direct completed-retry tests prevent later HTTP checks masking missing transaction checks.
diff --git a/go.mod b/go.mod
index 73a1de6..f5f194c 100644
--- a/go.mod
+++ b/go.mod
@@ -43,7 +43,7 @@ require (
)
require (
- amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000
+ amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3
)
diff --git a/go.sum b/go.sum
index 1c7e30c..992ae10 100644
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,7 @@
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw=
amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d h1:bSsf1NXVhXTfLLB9J7a5v9CqzdKj8CALHZ6W3H7A/4M=
+amadan.net/oficina/agent-access.git v0.0.0-20261025011012-4b94ff9e8a8d/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA=
amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768 h1:bVscoa9fH5LdLDjlyecZhrX7JzWPT0blb57MH0FIm2U=
amadan.net/oficina/estilo.git v0.0.0-20261001093750-530cb932e768/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/connect v0.0.0-20261001093757-2bec942ddd0c h1:3yxO2D8BxDLMGfFV2o6Sp9Z91yLnjDCIuRKHVWORa8A=
diff --git a/internal/calendar/agent_access.go b/internal/calendar/agent_access.go
index 5d92e82..1aa95b8 100644
--- a/internal/calendar/agent_access.go
+++ b/internal/calendar/agent_access.go
@@ -61,7 +61,7 @@ func (a *App) mountAgent(verifier access.Verifier, issuer, team string) error {
if err != nil {
return err
}
- a.agent = a.agentBoundary(verifier, registry.HTTP(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
+ a.agent = a.agentBoundary(verifier, registry.HTTPGuarded(access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) {
p, err := verifier.Verify(ctx, token)
if err != nil {
return access.Principal{}, err
@@ -70,7 +70,7 @@ func (a *App) mountAgent(verifier access.Verifier, issuer, team string) error {
return access.Principal{}, err
}
return p, nil
- })))
+ }), verifier, a.agentResponse))
return nil
}
func (a *App) agentPerson(ctx context.Context, p access.Principal, team string) (Person, error) {
@@ -95,6 +95,12 @@ func (a *App) agentPerson(ctx context.Context, p access.Principal, team string)
if person.ID != linked.ID || person.Address != linked.Label || !a.home.admitted.allows(person.Address) {
return Person{}, access.Fail("forbidden", "This account cannot access Calendar.")
}
+ if state, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if state.person.ID != 0 && (state.person.ID != person.ID || state.person.Address != person.Address) {
+ return Person{}, access.Fail("forbidden", "The linked identity changed.")
+ }
+ state.person = person
+ }
return person, nil
}
func agentFailure(err error) error {
@@ -132,6 +138,11 @@ func (a *App) agentGuard(team, scope string, fn func(context.Context, access.Pri
return nil, err
}
out, err := fn(ctx, p, person, raw)
+ if err == nil {
+ if state, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ state.selected = true
+ }
+ }
return out, agentFailure(err)
}
}
diff --git a/internal/calendar/agent_access_test.go b/internal/calendar/agent_access_test.go
index 09ef887..01b1812 100644
--- a/internal/calendar/agent_access_test.go
+++ b/internal/calendar/agent_access_test.go
@@ -51,7 +51,7 @@ func calendarAgentCall(a *App, name string, input any) *httptest.ResponseRecorde
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Authorization", "Bearer fixture")
w := httptest.NewRecorder()
- a.agent.ServeHTTP(w, r)
+ a.agent.ServeHTTP(responseRecorder{w}, r)
return w
}
func eventAgentInput(cal int64) map[string]any {
@@ -234,7 +234,7 @@ func TestAgentIdentityScopeAndCalendarIsolation(t *testing.T) {
r.AddCookie(c)
}
w := httptest.NewRecorder()
- f.app.agent.ServeHTTP(w, r)
+ f.app.agent.ServeHTTP(responseRecorder{w}, r)
if w.Code != 401 {
t.Fatal("cookie authorized API", w.Code)
}
diff --git a/internal/calendar/agent_authority.go b/internal/calendar/agent_authority.go
index 95b66bc..c324034 100644
--- a/internal/calendar/agent_authority.go
+++ b/internal/calendar/agent_authority.go
@@ -33,7 +33,8 @@ func (a *App) agentBoundary(verifier access.Verifier, next http.Handler) http.Ha
}
return nil
})
- next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), agentBoundaryKey{}, check)))
+ ctx := context.WithValue(r.Context(), agentResponseKey{}, &agentResponseState{})
+ next.ServeHTTP(w, r.WithContext(context.WithValue(ctx, agentBoundaryKey{}, check)))
})
}
func (a *App) bindAgent(tx *gorm.DB) error {
diff --git a/internal/calendar/agent_authority_test.go b/internal/calendar/agent_authority_test.go
index efa29fb..a619591 100644
--- a/internal/calendar/agent_authority_test.go
+++ b/internal/calendar/agent_authority_test.go
@@ -136,6 +136,6 @@ func calendarRawAgentCall(a *App, raw string) *httptest.ResponseRecorder {
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Authorization", "Bearer fixture")
w := httptest.NewRecorder()
- a.agent.ServeHTTP(w, r)
+ a.agent.ServeHTTP(responseRecorder{w}, r)
return w
}
diff --git a/internal/calendar/agent_boundaries_test.go b/internal/calendar/agent_boundaries_test.go
index 6db78ba..155caa4 100644
--- a/internal/calendar/agent_boundaries_test.go
+++ b/internal/calendar/agent_boundaries_test.go
@@ -76,7 +76,7 @@ func TestAgentMountedRouteUsesBearerAndRearms(t *testing.T) {
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Authorization", "Bearer fixture")
w := httptest.NewRecorder()
- f.app.mux.ServeHTTP(w, r)
+ f.app.mux.ServeHTTP(responseRecorder{w}, r)
if w.Code != 200 {
t.Fatal("mounted bearer operation", w.Code, w.Body.String())
}
diff --git a/internal/calendar/agent_create.go b/internal/calendar/agent_create.go
index a4f7548..1106fab 100644
--- a/internal/calendar/agent_create.go
+++ b/internal/calendar/agent_create.go
@@ -120,6 +120,7 @@ func (a *App) agentCreateEvent(ctx context.Context, principal access.Principal,
if err != nil {
return nil, err
}
+ captureAgentEvent(ctx, eventID, in.CalendarID)
return map[string]any{"id": eventID, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(eventID, 10), "invitations_sent": false}, nil
}
diff --git a/internal/calendar/agent_read.go b/internal/calendar/agent_read.go
index 2031ba4..46c9103 100644
--- a/internal/calendar/agent_read.go
+++ b/internal/calendar/agent_read.go
@@ -16,6 +16,7 @@ func (a *App) agentCalendars(ctx context.Context, _ access.Principal, p Person,
}
out := []map[string]any{}
for _, c := range cals {
+ captureAgentCalendar(ctx, c.ID)
out = append(out, map[string]any{"id": c.ID, "name": c.Name, "kind": c.Kind, "role": c.Role})
}
return map[string]any{"calendars": out}, nil
@@ -38,6 +39,7 @@ func (a *App) agentGetEvent(ctx context.Context, _ access.Principal, p Person, r
if c.ArchivedAt != nil {
return nil, ErrNotFound
}
+ captureAgentEvent(ctx, e.ID, e.CalendarID)
return map[string]any{"id": e.ID, "calendar_id": e.CalendarID, "title": e.Title, "location": e.Location, "notes": e.Notes, "all_day": e.AllDay, "start_local": e.StartLocal, "end_local": e.EndLocal, "tz": e.TZ, "start_utc": e.StartUTC, "end_utc": e.EndUTC, "sequence": e.Sequence, "kind": e.Kind, "status": e.Status, "url": a.cfg.Origin + "/events/" + strconv.FormatInt(e.ID, 10)}, nil
}
func (a *App) agentBusy(ctx context.Context, _ access.Principal, p Person, raw json.RawMessage) (any, error) {
@@ -50,10 +52,13 @@ func (a *App) agentBusy(ctx context.Context, _ access.Principal, p Person, raw j
if e1 != nil || e2 != nil || !start.Before(end) || end.Sub(start) > 31*24*time.Hour {
return nil, access.Fail("invalid", "Supply a positive RFC3339 time range of at most 31 days, with explicit offsets.")
}
- spans, err := a.store.BusyFor(ctx, p, start.Unix(), end.Unix(), nil)
+ spans, calendars, err := a.store.busyWithProvenance(a.store.g.WithContext(ctx), p, start.Unix(), end.Unix(), nil)
if err != nil {
return nil, err
}
+ for _, id := range calendars {
+ captureAgentCalendar(ctx, id)
+ }
if len(spans) > 10000 {
return nil, access.Fail("too_large", "Use a smaller time range.")
}
diff --git a/internal/calendar/agent_recorder_test.go b/internal/calendar/agent_recorder_test.go
new file mode 100644
index 0000000..c3ed2fe
--- /dev/null
+++ b/internal/calendar/agent_recorder_test.go
@@ -0,0 +1,12 @@
+package calendar
+
+import (
+ "net/http/httptest"
+ "time"
+)
+
+// Unit request fixtures use an in-memory transport. Real HTTP deadline and
+// truncation behavior is exercised separately.
+type responseRecorder struct{ *httptest.ResponseRecorder }
+
+func (responseRecorder) SetWriteDeadline(time.Time) error { return nil }
diff --git a/internal/calendar/agent_response.go b/internal/calendar/agent_response.go
new file mode 100644
index 0000000..9ad0c83
--- /dev/null
+++ b/internal/calendar/agent_response.go
@@ -0,0 +1,89 @@
+package calendar
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "context"
+ "encoding/json"
+)
+
+type agentResponseKey struct{}
+type agentResponseState struct {
+ person Person
+ selected bool
+ calendars []int64
+ calendarSet map[int64]bool
+ events map[int64]int64
+}
+
+func captureAgentCalendar(ctx context.Context, id int64) {
+ if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if s.calendarSet == nil {
+ s.calendarSet = map[int64]bool{}
+ }
+ if !s.calendarSet[id] {
+ s.calendarSet[id] = true
+ s.calendars = append(s.calendars, id)
+ }
+ }
+}
+func captureAgentEvent(ctx context.Context, id, calendarID int64) {
+ if s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState); ok {
+ if s.events == nil {
+ s.events = map[int64]int64{}
+ }
+ s.events[id] = calendarID
+ captureAgentCalendar(ctx, calendarID)
+ }
+}
+func (a *App) agentResponse(ctx context.Context, p access.Principal, name string, _ json.RawMessage, result any) error {
+ s, ok := ctx.Value(agentResponseKey{}).(*agentResponseState)
+ if !ok || s.person.ID == 0 || name != "" && !s.selected {
+ return access.Fail("forbidden", "Response authority is unavailable.")
+ }
+ if name != "" {
+ value, ok := result.(map[string]any)
+ if !ok {
+ return access.Fail("forbidden", "Response provenance is unavailable.")
+ }
+ switch name {
+ case "calendar_list":
+ rows, ok := value["calendars"].([]any)
+ if !ok || len(rows) != len(s.calendars) {
+ return access.Fail("forbidden", "Calendar provenance is unavailable.")
+ }
+ case "calendar_get_event", "calendar_create_event":
+ if len(s.events) != 1 || len(s.calendars) != 1 {
+ return access.Fail("forbidden", "Event provenance is unavailable.")
+ }
+ case "calendar_free_busy":
+ rows, ok := value["busy"].([]any)
+ if !ok || len(rows) > 0 && len(s.calendars) == 0 {
+ return access.Fail("forbidden", "Calendar provenance is unavailable.")
+ }
+ default:
+ return access.Fail("forbidden", "Response provenance is unavailable.")
+ }
+ }
+ if _, err := a.agentPerson(ctx, p, a.agentTeam); err != nil {
+ return err
+ }
+ for id, calendarID := range s.events {
+ e, err := a.store.Event(ctx, s.person.ID, id)
+ if err != nil {
+ return agentFailure(err)
+ }
+ if e.CalendarID != calendarID {
+ return access.Fail("forbidden", "Event access changed.")
+ }
+ }
+ for _, id := range s.calendars {
+ c, err := a.store.Calendar(ctx, s.person.ID, id)
+ if err != nil {
+ return agentFailure(err)
+ }
+ if c.ArchivedAt != nil {
+ return access.Fail("not_found", "This calendar is unavailable.")
+ }
+ }
+ return nil
+}
diff --git a/internal/calendar/agent_response_test.go b/internal/calendar/agent_response_test.go
new file mode 100644
index 0000000..2177916
--- /dev/null
+++ b/internal/calendar/agent_response_test.go
@@ -0,0 +1,224 @@
+package calendar
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/calendar/internal/calendar/seal"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type agentStreamWriter struct {
+ http.ResponseWriter
+ after func()
+}
+
+func (w agentStreamWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+func (w agentStreamWriter) Write(b []byte) (int, error) {
+ n, e := w.ResponseWriter.Write(b)
+ w.after()
+ return n, e
+}
+func calendarLiveCall(t *testing.T, h http.Handler, name string, input any) (int, []byte, error) {
+ t.Helper()
+ server := httptest.NewServer(h)
+ defer server.Close()
+ raw, _ := json.Marshal(input)
+ req, _ := http.NewRequest("POST", server.URL+"/api/v1/operations/"+name, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer fixture")
+ 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)
+ return resp.StatusCode, body, e
+}
+func TestAgentResponseCurrentEventAndIdentity(t *testing.T) {
+ for _, kind := range []string{"unlink", "calendar", "delete", "move", "archive"} {
+ t.Run(kind, func(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ w := calendarAgentCall(f.app, "calendar_create_event", eventAgentInput(cal))
+ if w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var created struct{ ID int64 }
+ json.Unmarshal(w.Body.Bytes(), &created)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ var e error
+ switch kind {
+ case "unlink":
+ e = f.app.db.G.Exec("DELETE FROM home_identity_links").Error
+ case "calendar":
+ e = f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error
+ case "delete":
+ e = f.app.db.G.Exec("UPDATE events SET deleted_at=? WHERE id=?", time.Now(), created.ID).Error
+ case "move":
+ cals, err := f.app.store.Calendars(t.Context(), person.ID)
+ if err != nil {
+ return access.Principal{}, err
+ }
+ for _, c := range cals {
+ if c.ID != cal {
+ e = f.app.db.G.Exec("UPDATE events SET calendar_id=? WHERE id=?", c.ID, created.ID).Error
+ break
+ }
+ }
+ case "archive":
+ e = f.app.db.G.Exec("UPDATE calendars SET archived_at=? WHERE id=?", time.Now(), cal).Error
+ }
+ if e != nil {
+ return access.Principal{}, e
+ }
+ }
+ return *p, nil
+ })
+ if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ status, body, e := calendarLiveCall(t, f.app.agent, "calendar_get_event", map[string]any{"team": "acme", "id": created.ID})
+ if e != nil || status == 200 || strings.Contains(string(body), "agent_title_") {
+ t.Fatalf("%s: %d %s %v", kind, status, body, e)
+ }
+ })
+ }
+}
+func TestAgentBusyKeepsEveryContributingCalendar(t *testing.T) {
+ f, p, person, _ := linkedCalendarAgent(t)
+ cals, e := f.app.store.Calendars(t.Context(), person.ID)
+ if e != nil || len(cals) < 2 {
+ t.Fatal(len(cals), e)
+ }
+ var input map[string]any
+ for i, c := range cals[:2] {
+ input = eventAgentInput(c.ID)
+ if i == 1 {
+ input["client_id"] = "55fca936-6f81-4132-9184-f22c61b7a478"
+ }
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ }
+ start, _ := time.Parse(LayoutLocal, input["start_local"].(string))
+ busy := map[string]any{"team": "acme", "start": start.Add(-time.Hour).Format(time.RFC3339), "end": start.Add(2 * time.Hour).Format(time.RFC3339)}
+ if w := calendarAgentCall(f.app, "calendar_free_busy", busy); w.Code != 200 || !strings.Contains(w.Body.String(), "start") {
+ t.Fatal(w.Code, w.Body.String())
+ }
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cals[1].ID, person.ID).Error; e != nil {
+ return access.Principal{}, e
+ }
+ }
+ return *p, nil
+ })
+ if e := f.app.mountAgent(v, f.app.agentIssuer, "acme"); e != nil {
+ t.Fatal(e)
+ }
+ status, body, e := calendarLiveCall(t, f.app.agent, "calendar_free_busy", busy)
+ if e != nil || status == 200 || strings.Contains(string(body), "busy") {
+ t.Fatalf("%d %s %v", status, body, e)
+ }
+}
+func TestAgentResponseStreamAbortsOnPermissionLoss(t *testing.T) {
+ f, _, person, cal := linkedCalendarAgent(t)
+ var base Calendar
+ if e := f.app.db.G.First(&base, cal).Error; e != nil {
+ t.Fatal(e)
+ }
+ name, e := f.app.store.seal.SealString(seal.PurposeCalendarName, strings.Repeat("private ", 160))
+ if e != nil {
+ t.Fatal(e)
+ }
+ for i := 0; i < 80; i++ {
+ clone := base
+ clone.ID = 0
+ clone.Kind = "personal"
+ clone.NameSealed = name
+ if e := f.app.db.G.Create(&clone).Error; e != nil {
+ t.Fatal(e)
+ }
+ if e := f.app.db.G.Create(&Grant{CalendarID: clone.ID, PersonID: person.ID, Role: "owner"}).Error; e != nil {
+ t.Fatal(e)
+ }
+ }
+ var writes atomic.Int32
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.app.agent.ServeHTTP(agentStreamWriter{w, func() {
+ if writes.Add(1) == 1 {
+ if e := f.app.db.G.Exec("DELETE FROM grants WHERE calendar_id=? AND person_id=?", cal, person.ID).Error; e != nil {
+ t.Error(e)
+ }
+ }
+ }}, r)
+ })
+ status, body, e := calendarLiveCall(t, h, "calendar_list", map[string]any{"team": "acme"})
+ if status != 200 || e == nil || len(body) != 64<<10 {
+ t.Fatalf("%d %d %v", status, len(body), e)
+ }
+}
+
+func TestAgentRetryFinalGuardWithoutResponseMask(t *testing.T) {
+ f, p, person, cal := linkedCalendarAgent(t)
+ input := eventAgentInput(cal)
+ if w := calendarAgentCall(f.app, "calendar_create_event", input); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ var checks int
+ ctx := context.WithValue(t.Context(), agentBoundaryKey{}, agentRecheck(func(context.Context, access.Principal) error {
+ checks++
+ if checks == 2 {
+ return access.Fail("unauthenticated", "Revoked.")
+ }
+ return nil
+ }))
+ raw, _ := json.Marshal(input)
+ _, err := f.app.agentCreateEvent(ctx, *p, person, raw)
+ if err == nil || access.SafeFailure(err).Code != "unauthenticated" || checks != 2 {
+ t.Fatalf("retry final guard: %v checks=%d", err, checks)
+ }
+}
+
+func TestAgentDiscoveryRechecksLocalIdentity(t *testing.T) {
+ for _, path := range []string{"connection", "operations"} {
+ t.Run(path, func(t *testing.T) {
+ f, p, _, _ := linkedCalendarAgent(t)
+ var checks atomic.Int32
+ v := access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
+ if checks.Add(1) == 2 {
+ if err := f.app.db.G.Exec("DELETE FROM home_identity_links").Error; err != nil {
+ return access.Principal{}, err
+ }
+ }
+ return *p, nil
+ })
+ if err := f.app.mountAgent(v, f.app.agentIssuer, "acme"); err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(f.app.agent)
+ defer server.Close()
+ req, _ := http.NewRequest("GET", server.URL+"/api/v1/"+path, nil)
+ req.Header.Set("Authorization", "Bearer fixture")
+ resp, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != 403 || strings.Contains(string(body), "acme") || strings.Contains(string(body), "operations") {
+ t.Fatalf("%d %s", resp.StatusCode, body)
+ }
+ })
+ }
+}
diff --git a/internal/calendar/store_slots.go b/internal/calendar/store_slots.go
index 03d8d59..890eecc 100644
--- a/internal/calendar/store_slots.go
+++ b/internal/calendar/store_slots.go
@@ -28,30 +28,38 @@ func (s *Store) BusyFor(ctx context.Context, host Person, from, to int64, skip m
// STRICT range reader: a busy series that could not be fully expanded
// is an error here, never a free afternoon (booking spec B23).
func (s *Store) busyOn(tx *gorm.DB, host Person, from, to int64, skip map[int64]bool) ([]Busy, error) {
+ spans, _, err := s.busyWithProvenance(tx, host, from, to, skip)
+ return spans, err
+}
+
+// busyWithProvenance keeps contributing calendars from the exact event expansion.
+func (s *Store) busyWithProvenance(tx *gorm.DB, host Person, from, to int64, skip map[int64]bool) ([]Busy, []int64, error) {
hostLoc, err := Zone(host.Zone)
if err != nil {
- return nil, err
+ return nil, nil, err
}
events, err := s.eventsInRange(tx, host.ID, from-86400, to+86400, true)
if err != nil {
- return nil, err
+ return nil, nil, err
}
var out []Busy
+ var calendars []int64
for _, e := range events {
if !OccupiesTime(e.Kind) || e.Status == StatusCancelled || skip[e.ID] {
continue
}
+ calendars = append(calendars, e.CalendarID)
if !e.AllDay {
out = append(out, Busy{StartUTC: e.OccStartUTC, EndUTC: e.OccEndUTC})
continue
}
spans, err := allDayBusy(e, host.Zone, hostLoc, from-86400, to+86400)
if err != nil {
- return nil, err
+ return nil, nil, err
}
out = append(out, spans...)
}
- return out, nil
+ return out, calendars, nil
}
// allDayBusy turns an all-day occurrence into one whole HOST day per