1use crate::{BinaryTarget, PermissionSet, Platform, ResourceLifecycle, ResourceType};
8use indexmap::IndexMap;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
14#[serde(rename_all = "camelCase")]
15pub struct ExtensionManifest {
16 pub name: String,
18 pub version: String,
20 pub digest: String,
22 #[cfg_attr(feature = "openapi", schema(value_type = HashMap<String, ResourceTypeDescriptor>))]
24 pub resource_types: IndexMap<ResourceType, ResourceTypeDescriptor>,
25 #[serde(default, skip_serializing_if = "Vec::is_empty")]
28 pub egress: Vec<String>,
29}
30
31impl ExtensionManifest {
32 pub fn owner_of(resource_type: &ResourceType) -> Option<&str> {
35 resource_type
36 .as_ref()
37 .split_once('/')
38 .map(|(extension, _)| extension)
39 }
40
41 pub fn owns(&self, resource_type: &ResourceType) -> bool {
43 Self::owner_of(resource_type) == Some(self.name.as_str())
44 }
45
46 pub fn identity_id(&self) -> String {
50 format!("{}-ext", self.name)
51 }
52}
53
54pub fn extension_identity_display_name(extension: &str) -> String {
57 format!("Extension identity ({extension})")
58}
59
60pub fn extension_identity_aws_role_name(prefix: &str, id: &str) -> String {
63 let full = format!("{prefix}-{id}");
64 if full.chars().count() <= 64 {
65 return full;
66 }
67 let stem: String = full.chars().take(55).collect();
68 format!("{stem}-{}", &sha1_hex(&full)[..8])
69}
70
71pub fn extension_identity_gcp_account_id(prefix: &str, id: &str) -> String {
75 let full = format!("{prefix}-{}", terraform_label(id))
76 .to_lowercase()
77 .replace('_', "-");
78 let stem: String = format!("a-{full}").chars().take(21).collect();
79 format!("{}-{}", stem.trim_matches('-'), &sha1_hex(&full)[..8])
80}
81
82fn terraform_label(id: &str) -> String {
84 let label: String = id
85 .chars()
86 .map(|c| {
87 if c.is_ascii_alphanumeric() {
88 c.to_ascii_lowercase()
89 } else {
90 '_'
91 }
92 })
93 .collect();
94 if label.starts_with(|c: char| c.is_ascii_digit()) {
95 format!("_{label}")
96 } else {
97 label
98 }
99}
100
101fn sha1_hex(value: &str) -> String {
102 use sha1::{Digest, Sha1};
103 format!("{:x}", Sha1::digest(value.as_bytes()))
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
109#[serde(rename_all = "camelCase")]
110pub struct ResourceTypeDescriptor {
111 pub lifecycles: Vec<ResourceLifecycle>,
113 pub holds_data: bool,
116 pub setup: SetupSupport,
118 pub controller_platforms: Vec<Platform>,
120 pub permission_sets: Vec<PermissionSet>,
123 pub link: LinkDescriptor,
125 pub schemas: ResourceTypeSchemas,
127 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
131 #[cfg_attr(feature = "openapi", schema(value_type = HashMap<String, Vec<String>>))]
132 pub services: IndexMap<Platform, Vec<String>>,
133 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
136 pub requires_network: bool,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub private_network_endpoints: Option<crate::PrivateEndpointPlacement>,
142}
143
144pub const TERRAFORM_MODULE_FILE_STEMS: [&str; 15] = [
149 "versions",
150 "variables",
151 "providers",
152 "resource_prefix",
153 "locals",
154 "iam_propagation",
155 "registration",
156 "setup_record",
157 "helm",
158 "outputs",
159 "retention-inventory",
160 "existing-cluster-network-guard",
161 "signing",
162 "override",
163 "main",
164];
165
166pub const MAX_EXTENSION_NAME_LENGTH: usize = 24;
171
172pub fn is_extension_name_segment(name: &str) -> bool {
177 name.starts_with(|c: char| c.is_ascii_lowercase())
178 && name
179 .chars()
180 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
181}
182
183pub fn extension_name_problem(name: &str) -> Option<String> {
188 if name.is_empty() {
189 Some("is empty".to_string())
190 } else if !is_extension_name_segment(name) {
191 Some(
192 "must start with a lowercase letter and hold only lowercase letters, digits and `-`"
193 .to_string(),
194 )
195 } else if name.chars().count() > MAX_EXTENSION_NAME_LENGTH {
196 Some(format!(
197 "is longer than {MAX_EXTENSION_NAME_LENGTH} characters, which the name of its identity's AWS role can't fit"
198 ))
199 } else if crate::RESERVED_TYPE_PREFIXES.contains(&name) {
200 Some("is reserved for Alien's own resource types".to_string())
201 } else if TERRAFORM_MODULE_FILE_STEMS.contains(&name) {
202 Some(format!(
203 "names the file `{name}.tf` in Alien's Terraform module, beside which a Terraform modifier writes `<extension>.tf`"
204 ))
205 } else {
206 None
207 }
208}
209
210pub fn is_cloud_service_name(platform: Platform, service: &str) -> bool {
214 match platform {
215 Platform::Gcp => service.strip_suffix(".googleapis.com").is_some_and(|name| {
216 name.starts_with(|c: char| c.is_ascii_lowercase())
217 && name
218 .chars()
219 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
220 }),
221 Platform::Azure => service.split_once('.').is_some_and(|(prefix, namespace)| {
222 prefix.eq_ignore_ascii_case("Microsoft")
223 && namespace.starts_with(|c: char| c.is_ascii_alphabetic())
224 && namespace.chars().all(|c| c.is_ascii_alphanumeric())
225 }),
226 _ => false,
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
233#[serde(rename_all = "camelCase")]
234pub struct SetupSupport {
235 pub cloudformation: Vec<Platform>,
237 pub terraform: Vec<Platform>,
239 pub helm: Vec<Platform>,
241 pub importers: Vec<Platform>,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum SetupFormat {
248 CloudFormation,
249 Terraform,
250 Helm,
251}
252
253impl std::fmt::Display for SetupFormat {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 f.write_str(match self {
256 SetupFormat::CloudFormation => "CloudFormation",
257 SetupFormat::Terraform => "Terraform",
258 SetupFormat::Helm => "Helm",
259 })
260 }
261}
262
263impl SetupSupport {
264 pub fn platforms(&self, format: SetupFormat) -> &[Platform] {
266 match format {
267 SetupFormat::CloudFormation => &self.cloudformation,
268 SetupFormat::Terraform => &self.terraform,
269 SetupFormat::Helm => &self.helm,
270 }
271 }
272}
273
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
281#[serde(rename_all = "camelCase")]
282pub struct LinkDescriptor {
283 pub permission_sets: Vec<String>,
285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
288 pub env: Vec<String>,
289}
290
291const LINK_ENV_RESERVED_PREFIXES: [&str; 4] = ["ALIEN_", "AWS_", "LAMBDA_", "_"];
294
295pub fn link_env_name_problem(name: &str) -> Option<String> {
298 let valid = name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
299 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
300 if !valid {
301 return Some(format!(
302 "`{name}` is not an environment variable name: use letters, digits and `_`, starting with a letter"
303 ));
304 }
305 let upper = name.to_ascii_uppercase();
306 LINK_ENV_RESERVED_PREFIXES
307 .iter()
308 .find(|prefix| upper.starts_with(*prefix))
309 .map(|prefix| {
310 format!(
311 "`{name}` starts with `{prefix}`, which Alien or the platform's runtime reserves"
312 )
313 })
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
319#[serde(rename_all = "camelCase")]
320pub struct ResourceTypeSchemas {
321 pub config: serde_json::Map<String, serde_json::Value>,
323 pub outputs: serde_json::Map<String, serde_json::Value>,
325}
326
327pub const EXTENSION_BUNDLE_MANIFEST: &str = "manifest.json";
329
330pub const EXTENSION_HOOKS_MODULE: &str = "hooks.wasm";
332
333pub const EXTENSION_CONTROLLER_MODULE: &str = "controller.wasm";
336
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct ExtensionBundleManifest {
343 pub name: String,
345 pub version: String,
347 pub protocol: ExtensionProtocols,
349 pub hooks_sha256: String,
351 pub controllers: IndexMap<BinaryTarget, Option<ControllerBinary>>,
354 pub resource_types: IndexMap<ResourceType, ResourceTypeDescriptor>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub controller_module_sha256: Option<String>,
361 #[serde(default, skip_serializing_if = "Vec::is_empty")]
364 pub egress: Vec<String>,
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase")]
370pub struct ExtensionProtocols {
371 pub hooks: u32,
373 pub controller: Option<u32>,
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "camelCase")]
380pub struct ControllerBinary {
381 pub sha256: String,
383 pub size: u64,
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
393 fn an_extension_name_is_a_short_lowercase_segment_alien_does_not_use() {
394 for (name, problem) in [
395 ("alien", "reserved"),
396 ("experimental", "reserved"),
397 ("", "empty"),
398 ("a/b", "lowercase letters"),
399 ("my_ext", "lowercase letters"),
400 ("foo_override", "lowercase letters"),
401 ("override", "override.tf"),
402 ("..", "lowercase letters"),
403 ("a..b", "lowercase letters"),
404 ("a\\b", "lowercase letters"),
405 ("Acme", "lowercase letters"),
406 ("a b", "lowercase letters"),
407 ("outputs", "outputs.tf"),
408 ("main", "main.tf"),
409 ("-acme", "lowercase letters"),
410 ("aaaaaaaaaaaaaaaaaaaaaaaaa", "longer than 24 characters"),
411 ("ééééééééééééé", "lowercase letters"),
412 ("retention-inventory", "retention-inventory.tf"),
413 ] {
414 let found = extension_name_problem(name).unwrap_or_default();
415 assert!(found.contains(problem), "{name:?}: {found:?}");
416 }
417 for name in [
418 "acme",
419 "a",
420 "aaaaaaaaaaaaaaaaaaaaaaaa",
421 "dns-zone-2",
422 "backups",
423 ] {
424 assert_eq!(extension_name_problem(name), None, "{name:?}");
425 }
426 }
427
428 #[test]
429 fn cloud_service_names_are_gcp_apis_or_azure_providers() {
430 for (platform, service) in [
431 (Platform::Gcp, "dns.googleapis.com"),
432 (Platform::Gcp, "storage-component.googleapis.com"),
433 (Platform::Azure, "Microsoft.Network"),
434 (Platform::Azure, "microsoft.dbforpostgresql"),
435 ] {
436 assert!(is_cloud_service_name(platform, service), "{service}");
437 }
438 for (platform, service) in [
439 (Platform::Gcp, "cloud.quotas"),
440 (Platform::Gcp, "dns_api.googleapis.com"),
441 (Platform::Gcp, "a.b.googleapis.com"),
442 (Platform::Gcp, "Dns.googleapis.com"),
443 (Platform::Gcp, ".googleapis.com"),
444 (Platform::Azure, "App"),
445 (Platform::Azure, "Microsoft."),
446 (Platform::Azure, "Microsoft.Network.Dns"),
447 (Platform::Azure, "Contoso.Network"),
448 (Platform::Aws, "route53.amazonaws.com"),
449 (Platform::Gcp, "Microsoft.Network"),
450 ] {
451 assert!(!is_cloud_service_name(platform, service), "{service}");
452 }
453 }
454}