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,
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    serde_json::from_str(json_str)
216        .into_alien_error()
217        .context(ErrorData::BindingJsonParseFailed {
218            binding_name: binding_name.to_string(),
219            reason: "Invalid JSON format".to_string(),
220        })
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use crate::bindings::{ArtifactRegistryBinding, BuildBinding, StorageBinding};
227    use serde_json::json;
228    use std::collections::HashMap;
229
230    #[test]
231    fn test_serialize_storage_binding_as_env_var() {
232        let binding = StorageBinding::s3("my-bucket");
233
234        let env_vars = serialize_binding_as_env_var("TEST", &binding).unwrap();
235
236        assert_eq!(env_vars.len(), 1);
237        let json_str = env_vars.get("ALIEN_TEST_BINDING").unwrap();
238        let parsed: StorageBinding = serde_json::from_str(json_str).unwrap();
239        assert_eq!(binding, parsed);
240    }
241
242    #[test]
243    fn test_serialize_binding_for_template() {
244        let binding = StorageBinding::S3(S3StorageBinding::bucket(BindingValue::expression(
245            json!({"Ref": "MyBucket"}),
246        )));
247
248        let env_vars = serialize_binding_for_template("TEST", &binding).unwrap();
249
250        assert_eq!(env_vars.len(), 1);
251        let fn_to_json_string = env_vars.get("ALIEN_TEST_BINDING").unwrap();
252
253        // Should be wrapped in Fn::ToJsonString
254        assert!(fn_to_json_string.get("Fn::ToJsonString").is_some());
255    }
256
257    #[test]
258    fn test_artifact_registry_binding_roundtrip() {
259        let binding = ArtifactRegistryBinding::ecr(
260            "my-project",
261            Some("arn:aws:iam::123456789012:role/PullRole".to_string()),
262            None::<String>,
263        );
264
265        let env_vars = serialize_binding_as_env_var("TEST", &binding).unwrap();
266
267        let reconstructed: ArtifactRegistryBinding =
268            parse_binding_from_env(&env_vars, "TEST").unwrap();
269        assert_eq!(binding, reconstructed);
270    }
271
272    #[test]
273    fn test_service_type_serialization() {
274        // Test S3 storage
275        let s3_binding = StorageBinding::s3("my-bucket");
276        let s3_json = serde_json::to_string(&s3_binding).unwrap();
277        assert!(s3_json.contains(r#""service":"s3""#));
278
279        // Test ECR registry
280        let ecr_binding = ArtifactRegistryBinding::ecr("my-repo", None::<String>, None::<String>);
281        let ecr_json = serde_json::to_string(&ecr_binding).unwrap();
282        assert!(ecr_json.contains(r#""service":"ecr""#));
283
284        // Test CodeBuild
285        let build_binding = BuildBinding::codebuild("my-project", HashMap::new(), None);
286        let build_json = serde_json::to_string(&build_binding).unwrap();
287        assert!(build_json.contains(r#""service":"codebuild""#));
288    }
289
290    #[test]
291    fn test_cross_provider_bindings() {
292        // Test that we can mix different service types in one environment
293        let storage_binding = StorageBinding::s3("prod-bucket");
294        let registry_binding = ArtifactRegistryBinding::acr("myregistry", "mygroup");
295        let build_binding = BuildBinding::cloudbuild(
296            HashMap::new(),
297            "build@project.iam.gserviceaccount.com",
298            None,
299        );
300
301        // Serialize all bindings
302        let storage_env = serialize_binding_as_env_var("STORAGE", &storage_binding).unwrap();
303        let registry_env = serialize_binding_as_env_var("REGISTRY", &registry_binding).unwrap();
304        let build_env = serialize_binding_as_env_var("BUILD", &build_binding).unwrap();
305
306        // All should work together
307        assert!(storage_env.contains_key("ALIEN_STORAGE_BINDING"));
308        assert!(registry_env.contains_key("ALIEN_REGISTRY_BINDING"));
309        assert!(build_env.contains_key("ALIEN_BUILD_BINDING"));
310    }
311
312    #[test]
313    fn test_binding_value_secret_ref() {
314        // Test SecretRef serialization
315        let secret_ref: BindingValue<String> = BindingValue::SecretRef {
316            secret_ref: SecretReference {
317                name: "my-secret".to_string(),
318                key: "password".to_string(),
319            },
320        };
321
322        let json = serde_json::to_string(&secret_ref).unwrap();
323        assert!(json.contains(r#""secretRef""#));
324        assert!(json.contains(r#""name":"my-secret""#));
325        assert!(json.contains(r#""key":"password""#));
326
327        // Test deserialization
328        let parsed: BindingValue<String> = serde_json::from_str(&json).unwrap();
329        assert_eq!(secret_ref, parsed);
330    }
331
332    #[test]
333    fn test_binding_value_into_value_secret_ref() {
334        let secret_ref: BindingValue<String> = BindingValue::SecretRef {
335            secret_ref: SecretReference {
336                name: "my-secret".to_string(),
337                key: "password".to_string(),
338            },
339        };
340
341        let result = secret_ref.into_value("test", "password");
342        assert!(result.is_err());
343        assert!(result
344            .unwrap_err()
345            .to_string()
346            .contains("SecretRef not resolved"));
347    }
348
349    #[test]
350    fn test_binding_value_variants() {
351        // Test Value variant
352        let value: BindingValue<String> = BindingValue::value("test".to_string());
353        assert_eq!(value.into_value("test", "field").unwrap(), "test");
354
355        // Test Expression variant
356        let expr: BindingValue<String> = BindingValue::expression(json!({"Ref": "Test"}));
357        assert!(expr.into_value("test", "field").is_err());
358    }
359}