Skip to main content

alien_core/bindings/
mod.rs

1//! Type-safe binding parameter definitions
2//!
3//! This module defines structs that represent the runtime parameters needed by bindings
4//! to interact with cloud resources. These structs are used by:
5//! - Controllers when returning binding parameters directly
6//! - Template generators when creating CloudFormation/Terraform templates (using Fn::ToJsonString)
7//! - Bindings when consuming runtime parameters (parsing JSON)
8//!
9//! This provides type safety and ensures consistency across all parts of the system.
10
11use crate::error::ErrorData;
12use alien_error::{AlienError, Context, IntoAlienError};
13use serde::{Deserialize, Serialize};
14use serde_json::Value as JsonValue;
15use std::collections::HashMap;
16
17mod ai;
18mod artifact_registry;
19mod build;
20mod container;
21mod container_apps_environment;
22mod key;
23mod kv;
24mod postgres;
25mod queue;
26mod sandbox;
27mod service_account;
28mod storage;
29mod vault;
30mod worker;
31
32pub use ai::{AiBinding, BedrockAiBinding, ExternalAiBinding, FoundryAiBinding, VertexAiBinding};
33pub use artifact_registry::{
34    AcrArtifactRegistryBinding, ArtifactRegistryBinding, EcrArtifactRegistryBinding,
35    GarArtifactRegistryBinding, LocalArtifactRegistryBinding, LEGACY_REPOSITORY_PUSH_REFUSAL,
36};
37pub use build::{
38    AcaBuildBinding, BuildBinding, CloudbuildBuildBinding, CodebuildBuildBinding, LocalBuildBinding,
39};
40pub use container::{
41    ContainerBinding, HorizonContainerBinding, KubernetesContainerBinding, LocalContainerBinding,
42};
43pub use container_apps_environment::ContainerAppsEnvironmentBinding;
44pub use key::{AwsKmsKeyBinding, AzureKeyVaultKeyBinding, GcpCloudKmsKeyBinding, KeyBinding};
45pub use kv::{
46    DynamodbKvBinding, FirestoreKvBinding, KvBinding, LocalKvBinding, RedisKvBinding,
47    TableStorageKvBinding,
48};
49pub use postgres::{
50    AuroraPostgresBinding, CloudSqlPostgresBinding, ExternalPostgresBinding,
51    ExternalPostgresSslMode, FlexibleServerPostgresBinding, LocalPostgresBinding, PostgresBinding,
52};
53pub use queue::{
54    LocalHttpQueueBinding, LocalQueueBinding, PubSubQueueBinding, QueueBinding,
55    ServiceBusQueueBinding, SqsQueueBinding,
56};
57pub use sandbox::{
58    AwsSandboxBinding, AzureSandboxBinding, GcpAgentPlatformSandboxBinding,
59    KubernetesSandboxBinding, LocalSandboxBinding, SandboxBinding, SandboxEgressBinding,
60    SandboxEgressGateway, SandboxEgressReplicas, SandboxEgressSigningKey,
61};
62pub use service_account::{
63    AwsServiceAccountBinding, AzureServiceAccountBinding, GcpServiceAccountBinding,
64    ServiceAccountBinding,
65};
66pub use storage::{
67    BlobStorageBinding, GcsStorageBinding, LocalStorageBinding, S3StorageBinding, StorageBinding,
68};
69pub use vault::{
70    KeyVaultBinding, KubernetesSecretVaultBinding, LocalVaultBinding, ParameterStoreVaultBinding,
71    SecretManagerVaultBinding, VaultBinding,
72};
73pub use worker::{
74    CloudRunWorkerBinding, ContainerAppWorkerBinding, KubernetesWorkerBinding, LambdaWorkerBinding,
75    LocalWorkerBinding, WorkerBinding,
76};
77
78/// Represents a value that can be either a concrete value, a template expression,
79/// or a reference to a Kubernetes Secret
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
82#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
83#[serde(untagged)]
84pub enum BindingValue<T> {
85    /// A concrete value (used by controllers)
86    Value(T),
87    /// A Kubernetes Secret reference (must come before Expression)
88    #[serde(rename_all = "camelCase")]
89    SecretRef { secret_ref: SecretReference },
90    /// A template expression (used by IaC template generators)
91    #[cfg_attr(feature = "jsonschema", schemars(skip))]
92    Expression(JsonValue),
93}
94
95/// Reference to a Kubernetes Secret
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
98#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
99#[serde(rename_all = "camelCase")]
100pub struct SecretReference {
101    pub name: String,
102    pub key: String,
103}
104
105impl<T> BindingValue<T> {
106    /// Creates a concrete value
107    pub fn value(val: T) -> Self {
108        Self::Value(val)
109    }
110
111    /// Creates a template expression
112    pub fn expression(expr: JsonValue) -> Self {
113        Self::Expression(expr)
114    }
115
116    /// Extracts the concrete value, returning an error if this is a template expression or SecretRef
117    pub fn into_value(self, binding_name: &str, field_name: &str) -> crate::error::Result<T> {
118        match self {
119            BindingValue::Value(val) => Ok(val),
120            BindingValue::Expression(_) => Err(AlienError::new(ErrorData::BindingConfigInvalid {
121                binding_name: binding_name.to_string(),
122                reason: format!("Template expressions not supported in runtime bindings for field '{}'", field_name),
123            })),
124            BindingValue::SecretRef { .. } => Err(AlienError::new(ErrorData::BindingConfigInvalid {
125                binding_name: binding_name.to_string(),
126                reason: format!("SecretRef not resolved for field '{}' - this should have been resolved by the controller", field_name),
127            }))
128        }
129    }
130}
131
132impl<T> From<T> for BindingValue<T> {
133    fn from(val: T) -> Self {
134        Self::Value(val)
135    }
136}
137
138impl From<&str> for BindingValue<String> {
139    fn from(val: &str) -> Self {
140        Self::Value(val.to_string())
141    }
142}
143
144impl From<JsonValue> for BindingValue<String> {
145    fn from(val: JsonValue) -> Self {
146        Self::Expression(val)
147    }
148}
149
150/// Helper worker to serialize binding struct as JSON for environment variables
151pub fn serialize_binding_as_env_var<T: Serialize>(
152    binding_name: &str,
153    binding: &T,
154) -> crate::error::Result<HashMap<String, String>> {
155    let mut env_vars = HashMap::new();
156    let key = binding_env_var_name(binding_name);
157    let binding_json = serde_json::to_string(binding).into_alien_error().context(
158        ErrorData::BindingConfigInvalid {
159            binding_name: binding_name.to_string(),
160            reason: "Failed to serialize binding to JSON".to_string(),
161        },
162    )?;
163    env_vars.insert(key, binding_json);
164    Ok(env_vars)
165}
166
167/// Helper worker to serialize binding struct for CloudFormation templates
168pub fn serialize_binding_for_template<T: Serialize>(
169    binding_name: &str,
170    binding: &T,
171) -> crate::error::Result<HashMap<String, JsonValue>> {
172    let mut env_vars = HashMap::new();
173    let key = binding_env_var_name(binding_name);
174    let binding_json = serde_json::to_value(binding).into_alien_error().context(
175        ErrorData::BindingConfigInvalid {
176            binding_name: binding_name.to_string(),
177            reason: "Failed to serialize binding to JSON for template".to_string(),
178        },
179    )?;
180
181    // Wrap in Fn::ToJsonString for CloudFormation
182    env_vars.insert(
183        key,
184        JsonValue::Object({
185            let mut map = serde_json::Map::new();
186            map.insert("Fn::ToJsonString".to_string(), binding_json);
187            map
188        }),
189    );
190
191    Ok(env_vars)
192}
193
194/// Helper worker to generate the environment variable name for a binding
195pub fn binding_env_var_name(binding_name: &str) -> String {
196    format!(
197        "ALIEN_{}_BINDING",
198        binding_name.replace('-', "_").to_uppercase()
199    )
200}
201
202/// Helper worker to parse binding from environment variable
203pub fn parse_binding_from_env<T: for<'de> Deserialize<'de>>(
204    env: &HashMap<String, String>,
205    binding_name: &str,
206) -> crate::error::Result<T> {
207    let key = binding_env_var_name(binding_name);
208    let json_str = env.get(&key).ok_or_else(|| {
209        AlienError::new(ErrorData::BindingEnvVarMissing {
210            binding_name: binding_name.to_string(),
211            env_var: key.clone(),
212        })
213    })?;
214
215    let mut value: JsonValue = serde_json::from_str(json_str).into_alien_error().context(
216        ErrorData::BindingJsonParseFailed {
217            binding_name: binding_name.to_string(),
218            reason: "Invalid JSON format".to_string(),
219        },
220    )?;
221    resolve_binding_env_refs(&mut value, env, binding_name)?;
222    serde_json::from_value(value)
223        .into_alien_error()
224        .context(ErrorData::BindingJsonParseFailed {
225            binding_name: binding_name.to_string(),
226            reason: "Invalid JSON format".to_string(),
227        })
228}
229
230/// Resolve projected Secret values after parsing JSON, preserving their exact bytes.
231/// Values read from the environment are literals, never recursively interpreted.
232pub fn resolve_binding_env_refs(
233    value: &mut JsonValue,
234    env: &HashMap<String, String>,
235    binding_name: &str,
236) -> crate::error::Result<()> {
237    match value {
238        JsonValue::Object(fields) => {
239            if fields.len() == 1 && fields.contains_key("envRef") {
240                let name = fields["envRef"].as_str().ok_or_else(|| {
241                    AlienError::new(ErrorData::BindingConfigInvalid {
242                        binding_name: binding_name.to_string(),
243                        reason: "envRef must name an environment variable".to_string(),
244                    })
245                })?;
246                let secret = env.get(name).ok_or_else(|| {
247                    AlienError::new(ErrorData::BindingEnvVarMissing {
248                        binding_name: binding_name.to_string(),
249                        env_var: name.to_string(),
250                    })
251                })?;
252                *value = JsonValue::String(secret.clone());
253            } else {
254                for field in fields.values_mut() {
255                    resolve_binding_env_refs(field, env, binding_name)?;
256                }
257            }
258        }
259        JsonValue::Array(items) => {
260            for item in items {
261                resolve_binding_env_refs(item, env, binding_name)?;
262            }
263        }
264        _ => {}
265    }
266    Ok(())
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use crate::bindings::{ArtifactRegistryBinding, BuildBinding, StorageBinding};
273    use serde_json::json;
274    use std::collections::HashMap;
275
276    #[test]
277    fn environment_references_are_resolved_as_literals() {
278        let original = json!({"nested": [{"envRef": "SECRET"}], "literal": "$(SECRET)"});
279        let secret = "{\"envRef\":\"OTHER\"}\n\\";
280        let env = HashMap::from([("SECRET".into(), secret.into())]);
281        let mut value = original.clone();
282        resolve_binding_env_refs(&mut value, &env, "database").unwrap();
283        assert_eq!(value, json!({"nested": [secret], "literal": "$(SECRET)"}));
284        let mut missing = original;
285        assert!(resolve_binding_env_refs(&mut missing, &HashMap::new(), "database").is_err());
286        let mut invalid = json!({"envRef": 7});
287        assert!(resolve_binding_env_refs(&mut invalid, &env, "database").is_err());
288    }
289
290    #[test]
291    fn test_serialize_storage_binding_as_env_var() {
292        let binding = StorageBinding::s3("my-bucket");
293
294        let env_vars = serialize_binding_as_env_var("TEST", &binding).unwrap();
295
296        assert_eq!(env_vars.len(), 1);
297        let json_str = env_vars.get("ALIEN_TEST_BINDING").unwrap();
298        let parsed: StorageBinding = serde_json::from_str(json_str).unwrap();
299        assert_eq!(binding, parsed);
300    }
301
302    #[test]
303    fn test_serialize_binding_for_template() {
304        let binding = StorageBinding::S3(S3StorageBinding::bucket(BindingValue::expression(
305            json!({"Ref": "MyBucket"}),
306        )));
307
308        let env_vars = serialize_binding_for_template("TEST", &binding).unwrap();
309
310        assert_eq!(env_vars.len(), 1);
311        let fn_to_json_string = env_vars.get("ALIEN_TEST_BINDING").unwrap();
312
313        // Should be wrapped in Fn::ToJsonString
314        assert!(fn_to_json_string.get("Fn::ToJsonString").is_some());
315    }
316
317    #[test]
318    fn test_artifact_registry_binding_roundtrip() {
319        let binding = ArtifactRegistryBinding::ecr(
320            "my-project",
321            Some("arn:aws:iam::123456789012:role/PullRole".to_string()),
322            None::<String>,
323        );
324
325        let env_vars = serialize_binding_as_env_var("TEST", &binding).unwrap();
326
327        let reconstructed: ArtifactRegistryBinding =
328            parse_binding_from_env(&env_vars, "TEST").unwrap();
329        assert_eq!(binding, reconstructed);
330    }
331
332    #[test]
333    fn test_service_type_serialization() {
334        // Test S3 storage
335        let s3_binding = StorageBinding::s3("my-bucket");
336        let s3_json = serde_json::to_string(&s3_binding).unwrap();
337        assert!(s3_json.contains(r#""service":"s3""#));
338
339        // Test ECR registry
340        let ecr_binding = ArtifactRegistryBinding::ecr("my-repo", None::<String>, None::<String>);
341        let ecr_json = serde_json::to_string(&ecr_binding).unwrap();
342        assert!(ecr_json.contains(r#""service":"ecr""#));
343
344        // Test CodeBuild
345        let build_binding = BuildBinding::codebuild("my-project", HashMap::new(), None);
346        let build_json = serde_json::to_string(&build_binding).unwrap();
347        assert!(build_json.contains(r#""service":"codebuild""#));
348    }
349
350    #[test]
351    fn test_cross_provider_bindings() {
352        // Test that we can mix different service types in one environment
353        let storage_binding = StorageBinding::s3("prod-bucket");
354        let registry_binding = ArtifactRegistryBinding::acr("myregistry", "mygroup");
355        let build_binding = BuildBinding::cloudbuild(
356            HashMap::new(),
357            "build@project.iam.gserviceaccount.com",
358            None,
359        );
360
361        // Serialize all bindings
362        let storage_env = serialize_binding_as_env_var("STORAGE", &storage_binding).unwrap();
363        let registry_env = serialize_binding_as_env_var("REGISTRY", &registry_binding).unwrap();
364        let build_env = serialize_binding_as_env_var("BUILD", &build_binding).unwrap();
365
366        // All should work together
367        assert!(storage_env.contains_key("ALIEN_STORAGE_BINDING"));
368        assert!(registry_env.contains_key("ALIEN_REGISTRY_BINDING"));
369        assert!(build_env.contains_key("ALIEN_BUILD_BINDING"));
370    }
371
372    #[test]
373    fn test_binding_value_secret_ref() {
374        // Test SecretRef serialization
375        let secret_ref: BindingValue<String> = BindingValue::SecretRef {
376            secret_ref: SecretReference {
377                name: "my-secret".to_string(),
378                key: "password".to_string(),
379            },
380        };
381
382        let json = serde_json::to_string(&secret_ref).unwrap();
383        assert!(json.contains(r#""secretRef""#));
384        assert!(json.contains(r#""name":"my-secret""#));
385        assert!(json.contains(r#""key":"password""#));
386
387        // Test deserialization
388        let parsed: BindingValue<String> = serde_json::from_str(&json).unwrap();
389        assert_eq!(secret_ref, parsed);
390    }
391
392    #[test]
393    fn test_binding_value_into_value_secret_ref() {
394        let secret_ref: BindingValue<String> = BindingValue::SecretRef {
395            secret_ref: SecretReference {
396                name: "my-secret".to_string(),
397                key: "password".to_string(),
398            },
399        };
400
401        let result = secret_ref.into_value("test", "password");
402        assert!(result.is_err());
403        assert!(result
404            .unwrap_err()
405            .to_string()
406            .contains("SecretRef not resolved"));
407    }
408
409    #[test]
410    fn test_binding_value_variants() {
411        // Test Value variant
412        let value: BindingValue<String> = BindingValue::value("test".to_string());
413        assert_eq!(value.into_value("test", "field").unwrap(), "test");
414
415        // Test Expression variant
416        let expr: BindingValue<String> = BindingValue::expression(json!({"Ref": "Test"}));
417        assert!(expr.into_value("test", "field").is_err());
418    }
419}