| 1 | // Package agentaccess defines Oficina operations independently of any transport. |
| 2 | package agentaccess |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "regexp" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | |
| 13 | "github.com/santhosh-tekuri/jsonschema/v6" |
| 14 | ) |
| 15 | |
| 16 | const MaxPayload = 2 << 20 |
| 17 | |
| 18 | // Principal is supplied by a verifier, never decoded from operation arguments. |
| 19 | type Principal struct { |
| 20 | Subject string `json:"subject"` |
| 21 | Client string `json:"client"` |
| 22 | Grant string `json:"grant"` |
| 23 | Teams []string `json:"teams"` |
| 24 | Scopes []string `json:"scopes"` |
| 25 | } |
| 26 | |
| 27 | func (p Principal) Allows(team, scope string) bool { |
| 28 | return p.Subject != "" && contains(p.Teams, team) && contains(p.Scopes, scope) |
| 29 | } |
| 30 | func contains(xs []string, x string) bool { |
| 31 | for _, s := range xs { |
| 32 | if s == x { |
| 33 | return true |
| 34 | } |
| 35 | } |
| 36 | return false |
| 37 | } |
| 38 | |
| 39 | type Operation struct { |
| 40 | Name string `json:"name"` |
| 41 | Description string `json:"description"` |
| 42 | Scope string `json:"scope"` |
| 43 | ReadOnly bool `json:"read_only"` |
| 44 | Destructive bool `json:"destructive"` |
| 45 | Idempotent bool `json:"idempotent"` |
| 46 | Input json.RawMessage `json:"input_schema"` |
| 47 | Output json.RawMessage `json:"output_schema"` |
| 48 | Invoke func(context.Context, Principal, json.RawMessage) (any, error) `json:"-"` |
| 49 | Available func(Principal) bool `json:"-"` |
| 50 | } |
| 51 | |
| 52 | type Failure struct { |
| 53 | Code string `json:"code"` |
| 54 | Message string `json:"message"` |
| 55 | } |
| 56 | |
| 57 | func (f Failure) Error() string { return f.Code + ": " + f.Message } |
| 58 | func Fail(code, message string) error { return Failure{code, message} } |
| 59 | func SafeFailure(err error) Failure { |
| 60 | var f Failure |
| 61 | if errors.As(err, &f) { |
| 62 | return f |
| 63 | } |
| 64 | return Failure{"internal", "The operation could not be completed."} |
| 65 | } |
| 66 | |
| 67 | type compiled struct { |
| 68 | op Operation |
| 69 | input, output *jsonschema.Schema |
| 70 | } |
| 71 | type Registry struct { |
| 72 | operations map[string]compiled |
| 73 | schedule *scheduler |
| 74 | } |
| 75 | |
| 76 | var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`) |
| 77 | |
| 78 | func NewRegistry(operations ...Operation) (*Registry, error) { |
| 79 | r := &Registry{operations: map[string]compiled{}} |
| 80 | for _, op := range operations { |
| 81 | if op.Name == "oficina_connection" || !namePattern.MatchString(op.Name) || op.Scope == "" || op.Description == "" || op.Invoke == nil { |
| 82 | return nil, fmt.Errorf("invalid operation registration: %s", op.Name) |
| 83 | } |
| 84 | if _, ok := r.operations[op.Name]; ok { |
| 85 | return nil, fmt.Errorf("duplicate operation: %s", op.Name) |
| 86 | } |
| 87 | parse := func(raw json.RawMessage) (*jsonschema.Schema, error) { |
| 88 | var schema map[string]any |
| 89 | if err := DecodeJSON(raw, &schema); err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | if schema["type"] != "object" { |
| 93 | return nil, errors.New("operation schema must describe an object") |
| 94 | } |
| 95 | compiler := jsonschema.NewCompiler() |
| 96 | compiler.UseLoader(localSchemas{}) |
| 97 | const location = "https://schema.oficina.invalid/operation" |
| 98 | if err := compiler.AddResource(location, schema); err != nil { |
| 99 | return nil, err |
| 100 | } |
| 101 | return compiler.Compile(location) |
| 102 | } |
| 103 | in, err := parse(op.Input) |
| 104 | if err != nil { |
| 105 | return nil, fmt.Errorf("%s input: %w", op.Name, err) |
| 106 | } |
| 107 | out, err := parse(op.Output) |
| 108 | if err != nil { |
| 109 | return nil, fmt.Errorf("%s output: %w", op.Name, err) |
| 110 | } |
| 111 | op.Input = append(json.RawMessage(nil), op.Input...) |
| 112 | op.Output = append(json.RawMessage(nil), op.Output...) |
| 113 | r.operations[op.Name] = compiled{op, in, out} |
| 114 | } |
| 115 | return r, nil |
| 116 | } |
| 117 | func (r *Registry) List(p Principal) []Operation { |
| 118 | out := []Operation{} |
| 119 | if p.Subject == "" || len(p.Teams) == 0 { |
| 120 | return out |
| 121 | } |
| 122 | for _, entry := range r.operations { |
| 123 | if contains(p.Scopes, entry.op.Scope) && (entry.op.Available == nil || entry.op.Available(p)) { |
| 124 | o := entry.op |
| 125 | o.Invoke = nil |
| 126 | o.Available = nil |
| 127 | o.Input = append(json.RawMessage(nil), o.Input...) |
| 128 | o.Output = append(json.RawMessage(nil), o.Output...) |
| 129 | out = append(out, o) |
| 130 | } |
| 131 | } |
| 132 | sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) |
| 133 | return out |
| 134 | } |
| 135 | func (r *Registry) Call(ctx context.Context, p Principal, name string, raw json.RawMessage) (any, error) { |
| 136 | if p.Subject == "" { |
| 137 | return nil, Fail("unauthenticated", "Connect to Oficina first.") |
| 138 | } |
| 139 | entry, ok := r.operations[name] |
| 140 | if !ok || entry.op.Available != nil && !entry.op.Available(p) { |
| 141 | return nil, Fail("not_found", "This operation is unavailable.") |
| 142 | } |
| 143 | if len(raw) > MaxPayload { |
| 144 | return nil, Fail("too_large", "The operation input is too large.") |
| 145 | } |
| 146 | if err := UniqueJSON(raw); err != nil { |
| 147 | return nil, Fail("invalid", "Send one JSON object with unique field names.") |
| 148 | } |
| 149 | var input map[string]any |
| 150 | if DecodeJSON(raw, &input) != nil || input == nil { |
| 151 | return nil, Fail("invalid", "Send a JSON object.") |
| 152 | } |
| 153 | team, err := teamOf(input) |
| 154 | if err != nil { |
| 155 | return nil, Fail("invalid", "Send one JSON object with unique field names.") |
| 156 | } |
| 157 | if !p.Allows(team, entry.op.Scope) { |
| 158 | return nil, Fail("forbidden", "This connection does not allow that team and operation.") |
| 159 | } |
| 160 | if entry.input.Validate(input) != nil { |
| 161 | return nil, Fail("invalid", "The input does not match the operation schema.") |
| 162 | } |
| 163 | result, err := entry.op.Invoke(ctx, p, raw) |
| 164 | if err != nil { |
| 165 | return nil, SafeFailure(err) |
| 166 | } |
| 167 | encoded, err := json.Marshal(result) |
| 168 | if err != nil || len(encoded) > MaxPayload { |
| 169 | return nil, Fail("internal", "The operation returned an invalid or oversized result.") |
| 170 | } |
| 171 | var value any |
| 172 | if DecodeJSON(encoded, &value) != nil { |
| 173 | return nil, Fail("internal", "The operation result does not match its schema.") |
| 174 | } |
| 175 | if entry.output.Validate(value) != nil { |
| 176 | return nil, Fail("internal", "The operation result does not match its schema.") |
| 177 | } |
| 178 | return value, nil |
| 179 | } |
| 180 | |
| 181 | var errAmbiguousTeam = errors.New("ambiguous operation team") |
| 182 | |
| 183 | // operationTeam is the one reader of an operation's team. Authorization, |
| 184 | // routing and the checks before a response is sent all use it, so they cannot |
| 185 | // settle on different teams for the same input. |
| 186 | func operationTeam(raw json.RawMessage) (string, error) { |
| 187 | var input map[string]any // DecodeJSON refuses duplicate keys. |
| 188 | if DecodeJSON(raw, &input) != nil || input == nil { |
| 189 | return "", errAmbiguousTeam |
| 190 | } |
| 191 | return teamOf(input) |
| 192 | } |
| 193 | |
| 194 | // teamOf reads the exact key "team". encoding/json matches keys without regard |
| 195 | // to case, and duplicate detection does not, so any other spelling is refused |
| 196 | // rather than left for a later decoder to prefer. |
| 197 | func teamOf(input map[string]any) (string, error) { |
| 198 | for key := range input { |
| 199 | if key != "team" && strings.EqualFold(key, "team") { |
| 200 | return "", errAmbiguousTeam |
| 201 | } |
| 202 | } |
| 203 | team, _ := input["team"].(string) |
| 204 | return team, nil |
| 205 | } |
| 206 | |
| 207 | // Contracts are self-contained. Schema compilation must never fetch URLs or |
| 208 | // read local files supplied through a reference in a deployment contract. |
| 209 | type localSchemas struct{} |
| 210 | |
| 211 | func (localSchemas) Load(string) (any, error) { |
| 212 | return nil, errors.New("external schema references are disabled") |
| 213 | } |
| 214 | |