Skip to main content

alien_core/import/data/
mod.rs

1//! Typed ImportData payloads by cloud and resource.
2
3use serde::{Deserialize, Deserializer};
4
5pub mod aws;
6pub mod azure;
7pub mod gcp;
8pub mod kubernetes_cluster;
9pub mod signing_verifier;
10
11pub use aws::{
12    AwsAiImportData, AwsArtifactRegistryImportData, AwsBuildImportData,
13    AwsComputeClusterImportData, AwsEmailDkimTokenImportData, AwsEmailDomainImportData,
14    AwsEmailImportData, AwsKeyImportData, AwsKvImportData, AwsNetworkImportData,
15    AwsOpenSearchImportData, AwsPostgresImportData, AwsQueueImportData, AwsRedisImportData,
16    AwsRemoteBindingsImportData, AwsRemoteStackManagementImportData, AwsSandboxImportData,
17    AwsSandboxNetwork, AwsServiceAccountImportData, AwsStorageImportData, AwsVaultImportData,
18    AwsWorkerImportData,
19};
20pub use azure::{
21    AzureAiImportData, AzureArtifactRegistryImportData, AzureBuildImportData,
22    AzureComputeClusterImportData, AzureContainerAppsEnvironmentImportData,
23    AzureFlexibleServerPostgresImportData, AzureKeyImportData, AzureKvImportData,
24    AzureManagedRedisImportData, AzureNetworkImportData, AzureQueueImportData,
25    AzureRemoteBindingsImportData, AzureRemoteStackManagementImportData,
26    AzureResourceGroupImportData, AzureSandboxImportData, AzureSandboxNetwork,
27    AzureServiceAccountImportData, AzureServiceActivationImportData,
28    AzureServiceBusNamespaceImportData, AzureStorageAccountImportData, AzureStorageImportData,
29    AzureVaultImportData, AzureWorkerImportData,
30};
31pub use gcp::{
32    GcpAgentPlatformEngineImportData, GcpAiImportData, GcpArtifactRegistryImportData,
33    GcpBuildImportData, GcpComputeClusterImportData, GcpKeyImportData, GcpKvImportData,
34    GcpMemorystoreImportData, GcpNetworkImportData, GcpPostgresImportData, GcpQueueImportData,
35    GcpRemoteBindingsImportData, GcpRemoteStackManagementImportData, GcpSandboxImportData,
36    GcpSandboxNetwork, GcpServiceAccountImportData, GcpServiceActivationImportData,
37    GcpStorageImportData, GcpVaultImportData, GcpWorkerImportData,
38};
39pub use kubernetes_cluster::{
40    AzureApplicationGatewayForContainersBootstrap, KubernetesClusterImportData,
41};
42pub use signing_verifier::SigningVerifierImportData;
43
44pub(crate) fn deserialize_bool_from_bool_or_string<'de, D>(
45    deserializer: D,
46) -> Result<bool, D::Error>
47where
48    D: Deserializer<'de>,
49{
50    bool_from_bool_or_string(serde_json::Value::deserialize(deserializer)?)
51}
52
53/// Optional form of [`deserialize_bool_from_bool_or_string`]: `null` stays `None`. Pair it with
54/// `#[serde(default)]` so an absent field is also `None`.
55pub(crate) fn deserialize_optional_bool_from_bool_or_string<'de, D>(
56    deserializer: D,
57) -> Result<Option<bool>, D::Error>
58where
59    D: Deserializer<'de>,
60{
61    match serde_json::Value::deserialize(deserializer)? {
62        serde_json::Value::Null => Ok(None),
63        value => bool_from_bool_or_string(value).map(Some),
64    }
65}
66
67fn bool_from_bool_or_string<E: serde::de::Error>(value: serde_json::Value) -> Result<bool, E> {
68    match value {
69        serde_json::Value::Bool(value) => Ok(value),
70        serde_json::Value::String(value) if value.eq_ignore_ascii_case("true") => Ok(true),
71        serde_json::Value::String(value) if value.eq_ignore_ascii_case("false") => Ok(false),
72        other => Err(E::custom(format!(
73            "expected boolean or boolean string, got {other}"
74        ))),
75    }
76}
77
78/// A single port from a JSON number or a numeric string (CloudFormation stringifies every leaf
79/// of a custom resource's properties).
80pub(crate) fn deserialize_u16_from_number_or_string<'de, D>(
81    deserializer: D,
82) -> Result<u16, D::Error>
83where
84    D: Deserializer<'de>,
85{
86    match serde_json::Value::deserialize(deserializer)? {
87        serde_json::Value::Number(number) => number
88            .as_u64()
89            .and_then(|n| u16::try_from(n).ok())
90            .ok_or_else(|| serde::de::Error::custom(format!("port {number} is out of range"))),
91        serde_json::Value::String(text) => text
92            .parse::<u16>()
93            .map_err(|_| serde::de::Error::custom(format!("expected a port number, got {text:?}"))),
94        other => Err(serde::de::Error::custom(format!(
95            "expected a port number or numeric string, got {other}"
96        ))),
97    }
98}
99
100/// Same reason as the boolean helper: CloudFormation stringifies the leaves of a custom
101/// resource's properties, so a declared port list arrives as `["3000"]` rather than `[3000]`.
102pub(crate) fn deserialize_u16_vec_from_numbers_or_strings<'de, D>(
103    deserializer: D,
104) -> Result<Vec<u16>, D::Error>
105where
106    D: Deserializer<'de>,
107{
108    let values = Vec::<serde_json::Value>::deserialize(deserializer)?;
109    values
110        .into_iter()
111        .map(|value| match value {
112            serde_json::Value::Number(number) => number
113                .as_u64()
114                .and_then(|n| u16::try_from(n).ok())
115                .ok_or_else(|| serde::de::Error::custom(format!("port {number} is out of range"))),
116            serde_json::Value::String(text) => text.parse::<u16>().map_err(|_| {
117                serde::de::Error::custom(format!("expected a port number, got {text:?}"))
118            }),
119            other => Err(serde::de::Error::custom(format!(
120                "expected a port number or numeric string, got {other}"
121            ))),
122        })
123        .collect()
124}
125
126#[cfg(all(test, feature = "jsonschema"))]
127mod schema_snapshots {
128    use super::*;
129    use indexmap::IndexMap;
130
131    fn schema<T: schemars::JsonSchema>() -> serde_json::Value {
132        let mut schema =
133            serde_json::to_value(schemars::schema_for!(T)).expect("schema should serialize");
134        // Dependency features can enable preserve_order; object key order is not schema data.
135        schema.sort_all_objects();
136        schema
137    }
138
139    #[test]
140    fn import_data_schema_snapshot() {
141        let schemas = IndexMap::from([
142            ("aws_ai", schema::<AwsAiImportData>()),
143            ("signing_verifier", schema::<SigningVerifierImportData>()),
144            (
145                "aws_artifact_registry",
146                schema::<AwsArtifactRegistryImportData>(),
147            ),
148            ("aws_build", schema::<AwsBuildImportData>()),
149            (
150                "aws_compute_cluster",
151                schema::<AwsComputeClusterImportData>(),
152            ),
153            ("aws_email", schema::<AwsEmailImportData>()),
154            ("aws_function", schema::<AwsWorkerImportData>()),
155            ("aws_kv", schema::<AwsKvImportData>()),
156            ("aws_key", schema::<AwsKeyImportData>()),
157            ("aws_sandbox", schema::<AwsSandboxImportData>()),
158            ("aws_network", schema::<AwsNetworkImportData>()),
159            ("aws_open_search", schema::<AwsOpenSearchImportData>()),
160            ("aws_postgres", schema::<AwsPostgresImportData>()),
161            ("aws_redis", schema::<AwsRedisImportData>()),
162            ("aws_queue", schema::<AwsQueueImportData>()),
163            (
164                "aws_remote_stack_management",
165                schema::<AwsRemoteStackManagementImportData>(),
166            ),
167            (
168                "aws_service_account",
169                schema::<AwsServiceAccountImportData>(),
170            ),
171            ("aws_storage", schema::<AwsStorageImportData>()),
172            ("aws_vault", schema::<AwsVaultImportData>()),
173            ("azure_ai", schema::<AzureAiImportData>()),
174            (
175                "azure_artifact_registry",
176                schema::<AzureArtifactRegistryImportData>(),
177            ),
178            ("azure_build", schema::<AzureBuildImportData>()),
179            (
180                "azure_container_apps_environment",
181                schema::<AzureContainerAppsEnvironmentImportData>(),
182            ),
183            (
184                "azure_compute_cluster",
185                schema::<AzureComputeClusterImportData>(),
186            ),
187            ("azure_function", schema::<AzureWorkerImportData>()),
188            ("azure_kv", schema::<AzureKvImportData>()),
189            ("azure_key", schema::<AzureKeyImportData>()),
190            ("azure_sandbox", schema::<AzureSandboxImportData>()),
191            ("azure_network", schema::<AzureNetworkImportData>()),
192            (
193                "azure_postgres",
194                schema::<AzureFlexibleServerPostgresImportData>(),
195            ),
196            ("azure_queue", schema::<AzureQueueImportData>()),
197            ("azure_redis", schema::<AzureManagedRedisImportData>()),
198            (
199                "azure_remote_stack_management",
200                schema::<AzureRemoteStackManagementImportData>(),
201            ),
202            (
203                "azure_resource_group",
204                schema::<AzureResourceGroupImportData>(),
205            ),
206            (
207                "azure_service_account",
208                schema::<AzureServiceAccountImportData>(),
209            ),
210            (
211                "azure_service_activation",
212                schema::<AzureServiceActivationImportData>(),
213            ),
214            (
215                "azure_service_bus_namespace",
216                schema::<AzureServiceBusNamespaceImportData>(),
217            ),
218            ("azure_storage", schema::<AzureStorageImportData>()),
219            (
220                "azure_storage_account",
221                schema::<AzureStorageAccountImportData>(),
222            ),
223            ("azure_vault", schema::<AzureVaultImportData>()),
224            (
225                "gcp_agent_platform_engine",
226                schema::<GcpAgentPlatformEngineImportData>(),
227            ),
228            ("gcp_ai", schema::<GcpAiImportData>()),
229            (
230                "gcp_artifact_registry",
231                schema::<GcpArtifactRegistryImportData>(),
232            ),
233            ("gcp_build", schema::<GcpBuildImportData>()),
234            (
235                "gcp_compute_cluster",
236                schema::<GcpComputeClusterImportData>(),
237            ),
238            ("gcp_function", schema::<GcpWorkerImportData>()),
239            ("gcp_kv", schema::<GcpKvImportData>()),
240            ("gcp_key", schema::<GcpKeyImportData>()),
241            ("gcp_network", schema::<GcpNetworkImportData>()),
242            ("gcp_postgres", schema::<GcpPostgresImportData>()),
243            ("gcp_redis", schema::<GcpMemorystoreImportData>()),
244            ("gcp_queue", schema::<GcpQueueImportData>()),
245            (
246                "gcp_remote_stack_management",
247                schema::<GcpRemoteStackManagementImportData>(),
248            ),
249            (
250                "kubernetes_cluster",
251                schema::<KubernetesClusterImportData>(),
252            ),
253            (
254                "gcp_service_account",
255                schema::<GcpServiceAccountImportData>(),
256            ),
257            (
258                "gcp_service_activation",
259                schema::<GcpServiceActivationImportData>(),
260            ),
261            ("gcp_sandbox", schema::<GcpSandboxImportData>()),
262            ("gcp_storage", schema::<GcpStorageImportData>()),
263            ("gcp_vault", schema::<GcpVaultImportData>()),
264        ]);
265
266        insta::assert_json_snapshot!("import_data_schemas", schemas);
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use serde_json::json;
274
275    #[test]
276    fn aws_redis_import_data_accepts_cloudformation_stringified_leaves() {
277        let redis: AwsRedisImportData = serde_json::from_value(json!({
278            "replicationGroupId": "rg",
279            "subnetGroupName": "subnets",
280            "securityGroupId": "sg-123",
281            "parameterGroupName": "params",
282            "authSecretArn": "arn:aws:secretsmanager:us-east-2:123456789012:secret:auth",
283            "endpoint": "rg.cache.amazonaws.com",
284            "port": "6379",
285            "nodeType": "cache.r7g.large",
286            "engineVersion": "7.2",
287            "highAvailability": "false",
288        }))
289        .expect("redis import data should parse CloudFormation's stringified leaves");
290        assert_eq!(redis.port, 6379);
291        assert!(!redis.high_availability);
292    }
293
294    #[test]
295    fn aws_postgres_import_data_accepts_cloudformation_stringified_leaves() {
296        let postgres: AwsPostgresImportData = serde_json::from_value(json!({
297            "clusterIdentifier": "db",
298            "instanceIdentifier": "db-1",
299            "subnetGroupName": "subnets",
300            "securityGroupId": "sg-123",
301            "passwordSecretArn": "arn:aws:secretsmanager:us-east-2:123456789012:secret:pw",
302            "managedPassword": "true",
303            "clusterEndpoint": "db.cluster.rds.amazonaws.com",
304            "database": "app",
305            "username": "app",
306            "engineVersion": "16.4",
307        }))
308        .expect("postgres import data should parse CloudFormation's stringified leaves");
309        assert!(postgres.managed_password);
310    }
311
312    #[test]
313    fn aws_import_data_accepts_cloudformation_stringified_leaves() {
314        let network: AwsNetworkImportData = serde_json::from_value(json!({
315            "vpcId": "vpc-123",
316            "cidrBlock": null,
317            "internetGatewayId": null,
318            "natGatewayId": null,
319            "eipAllocationId": null,
320            "publicSubnetIds": ["subnet-public"],
321            "privateSubnetIds": ["subnet-private"],
322            "publicRouteTableId": null,
323            "privateRouteTableId": null,
324            "securityGroupId": "sg-123",
325            "availabilityZones": [],
326            "isByoVpc": "true",
327        }))
328        .expect("network import data should parse");
329        assert!(network.is_byo_vpc);
330
331        let remote_stack_management: AwsRemoteStackManagementImportData =
332            serde_json::from_value(json!({
333                "roleName": "alien-manager",
334                "roleArn": "arn:aws:iam::123456789012:role/alien-manager",
335                "managementPermissionsApplied": "true",
336            }))
337            .expect("remote stack management import data should parse");
338        assert!(remote_stack_management.management_permissions_applied);
339
340        let service_account: AwsServiceAccountImportData = serde_json::from_value(json!({
341            "roleName": "alien-worker",
342            "roleArn": "arn:aws:iam::123456789012:role/alien-worker",
343            "stackPermissionsApplied": "false",
344        }))
345        .expect("service account import data should parse");
346        assert!(!service_account.stack_permissions_applied);
347
348        // CloudFormation stringifies every leaf of a custom resource's properties, so this is the
349        // shape the importer actually receives — a sandbox declared with open egress and a preview
350        // port reaches it as strings, and rejecting them fails the customer's stack at setup.
351        let sandbox: AwsSandboxImportData = serde_json::from_value(json!({
352            "imageIdentifier": "runner",
353            "imageArn": "arn:aws:lambda:us-east-2:123456789012:microvm-image/runner",
354            "imageVersion": "1",
355            "egressConnectorArns": [],
356            "allowEgress": "true",
357            "previewPorts": ["3000", "8080"],
358        }))
359        .expect("sandbox import data should parse CloudFormation's stringified leaves");
360        assert!(sandbox.allow_egress);
361        assert_eq!(sandbox.preview_ports, vec![3000, 8080]);
362
363        let native: AwsSandboxImportData = serde_json::from_value(json!({
364            "imageIdentifier": "runner",
365            "imageArn": "arn:aws:lambda:us-east-2:123456789012:microvm-image/runner",
366            "imageVersion": "1",
367            "egressConnectorArns": [],
368            "allowEgress": false,
369            "previewPorts": [3000],
370        }))
371        .expect("sandbox import data should still parse native JSON types");
372        assert!(!native.allow_egress);
373        assert_eq!(native.preview_ports, vec![3000]);
374    }
375
376    /// CloudFormation delivers every boolean property as a string, so a setup that declares a
377    /// customer encryption key or a CloudFormation-created EKS cluster registers with "true" or
378    /// "false" here. Rejecting the string form fails registration and rolls the customer's stack back.
379    #[test]
380    fn stringified_key_and_kubernetes_cluster_booleans_parse() {
381        let key = |probe: serde_json::Value| -> Result<AwsKeyImportData, serde_json::Error> {
382            let mut data = json!({ "keyArn": "arn:aws:kms:us-east-1:123456789012:key/k-1" });
383            if !probe.is_null() {
384                data["availabilityProbe"] = probe;
385            }
386            serde_json::from_value(data)
387        };
388        assert!(key(json!("true")).expect("string true").availability_probe);
389        assert!(
390            !key(json!("false"))
391                .expect("string false")
392                .availability_probe
393        );
394        assert!(key(json!(true)).expect("native true").availability_probe);
395        assert!(!key(json!(false)).expect("native false").availability_probe);
396        assert!(
397            !key(serde_json::Value::Null)
398                .expect("an absent probe defaults to false")
399                .availability_probe
400        );
401        assert!(
402            key(json!("yes")).is_err(),
403            "a non-boolean string must be rejected"
404        );
405        assert!(key(json!(1)).is_err(), "a number must be rejected");
406
407        let cluster = |ready: Option<serde_json::Value>| -> Result<
408            KubernetesClusterImportData,
409            serde_json::Error,
410        > {
411            let mut data = json!({
412                "provider": "eks",
413                "ownership": "managed",
414                "namespace": "alien",
415                "clusterName": "acme",
416            });
417            if let Some(ready) = ready {
418                data["cloudMetadataReady"] = ready;
419            }
420            serde_json::from_value(data)
421        };
422        assert_eq!(
423            cluster(Some(json!("true")))
424                .expect("string true")
425                .cloud_metadata_ready,
426            Some(true)
427        );
428        assert_eq!(
429            cluster(Some(json!("false")))
430                .expect("string false")
431                .cloud_metadata_ready,
432            Some(false)
433        );
434        assert_eq!(
435            cluster(Some(json!(true)))
436                .expect("native true")
437                .cloud_metadata_ready,
438            Some(true)
439        );
440        assert_eq!(
441            cluster(Some(json!(false)))
442                .expect("native false")
443                .cloud_metadata_ready,
444            Some(false)
445        );
446        assert_eq!(
447            cluster(Some(serde_json::Value::Null))
448                .expect("null")
449                .cloud_metadata_ready,
450            None
451        );
452        assert_eq!(cluster(None).expect("absent").cloud_metadata_ready, None);
453        assert!(
454            cluster(Some(json!("ready"))).is_err(),
455            "a non-boolean string must be rejected"
456        );
457    }
458
459    /// A runtime-provisioned sandbox registers without an image; the build role and bundle take its
460    /// place. A contract that silently drops those fields as unknown fails only after `terraform
461    /// apply` or stack creation has already succeeded, in the customer's own account.
462    #[test]
463    fn a_runtime_provisioned_sandbox_registers_without_an_image() {
464        let runtime: AwsSandboxImportData = serde_json::from_value(json!({
465            "egressConnectorArns": ["arn:aws:lambda:us-east-2:123456789012:network-connector/c-1"],
466            "allowEgress": "false",
467            "previewPorts": ["8080"],
468            "buildRoleArn": "arn:aws:iam::123456789012:role/acme-agents-build",
469            "bundleUri": "s3://acme-artifacts-us-east-2/agents/bundle.zip",
470        }))
471        .expect("a runtime-provisioned sandbox must register without image fields");
472
473        assert_eq!(runtime.image_arn, None);
474        assert_eq!(runtime.image_identifier, None);
475        assert_eq!(runtime.image_version, None);
476        assert_eq!(
477            runtime.build_role_arn.as_deref(),
478            Some("arn:aws:iam::123456789012:role/acme-agents-build")
479        );
480        assert_eq!(
481            runtime.bundle_uri.as_deref(),
482            Some("s3://acme-artifacts-us-east-2/agents/bundle.zip")
483        );
484        assert_eq!(runtime.preview_ports, vec![8080]);
485
486        // The setup-built shape carries no build inputs, so the two are distinguishable rather
487        // than merely both accepted.
488        let frozen: AwsSandboxImportData = serde_json::from_value(json!({
489            "imageIdentifier": "runner",
490            "imageArn": "arn:aws:lambda:us-east-2:123456789012:microvm-image/runner",
491            "imageVersion": "1.0",
492        }))
493        .expect("the setup-built shape still parses");
494        assert_eq!(frozen.build_role_arn, None);
495        assert_eq!(frozen.bundle_uri, None);
496        assert_eq!(frozen.image_version.as_deref(), Some("1.0"));
497    }
498}