Skip to main content

alien_core/
external_bindings.rs

1//! External bindings for pre-existing infrastructure services.
2//!
3//! External bindings allow using existing infrastructure (MinIO, Kafka, Redis, etc.)
4//! instead of having Alien provision cloud resources. This is required for Kubernetes
5//! platform deployments and optional for cloud platforms (to override specific resources).
6
7use std::collections::HashMap;
8
9use alien_error::AlienError;
10use serde::{Deserialize, Serialize};
11
12use crate::bindings::{
13    ArtifactRegistryBinding, BindingValue, ContainerAppsEnvironmentBinding, ExternalAi, KvBinding,
14    PostgresBinding, QueueBinding, RedisBinding, StorageBinding, VaultBinding,
15};
16use crate::error::ErrorData;
17use crate::resource::{ResourceOutputs, ResourceType};
18use crate::resources::AzureContainerAppsEnvironmentOutputs;
19use crate::{CustomResourceOutputs, Resource, ResourceTypeDescriptor};
20
21/// Represents a binding to pre-existing infrastructure.
22///
23/// The binding type must match the resource type it's applied to.
24/// Validated at runtime by the executor.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(tag = "type", rename_all = "snake_case", remote = "Self")]
27pub enum ExternalBinding {
28    /// External storage binding (S3-compatible, GCS, Blob Storage)
29    Storage(StorageBinding),
30    /// External queue binding (Kafka, SQS, etc.)
31    Queue(QueueBinding),
32    /// External KV binding (Redis, etc.)
33    Kv(KvBinding),
34    /// External artifact registry binding (OCI registry)
35    ArtifactRegistry(ArtifactRegistryBinding),
36    /// External vault binding (HashiCorp Vault, etc.)
37    Vault(VaultBinding),
38    /// External Azure Container Apps Environment binding (pre-existing environment)
39    ContainerAppsEnvironment(ContainerAppsEnvironmentBinding),
40    /// External Postgres binding (operator-provided / BYO database)
41    Postgres(PostgresBinding),
42    /// External Redis binding (operator-provided Redis-compatible server)
43    Redis(RedisBinding),
44    /// External AI binding: a BYO-key provider (OpenAI/Anthropic, etc.) or a cloud AI service
45    /// reached with the workload's own identity (Bedrock)
46    Ai(ExternalAi),
47    /// A binding to an existing resource of a type an extension defines. It serializes to the
48    /// same object as the variants above, with the extension's type as the tag.
49    #[serde(skip)]
50    Custom(CustomExternalBinding),
51}
52
53// `remote = "Self"` turns the derived impls into inherent fns, which these two call for the
54// built-in variants.
55impl Serialize for ExternalBinding {
56    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
57        match self {
58            ExternalBinding::Custom(custom) => custom.serialize(serializer),
59            built_in => ExternalBinding::serialize(built_in, serializer),
60        }
61    }
62}
63
64/// Only a tag that names an extension's type reads as `Custom`. A built-in tag takes its own
65/// variant's shape and any other tag is refused, so a malformed built-in binding never loads as
66/// custom.
67impl<'de> Deserialize<'de> for ExternalBinding {
68    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
69        let value = serde_json::Value::deserialize(deserializer)?;
70        let is_custom = value
71            .get("type")
72            .and_then(serde_json::Value::as_str)
73            .is_some_and(crate::custom_resource::is_custom_resource_type);
74        if is_custom {
75            serde_json::from_value::<CustomExternalBinding>(value)
76                .map(ExternalBinding::Custom)
77                .map_err(serde::de::Error::custom)
78        } else {
79            ExternalBinding::deserialize(value).map_err(serde::de::Error::custom)
80        }
81    }
82}
83
84// Utoipa drops a variant marked `#[serde(skip)]`, as `Custom` is, so `ExternalBinding`'s schema
85// is this enum's, with `Custom` added. Its docs repeat `ExternalBinding`'s word for word: they
86// become the TypeScript SDK's descriptions.
87/// Represents a binding to pre-existing infrastructure.
88///
89/// The binding type must match the resource type it's applied to.
90/// Validated at runtime by the executor.
91#[cfg(feature = "openapi")]
92#[derive(Serialize, utoipa::ToSchema)]
93#[serde(tag = "type", rename_all = "snake_case")]
94#[allow(dead_code)]
95enum BuiltInExternalBinding {
96    /// External storage binding (S3-compatible, GCS, Blob Storage)
97    Storage(StorageBinding),
98    /// External queue binding (Kafka, SQS, etc.)
99    Queue(QueueBinding),
100    /// External KV binding (Redis, etc.)
101    Kv(KvBinding),
102    /// External artifact registry binding (OCI registry)
103    ArtifactRegistry(ArtifactRegistryBinding),
104    /// External vault binding (HashiCorp Vault, etc.)
105    Vault(VaultBinding),
106    /// External Azure Container Apps Environment binding (pre-existing environment)
107    ContainerAppsEnvironment(ContainerAppsEnvironmentBinding),
108    /// External Postgres binding (operator-provided / BYO database)
109    Postgres(PostgresBinding),
110    /// External Redis binding (operator-provided Redis-compatible server)
111    Redis(RedisBinding),
112    /// External AI binding: a BYO-key provider (OpenAI/Anthropic, etc.) or a cloud AI service
113    /// reached with the workload's own identity (Bedrock)
114    Ai(ExternalAi),
115}
116
117#[cfg(feature = "openapi")]
118impl utoipa::PartialSchema for ExternalBinding {
119    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
120        use utoipa::openapi::schema::Schema;
121        use utoipa::openapi::{Ref, RefOr};
122        use utoipa::ToSchema as _;
123        let mut schema = BuiltInExternalBinding::schema();
124        if let RefOr::T(Schema::OneOf(one_of)) = &mut schema {
125            one_of
126                .items
127                .push(Ref::from_schema_name(CustomExternalBinding::name()).into());
128        }
129        schema
130    }
131}
132
133#[cfg(feature = "openapi")]
134impl utoipa::ToSchema for ExternalBinding {
135    fn schemas(
136        schemas: &mut Vec<(
137            String,
138            utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
139        )>,
140    ) {
141        use utoipa::PartialSchema as _;
142        BuiltInExternalBinding::schemas(schemas);
143        schemas.push((
144            CustomExternalBinding::name().into_owned(),
145            CustomExternalBinding::schema(),
146        ));
147        CustomExternalBinding::schemas(schemas);
148    }
149}
150
151/// A binding to an existing resource of a type an extension defines, such as a DNS zone the
152/// customer already has. Its fields are the resource's outputs, as the type's descriptor declares
153/// them in `schemas.outputs`.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
156#[serde(rename_all = "camelCase")]
157pub struct CustomExternalBinding {
158    /// The extension's type, such as `acme/dns-zone`.
159    #[serde(rename = "type")]
160    #[cfg_attr(
161        feature = "openapi",
162        schema(value_type = crate::heartbeat::CustomResourceType)
163    )]
164    pub resource_type: ResourceType,
165    /// The service the existing resource lives in, such as `route53`.
166    pub service: String,
167    /// The resource's outputs, such as its `zoneId`.
168    #[serde(flatten)]
169    pub fields: serde_json::Map<String, serde_json::Value>,
170}
171
172impl CustomExternalBinding {
173    /// Checks the fields against the outputs schema in `descriptor`, failing closed: a schema
174    /// keyword the check doesn't read refuses the binding.
175    pub fn validate(&self, descriptor: &ResourceTypeDescriptor) -> Result<(), String> {
176        let problems = crate::binding_schema::problems(
177            &descriptor.schemas.outputs,
178            &serde_json::Value::Object(self.fields.clone()),
179        );
180        if problems.is_empty() {
181            Ok(())
182        } else {
183            Err(format!(
184                "The binding for type '{}' does not match the outputs its extension declares: {}",
185                self.resource_type,
186                problems.join("; ")
187            ))
188        }
189    }
190}
191
192/// The binding's own fields beside the outputs, which an outputs schema must not name: they would
193/// read as the binding's tag and service instead of outputs.
194pub const CUSTOM_BINDING_RESERVED_FIELDS: [&str; 2] = ["type", "service"];
195
196/// Map from resource ID to external binding.
197///
198/// Validated at runtime: binding type must match resource type.
199#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
200#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
201#[serde(transparent)]
202pub struct ExternalBindings(pub HashMap<String, ExternalBinding>);
203
204impl ExternalBindings {
205    /// Creates an empty ExternalBindings map.
206    pub fn new() -> Self {
207        Self(HashMap::new())
208    }
209
210    /// Returns true if there are no external bindings.
211    pub fn is_empty(&self) -> bool {
212        self.0.is_empty()
213    }
214
215    /// Checks if a binding exists for the given resource ID.
216    pub fn has(&self, resource_id: &str) -> bool {
217        self.0.contains_key(resource_id)
218    }
219
220    /// Gets an external binding by resource ID.
221    pub fn get(&self, resource_id: &str) -> Option<&ExternalBinding> {
222        self.0.get(resource_id)
223    }
224
225    /// Gets a storage binding for the given resource ID.
226    /// Returns an error if the binding exists but is not a Storage type.
227    pub fn get_storage(&self, id: &str) -> crate::error::Result<Option<&StorageBinding>> {
228        match self.0.get(id) {
229            Some(ExternalBinding::Storage(b)) => Ok(Some(b)),
230            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
231                resource_id: id.to_string(),
232                expected: "storage".to_string(),
233                actual: other.binding_type().to_string(),
234            })),
235            None => Ok(None),
236        }
237    }
238
239    /// Gets a queue binding for the given resource ID.
240    /// Returns an error if the binding exists but is not a Queue type.
241    pub fn get_queue(&self, id: &str) -> crate::error::Result<Option<&QueueBinding>> {
242        match self.0.get(id) {
243            Some(ExternalBinding::Queue(b)) => Ok(Some(b)),
244            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
245                resource_id: id.to_string(),
246                expected: "queue".to_string(),
247                actual: other.binding_type().to_string(),
248            })),
249            None => Ok(None),
250        }
251    }
252
253    /// Gets a KV binding for the given resource ID.
254    /// Returns an error if the binding exists but is not a Kv type.
255    pub fn get_kv(&self, id: &str) -> crate::error::Result<Option<&KvBinding>> {
256        match self.0.get(id) {
257            Some(ExternalBinding::Kv(b)) => Ok(Some(b)),
258            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
259                resource_id: id.to_string(),
260                expected: "kv".to_string(),
261                actual: other.binding_type().to_string(),
262            })),
263            None => Ok(None),
264        }
265    }
266
267    /// Gets an artifact registry binding for the given resource ID.
268    /// Returns an error if the binding exists but is not an ArtifactRegistry type.
269    pub fn get_artifact_registry(
270        &self,
271        id: &str,
272    ) -> crate::error::Result<Option<&ArtifactRegistryBinding>> {
273        match self.0.get(id) {
274            Some(ExternalBinding::ArtifactRegistry(b)) => Ok(Some(b)),
275            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
276                resource_id: id.to_string(),
277                expected: "artifact_registry".to_string(),
278                actual: other.binding_type().to_string(),
279            })),
280            None => Ok(None),
281        }
282    }
283
284    /// Gets a vault binding for the given resource ID.
285    /// Returns an error if the binding exists but is not a Vault type.
286    pub fn get_vault(&self, id: &str) -> crate::error::Result<Option<&VaultBinding>> {
287        match self.0.get(id) {
288            Some(ExternalBinding::Vault(b)) => Ok(Some(b)),
289            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
290                resource_id: id.to_string(),
291                expected: "vault".to_string(),
292                actual: other.binding_type().to_string(),
293            })),
294            None => Ok(None),
295        }
296    }
297
298    /// Gets an AI binding for the given resource ID.
299    /// Returns an error if the binding exists but is not an Ai type.
300    pub fn get_ai(&self, id: &str) -> crate::error::Result<Option<&ExternalAi>> {
301        match self.0.get(id) {
302            Some(ExternalBinding::Ai(b)) => Ok(Some(b)),
303            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
304                resource_id: id.to_string(),
305                expected: "ai".to_string(),
306                actual: other.binding_type().to_string(),
307            })),
308            None => Ok(None),
309        }
310    }
311
312    /// Gets a container apps environment binding for the given resource ID.
313    /// Returns an error if the binding exists but is not a ContainerAppsEnvironment type.
314    pub fn get_container_apps_environment(
315        &self,
316        id: &str,
317    ) -> crate::error::Result<Option<&ContainerAppsEnvironmentBinding>> {
318        match self.0.get(id) {
319            Some(ExternalBinding::ContainerAppsEnvironment(b)) => Ok(Some(b)),
320            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
321                resource_id: id.to_string(),
322                expected: "azure_container_apps_environment".to_string(),
323                actual: other.binding_type().to_string(),
324            })),
325            None => Ok(None),
326        }
327    }
328
329    /// Returns an error if the binding exists but is not a Postgres type.
330    pub fn get_postgres(&self, id: &str) -> crate::error::Result<Option<&PostgresBinding>> {
331        match self.0.get(id) {
332            Some(ExternalBinding::Postgres(b)) => Ok(Some(b)),
333            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
334                resource_id: id.to_string(),
335                expected: "postgres".to_string(),
336                actual: other.binding_type().to_string(),
337            })),
338            None => Ok(None),
339        }
340    }
341
342    /// Returns an error if the binding exists but is not a Redis type.
343    pub fn get_redis(&self, id: &str) -> crate::error::Result<Option<&RedisBinding>> {
344        match self.0.get(id) {
345            Some(ExternalBinding::Redis(b)) => Ok(Some(b)),
346            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
347                resource_id: id.to_string(),
348                expected: "redis".to_string(),
349                actual: other.binding_type().to_string(),
350            })),
351            None => Ok(None),
352        }
353    }
354
355    /// Inserts an external binding for a resource.
356    pub fn insert(&mut self, resource_id: impl Into<String>, binding: ExternalBinding) {
357        self.0.insert(resource_id.into(), binding);
358    }
359}
360
361impl ExternalBinding {
362    /// Returns the type name of this binding variant.
363    pub fn binding_type(&self) -> &str {
364        match self {
365            ExternalBinding::Storage(_) => "storage",
366            ExternalBinding::Queue(_) => "queue",
367            ExternalBinding::Kv(_) => "kv",
368            ExternalBinding::ArtifactRegistry(_) => "artifact_registry",
369            ExternalBinding::Vault(_) => "vault",
370            ExternalBinding::ContainerAppsEnvironment(_) => "azure_container_apps_environment",
371            ExternalBinding::Postgres(_) => "postgres",
372            ExternalBinding::Redis(_) => "redis",
373            ExternalBinding::Ai(_) => "ai",
374            ExternalBinding::Custom(custom) => custom.resource_type.as_ref(),
375        }
376    }
377
378    /// Converts this external binding into resource outputs that dependent resources
379    /// can read via `get_resource_outputs()`.
380    ///
381    /// Infrastructure bindings (Container Apps Environment) produce typed outputs so that
382    /// dependent resources like functions and builds can read the environment's name,
383    /// resource ID, and resource group. Application-level bindings (Storage, Queue, KV, etc.)
384    /// return `None` — they are consumed via `remote_binding_params` and environment variables
385    /// rather than `get_resource_outputs()`.
386    pub fn to_resource_outputs(&self) -> Option<ResourceOutputs> {
387        match self {
388            ExternalBinding::ContainerAppsEnvironment(binding) => {
389                // Extract concrete values from BindingValue wrappers.
390                // External bindings for pre-provisioned resources always use concrete values.
391                let environment_name = match &binding.environment_name {
392                    BindingValue::Value(v) => v.clone(),
393                    _ => return None,
394                };
395                let resource_id = match &binding.resource_id {
396                    BindingValue::Value(v) => v.clone(),
397                    _ => return None,
398                };
399                let resource_group_name = match &binding.resource_group_name {
400                    BindingValue::Value(v) => v.clone(),
401                    _ => return None,
402                };
403                let default_domain = match &binding.default_domain {
404                    BindingValue::Value(v) => v.clone(),
405                    _ => return None,
406                };
407                let static_ip = binding.static_ip.as_ref().and_then(|v| match v {
408                    BindingValue::Value(v) => Some(v.clone()),
409                    _ => None,
410                });
411
412                Some(ResourceOutputs::new(AzureContainerAppsEnvironmentOutputs {
413                    environment_name,
414                    resource_id,
415                    resource_group_name,
416                    default_domain,
417                    static_ip,
418                    custom_domain_verification_id: None,
419                }))
420            }
421            // A custom binding's fields are the resource's outputs.
422            ExternalBinding::Custom(binding) => Some(ResourceOutputs::new(
423                CustomResourceOutputs::new(binding.resource_type.clone(), binding.fields.clone()),
424            )),
425            // Application-level bindings are consumed via remote_binding_params, not outputs
426            _ => None,
427        }
428    }
429
430    /// Serializes this external binding to the JSON value injected into the worker
431    /// environment as `ALIEN_<NAME>_BINDING`, matching the shape the SDK parses.
432    ///
433    /// The AI arm converts to an `AiBinding` so the value keeps the `service` tag the
434    /// SDK's `ai(name)` parser discriminates on: `external-ai` for a BYO key, `bedrock`
435    /// for ambient credentials. Every other arm serializes the
436    /// carried binding directly, like the runtime controllers' `get_binding_params`.
437    pub fn to_env_binding_value(&self) -> serde_json::Result<serde_json::Value> {
438        match self {
439            ExternalBinding::Storage(b) => serde_json::to_value(b),
440            ExternalBinding::Queue(b) => serde_json::to_value(b),
441            ExternalBinding::Kv(b) => serde_json::to_value(b),
442            ExternalBinding::ArtifactRegistry(b) => serde_json::to_value(b),
443            ExternalBinding::Vault(b) => serde_json::to_value(b),
444            ExternalBinding::ContainerAppsEnvironment(b) => serde_json::to_value(b),
445            ExternalBinding::Postgres(b) => serde_json::to_value(b),
446            ExternalBinding::Redis(b) => serde_json::to_value(b),
447            ExternalBinding::Ai(b) => serde_json::to_value(b.to_ai_binding()),
448            // As a built-in binding, the value carries the service and the fields, not the tag.
449            ExternalBinding::Custom(b) => {
450                let mut value = serde_json::to_value(b)?;
451                if let serde_json::Value::Object(fields) = &mut value {
452                    fields.remove("type");
453                }
454                Ok(value)
455            }
456        }
457    }
458}
459
460/// Validates that an external binding type matches the resource type.
461pub fn validate_binding_type(
462    resource: &Resource,
463    binding: &ExternalBinding,
464) -> crate::error::Result<()> {
465    let resource_type = resource.resource_type();
466    let resource_type_str = resource_type.as_ref();
467
468    let valid = match (resource_type_str, binding) {
469        ("storage", ExternalBinding::Storage(_)) => true,
470        ("queue", ExternalBinding::Queue(_)) => true,
471        ("kv", ExternalBinding::Kv(_)) => true,
472        ("artifact_registry", ExternalBinding::ArtifactRegistry(_)) => true,
473        ("vault", ExternalBinding::Vault(_)) => true,
474        ("azure_container_apps_environment", ExternalBinding::ContainerAppsEnvironment(_)) => true,
475        ("postgres", ExternalBinding::Postgres(_)) => true,
476        ("redis", ExternalBinding::Redis(_)) => true,
477        ("ai", ExternalBinding::Ai(_)) => true,
478        (_, ExternalBinding::Custom(custom)) => custom.resource_type == resource_type,
479        _ => false,
480    };
481
482    if !valid {
483        return Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
484            resource_id: resource.id().to_string(),
485            expected: resource_type_str.to_string(),
486            actual: binding.binding_type().to_string(),
487        }));
488    }
489    Ok(())
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495    use crate::bindings::{KvBinding, StorageBinding};
496
497    #[test]
498    fn test_external_bindings_storage() {
499        let mut bindings = ExternalBindings::new();
500        bindings.insert(
501            "data-storage",
502            ExternalBinding::Storage(StorageBinding::s3("my-bucket")),
503        );
504
505        assert!(bindings.has("data-storage"));
506        assert!(bindings.get_storage("data-storage").unwrap().is_some());
507        assert!(bindings.get_queue("data-storage").is_err()); // Wrong type
508    }
509
510    #[test]
511    fn test_external_bindings_kv() {
512        let mut bindings = ExternalBindings::new();
513        bindings.insert(
514            "cache",
515            ExternalBinding::Kv(KvBinding::redis("redis://localhost:6379")),
516        );
517
518        assert!(bindings.has("cache"));
519        assert!(bindings.get_kv("cache").unwrap().is_some());
520        assert!(bindings.get_storage("cache").is_err()); // Wrong type
521    }
522
523    #[test]
524    fn test_external_bindings_ai() {
525        use crate::bindings::ExternalAiBinding;
526
527        let mut bindings = ExternalBindings::new();
528        bindings.insert(
529            "llm",
530            ExternalBinding::Ai(
531                ExternalAiBinding {
532                    provider: "openai".to_string(),
533                    api_key: "sk-test".into(),
534                }
535                .into(),
536            ),
537        );
538
539        assert!(bindings.has("llm"));
540        assert_eq!(bindings.get("llm").unwrap().binding_type(), "ai");
541        assert!(matches!(
542            bindings.get_ai("llm").unwrap().unwrap(),
543            ExternalAi::ApiKey(b) if b.provider == "openai"
544        ));
545        assert!(bindings.get_kv("llm").is_err()); // Wrong type
546    }
547
548    fn zone_binding(fields: serde_json::Value) -> ExternalBinding {
549        let mut value = serde_json::json!({ "type": "acme/dns-zone", "service": "route53" });
550        value
551            .as_object_mut()
552            .unwrap()
553            .extend(fields.as_object().unwrap().clone());
554        serde_json::from_value(value).unwrap()
555    }
556
557    fn zone_descriptor() -> ResourceTypeDescriptor {
558        serde_json::from_value(serde_json::json!({
559            "lifecycles": ["frozen", "live"],
560            "holdsData": false,
561            "setup": { "cloudformation": [], "terraform": [], "helm": ["kubernetes"], "importers": [] },
562            "controllerPlatforms": [],
563            "permissionSets": [],
564            "link": { "permissionSets": [] },
565            "schemas": {
566                "config": {},
567                "outputs": {
568                    "type": "object",
569                    "required": ["zoneId"],
570                    "properties": { "zoneId": { "type": "string" }, "ttl": { "type": ["integer", "null"] } }
571                }
572            }
573        }))
574        .unwrap()
575    }
576
577    /// A custom binding reads back as it was written, and becomes the resource's outputs and the
578    /// value a linked workload gets.
579    #[test]
580    fn a_custom_binding_is_the_resource_s_outputs() {
581        let json =
582            serde_json::json!({ "type": "acme/dns-zone", "service": "route53", "zoneId": "Z1" });
583        let binding: ExternalBinding = serde_json::from_value(json.clone()).unwrap();
584        assert_eq!(serde_json::to_value(&binding).unwrap(), json);
585        assert_eq!(binding.binding_type(), "acme/dns-zone");
586        assert_eq!(
587            serde_json::to_value(binding.to_resource_outputs().unwrap()).unwrap(),
588            serde_json::json!({ "type": "acme/dns-zone", "zoneId": "Z1" })
589        );
590        assert_eq!(
591            binding.to_env_binding_value().unwrap(),
592            serde_json::json!({ "service": "route53", "zoneId": "Z1" })
593        );
594    }
595
596    /// A malformed built-in binding, a reserved prefix and an unknown plain tag stay errors.
597    #[test]
598    fn only_an_extension_s_type_reads_as_a_custom_binding() {
599        for json in [
600            r#"{"type":"storage","service":"bogus","bucketName":"b"}"#,
601            r#"{"type":"alien/zone","service":"route53","zoneId":"Z1"}"#,
602            r#"{"type":"storge","service":"s3","bucketName":"b"}"#,
603        ] {
604            assert!(
605                serde_json::from_str::<ExternalBinding>(json).is_err(),
606                "{json} must not read"
607            );
608        }
609    }
610
611    #[test]
612    fn a_custom_binding_matches_only_its_own_type() {
613        let zone = Resource::new(
614            crate::CustomResource::from_untagged(
615                "acme/dns-zone",
616                serde_json::json!({ "id": "zone", "domain": "a.example" }),
617            )
618            .unwrap(),
619        );
620        let other = Resource::new(
621            crate::CustomResource::from_untagged(
622                "acme/record",
623                serde_json::json!({ "id": "zone" }),
624            )
625            .unwrap(),
626        );
627        let binding = zone_binding(serde_json::json!({ "zoneId": "Z1" }));
628        assert!(validate_binding_type(&zone, &binding).is_ok());
629        assert!(validate_binding_type(&other, &binding).is_err());
630        let storage = Resource::new(crate::Storage::new("zone".to_string()).build());
631        assert!(validate_binding_type(&storage, &binding).is_err());
632    }
633
634    #[test]
635    fn a_custom_binding_is_checked_against_the_type_s_outputs() {
636        let descriptor = zone_descriptor();
637        assert!(zone_binding(serde_json::json!({ "zoneId": "Z1" }))
638            .as_custom()
639            .validate(&descriptor)
640            .is_ok());
641        assert!(
642            zone_binding(serde_json::json!({ "zoneId": "Z1", "ttl": 60 }))
643                .as_custom()
644                .validate(&descriptor)
645                .is_ok()
646        );
647        for (fields, problem) in [
648            (serde_json::json!({}), "the binding has no 'zoneId'"),
649            (
650                serde_json::json!({ "zoneID": "Z1", "zoneId": "Z1" }),
651                "'zoneID' is not one of the outputs its schema names",
652            ),
653            (
654                serde_json::json!({ "zoneId": 7 }),
655                "'zoneId' is number, where the outputs schema says string",
656            ),
657            (
658                serde_json::json!({ "zoneId": "Z1", "ttl": "60" }),
659                "'ttl' is string, where the outputs schema says integer or null",
660            ),
661        ] {
662            let error = zone_binding(fields.clone())
663                .as_custom()
664                .validate(&descriptor)
665                .unwrap_err();
666            assert!(error.contains(problem), "{fields}: {error}");
667        }
668    }
669
670    impl ExternalBinding {
671        fn as_custom(&self) -> &CustomExternalBinding {
672            match self {
673                ExternalBinding::Custom(custom) => custom,
674                other => panic!("{other:?} is not custom"),
675            }
676        }
677    }
678
679    #[test]
680    fn external_ai_bedrock_with_ambient_credentials_parses_and_reaches_the_workload() {
681        let binding: ExternalBinding = serde_json::from_value(serde_json::json!({
682            "type": "ai", "service": "bedrock", "region": "us-east-1"
683        }))
684        .expect("ambient Bedrock external binding should parse");
685
686        // The workload env value is the first-class Bedrock binding: no key, no secret.
687        let value = binding.to_env_binding_value().unwrap();
688        assert_eq!(
689            value,
690            serde_json::json!({"service": "bedrock", "region": "us-east-1"})
691        );
692        assert_eq!(
693            serde_json::from_value::<crate::bindings::AiBinding>(value).unwrap(),
694            crate::bindings::AiBinding::bedrock("us-east-1")
695        );
696        // Round-trips as stored.
697        let stored = serde_json::to_value(&binding).unwrap();
698        assert_eq!(
699            serde_json::from_value::<ExternalBinding>(stored).unwrap(),
700            binding
701        );
702    }
703
704    #[test]
705    fn external_ai_byo_key_input_still_parses_unchanged() {
706        let binding: ExternalBinding = serde_json::from_value(serde_json::json!({
707            "type": "ai", "provider": "openai", "apiKey": "sk-test"
708        }))
709        .expect("stored BYO-key input must keep parsing");
710        assert_eq!(
711            binding.to_env_binding_value().unwrap(),
712            serde_json::json!({
713                "service": "external-ai", "provider": "openai", "apiKey": "sk-test"
714            })
715        );
716    }
717
718    #[test]
719    fn external_ai_rejects_a_bedrock_binding_without_region() {
720        assert!(
721            serde_json::from_value::<ExternalBinding>(serde_json::json!({
722                "type": "ai", "service": "bedrock"
723            }))
724            .is_err()
725        );
726    }
727
728    #[test]
729    fn test_external_bindings_serialization() {
730        let mut bindings = ExternalBindings::new();
731        bindings.insert(
732            "data",
733            ExternalBinding::Storage(StorageBinding::s3("test-bucket")),
734        );
735
736        let json = serde_json::to_string(&bindings).unwrap();
737        let deserialized: ExternalBindings = serde_json::from_str(&json).unwrap();
738        assert_eq!(bindings, deserialized);
739    }
740}
741
742/// Resource types an installer can bind to existing infrastructure with an
743/// [`ExternalBinding`].
744pub const EXTERNAL_BINDING_TYPES: &[&str] = &[
745    "storage",
746    "queue",
747    "kv",
748    "artifact-registry",
749    "vault",
750    "postgres",
751    "redis",
752    "ai",
753];