| 1 | package agentaccess |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "reflect" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | // Route is operator-owned configuration, not an operation argument. Contracts |
| 16 | // come from the app's exported operations, pinned with the deployment. |
| 17 | type Route struct { |
| 18 | Team string `json:"team"` |
| 19 | Resource string `json:"resource"` |
| 20 | Operations []Operation `json:"operations"` |
| 21 | } |
| 22 | |
| 23 | type CredentialProvider interface { |
| 24 | Downstream(context.Context, Principal, string, string, []string) (string, error) |
| 25 | } |
| 26 | |
| 27 | // Gateway forwards the selected operation to its configured app with a fresh, |
| 28 | // audience-bound credential. It stores no content and never follows redirects. |
| 29 | func Gateway(routes []Route, credentials CredentialProvider, transport http.RoundTripper) (*Registry, error) { |
| 30 | if credentials == nil || len(routes) == 0 { |
| 31 | return nil, errors.New("gateway needs routes and a credential provider") |
| 32 | } |
| 33 | type coordinate struct{ team, name string } |
| 34 | destinations := map[coordinate]string{} |
| 35 | contracts := map[string]Operation{} |
| 36 | for _, route := range routes { |
| 37 | u, err := url.Parse(route.Resource) |
| 38 | if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.Path != "/api/v1" || u.RawQuery != "" || u.Fragment != "" || route.Team == "" || len(route.Operations) == 0 { |
| 39 | return nil, errors.New("invalid gateway route") |
| 40 | } |
| 41 | for _, op := range route.Operations { |
| 42 | key := coordinate{route.Team, op.Name} |
| 43 | if _, exists := destinations[key]; exists { |
| 44 | return nil, errors.New("duplicate team operation route") |
| 45 | } |
| 46 | op.Invoke = nil |
| 47 | op.Available = nil |
| 48 | if previous, exists := contracts[op.Name]; exists && !reflect.DeepEqual(previous, op) { |
| 49 | return nil, errors.New("operation contracts differ across teams") |
| 50 | } |
| 51 | contracts[op.Name] = op |
| 52 | destinations[key] = route.Resource |
| 53 | } |
| 54 | } |
| 55 | // destination is the one reader of where a team's operation goes. |
| 56 | destination := func(team, name string) (string, bool) { |
| 57 | resource, ok := destinations[coordinate{team, name}] |
| 58 | return resource, ok |
| 59 | } |
| 60 | httpClient := &http.Client{Transport: transport, Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 61 | operations := make([]Operation, 0, len(contracts)) |
| 62 | for _, contract := range contracts { |
| 63 | op := contract |
| 64 | op.Available = func(p Principal) bool { |
| 65 | for _, team := range p.Teams { |
| 66 | if _, ok := destination(team, op.Name); ok { |
| 67 | return true |
| 68 | } |
| 69 | } |
| 70 | return false |
| 71 | } |
| 72 | op.Invoke = func(ctx context.Context, p Principal, input json.RawMessage) (any, error) { |
| 73 | team, err := operationTeam(input) |
| 74 | if err != nil { |
| 75 | return nil, Fail("invalid", "Invalid operation input.") |
| 76 | } |
| 77 | resource, exists := destination(team, op.Name) |
| 78 | if !exists { |
| 79 | return nil, Fail("not_found", "This app operation is unavailable for the selected team.") |
| 80 | } |
| 81 | token, err := credentials.Downstream(ctx, p, resource, team, []string{op.Scope}) |
| 82 | if err != nil { |
| 83 | if f := SafeFailure(err); f.Code == "unavailable" || f.Code == "forbidden" { |
| 84 | return nil, f |
| 85 | } |
| 86 | return nil, Fail("unauthenticated", "The connection is no longer authorized.") |
| 87 | } |
| 88 | req, err := http.NewRequestWithContext(ctx, "POST", resource+"/operations/"+op.Name, bytes.NewReader(input)) |
| 89 | if err != nil { |
| 90 | return nil, Fail("unavailable", "The app is unavailable.") |
| 91 | } |
| 92 | req.Header.Set("Authorization", "Bearer "+token) |
| 93 | req.Header.Set("Content-Type", "application/json") |
| 94 | response, err := httpClient.Do(req) |
| 95 | if err != nil { |
| 96 | return nil, Fail("unavailable", "The app could not confirm the operation. Retry only with the same supported client_id.") |
| 97 | } |
| 98 | defer response.Body.Close() |
| 99 | body, err := io.ReadAll(io.LimitReader(response.Body, MaxPayload+1)) |
| 100 | if err != nil || len(body) > MaxPayload { |
| 101 | return nil, Fail("unavailable", "The app returned an unreadable response.") |
| 102 | } |
| 103 | if response.StatusCode != 200 { |
| 104 | return nil, FailureForStatus(response.StatusCode) |
| 105 | } |
| 106 | var output any |
| 107 | if DecodeJSON(body, &output) != nil { |
| 108 | return nil, Fail("unavailable", "The app returned an invalid result.") |
| 109 | } |
| 110 | return output, nil |
| 111 | } |
| 112 | operations = append(operations, op) |
| 113 | } |
| 114 | base, err := NewRegistry(operations...) |
| 115 | if err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | schedule := &scheduler{registry: base, credentials: credentials, routes: map[string]map[string]string{}} |
| 119 | for key, resource := range destinations { |
| 120 | if schedule.routes[key.team] == nil { |
| 121 | schedule.routes[key.team] = map[string]string{} |
| 122 | } |
| 123 | schedule.routes[key.team][key.name] = resource |
| 124 | } |
| 125 | // A reservation-capable Calls release opts a team into the composite. Old |
| 126 | // deployments retain exactly their existing operation set. |
| 127 | for team := range schedule.routes { |
| 128 | ready := true |
| 129 | for _, name := range schedule.required(false) { |
| 130 | ready = ready && schedule.routes[team][name] != "" |
| 131 | } |
| 132 | if !ready { |
| 133 | continue |
| 134 | } |
| 135 | out, err := NewRegistry(append(operations, schedule.operation())...) |
| 136 | if err != nil { |
| 137 | return nil, err |
| 138 | } |
| 139 | out.schedule = schedule |
| 140 | return out, nil |
| 141 | } |
| 142 | return base, nil |
| 143 | } |
| 144 | |