| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/hmac" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | access "amadan.net/oficina/agent-access.git" |
| 13 | "amadan.net/oficina/home/connect/linkstore" |
| 14 | "amadan.net/oficina/home/teammode" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | type agentBoundaryKey struct{} |
| 19 | type agentRequest struct { |
| 20 | standing *teammode.Access |
| 21 | verify func(context.Context, access.Principal, string) error |
| 22 | personID int64 |
| 23 | address string |
| 24 | selected bool |
| 25 | passages []Result |
| 26 | noteID int64 |
| 27 | noteRevision int |
| 28 | noteKey, noteExternal string |
| 29 | } |
| 30 | |
| 31 | func (a *app) agentBoundary(verifier access.Verifier, next http.Handler) http.Handler { |
| 32 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 | parts := strings.Fields(r.Header.Get("Authorization")) |
| 34 | token := "" |
| 35 | if len(parts) == 2 { |
| 36 | token = parts[1] |
| 37 | } |
| 38 | state := &agentRequest{verify: func(ctx context.Context, p access.Principal, scope string) error { |
| 39 | current, e := verifier.Verify(ctx, token) |
| 40 | if e != nil { |
| 41 | return e |
| 42 | } |
| 43 | if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.agentTeam, scope) { |
| 44 | return access.Fail("forbidden", "This connection is no longer authorized.") |
| 45 | } |
| 46 | return nil |
| 47 | }} |
| 48 | next.ServeHTTP(&agentLeaseWriter{ResponseWriter: w, state: state, team: a.teamMode()}, r.WithContext(context.WithValue(r.Context(), agentBoundaryKey{}, state))) |
| 49 | }) |
| 50 | } |
| 51 | func (a *app) bindAgent(tx *gorm.DB) error { |
| 52 | raw, _ := json.Marshal([]string{a.home.issuer, a.agentIssuer, a.agentTeam}) |
| 53 | want, e := a.store.sealer.Fingerprint("agent.authority.v1", raw) |
| 54 | if e != nil { |
| 55 | return e |
| 56 | } |
| 57 | if e = tx.Exec("INSERT INTO memoria_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM memoria_agent_notes) AND NOT EXISTS(SELECT 1 FROM memoria_agent_note_updates) ON CONFLICT(id) DO NOTHING", want).Error; e != nil { |
| 58 | return e |
| 59 | } |
| 60 | var got string |
| 61 | if e = tx.Raw("SELECT keycheck FROM memoria_agent_state WHERE id=1").Scan(&got).Error; e != nil { |
| 62 | return e |
| 63 | } |
| 64 | if !hmac.Equal([]byte(want), []byte(got)) { |
| 65 | return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.") |
| 66 | } |
| 67 | return nil |
| 68 | } |
| 69 | func (a *app) checkAgentWriter(ctx context.Context, tx *gorm.DB, p access.Principal, address string) error { |
| 70 | state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| 71 | if !ok || state == nil || state.verify == nil || state.personID <= 0 { |
| 72 | return access.Fail("forbidden", "Agent authority is unavailable.") |
| 73 | } |
| 74 | if e := state.verify(ctx, p, "notes:write"); e != nil { |
| 75 | return e |
| 76 | } |
| 77 | person, e := a.home.bridge.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) |
| 78 | if errors.Is(e, linkstore.ErrRefused) { |
| 79 | return access.Fail("forbidden", "The linked identity is unavailable.") |
| 80 | } |
| 81 | if e != nil { |
| 82 | return e |
| 83 | } |
| 84 | if person.ID != state.personID || person.Label != address || !a.teamMode() && !a.Admit(person.Label) { |
| 85 | return access.Fail("forbidden", "The linked identity changed.") |
| 86 | } |
| 87 | |
| 88 | return a.agentStanding(ctx, p.Subject) |
| 89 | } |
| 90 | |
| 91 | // Hooks are private: only the agent creation path can bind an effect receipt |
| 92 | // into canonical ingestion. Public ingestion retains its existing upsert rules. |
| 93 | type ingestBoundary struct { |
| 94 | external string |
| 95 | refresh bool |
| 96 | before func(*gormTx, string) (int64, bool, error) |
| 97 | after func(*gormTx, int64) error |
| 98 | } |
| 99 | |
| 100 | func (s *Store) ingestAgent(ctx context.Context, spec IngestSpec, guard *ingestBoundary) (int64, error) { |
| 101 | if guard == nil || guard.before == nil || guard.after == nil { |
| 102 | return 0, errors.New("memoria: missing ingest authority") |
| 103 | } |
| 104 | return s.ingest(ctx, spec, guard) |
| 105 | } |
| 106 | |
| 107 | // The shared transport's five-second I/O budget cannot outlive the roster lease. |
| 108 | // Read only this request's captured decision; never refresh standing here. |
| 109 | type agentLeaseWriter struct { |
| 110 | http.ResponseWriter |
| 111 | state *agentRequest |
| 112 | team bool |
| 113 | } |
| 114 | |
| 115 | func (w *agentLeaseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 116 | func (w *agentLeaseWriter) SetWriteDeadline(deadline time.Time) error { |
| 117 | if w.team && !deadline.IsZero() { |
| 118 | now := time.Now() |
| 119 | if w.state == nil || w.state.standing == nil { |
| 120 | return access.Fail("unavailable", "Team authority is unavailable.") |
| 121 | } |
| 122 | remaining := w.state.standing.Remaining() |
| 123 | if remaining <= 0 { |
| 124 | return access.Fail("unavailable", "Team membership cannot be verified now.") |
| 125 | } |
| 126 | if lease := now.Add(remaining); lease.Before(deadline) { |
| 127 | deadline = lease |
| 128 | } |
| 129 | } |
| 130 | return http.NewResponseController(w.ResponseWriter).SetWriteDeadline(deadline) |
| 131 | } |
| 132 | |