Skip to main content

infra_api_gateway_contract/
lib.rs

1//! Transport-neutral contract for the Agent Infra gateway.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8pub const DISCOVERY_PATH: &str = "/.well-known/agent-infra";
9pub const LIVE_PATH: &str = "/health/live";
10pub const READY_PATH: &str = "/health/ready";
11pub const DEPENDENCIES_PATH: &str = "/health/dependencies";
12pub const ROUTES_PATH: &str = "/internal/gateway/routes";
13pub const METRICS_PATH: &str = "/internal/gateway/metrics";
14pub const PORTAL_PATH: &str = "/portal";
15pub const EFFECTIVE_POLICY_PATH: &str = "/v1/gateway/me";
16pub const CREDENTIAL_EXCHANGE_PATH: &str = "/v1/gateway/credentials:exchange";
17/// Exchanges a Runtime Identity bootstrap proof for the Runtime's first
18/// workload credential. The proof is self-authenticating and single-use, so
19/// this endpoint deliberately does not require an existing Gateway bearer.
20pub const RUNTIME_CREDENTIAL_BOOTSTRAP_PATH: &str = "/v1/gateway/runtime-credentials:bootstrap";
21pub const RUNTIME_CREDENTIAL_RECOVER_PATH: &str = "/v1/gateway/runtime-credentials:recover";
22pub const EXECUTION_DELEGATIONS_PATH: &str = "/v1/gateway/execution-delegations";
23pub const EXECUTION_DELEGATION_CREDENTIAL_PATH: &str =
24    "/v1/gateway/execution-delegations/credentials:mint";
25pub const EXECUTION_DELEGATION_RENEW_PATH: &str = "/v1/gateway/execution-delegations:renew";
26pub const EXECUTION_DELEGATION_REVOKE_PATH: &str = "/v1/gateway/execution-delegations:revoke";
27pub const CALLER_AUTHORIZATION_HEADER: &str = "x-agent-infra-caller-authorization";
28pub const AUDIT_PATH: &str = "/internal/gateway/audit";
29pub const ADMIN_CORS_CONFIG_PATH: &str = "/admin/api/cors-config";
30
31/// Extra registrable domains allowed to call the Gateway from a browser.
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
33#[serde(rename_all = "camelCase", deny_unknown_fields)]
34pub struct CorsAdminConfig {
35    pub allowed_domains: Vec<String>,
36    #[serde(default)]
37    pub legacy_exact_origins: Vec<String>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub api_registrable_domain: Option<String>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43#[serde(rename_all = "camelCase", deny_unknown_fields)]
44pub struct UpdateCorsAdminConfigRequest {
45    pub allowed_domains: Vec<String>,
46}
47
48/// Establishes an execution-bound delegation. Caller bearer material is sent
49/// in the dedicated transient header, never in this serializable request.
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52pub struct EstablishExecutionDelegationRequest {
53    pub execution_id: String,
54    pub workload_subject: String,
55    pub audience_capabilities: BTreeMap<String, Vec<String>>,
56    pub expires_in_seconds: u64,
57    pub idempotency_key: String,
58}
59
60#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62pub struct ExecutionDelegationLease {
63    pub lease_ref: String,
64    pub execution_id: String,
65    pub expires_at_seconds: u64,
66    pub revision: u64,
67}
68
69impl fmt::Debug for ExecutionDelegationLease {
70    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
71        formatter
72            .debug_struct("ExecutionDelegationLease")
73            .field("lease_ref", &"[REDACTED OPAQUE REFERENCE]")
74            .field("execution_id", &self.execution_id)
75            .field("expires_at_seconds", &self.expires_at_seconds)
76            .field("revision", &self.revision)
77            .finish()
78    }
79}
80
81#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
82#[serde(rename_all = "camelCase", deny_unknown_fields)]
83pub struct MintExecutionDelegationCredentialRequest {
84    pub lease_ref: String,
85    pub audience: String,
86    pub capabilities: Vec<String>,
87}
88
89impl fmt::Debug for MintExecutionDelegationCredentialRequest {
90    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91        formatter
92            .debug_struct("MintExecutionDelegationCredentialRequest")
93            .field("lease_ref", &"[REDACTED OPAQUE REFERENCE]")
94            .field("audience", &self.audience)
95            .field("capabilities", &self.capabilities)
96            .finish()
97    }
98}
99
100#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
101#[serde(rename_all = "camelCase", deny_unknown_fields)]
102pub struct RenewExecutionDelegationRequest {
103    pub lease_ref: String,
104    pub expected_revision: u64,
105    pub extend_by_seconds: u64,
106    pub idempotency_key: String,
107}
108
109impl fmt::Debug for RenewExecutionDelegationRequest {
110    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
111        formatter
112            .debug_struct("RenewExecutionDelegationRequest")
113            .field("lease_ref", &"[REDACTED OPAQUE REFERENCE]")
114            .field("expected_revision", &self.expected_revision)
115            .field("extend_by_seconds", &self.extend_by_seconds)
116            .field("idempotency_key", &self.idempotency_key)
117            .finish()
118    }
119}
120
121#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
122#[serde(rename_all = "camelCase", deny_unknown_fields)]
123pub struct RevokeExecutionDelegationRequest {
124    pub lease_ref: String,
125    pub idempotency_key: String,
126}
127
128impl fmt::Debug for RevokeExecutionDelegationRequest {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter
131            .debug_struct("RevokeExecutionDelegationRequest")
132            .field("lease_ref", &"[REDACTED OPAQUE REFERENCE]")
133            .field("idempotency_key", &self.idempotency_key)
134            .finish()
135    }
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
139#[serde(rename_all = "camelCase")]
140pub struct DiscoveryDocument {
141    pub service: String,
142    pub api_version: String,
143    pub routes: BTreeMap<String, String>,
144    pub health: BTreeMap<String, String>,
145    pub openapi: String,
146    pub portal: String,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
150#[serde(rename_all = "camelCase", deny_unknown_fields)]
151pub struct CredentialExchangeRequest {
152    pub audience: String,
153    pub capabilities: Vec<String>,
154}
155
156#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
157#[serde(rename_all = "camelCase")]
158pub struct CredentialExchangeResponse {
159    pub access_token: String,
160    pub token_type: String,
161    pub expires_in_seconds: u64,
162}
163
164impl fmt::Debug for CredentialExchangeResponse {
165    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166        formatter
167            .debug_struct("CredentialExchangeResponse")
168            .field("access_token", &"[REDACTED]")
169            .field("token_type", &self.token_type)
170            .field("expires_in_seconds", &self.expires_in_seconds)
171            .finish()
172    }
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
176#[serde(rename_all = "camelCase")]
177pub struct EffectivePolicy {
178    pub subject: String,
179    pub tenant_id: String,
180    pub project_id: String,
181    pub capabilities: Vec<String>,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
185#[serde(rename_all = "camelCase")]
186pub struct GatewayAuditRecord {
187    pub observed_at_ms: u64,
188    pub request_id: String,
189    pub tenant: String,
190    pub subject: String,
191    pub service: String,
192    pub route: String,
193    pub method: String,
194    pub status: u16,
195    pub latency_ms: u64,
196    pub decision: String,
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
200#[serde(rename_all = "camelCase")]
201pub struct GatewayAuditPage {
202    pub items: Vec<GatewayAuditRecord>,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub next_cursor: Option<String>,
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
208pub struct HealthSnapshot {
209    pub status: String,
210    pub services: BTreeMap<String, String>,
211}
212
213/// Liveness/readiness probe body returned by `/health/live` and
214/// `/health/ready`. Readiness responds `200` with `status = "ok"` when the
215/// gateway and its control-plane dependencies are ready, and `503` with
216/// `status = "not_ready"` otherwise.
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
218pub struct GatewayStatus {
219    pub status: String,
220    pub service: String,
221}
222
223impl GatewayStatus {
224    pub fn is_ready(&self) -> bool {
225        self.status == "ok"
226    }
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
230#[serde(rename_all = "camelCase")]
231pub struct GatewayMetricsSnapshot {
232    pub requests: u64,
233    pub responses: u64,
234    pub errors: u64,
235    pub rate_limited: u64,
236    pub in_flight: u64,
237    pub average_latency_micros: u64,
238    #[serde(default)]
239    pub latency_p50_micros: u64,
240    #[serde(default)]
241    pub latency_p95_micros: u64,
242    #[serde(default)]
243    pub latency_p99_micros: u64,
244    #[serde(default)]
245    pub response_size_samples: u64,
246    #[serde(default)]
247    pub average_response_bytes: u64,
248    #[serde(default)]
249    pub route_requests: BTreeMap<String, u64>,
250    pub audit_events_dropped: u64,
251}
252
253impl HealthSnapshot {
254    pub fn healthy(&self) -> bool {
255        self.status == "ok"
256    }
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
260#[serde(rename_all = "camelCase")]
261pub struct WeightedEndpoint {
262    pub url: String,
263    #[serde(default = "default_weight")]
264    pub weight: u32,
265    /// Optional deployment region. The gateway prefers an exact requested
266    /// region and falls back to the global pool when it is unavailable.
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub region: Option<String>,
269    /// Lower values are preferred. Weighting only occurs within the lowest
270    /// available priority tier, enabling deterministic regional failover.
271    #[serde(default)]
272    pub priority: u16,
273}
274
275fn default_weight() -> u32 {
276    100
277}
278
279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
280#[serde(rename_all = "camelCase")]
281pub struct RouteSnapshot {
282    pub version: u64,
283    pub services: BTreeMap<String, Vec<WeightedEndpoint>>,
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
287#[serde(rename_all = "camelCase")]
288pub struct GatewayErrorEnvelope {
289    pub error: GatewayError,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
293#[serde(rename_all = "camelCase")]
294pub struct GatewayError {
295    pub code: String,
296    pub message: String,
297    pub category: String,
298    pub retryable: bool,
299    pub request_id: String,
300    #[serde(default)]
301    pub details: serde_json::Value,
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    #[test]
309    fn delegation_wire_contract_is_camel_case_and_never_contains_caller_secret() {
310        let request = EstablishExecutionDelegationRequest {
311            execution_id: "execution-1".into(),
312            workload_subject: "runtime-1".into(),
313            audience_capabilities: BTreeMap::from([(
314                "agent-model-infra".into(),
315                vec!["model-profile:code:invoke".into()],
316            )]),
317            expires_in_seconds: 300,
318            idempotency_key: "execution-1:delegate".into(),
319        };
320        let value = serde_json::to_value(request).unwrap();
321        assert_eq!(value["executionId"], "execution-1");
322        assert_eq!(value["workloadSubject"], "runtime-1");
323        assert!(value.get("authorization").is_none());
324        assert!(value.get("callerAuthorization").is_none());
325    }
326
327    #[test]
328    fn opaque_delegation_references_are_redacted_from_debug() {
329        let lease = ExecutionDelegationLease {
330            lease_ref: "edl_super_secret".into(),
331            execution_id: "execution-1".into(),
332            expires_at_seconds: 42,
333            revision: 1,
334        };
335        assert!(!format!("{lease:?}").contains("edl_super_secret"));
336    }
337}