use crate::{BinaryTarget, PermissionSet, Platform, ResourceLifecycle, ResourceType};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ExtensionManifest {
pub name: String,
pub version: String,
pub digest: String,
#[cfg_attr(feature = "openapi", schema(value_type = HashMap<String, ResourceTypeDescriptor>))]
pub resource_types: IndexMap<ResourceType, ResourceTypeDescriptor>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub egress: Vec<String>,
}
impl ExtensionManifest {
pub fn owner_of(resource_type: &ResourceType) -> Option<&str> {
resource_type
.as_ref()
.split_once('/')
.map(|(extension, _)| extension)
}
pub fn owns(&self, resource_type: &ResourceType) -> bool {
Self::owner_of(resource_type) == Some(self.name.as_str())
}
pub fn identity_id(&self) -> String {
format!("{}-ext", self.name)
}
}
pub fn extension_identity_display_name(extension: &str) -> String {
format!("Extension identity ({extension})")
}
pub fn extension_identity_aws_role_name(prefix: &str, id: &str) -> String {
let full = format!("{prefix}-{id}");
if full.chars().count() <= 64 {
return full;
}
let stem: String = full.chars().take(55).collect();
format!("{stem}-{}", &sha1_hex(&full)[..8])
}
pub fn extension_identity_gcp_account_id(prefix: &str, id: &str) -> String {
let full = format!("{prefix}-{}", terraform_label(id))
.to_lowercase()
.replace('_', "-");
let stem: String = format!("a-{full}").chars().take(21).collect();
format!("{}-{}", stem.trim_matches('-'), &sha1_hex(&full)[..8])
}
fn terraform_label(id: &str) -> String {
let label: String = id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect();
if label.starts_with(|c: char| c.is_ascii_digit()) {
format!("_{label}")
} else {
label
}
}
fn sha1_hex(value: &str) -> String {
use sha1::{Digest, Sha1};
format!("{:x}", Sha1::digest(value.as_bytes()))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ResourceTypeDescriptor {
pub lifecycles: Vec<ResourceLifecycle>,
pub holds_data: bool,
pub setup: SetupSupport,
pub controller_platforms: Vec<Platform>,
pub permission_sets: Vec<PermissionSet>,
pub link: LinkDescriptor,
pub schemas: ResourceTypeSchemas,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
#[cfg_attr(feature = "openapi", schema(value_type = HashMap<String, Vec<String>>))]
pub services: IndexMap<Platform, Vec<String>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub requires_network: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub private_network_endpoints: Option<crate::PrivateEndpointPlacement>,
}
pub const TERRAFORM_MODULE_FILE_STEMS: [&str; 15] = [
"versions",
"variables",
"providers",
"resource_prefix",
"locals",
"iam_propagation",
"registration",
"setup_record",
"helm",
"outputs",
"retention-inventory",
"existing-cluster-network-guard",
"signing",
"override",
"main",
];
pub const MAX_EXTENSION_NAME_LENGTH: usize = 24;
pub fn is_extension_name_segment(name: &str) -> bool {
name.starts_with(|c: char| c.is_ascii_lowercase())
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
pub fn extension_name_problem(name: &str) -> Option<String> {
if name.is_empty() {
Some("is empty".to_string())
} else if !is_extension_name_segment(name) {
Some(
"must start with a lowercase letter and hold only lowercase letters, digits and `-`"
.to_string(),
)
} else if name.chars().count() > MAX_EXTENSION_NAME_LENGTH {
Some(format!(
"is longer than {MAX_EXTENSION_NAME_LENGTH} characters, which the name of its identity's AWS role can't fit"
))
} else if crate::RESERVED_TYPE_PREFIXES.contains(&name) {
Some("is reserved for Alien's own resource types".to_string())
} else if TERRAFORM_MODULE_FILE_STEMS.contains(&name) {
Some(format!(
"names the file `{name}.tf` in Alien's Terraform module, beside which a Terraform modifier writes `<extension>.tf`"
))
} else {
None
}
}
pub fn is_cloud_service_name(platform: Platform, service: &str) -> bool {
match platform {
Platform::Gcp => service.strip_suffix(".googleapis.com").is_some_and(|name| {
name.starts_with(|c: char| c.is_ascii_lowercase())
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}),
Platform::Azure => service.split_once('.').is_some_and(|(prefix, namespace)| {
prefix.eq_ignore_ascii_case("Microsoft")
&& namespace.starts_with(|c: char| c.is_ascii_alphabetic())
&& namespace.chars().all(|c| c.is_ascii_alphanumeric())
}),
_ => false,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct SetupSupport {
pub cloudformation: Vec<Platform>,
pub terraform: Vec<Platform>,
pub helm: Vec<Platform>,
pub importers: Vec<Platform>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SetupFormat {
CloudFormation,
Terraform,
Helm,
}
impl std::fmt::Display for SetupFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
SetupFormat::CloudFormation => "CloudFormation",
SetupFormat::Terraform => "Terraform",
SetupFormat::Helm => "Helm",
})
}
}
impl SetupSupport {
pub fn platforms(&self, format: SetupFormat) -> &[Platform] {
match format {
SetupFormat::CloudFormation => &self.cloudformation,
SetupFormat::Terraform => &self.terraform,
SetupFormat::Helm => &self.helm,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct LinkDescriptor {
pub permission_sets: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub env: Vec<String>,
}
const LINK_ENV_RESERVED_PREFIXES: [&str; 4] = ["ALIEN_", "AWS_", "LAMBDA_", "_"];
pub fn link_env_name_problem(name: &str) -> Option<String> {
let valid = name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !valid {
return Some(format!(
"`{name}` is not an environment variable name: use letters, digits and `_`, starting with a letter"
));
}
let upper = name.to_ascii_uppercase();
LINK_ENV_RESERVED_PREFIXES
.iter()
.find(|prefix| upper.starts_with(*prefix))
.map(|prefix| {
format!(
"`{name}` starts with `{prefix}`, which Alien or the platform's runtime reserves"
)
})
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ResourceTypeSchemas {
pub config: serde_json::Map<String, serde_json::Value>,
pub outputs: serde_json::Map<String, serde_json::Value>,
}
pub const EXTENSION_BUNDLE_MANIFEST: &str = "manifest.json";
pub const EXTENSION_HOOKS_MODULE: &str = "hooks.wasm";
pub const EXTENSION_CONTROLLER_MODULE: &str = "controller.wasm";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionBundleManifest {
pub name: String,
pub version: String,
pub protocol: ExtensionProtocols,
pub hooks_sha256: String,
pub controllers: IndexMap<BinaryTarget, Option<ControllerBinary>>,
pub resource_types: IndexMap<ResourceType, ResourceTypeDescriptor>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub controller_module_sha256: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub egress: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionProtocols {
pub hooks: u32,
pub controller: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ControllerBinary {
pub sha256: String,
pub size: u64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_extension_name_is_a_short_lowercase_segment_alien_does_not_use() {
for (name, problem) in [
("alien", "reserved"),
("experimental", "reserved"),
("", "empty"),
("a/b", "lowercase letters"),
("my_ext", "lowercase letters"),
("foo_override", "lowercase letters"),
("override", "override.tf"),
("..", "lowercase letters"),
("a..b", "lowercase letters"),
("a\\b", "lowercase letters"),
("Acme", "lowercase letters"),
("a b", "lowercase letters"),
("outputs", "outputs.tf"),
("main", "main.tf"),
("-acme", "lowercase letters"),
("aaaaaaaaaaaaaaaaaaaaaaaaa", "longer than 24 characters"),
("ééééééééééééé", "lowercase letters"),
("retention-inventory", "retention-inventory.tf"),
] {
let found = extension_name_problem(name).unwrap_or_default();
assert!(found.contains(problem), "{name:?}: {found:?}");
}
for name in [
"acme",
"a",
"aaaaaaaaaaaaaaaaaaaaaaaa",
"dns-zone-2",
"backups",
] {
assert_eq!(extension_name_problem(name), None, "{name:?}");
}
}
#[test]
fn cloud_service_names_are_gcp_apis_or_azure_providers() {
for (platform, service) in [
(Platform::Gcp, "dns.googleapis.com"),
(Platform::Gcp, "storage-component.googleapis.com"),
(Platform::Azure, "Microsoft.Network"),
(Platform::Azure, "microsoft.dbforpostgresql"),
] {
assert!(is_cloud_service_name(platform, service), "{service}");
}
for (platform, service) in [
(Platform::Gcp, "cloud.quotas"),
(Platform::Gcp, "dns_api.googleapis.com"),
(Platform::Gcp, "a.b.googleapis.com"),
(Platform::Gcp, "Dns.googleapis.com"),
(Platform::Gcp, ".googleapis.com"),
(Platform::Azure, "App"),
(Platform::Azure, "Microsoft."),
(Platform::Azure, "Microsoft.Network.Dns"),
(Platform::Azure, "Contoso.Network"),
(Platform::Aws, "route53.amazonaws.com"),
(Platform::Gcp, "Microsoft.Network"),
] {
assert!(!is_cloud_service_name(platform, service), "{service}");
}
}
}