| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "mime" |
| 8 | "net/http" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // ResponseGuard revalidates local identity and every resource selected by the |
| 15 | // operation. It must never replay the operation or mutate application state. |
| 16 | // Discovery uses an empty name/input. Captured provenance belongs to the request. |
| 17 | type ResponseGuard func(context.Context, Principal, string, json.RawMessage, any) error |
| 18 | |
| 19 | // HTTPGuarded retains HTTP's contracts while authorizing bounded response |
| 20 | // emission. initial may charge a quota; recheck must be a pure credential check. |
| 21 | func (registry *Registry) HTTPGuarded(initial, recheck Verifier, guard ResponseGuard) http.Handler { |
| 22 | if initial == nil || recheck == nil || guard == nil { |
| 23 | panic("agentaccess: guarded HTTP requires both verifiers and an app guard") |
| 24 | } |
| 25 | mux := http.NewServeMux() |
| 26 | emit := func(w http.ResponseWriter, r *http.Request, name string, raw json.RawMessage, result any) { |
| 27 | p := principalFrom(r.Context()) |
| 28 | token := strings.Fields(r.Header.Get("Authorization"))[1] // Authenticate validated the header. |
| 29 | var disclosed []Operation |
| 30 | if metadata, ok := result.(map[string]any); ok && name == "" { |
| 31 | disclosed, _ = metadata["operations"].([]Operation) |
| 32 | } |
| 33 | var team string |
| 34 | if name != "" { |
| 35 | // An unreadable team stays empty, which no connection allows. |
| 36 | team, _ = operationTeam(raw) |
| 37 | } |
| 38 | check := func(ctx context.Context) error { |
| 39 | fresh, err := recheck.Verify(ctx, token) |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | if err = ctx.Err(); err != nil { |
| 44 | return err |
| 45 | } |
| 46 | if fresh.Subject != p.Subject || fresh.Client != p.Client || fresh.Grant != p.Grant { |
| 47 | return Fail("unauthenticated", "Reconnect to Oficina.") |
| 48 | } |
| 49 | if name == "" { |
| 50 | for _, t := range p.Teams { |
| 51 | if !contains(fresh.Teams, t) { |
| 52 | return Fail("forbidden", "Connection access changed.") |
| 53 | } |
| 54 | } |
| 55 | for _, s := range p.Scopes { |
| 56 | if !contains(fresh.Scopes, s) { |
| 57 | return Fail("forbidden", "Connection access changed.") |
| 58 | } |
| 59 | } |
| 60 | for _, op := range disclosed { |
| 61 | entry := registry.operations[op.Name] |
| 62 | if entry.op.Available != nil && !entry.op.Available(fresh) { |
| 63 | return Fail("forbidden", "Connection access changed.") |
| 64 | } |
| 65 | } |
| 66 | } else { |
| 67 | entry := registry.operations[name] |
| 68 | if !fresh.Allows(team, entry.op.Scope) || entry.op.Available != nil && !entry.op.Available(fresh) { |
| 69 | return Fail("forbidden", "Connection access changed.") |
| 70 | } |
| 71 | } |
| 72 | if err = guard(ctx, p, name, raw, result); err != nil { |
| 73 | return err |
| 74 | } |
| 75 | return ctx.Err() |
| 76 | } |
| 77 | guardedJSON(w, r, result, check) |
| 78 | } |
| 79 | mux.HandleFunc("GET /api/v1/connection", func(w http.ResponseWriter, r *http.Request) { |
| 80 | emit(w, r, "", nil, ConnectionFrom(principalFrom(r.Context()))) |
| 81 | }) |
| 82 | mux.HandleFunc("GET /api/v1/operations", func(w http.ResponseWriter, r *http.Request) { |
| 83 | emit(w, r, "", nil, map[string]any{"operations": registry.List(principalFrom(r.Context()))}) |
| 84 | }) |
| 85 | mux.HandleFunc("POST /api/v1/operations/{name}", func(w http.ResponseWriter, r *http.Request) { |
| 86 | media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 87 | if err != nil || media != "application/json" { |
| 88 | writeFailure(w, Fail("unsupported_media_type", "Send application/json.")) |
| 89 | return |
| 90 | } |
| 91 | raw, err := io.ReadAll(io.LimitReader(r.Body, MaxPayload+1)) |
| 92 | if err != nil { |
| 93 | writeFailure(w, Fail("invalid", "Could not read the request.")) |
| 94 | return |
| 95 | } |
| 96 | result, err := registry.Call(r.Context(), principalFrom(r.Context()), r.PathValue("name"), raw) |
| 97 | if err != nil { |
| 98 | writeFailure(w, err) |
| 99 | return |
| 100 | } |
| 101 | emit(w, r, r.PathValue("name"), raw, result) |
| 102 | }) |
| 103 | return Authenticate(initial, mux) |
| 104 | } |
| 105 | |
| 106 | func guardedJSON(w http.ResponseWriter, r *http.Request, result any, check func(context.Context) error) { |
| 107 | body, err := json.Marshal(result) |
| 108 | if err != nil || len(body) > MaxPayload { |
| 109 | writeFailure(w, Fail("too_large", "The response is too large.")) |
| 110 | return |
| 111 | } |
| 112 | body = append(body, '\n') |
| 113 | controller := http.NewResponseController(w) |
| 114 | // Refuse unsupported transports before emitting any application data. |
| 115 | deadline := time.Now().Add(5 * time.Second) |
| 116 | if d, ok := r.Context().Deadline(); ok && d.Before(deadline) { |
| 117 | deadline = d |
| 118 | } |
| 119 | if err = controller.SetWriteDeadline(deadline); err != nil { |
| 120 | writeFailure(w, Fail("unavailable", "This transport cannot safely send the response.")) |
| 121 | return |
| 122 | } |
| 123 | defer func() { _ = controller.SetWriteDeadline(time.Time{}) }() |
| 124 | verify := func() error { |
| 125 | ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) |
| 126 | defer cancel() |
| 127 | if err := check(ctx); err != nil { |
| 128 | return err |
| 129 | } |
| 130 | if err := ctx.Err(); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | d, _ := ctx.Deadline() |
| 134 | return controller.SetWriteDeadline(d) |
| 135 | } |
| 136 | if err = verify(); err != nil { |
| 137 | writeFailure(w, err) |
| 138 | return |
| 139 | } |
| 140 | w.Header().Set("Content-Type", "application/json") |
| 141 | w.Header().Set("Content-Length", strconv.Itoa(len(body))) |
| 142 | // Do not commit headers until the first chunk check has also passed. |
| 143 | for offset := 0; offset < len(body); { |
| 144 | if err = verify(); err != nil { |
| 145 | if offset == 0 { |
| 146 | w.Header().Del("Content-Length") |
| 147 | writeFailure(w, err) |
| 148 | return |
| 149 | } |
| 150 | panic(http.ErrAbortHandler) |
| 151 | } |
| 152 | end := min(offset+(64<<10), len(body)) |
| 153 | n, err := w.Write(body[offset:end]) |
| 154 | if err != nil || n != end-offset { |
| 155 | panic(http.ErrAbortHandler) |
| 156 | } |
| 157 | if err = controller.Flush(); err != nil { |
| 158 | panic(http.ErrAbortHandler) |
| 159 | } |
| 160 | offset = end |
| 161 | } |
| 162 | } |
| 163 | |