| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "mime" |
| 9 | "net/http" |
| 10 | "strings" |
| 11 | |
| 12 | access "amadan.net/oficina/agent-access.git" |
| 13 | strictjson "github.com/go-json-experiment/json" |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | var errAgentConfig = errors.New("docs: invalid agent access configuration") |
| 18 | |
| 19 | func validatedAgentConfig(cfg Config, home *homeSettings, team *teamSettings) (*access.RemoteVerifier, error) { |
| 20 | if cfg.AgentIssuer == "" && cfg.AgentTeam == "" { |
| 21 | return nil, nil |
| 22 | } |
| 23 | if home == nil || cfg.AgentIssuer == "" || cfg.AgentTeam == "" || len(cfg.AgentTeam) > 128 || strings.TrimSpace(cfg.AgentTeam) != cfg.AgentTeam { |
| 24 | return nil, errAgentConfig |
| 25 | } |
| 26 | if team != nil && cfg.AgentTeam != team.Settings.Bindings().Team { |
| 27 | return nil, errAgentConfig |
| 28 | } |
| 29 | verifier, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", home.issuer) |
| 30 | if err != nil { |
| 31 | return nil, errAgentConfig |
| 32 | } |
| 33 | return verifier, nil |
| 34 | } |
| 35 | |
| 36 | const agentSummaryProperties = `"id":{"type":"string"},"title":{"type":"string"},"url":{"type":"string"},"updated_at":{"type":"string"}` |
| 37 | const agentCreatedSchema = `{"type":"object","required":["id","title","url","updated_at","body_revision"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"}}}` |
| 38 | const agentBodySchema = `{"type":"object","required":["id","title","url","updated_at","body_revision","text","content"],"additionalProperties":false,"properties":{` + agentSummaryProperties + `,"body_revision":{"type":"string","pattern":"^[0-9]+$"},"text":{"type":"string"},"content":{"type":"object"}}}` |
| 39 | |
| 40 | func (a *documentAgent) registry() (*access.Registry, error) { |
| 41 | input := func(properties, required string) json.RawMessage { |
| 42 | return json.RawMessage(`{"type":"object","additionalProperties":false,"required":["team"` + required + `],"properties":{"team":{"type":"string","minLength":1,"maxLength":128}` + properties + `}}`) |
| 43 | } |
| 44 | ops := []access.Operation{ |
| 45 | {Name: "docs_list", Description: "List documents currently readable in this team.", Scope: "docs:read", ReadOnly: true, Idempotent: true, |
| 46 | Input: input(`,"limit":{"type":"integer","minimum":1,"maximum":100},"cursor":{"type":"string","maxLength":512}`, ""), |
| 47 | Output: json.RawMessage(`{"type":"object","required":["documents","next_cursor"],"additionalProperties":false,"properties":{"documents":{"type":"array","maxItems":100,"items":{"type":"object","additionalProperties":false,"required":["id","title","url","updated_at"],"properties":{` + agentSummaryProperties + `}}},"next_cursor":{"type":"string"}}}`), |
| 48 | Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 49 | ctx, id, err := a.prepare(ctx, p, false) |
| 50 | if err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | var in struct { |
| 54 | Limit int `json:"limit"` |
| 55 | Cursor string `json:"cursor"` |
| 56 | } |
| 57 | if err = json.Unmarshal(raw, &in); err != nil { |
| 58 | return nil, access.Fail("invalid", "Invalid operation arguments.") |
| 59 | } |
| 60 | return a.documents(ctx, id.Actor, in.Limit, in.Cursor) |
| 61 | }}, |
| 62 | {Name: "docs_get", Description: "Read a document as plain text and structured content at one body revision.", Scope: "docs:read", ReadOnly: true, Idempotent: true, |
| 63 | Input: input(`,"id":{"type":"string","pattern":"^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"}`, `,"id"`), Output: json.RawMessage(agentBodySchema), |
| 64 | Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 65 | ctx, id, err := a.prepare(ctx, p, false) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | var in struct { |
| 70 | ID string `json:"id"` |
| 71 | } |
| 72 | if err = json.Unmarshal(raw, &in); err != nil { |
| 73 | return nil, access.Fail("invalid", "Invalid operation arguments.") |
| 74 | } |
| 75 | return a.body(ctx, id.Actor, in.ID) |
| 76 | }}, |
| 77 | {Name: "docs_create", Description: "Create a document with literal paragraph and heading text; reuse the same client UUID only for retries.", Scope: "docs:write", Idempotent: true, |
| 78 | Input: input(`,"client_id":{"type":"string","maxLength":36},"title":{"type":"string","minLength":1,"maxLength":512},"blocks":{"type":"array","maxItems":200,"items":{"type":"object","required":["type","text"],"additionalProperties":false,"properties":{"type":{"enum":["paragraph","heading"]},"text":{"type":"string","maxLength":131072},"level":{"type":"integer","minimum":0,"maximum":6}}}}`, `,"client_id","title","blocks"`), Output: json.RawMessage(agentCreatedSchema), |
| 79 | Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 80 | ctx, id, err := a.prepare(ctx, p, true) |
| 81 | if err != nil { |
| 82 | return nil, err |
| 83 | } |
| 84 | var in agentCreateInput |
| 85 | if err = json.Unmarshal(raw, &in); err != nil { |
| 86 | return nil, access.Fail("invalid", "Invalid operation arguments.") |
| 87 | } |
| 88 | return a.create(ctx, p, id, in) |
| 89 | }}, |
| 90 | } |
| 91 | ops = append(ops, access.Operation{ |
| 92 | Name: "docs_update", Description: "Edit top-level paragraph/heading blocks at expected_revision from docs_get.body_revision. Retry with the same UUID and exact arguments; revision acknowledges the original applied edit.", Scope: "docs:write", Idempotent: true, |
| 93 | Input: input(`,"id":{"type":"string","pattern":"^[23456789abcdefghjkmnpqrstuvwxyz]{10}$"},"client_id":{"type":"string","maxLength":36},"expected_revision":{"type":"string","pattern":"^(0|[1-9][0-9]*)$","maxLength":19},"edits":{"type":"array","minItems":1,"maxItems":32,"items":{"type":"object","additionalProperties":false,"required":["index","delete_count","blocks"],"properties":{"index":{"type":"integer","minimum":0,"maximum":4294967295},"delete_count":{"type":"integer","minimum":0,"maximum":200},"blocks":{"type":"array","maxItems":200,"items":{"type":"object","required":["type","text"],"additionalProperties":false,"properties":{"type":{"enum":["paragraph","heading"]},"text":{"type":"string","maxLength":131072},"level":{"type":"integer","minimum":0,"maximum":6}}}}}}}`, `,"id","client_id","expected_revision","edits"`), |
| 94 | Output: json.RawMessage(`{"type":"object","additionalProperties":false,"required":["id","url","revision"],"properties":{"id":{"type":"string"},"url":{"type":"string"},"revision":{"type":"string","pattern":"^[1-9][0-9]*$"}}}`), |
| 95 | Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 96 | ctx, id, err := a.prepareMode(ctx, p, true, false) |
| 97 | if err != nil { |
| 98 | return nil, err |
| 99 | } |
| 100 | var in agentUpdateInput |
| 101 | if json.Unmarshal(raw, &in) != nil { |
| 102 | return nil, access.Fail("invalid", "Invalid document edits.") |
| 103 | } |
| 104 | return a.update(ctx, p, id, in) |
| 105 | }, |
| 106 | }) |
| 107 | |
| 108 | for i := range ops { |
| 109 | invoke := ops[i].Invoke |
| 110 | ops[i].Invoke = func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) { |
| 111 | var parsed struct { |
| 112 | Team string `json:"team"` |
| 113 | } |
| 114 | if strictjson.Unmarshal(raw, &parsed) != nil { |
| 115 | return nil, access.Fail("invalid", "Send valid Unicode JSON.") |
| 116 | } |
| 117 | if parsed.Team != a.team { |
| 118 | return nil, access.Fail("forbidden", "This instance does not serve that team.") |
| 119 | } |
| 120 | return invoke(ctx, p, raw) |
| 121 | } |
| 122 | scope := ops[i].Scope |
| 123 | ops[i].Available = func(p access.Principal) bool { return p.Allows(a.team, scope) } |
| 124 | } |
| 125 | return access.NewRegistry(ops...) |
| 126 | } |
| 127 | |
| 128 | func agentWriteFailure(w http.ResponseWriter, err error) { |
| 129 | f := access.SafeFailure(err) |
| 130 | status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "conflict": 409, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503}[f.Code] |
| 131 | if status == 0 { |
| 132 | status = 500 |
| 133 | } |
| 134 | if status == 401 { |
| 135 | w.Header().Set("WWW-Authenticate", "Bearer") |
| 136 | } |
| 137 | w.Header().Set("Content-Type", "application/json") |
| 138 | w.WriteHeader(status) |
| 139 | _ = json.NewEncoder(w).Encode(map[string]any{"error": f}) |
| 140 | } |
| 141 | |
| 142 | // httpHandler keeps final Docs permission/epoch checks on the real writer. |
| 143 | func (a *documentAgent) httpHandler(verifier access.Verifier) (http.Handler, error) { |
| 144 | registry, err := a.registry() |
| 145 | if err != nil { |
| 146 | return nil, err |
| 147 | } |
| 148 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 149 | w.Header().Set("Cache-Control", "no-store") |
| 150 | parts := strings.Fields(r.Header.Get("Authorization")) |
| 151 | if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { |
| 152 | agentWriteFailure(w, access.Fail("unauthenticated", "Connect to Oficina first.")) |
| 153 | return |
| 154 | } |
| 155 | p, err := verifier.Verify(r.Context(), parts[1]) |
| 156 | if err != nil { |
| 157 | agentWriteFailure(w, err) |
| 158 | return |
| 159 | } |
| 160 | name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/") |
| 161 | write := name == "docs_create" || name == "docs_update" |
| 162 | // Discovery can describe a write-only connection without granting reads. |
| 163 | discovery := r.Method == "GET" && r.URL.Path == "/api/v1/operations" |
| 164 | if discovery && !p.Allows(a.team, "docs:read") { |
| 165 | write = true |
| 166 | } |
| 167 | ctx, id, err := a.prepareMode(r.Context(), p, write, write && name != "docs_update") |
| 168 | if err != nil { |
| 169 | agentWriteFailure(w, err) |
| 170 | return |
| 171 | } |
| 172 | guard := ctx.Value(accessContextKey{}).(*requestAccess) |
| 173 | guard.delegationCheck = func(ctx context.Context) error { |
| 174 | current, e := verifier.Verify(ctx, parts[1]) |
| 175 | if e != nil { |
| 176 | return e |
| 177 | } |
| 178 | scope := "docs:read" |
| 179 | if write { |
| 180 | scope = "docs:write" |
| 181 | } |
| 182 | if current.Subject != p.Subject || current.Client != p.Client || current.Grant != p.Grant || !current.Allows(a.team, scope) { |
| 183 | return errIdentityRefused |
| 184 | } |
| 185 | return nil |
| 186 | } |
| 187 | guard.extraCheck = func(ctx context.Context) error { |
| 188 | if err := guard.delegationCheck(ctx); err != nil { |
| 189 | return err |
| 190 | } |
| 191 | fresh, e := a.resolver.resolveHome(ctx, p.Subject) |
| 192 | if e != nil { |
| 193 | return e |
| 194 | } |
| 195 | if !sameActor(fresh.Actor, id.Actor) { |
| 196 | return errIdentityRefused |
| 197 | } |
| 198 | if a.store.team == nil { |
| 199 | allowed, e := a.list.allows(actorAddress(id.Actor)) |
| 200 | if e != nil { |
| 201 | return e |
| 202 | } |
| 203 | if !allowed { |
| 204 | return errIdentityRefused |
| 205 | } |
| 206 | } |
| 207 | return nil |
| 208 | } |
| 209 | var result any |
| 210 | if discovery { |
| 211 | result = map[string]any{"operations": registry.List(p)} |
| 212 | } else { |
| 213 | if r.Method != "POST" || !strings.HasPrefix(r.URL.Path, "/api/v1/operations/") || strings.Contains(name, "/") { |
| 214 | agentWriteFailure(w, access.Fail("not_found", "This operation is unavailable.")) |
| 215 | return |
| 216 | } |
| 217 | media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 218 | if e != nil || media != "application/json" { |
| 219 | agentWriteFailure(w, access.Fail("unsupported_media_type", "Send application/json.")) |
| 220 | return |
| 221 | } |
| 222 | raw, e := io.ReadAll(io.LimitReader(r.Body, access.MaxPayload+1)) |
| 223 | if e != nil { |
| 224 | agentWriteFailure(w, access.Fail("invalid", "Could not read the request.")) |
| 225 | return |
| 226 | } |
| 227 | result, err = registry.Call(ctx, p, name, raw) |
| 228 | if err != nil { |
| 229 | agentWriteFailure(w, err) |
| 230 | return |
| 231 | } |
| 232 | } |
| 233 | body, err := json.Marshal(result) |
| 234 | if err != nil { |
| 235 | agentWriteFailure(w, agentFailure(err)) |
| 236 | return |
| 237 | } |
| 238 | if len(body) > agentResultLimit { |
| 239 | agentWriteFailure(w, access.Fail("too_large", "The document result exceeds 1 MiB.")) |
| 240 | return |
| 241 | } |
| 242 | w.Header().Set("Content-Type", "application/json") |
| 243 | if err = writeGuardedBody(w, r.WithContext(ctx), http.StatusOK, body); err != nil { |
| 244 | panic(http.ErrAbortHandler) |
| 245 | } |
| 246 | }), nil |
| 247 | } |
| 248 | |
| 249 | func newDocumentAgent(cfg Config, settings *homeSettings, home *homeRoutes, store *Store, list allowlist, verifier access.Verifier, notify func(int64, int64)) (http.Handler, error) { |
| 250 | a := &documentAgent{notify: notify, store: store, resolver: home.resolver, list: list, origin: cfg.Origin, issuer: cfg.AgentIssuer, identityIssuer: settings.issuer, team: cfg.AgentTeam, key: append([]byte(nil), settings.dek...)} |
| 251 | if err := store.db.Transaction(func(tx *gorm.DB) error { return a.bind(tx) }); err != nil { |
| 252 | return nil, err |
| 253 | } |
| 254 | return a.httpHandler(verifier) |
| 255 | } |
| 256 | |
| 257 | // AgentContracts exports identical operation contracts for every Docs team. |
| 258 | func AgentContracts() ([]access.Operation, error) { |
| 259 | a := &documentAgent{team: "contract"} |
| 260 | registry, err := a.registry() |
| 261 | if err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | return registry.List(access.Principal{Subject: "contract", Teams: []string{"contract"}, Scopes: []string{"docs:read", "docs:write"}}), nil |
| 265 | } |
| 266 | |