1use super::BindingValue;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
14#[serde(tag = "service", rename_all = "lowercase")]
15pub enum AiBinding {
16 Bedrock(BedrockAiBinding),
18 Vertex(VertexAiBinding),
20 Foundry(FoundryAiBinding),
22 #[serde(rename = "external-ai")]
27 External(ExternalAiBinding),
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
33#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
34#[serde(rename_all = "camelCase")]
35pub struct BedrockAiBinding {
36 #[serde(deserialize_with = "deserialize_aws_region")]
40 pub region: String,
41}
42
43impl BedrockAiBinding {
44 pub fn new(region: impl Into<String>) -> Result<Self, String> {
46 let region = region.into();
47 validate_aws_region(®ion)?;
48 Ok(Self { region })
49 }
50}
51
52pub fn validate_aws_region(region: &str) -> Result<(), String> {
57 let invalid = || {
58 format!(
59 "invalid AWS region {region:?}: expected a region name such as \"us-east-1\" \
60 (lowercase letters, digits and single dashes only)"
61 )
62 };
63 if region.len() > 30 {
64 return Err(invalid());
65 }
66 let parts: Vec<&str> = region.split('-').collect();
67 let [geography, middle @ .., number] = parts.as_slice() else {
68 return Err(invalid());
69 };
70 let lowercase = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase());
71 let valid = geography.len() == 2
72 && lowercase(geography)
73 && !middle.is_empty()
74 && middle.iter().all(|m| lowercase(m))
75 && !number.is_empty()
76 && number.len() <= 2
77 && number.bytes().all(|b| b.is_ascii_digit());
78 if valid {
79 Ok(())
80 } else {
81 Err(invalid())
82 }
83}
84
85fn deserialize_aws_region<'de, D: serde::Deserializer<'de>>(
86 deserializer: D,
87) -> Result<String, D::Error> {
88 let region = String::deserialize(deserializer)?;
89 validate_aws_region(®ion).map_err(serde::de::Error::custom)?;
90 Ok(region)
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
96#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
97#[serde(rename_all = "camelCase")]
98pub struct VertexAiBinding {
99 pub project: String,
101 pub location: String,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
108#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
109#[serde(rename_all = "camelCase")]
110pub struct FoundryAiBinding {
111 pub endpoint: String,
113 pub account: String,
115}
116
117#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
126#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
127#[serde(rename_all = "camelCase")]
128pub struct ExternalAiBinding {
129 pub provider: String,
131 pub api_key: BindingValue<String>,
134}
135
136impl std::fmt::Debug for ExternalAiBinding {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 f.debug_struct("ExternalAiBinding")
141 .field("provider", &self.provider)
142 .field("api_key", &"<redacted>")
143 .finish()
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
170#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
171#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
172#[serde(untagged)]
173pub enum ExternalAi {
174 Ambient(AmbientAiBinding),
176 ApiKey(ExternalAiBinding),
178}
179
180impl<'de> Deserialize<'de> for ExternalAi {
181 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
182 use serde::de::Error;
183 const FORMS: &str = "expected either {\"service\": \"bedrock\", \"region\": \"<region>\"} \
184 (the pod's cloud identity, no key) or {\"provider\": \"<name>\", \"apiKey\": \"<key>\"} (your own key)";
185 let value = serde_json::Value::deserialize(deserializer)?;
186 let Some(object) = value.as_object() else {
187 return Err(D::Error::custom(format!(
188 "invalid external AI binding: {FORMS}"
189 )));
190 };
191 let service = object.get("service").and_then(|v| v.as_str());
195 if object.contains_key("service") && service != Some("external-ai") {
196 if let Some(extra) = object.keys().find(|k| *k != "service" && *k != "region") {
197 return Err(D::Error::custom(format!(
198 "invalid external AI binding: field `{extra}` is not allowed with `service` \
199 (it uses the workload's cloud identity and takes only `region`); {FORMS}"
200 )));
201 }
202 serde_json::from_value(value)
203 .map(Self::Ambient)
204 .map_err(|e| D::Error::custom(format!("invalid external AI binding: {e}; {FORMS}")))
205 } else {
206 serde_json::from_value(value)
207 .map(Self::ApiKey)
208 .map_err(|e| D::Error::custom(format!("invalid external AI binding: {e}; {FORMS}")))
209 }
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
216#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
217#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
218#[serde(tag = "service", rename_all = "lowercase")]
219pub enum AmbientAiBinding {
220 Bedrock(BedrockAiBinding),
222}
223
224impl From<ExternalAiBinding> for ExternalAi {
225 fn from(binding: ExternalAiBinding) -> Self {
226 Self::ApiKey(binding)
227 }
228}
229
230impl ExternalAi {
231 pub fn to_ai_binding(&self) -> AiBinding {
233 match self {
234 Self::Ambient(AmbientAiBinding::Bedrock(b)) => AiBinding::Bedrock(b.clone()),
235 Self::ApiKey(b) => AiBinding::External(b.clone()),
236 }
237 }
238}
239
240impl AiBinding {
241 pub const LOCAL_API_KEY_ENV: &'static str = "OPENAI_API_KEY";
245 pub const LOCAL_DEFAULT_PROVIDER: &'static str = "openai";
247 pub const LOCAL_BEDROCK_REGION_ENV: &'static str = "ALIEN_AI_LOCAL_BEDROCK_REGION";
252 pub const LOCAL_BEDROCK_PROVIDER: &'static str = "bedrock";
254
255 pub fn local_bedrock_region() -> Result<Option<String>, String> {
257 match std::env::var(Self::LOCAL_BEDROCK_REGION_ENV) {
258 Ok(region) if !region.is_empty() => BedrockAiBinding::new(region)
259 .map(|binding| Some(binding.region))
260 .map_err(|error| format!("{}: {error}", Self::LOCAL_BEDROCK_REGION_ENV)),
261 _ => Ok(None),
262 }
263 }
264
265 pub fn bedrock(region: impl Into<String>) -> Self {
266 Self::Bedrock(BedrockAiBinding {
267 region: region.into(),
268 })
269 }
270
271 pub fn vertex(project: impl Into<String>, location: impl Into<String>) -> Self {
272 Self::Vertex(VertexAiBinding {
273 project: project.into(),
274 location: location.into(),
275 })
276 }
277
278 pub fn foundry(endpoint: impl Into<String>, account: impl Into<String>) -> Self {
279 Self::Foundry(FoundryAiBinding {
280 endpoint: endpoint.into(),
281 account: account.into(),
282 })
283 }
284
285 pub fn external(provider: impl Into<String>, api_key: impl Into<BindingValue<String>>) -> Self {
286 Self::External(ExternalAiBinding {
287 provider: provider.into(),
288 api_key: api_key.into(),
289 })
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn test_bedrock_binding_roundtrip() {
299 let binding = AiBinding::bedrock("us-east-1");
300
301 let json = serde_json::to_string(&binding).unwrap();
302 assert!(json.contains(r#""service":"bedrock""#));
303
304 let deserialized: AiBinding = serde_json::from_str(&json).unwrap();
305 assert_eq!(binding, deserialized);
306 }
307
308 #[test]
309 fn test_vertex_binding_roundtrip() {
310 let binding = AiBinding::vertex("my-project", "us-central1");
311
312 let json = serde_json::to_string(&binding).unwrap();
313 assert!(json.contains(r#""service":"vertex""#));
314
315 let deserialized: AiBinding = serde_json::from_str(&json).unwrap();
316 assert_eq!(binding, deserialized);
317 }
318
319 #[test]
320 fn test_foundry_binding_roundtrip() {
321 let binding = AiBinding::foundry("https://my-foundry.openai.azure.com", "my-subscription");
322
323 let json = serde_json::to_value(&binding).unwrap();
324 let json_str = json.to_string();
325 assert!(json_str.contains(r#""service":"foundry""#));
326 assert!(
327 !json_str.contains("instantAccess"),
328 "foundry binding must not serialize instant_access"
329 );
330
331 let deserialized: AiBinding = serde_json::from_value(json).unwrap();
332 assert_eq!(binding, deserialized);
333 }
334
335 #[test]
336 fn test_external_binding_roundtrip() {
337 let binding = AiBinding::external("openai", "sk-test-key");
338
339 let json = serde_json::to_value(&binding).unwrap();
342 let json_str = json.to_string();
343 assert!(
344 json_str.contains(r#""apiKey""#),
345 "external binding must serialize apiKey in camelCase"
346 );
347 assert_eq!(
348 json,
349 serde_json::json!({
350 "service": "external-ai",
351 "provider": "openai",
352 "apiKey": "sk-test-key",
353 })
354 );
355
356 let deserialized: AiBinding =
357 serde_json::from_value(json).expect("external binding should round-trip");
358 assert_eq!(binding, deserialized);
359 }
360
361 #[test]
362 fn external_ai_with_the_external_ai_service_tag_still_parses_as_a_key() {
363 let parsed: ExternalAi = serde_json::from_value(serde_json::json!({
364 "service": "external-ai", "provider": "openai", "apiKey": "sk-x"
365 }))
366 .expect("the tagged BYO-key input parsed before and must keep parsing");
367 assert!(matches!(&parsed, ExternalAi::ApiKey(b) if b.provider == "openai"));
368 let binding: crate::ExternalBinding = serde_json::from_value(serde_json::json!({
371 "type": "ai", "service": "external-ai", "provider": "openai", "apiKey": "sk-x"
372 }))
373 .unwrap();
374 assert_eq!(
375 binding.to_env_binding_value().unwrap(),
376 serde_json::json!({"service": "external-ai", "provider": "openai", "apiKey": "sk-x"})
377 );
378 let err = serde_json::from_value::<ExternalAi>(
379 serde_json::json!({"service": "external-ai", "provider": "openai"}),
380 )
381 .unwrap_err()
382 .to_string();
383 assert!(err.contains("invalid external AI binding"), "{err}");
384 }
385
386 #[test]
387 fn bedrock_region_must_be_a_plain_aws_region() {
388 for ok in [
389 "us-east-1",
390 "eu-central-2",
391 "ap-southeast-4",
392 "us-gov-west-1",
393 "us-iso-east-1",
394 "cn-north-1",
395 ] {
396 let binding: BedrockAiBinding =
397 serde_json::from_value(serde_json::json!({ "region": ok }))
398 .unwrap_or_else(|e| panic!("{ok} must parse: {e}"));
399 assert_eq!(binding.region, ok);
400 assert!(BedrockAiBinding::new(ok).is_ok());
401 }
402 for bad in [
403 "x.evil.com/",
404 "us-east-1.evil.com",
405 "",
406 "US-EAST-1",
407 "us east 1",
408 "us-east-1/",
409 "us-east-1@evil.com",
410 "us-east",
411 "useast1",
412 "us--east-1",
413 "-us-east-1",
414 "us-east-1-",
415 "us-east-1\n",
416 "us-east-123",
417 ] {
418 let err =
419 serde_json::from_value::<BedrockAiBinding>(serde_json::json!({ "region": bad }))
420 .expect_err(&format!("{bad:?} must be refused"))
421 .to_string();
422 assert!(
423 err.contains("invalid AWS region"),
424 "unclear error for {bad:?}: {err}"
425 );
426 assert!(BedrockAiBinding::new(bad).is_err());
427 assert!(serde_json::from_value::<AiBinding>(
429 serde_json::json!({ "service": "bedrock", "region": bad })
430 )
431 .is_err());
432 assert!(serde_json::from_value::<ExternalAi>(
433 serde_json::json!({ "service": "bedrock", "region": bad })
434 )
435 .is_err());
436 }
437 }
438
439 #[test]
440 fn test_external_ai_rejects_typos_and_unused_keys_with_clear_errors() {
441 for bad in [
442 serde_json::json!({"service": "bedrok", "region": "us-east-1"}),
443 serde_json::json!({"service": "bedrock"}),
444 serde_json::json!({"service": "bedrock", "region": "us-east-1", "apiKey": "sk-x"}),
445 serde_json::json!({"provider": "openai"}),
446 serde_json::json!("bedrock"),
447 ] {
448 let err = serde_json::from_value::<ExternalAi>(bad.clone())
449 .expect_err(&format!("{bad} must be refused"))
450 .to_string();
451 assert!(
452 err.contains("invalid external AI binding") && err.contains("\"apiKey\""),
453 "unclear error for {bad}: {err}"
454 );
455 assert!(!err.contains("sk-x"), "error must not echo the key: {err}");
456 }
457 let err = serde_json::from_value::<ExternalAi>(
458 serde_json::json!({"service": "bedrock", "region": "us-east-1", "apiKey": "sk-x"}),
459 )
460 .unwrap_err()
461 .to_string();
462 assert!(err.contains("`apiKey` is not allowed"), "{err}");
463 }
464}