| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | |
| 11 | access "amadan.net/oficina/agent-access.git" |
| 12 | "amadan.net/oficina/home/connect/linkstore" |
| 13 | "amadan.net/oficina/home/roster" |
| 14 | "amadan.net/oficina/home/teammode" |
| 15 | "amadan.net/oficina/suite" |
| 16 | "amadan.net/rastrillo/rastrillo/migrate" |
| 17 | strictjson "github.com/go-json-experiment/json" |
| 18 | "gorm.io/gorm" |
| 19 | ) |
| 20 | |
| 21 | // WireAgentAccess mounts a bearer-only API outside browser sessions and CSRF. |
| 22 | // Home linking and the instance's admission policy remain mandatory. |
| 23 | func (a *app) WireAgentAccess(mux *http.ServeMux, cfg Config) error { |
| 24 | if cfg.AgentIssuer == "" && cfg.AgentTeam == "" { |
| 25 | return nil |
| 26 | } |
| 27 | if a.home == nil || cfg.Home == nil || cfg.AgentTeam == "" || mux == nil { |
| 28 | return errors.New("memoria: agent access requires Home and a team") |
| 29 | } |
| 30 | v, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", cfg.Home.Issuer) |
| 31 | if err != nil { |
| 32 | return errors.New("memoria: invalid agent access configuration") |
| 33 | } |
| 34 | return a.mountAgentAccess(mux, cfg.AgentIssuer, cfg.AgentTeam, v) |
| 35 | } |
| 36 | |
| 37 | func (a *app) mountAgentAccess(mux *http.ServeMux, issuer, team string, verifier access.Verifier) error { |
| 38 | if a.teamMode() && (a.team == nil || a.team.Bindings().Team != team) { |
| 39 | return errors.New("memoria: agent team must match provisioned roster authority") |
| 40 | } |
| 41 | if _, err := migrate.Apply(context.Background(), a.db, agentSchema); err != nil { |
| 42 | return err |
| 43 | } |
| 44 | a.agentIssuer, a.agentTeam = issuer, team |
| 45 | if a.home == nil || issuer == "" { |
| 46 | return errors.New("memoria: agent authority unavailable") |
| 47 | } |
| 48 | if err := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindAgent(tx) }); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | registry, err := access.NewRegistry(a.agentOperations(team)...) |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | checked := access.VerifyFunc(func(ctx context.Context, token string) (access.Principal, error) { |
| 56 | p, err := verifier.Verify(ctx, token) |
| 57 | if err != nil { |
| 58 | return access.Principal{}, err |
| 59 | } |
| 60 | if _, err = a.agentAddress(ctx, p, team); err != nil { |
| 61 | return access.Principal{}, err |
| 62 | } |
| 63 | return p, nil |
| 64 | }) |
| 65 | h := a.agentBoundary(verifier, registry.HTTPGuarded(checked, verifier, a.agentResponse)) |
| 66 | mux.Handle("/api/v1/operations", h) |
| 67 | mux.Handle("/api/v1/operations/", h) |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | func (a *app) agentAddress(ctx context.Context, p access.Principal, team string) (string, error) { |
| 72 | allowed := false |
| 73 | for _, t := range p.Teams { |
| 74 | allowed = allowed || t == team |
| 75 | } |
| 76 | if !allowed || p.Client == "" || p.Grant == "" || p.Subject == "" || a.home == nil { |
| 77 | return "", access.Fail("forbidden", "This connection cannot access this app.") |
| 78 | } |
| 79 | person, err := a.home.bridge.ResolveOn(ctx, a.db.G.Statement.ConnPool, p.Subject) |
| 80 | if errors.Is(err, linkstore.ErrStorage) { |
| 81 | return "", access.Fail("unavailable", "Account verification is temporarily unavailable.") |
| 82 | } |
| 83 | if err != nil || person.ID <= 0 || person.Label == "" || !a.teamMode() && !a.Admit(person.Label) { |
| 84 | return "", access.Fail("forbidden", "Link an admitted Memoria account to Home first.") |
| 85 | } |
| 86 | if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| 87 | if state.personID != 0 && (state.personID != person.ID || state.address != person.Label) { |
| 88 | return "", access.Fail("forbidden", "The linked identity changed.") |
| 89 | } |
| 90 | state.personID = person.ID |
| 91 | state.address = person.Label |
| 92 | } |
| 93 | if a.teamMode() { |
| 94 | state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| 95 | if !ok || state == nil || a.team == nil || a.team.Bindings().Team != team { |
| 96 | return "", access.Fail("unavailable", "Team authority is unavailable.") |
| 97 | } |
| 98 | if state.standing == nil { |
| 99 | state.standing = a.team.Access(ctx, p.Subject) |
| 100 | } |
| 101 | if err := a.agentStanding(ctx, p.Subject); err != nil { |
| 102 | return "", err |
| 103 | } |
| 104 | } |
| 105 | return person.Label, nil |
| 106 | } |
| 107 | |
| 108 | // agentStanding reads only the request's original leased decision. In particular |
| 109 | // the SQLite writer never refreshes membership or opens another connection. |
| 110 | func (a *app) agentStanding(ctx context.Context, subject string) error { |
| 111 | if !a.teamMode() { |
| 112 | return nil |
| 113 | } |
| 114 | state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| 115 | if !ok || state == nil || state.standing == nil || state.standing.Subject() != subject { |
| 116 | return access.Fail("unavailable", "Team authority is unavailable.") |
| 117 | } |
| 118 | switch state.standing.State() { |
| 119 | case roster.Member: |
| 120 | return nil |
| 121 | case roster.NotMember: |
| 122 | return access.Fail("forbidden", "This account is not a team member.") |
| 123 | default: |
| 124 | return access.Fail("unavailable", "Team membership cannot be verified now.") |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func (a *app) agentOperations(team string) []access.Operation { |
| 129 | guard := func(scope string, fn func(context.Context, access.Principal, json.RawMessage, string) (any, error)) func(context.Context, access.Principal, json.RawMessage) (any, error) { |
| 130 | return func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 131 | var in struct { |
| 132 | Team string `json:"team"` |
| 133 | } |
| 134 | if strictjson.Unmarshal(raw, &in) != nil { |
| 135 | return nil, access.Fail("invalid", "Send valid Unicode JSON.") |
| 136 | } |
| 137 | if in.Team != team || !p.Allows(team, scope) { |
| 138 | return nil, access.Fail("forbidden", "This connection cannot access this team.") |
| 139 | } |
| 140 | address, err := a.agentAddress(ctx, p, team) |
| 141 | if err != nil { |
| 142 | return nil, err |
| 143 | } |
| 144 | if a.teamMode() { |
| 145 | state := ctx.Value(agentBoundaryKey{}).(*agentRequest) |
| 146 | ctx = teammode.WithAccess(ctx, state.standing) |
| 147 | } |
| 148 | out, err := fn(ctx, p, raw, address) |
| 149 | if err != nil { |
| 150 | var failure access.Failure |
| 151 | if errors.As(err, &failure) { |
| 152 | return nil, failure |
| 153 | } |
| 154 | return nil, access.Fail("unavailable", "Note storage or authority is unavailable.") |
| 155 | } |
| 156 | if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| 157 | state.selected = true |
| 158 | } |
| 159 | return out, nil |
| 160 | } |
| 161 | } |
| 162 | ops := []access.Operation{ |
| 163 | {Name: "notes_search", Description: "Search currently visible Memoria passages for a team. Sibling apps check access on every query.", Scope: "notes:read", ReadOnly: true, Idempotent: true, |
| 164 | Input: json.RawMessage(`{"type":"object","required":["team","query"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"query":{"type":"string","minLength":1,"maxLength":2048}}}`), |
| 165 | Output: json.RawMessage(`{"type":"object","required":["results","notices"],"additionalProperties":false,"properties":{"results":{"type":"array","items":{"type":"object","required":["id","document_id","title","text","source"],"properties":{"id":{"type":"integer"},"document_id":{"type":"integer"},"title":{"type":"string"},"text":{"type":"string"},"source":{"type":"string"}}}},"notices":{"type":"array","items":{"type":"string"}}}}`), |
| 166 | Invoke: guard("notes:read", a.agentSearch)}, |
| 167 | {Name: "notes_create", Description: "Create a team-shared note. Reuse client_id only to retry the same title and body.", Scope: "notes:write", Idempotent: true, |
| 168 | Input: json.RawMessage(`{"type":"object","required":["team","title","body","client_id"],"additionalProperties":false,"properties":{"team":{"type":"string","minLength":1},"title":{"type":"string","minLength":1,"maxLength":512},"body":{"type":"string","minLength":1,"maxLength":1048576},"client_id":{"type":"string","minLength":36,"maxLength":36}}}`), |
| 169 | Output: json.RawMessage(`{"type":"object","required":["id","indexed"],"additionalProperties":false,"properties":{"id":{"type":"integer","minimum":1},"indexed":{"type":"boolean"}}}`), |
| 170 | Invoke: guard("notes:write", a.agentCreate)}, |
| 171 | } |
| 172 | edits := noteEditContracts() |
| 173 | edits[0].Invoke = guard("notes:read", a.agentGetNote) |
| 174 | edits[1].Invoke = guard("notes:write", a.agentUpdateNote) |
| 175 | return append(ops, edits...) |
| 176 | } |
| 177 | |
| 178 | func (a *app) agentSearch(ctx context.Context, p access.Principal, raw json.RawMessage, address string) (any, error) { |
| 179 | var in struct { |
| 180 | Query string `json:"query"` |
| 181 | } |
| 182 | if json.Unmarshal(raw, &in) != nil || strings.TrimSpace(in.Query) == "" || len(in.Query) > 2048 { |
| 183 | return nil, access.Fail("invalid", "Enter a query of at most 2048 bytes.") |
| 184 | } |
| 185 | found, err := a.store.SearchWithoutFacts(ctx, a.agentSubject(p, address), strings.TrimSpace(in.Query), 25) |
| 186 | if err != nil { |
| 187 | return nil, access.Fail("unavailable", "Search is unavailable. Try again.") |
| 188 | } |
| 189 | if state, ok := ctx.Value(agentBoundaryKey{}).(*agentRequest); ok { |
| 190 | state.passages = append([]Result{}, found.Results...) |
| 191 | } |
| 192 | type result struct { |
| 193 | ID int64 `json:"id"` |
| 194 | DocumentID int64 `json:"document_id"` |
| 195 | Title string `json:"title"` |
| 196 | Text string `json:"text"` |
| 197 | Source string `json:"source"` |
| 198 | } |
| 199 | out := make([]result, 0, len(found.Results)) |
| 200 | for _, v := range found.Results { |
| 201 | out = append(out, result{v.ChunkID, v.DocumentID, v.Title, strings.NewReplacer("<mark>", "", "</mark>", "").Replace(v.Snippet), v.Source}) |
| 202 | } |
| 203 | notices := found.Notices |
| 204 | if notices == nil { |
| 205 | notices = []string{} |
| 206 | } |
| 207 | return map[string]any{"results": out, "notices": notices}, nil |
| 208 | } |
| 209 | |
| 210 | type agentNoteResult struct { |
| 211 | ID int64 `json:"id"` |
| 212 | Indexed bool `json:"indexed"` |
| 213 | } |
| 214 | |
| 215 | // AgentContracts exports the same descriptors used by the live app, without |
| 216 | // opening a database or reading deployment credentials. The connection service |
| 217 | // consumes these descriptors as operator-reviewed routing configuration. |
| 218 | func AgentContracts() ([]access.Operation, error) { |
| 219 | a := &app{} |
| 220 | operations := a.agentOperations("contract") |
| 221 | scopes := make([]string, 0, len(operations)) |
| 222 | for _, op := range operations { |
| 223 | scopes = append(scopes, op.Scope) |
| 224 | } |
| 225 | registry, err := access.NewRegistry(operations...) |
| 226 | if err != nil { |
| 227 | return nil, err |
| 228 | } |
| 229 | return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: scopes}), nil |
| 230 | } |
| 231 | |
| 232 | func (a *app) agentSubject(p access.Principal, address string) suite.Subject { |
| 233 | if a.teamMode() { |
| 234 | return suite.Subject{Kind: suite.SubjectPersonRef, Value: p.Subject} |
| 235 | } |
| 236 | return suite.Subject{Kind: suite.SubjectAddress, Value: address} |
| 237 | } |
| 238 | |