| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "time" |
| 11 | _ "time/tzdata" // Standalone binaries must validate IANA zones on minimal hosts. |
| 12 | |
| 13 | strictjson "github.com/go-json-experiment/json" |
| 14 | "github.com/google/uuid" |
| 15 | ) |
| 16 | |
| 17 | type scheduler struct { |
| 18 | registry *Registry |
| 19 | credentials CredentialProvider |
| 20 | routes map[string]map[string]string // team, operation -> trusted resource |
| 21 | } |
| 22 | |
| 23 | var scheduleNamespace = uuid.MustParse("8ba3600d-9e03-52df-8c34-9ff05a6e66cb") |
| 24 | |
| 25 | func scheduleID(root, step string) string { |
| 26 | return uuid.NewSHA1(scheduleNamespace, []byte("oficina.schedule.v1/"+root+"/"+step)).String() |
| 27 | } |
| 28 | func (s *scheduler) required(agenda bool) []string { |
| 29 | ops := []string{"calls_reserve_schedule", "calls_create_meeting", "calls_get_meeting", "calendar_create_event", "calendar_get_event"} |
| 30 | if agenda { |
| 31 | ops = append(ops, "docs_create", "docs_get") |
| 32 | } |
| 33 | return ops |
| 34 | } |
| 35 | func (s *scheduler) available(p Principal) bool { |
| 36 | for _, team := range p.Teams { |
| 37 | if s.eligible(p, team, false) == nil { |
| 38 | return true |
| 39 | } |
| 40 | } |
| 41 | return false |
| 42 | } |
| 43 | func (s *scheduler) eligible(p Principal, team string, agenda bool) error { |
| 44 | for _, name := range s.required(agenda) { |
| 45 | op, ok := s.registry.operations[name] |
| 46 | if !ok || s.routes[team][name] == "" { |
| 47 | return Fail("not_found", "Scheduling is unavailable for this team.") |
| 48 | } |
| 49 | if !p.Allows(team, op.op.Scope) { |
| 50 | return Fail("forbidden", "Scheduling requires read and write access to each selected app.") |
| 51 | } |
| 52 | } |
| 53 | return nil |
| 54 | } |
| 55 | |
| 56 | // Revalidate every composite scope before each effect, including scopes whose |
| 57 | // step has already completed. The provider binds the original grant identity. |
| 58 | func (s *scheduler) authorize(ctx context.Context, p Principal, in scheduleInput) error { |
| 59 | if err := s.eligible(p, in.Team, in.Agenda != nil); err != nil { |
| 60 | return err |
| 61 | } |
| 62 | for _, name := range s.required(in.Agenda != nil) { |
| 63 | op := s.registry.operations[name].op |
| 64 | if _, err := s.credentials.Downstream(ctx, p, s.routes[in.Team][name], in.Team, []string{op.Scope}); err != nil { |
| 65 | return err |
| 66 | } |
| 67 | } |
| 68 | return ctx.Err() |
| 69 | } |
| 70 | func (s *scheduler) validate(name string, input any) error { |
| 71 | op, ok := s.registry.operations[name] |
| 72 | if !ok { |
| 73 | return Fail("not_found", "Required app operation is unavailable.") |
| 74 | } |
| 75 | raw, err := json.Marshal(input) |
| 76 | if err != nil || len(raw) > MaxPayload { |
| 77 | return Fail("too_large", "Scheduling input is too large.") |
| 78 | } |
| 79 | var value any |
| 80 | if DecodeJSON(raw, &value) != nil || op.input.Validate(value) != nil { |
| 81 | return Fail("invalid", "Scheduling fields do not match an app contract.") |
| 82 | } |
| 83 | return nil |
| 84 | } |
| 85 | func (s *scheduler) call(ctx context.Context, p Principal, name string, input any) (map[string]any, error) { |
| 86 | if err := s.validate(name, input); err != nil { |
| 87 | return nil, err |
| 88 | } |
| 89 | raw, _ := json.Marshal(input) |
| 90 | out, err := s.registry.Call(ctx, p, name, raw) |
| 91 | if err != nil { |
| 92 | return nil, err |
| 93 | } |
| 94 | value, ok := out.(map[string]any) |
| 95 | if !ok { |
| 96 | return nil, Fail("unavailable", "The app returned an invalid result.") |
| 97 | } |
| 98 | return value, nil |
| 99 | } |
| 100 | |
| 101 | // Reject ambiguous folds as well as gaps. Calendar's canonical validator still |
| 102 | // decides whether this event can be created; schema checks cannot promise that. |
| 103 | func scheduleTimes(in scheduleInput) (string, string, error) { |
| 104 | zone, err := time.LoadLocation(in.TZ) |
| 105 | if err != nil || in.TZ == "" || in.TZ == "Local" { |
| 106 | return "", "", Fail("invalid", "Supply an explicit IANA time zone.") |
| 107 | } |
| 108 | parse := func(raw string) (time.Time, string, error) { |
| 109 | t, err := time.Parse(time.RFC3339, raw) |
| 110 | if err != nil || t.Format(time.RFC3339) != raw || t.Second() != 0 || t.Nanosecond() != 0 { |
| 111 | return t, "", Fail("invalid", "Use canonical RFC3339 times at whole-minute precision.") |
| 112 | } |
| 113 | _, given := t.Zone() |
| 114 | _, actual := t.In(zone).Zone() |
| 115 | local := t.In(zone).Format("2006-01-02T15:04") |
| 116 | if given != actual { |
| 117 | return t, "", Fail("invalid", "The time offset does not match the named zone.") |
| 118 | } |
| 119 | // Offsets spanning nearby transitions cover non-hour and date-line folds. |
| 120 | offsets := map[int]bool{} |
| 121 | for h := -48; h <= 48; h++ { |
| 122 | _, off := t.Add(time.Duration(h) * time.Hour).In(zone).Zone() |
| 123 | offsets[off] = true |
| 124 | } |
| 125 | for off := range offsets { |
| 126 | other := t.Add(time.Duration(actual-off) * time.Second) |
| 127 | if !other.Equal(t) && other.In(zone).Format("2006-01-02T15:04") == local { |
| 128 | return t, "", Fail("invalid", "Ambiguous local times are unsupported.") |
| 129 | } |
| 130 | } |
| 131 | return t, local, nil |
| 132 | } |
| 133 | start, sl, err := parse(in.Start) |
| 134 | if err != nil { |
| 135 | return "", "", err |
| 136 | } |
| 137 | end, el, err := parse(in.End) |
| 138 | if err != nil { |
| 139 | return "", "", err |
| 140 | } |
| 141 | if !end.After(start) { |
| 142 | return "", "", Fail("invalid", "The event must end after it starts.") |
| 143 | } |
| 144 | return sl, el, nil |
| 145 | } |
| 146 | |
| 147 | func (s *scheduler) invoke(ctx context.Context, p Principal, raw json.RawMessage) (any, error) { |
| 148 | var in scheduleInput |
| 149 | if strictjson.Unmarshal(raw, &in) != nil { |
| 150 | return nil, Fail("invalid", "Invalid scheduling request.") |
| 151 | } |
| 152 | uid, err := uuid.Parse(in.ClientID) |
| 153 | if err != nil || uid == uuid.Nil || uid.String() != in.ClientID || strings.TrimSpace(in.Title) == "" { |
| 154 | return nil, Fail("invalid", "Supply a title and canonical nonzero UUID client_id.") |
| 155 | } |
| 156 | start, end, err := scheduleTimes(in) |
| 157 | if err != nil { |
| 158 | return nil, err |
| 159 | } |
| 160 | if err = s.authorize(ctx, p, in); err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | meeting := map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "meeting"), "title": in.Title, "starts_at": in.Start} |
| 164 | event := map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "event"), "calendar_id": in.CalendarID, "title": in.Title, "start_local": start, "end_local": end, "tz": in.TZ, "all_day": false, "kind": "meeting", "status": "confirmed", "location": "", "notes": in.Notes} |
| 165 | var agenda map[string]any |
| 166 | if in.Agenda != nil { |
| 167 | agenda = map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "agenda"), "title": in.Agenda.Title, "blocks": in.Agenda.Blocks} |
| 168 | if err = s.validate("docs_create", agenda); err != nil { |
| 169 | return nil, err |
| 170 | } |
| 171 | } |
| 172 | if err = s.validate("calls_create_meeting", meeting); err != nil { |
| 173 | return nil, err |
| 174 | } |
| 175 | if err = s.validate("calendar_create_event", event); err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | fingerprint, _ := json.Marshal(struct { |
| 179 | Version int `json:"version"` |
| 180 | Input scheduleInput `json:"input"` |
| 181 | }{1, in}) |
| 182 | digest := sha256.Sum256(fingerprint) |
| 183 | if _, err = s.call(ctx, p, "calls_reserve_schedule", map[string]any{"team": in.Team, "client_id": in.ClientID, "fingerprint": hex.EncodeToString(digest[:])}); err != nil { |
| 184 | return nil, err |
| 185 | } |
| 186 | out := scheduleResult{Team: in.Team, ClientID: in.ClientID, Status: "complete", Steps: []scheduleStep{}} |
| 187 | if agenda != nil { |
| 188 | out.Steps = append(out.Steps, scheduleStep{Name: "agenda", State: "pending"}) |
| 189 | } |
| 190 | out.Steps = append(out.Steps, scheduleStep{Name: "meeting", State: "pending"}, scheduleStep{Name: "event", State: "pending"}) |
| 191 | for i := range out.Steps { |
| 192 | step := &out.Steps[i] |
| 193 | if err = s.authorize(ctx, p, in); err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | name, args := "calls_create_meeting", meeting |
| 197 | switch step.Name { |
| 198 | case "agenda": |
| 199 | name, args = "docs_create", agenda |
| 200 | case "event": |
| 201 | name, args = "calendar_create_event", event |
| 202 | } |
| 203 | result, callErr := s.call(ctx, p, name, args) |
| 204 | if callErr == nil { |
| 205 | step.Resource, callErr = s.reference(in.Team, step.Name, result) |
| 206 | } |
| 207 | if callErr != nil { |
| 208 | f := SafeFailure(callErr) |
| 209 | if f.Code == "unauthenticated" || f.Code == "forbidden" { |
| 210 | return nil, f |
| 211 | } |
| 212 | step.State = "unconfirmed" |
| 213 | out.Status = "partial" |
| 214 | out.Failure = &scheduleFailure{step.Name, f.Code} |
| 215 | break |
| 216 | } |
| 217 | step.State = "confirmed" |
| 218 | if step.Name != "event" { |
| 219 | event["notes"] = event["notes"].(string) + "\n\n" + step.Name + ": " + step.Resource.URL |
| 220 | } |
| 221 | } |
| 222 | if err = s.revalidate(ctx, p, in, out); err != nil { |
| 223 | return nil, err |
| 224 | } |
| 225 | encoded, _ := json.Marshal(out) |
| 226 | if len(encoded) > 65535 { |
| 227 | return nil, Fail("too_large", "Scheduling result is too large.") |
| 228 | } |
| 229 | return out, nil |
| 230 | } |
| 231 | |
| 232 | func (s *scheduler) reference(team, step string, value map[string]any) (*ResourceReference, error) { |
| 233 | if step != "agenda" && step != "meeting" && step != "event" { |
| 234 | return nil, Fail("unavailable", "The app returned an invalid resource reference.") |
| 235 | } |
| 236 | app, operation, idField, path := "calls", "calls_create_meeting", "sqid", "/m/" |
| 237 | if step == "agenda" { |
| 238 | app, operation, idField, path = "docs", "docs_create", "id", "/d/" |
| 239 | } |
| 240 | if step == "event" { |
| 241 | app, operation, idField, path = "calendar", "calendar_create_event", "id", "/events/" |
| 242 | } |
| 243 | id, ok := value[idField].(string) |
| 244 | if app == "calendar" { |
| 245 | if n, yes := value[idField].(json.Number); yes { |
| 246 | v, e := strconv.ParseInt(n.String(), 10, 64) |
| 247 | if e == nil && v > 0 { |
| 248 | id, ok = n.String(), true |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | if !ok || id == "" || strings.ContainsAny(id, "/?#%\\") { |
| 253 | return nil, Fail("unavailable", "The app returned an invalid resource reference.") |
| 254 | } |
| 255 | if app != "calendar" && (len(id) != 10 || strings.Trim(id, "23456789abcdefghjkmnpqrstuvwxyz") != "") { |
| 256 | return nil, Fail("unavailable", "The app returned an invalid resource reference.") |
| 257 | } |
| 258 | get := strings.Replace(operation, "create", "get", 1) |
| 259 | if err := s.validate(get, map[string]any{"team": team, idField: value[idField]}); err != nil { |
| 260 | return nil, Fail("unavailable", "The app returned an unreadable resource reference.") |
| 261 | } |
| 262 | want := strings.TrimSuffix(s.routes[team][operation], "/api/v1") + path + id |
| 263 | if value["url"] != want { |
| 264 | return nil, Fail("unavailable", "The app returned a foreign resource reference.") |
| 265 | } |
| 266 | return &ResourceReference{team, app, id, want}, nil |
| 267 | } |
| 268 | |
| 269 | func (s *scheduler) revalidate(ctx context.Context, p Principal, in scheduleInput, out scheduleResult) error { |
| 270 | if err := s.authorize(ctx, p, in); err != nil { |
| 271 | return err |
| 272 | } |
| 273 | for _, step := range out.Steps { |
| 274 | if step.State != "confirmed" { |
| 275 | continue |
| 276 | } |
| 277 | ref := step.Resource |
| 278 | if ref == nil || ref.Team != in.Team { |
| 279 | return Fail("unavailable", "Workflow provenance is unavailable.") |
| 280 | } |
| 281 | name, key := "calls_get_meeting", "sqid" |
| 282 | var id any = ref.ID |
| 283 | switch ref.App { |
| 284 | case "docs": |
| 285 | name, key = "docs_get", "id" |
| 286 | case "calendar": |
| 287 | name, key = "calendar_get_event", "id" |
| 288 | n, e := strconv.ParseInt(ref.ID, 10, 64) |
| 289 | if e != nil { |
| 290 | return Fail("unavailable", "Workflow provenance is unavailable.") |
| 291 | } |
| 292 | id = json.Number(strconv.FormatInt(n, 10)) |
| 293 | case "calls": |
| 294 | default: |
| 295 | return Fail("unavailable", "Workflow provenance is unavailable.") |
| 296 | } |
| 297 | checked, err := s.reference(in.Team, step.Name, map[string]any{key: id, "url": ref.URL}) |
| 298 | if err != nil || *checked != *ref { |
| 299 | return Fail("unavailable", "Workflow provenance changed.") |
| 300 | } |
| 301 | current, err := s.call(ctx, p, name, map[string]any{"team": in.Team, key: id}) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | if ref.App == "calendar" { |
| 306 | if current[key] != json.Number(ref.ID) { |
| 307 | return Fail("unavailable", "Workflow provenance changed.") |
| 308 | } |
| 309 | } else if current[key] != ref.ID { |
| 310 | return Fail("unavailable", "Workflow provenance changed.") |
| 311 | } |
| 312 | } |
| 313 | return s.authorize(ctx, p, in) |
| 314 | } |
| 315 | |