use std::fmt;
use alien_error::AlienError;
use serde::{Deserialize, Serialize};
use crate::error::{ErrorData, Result};
use crate::signer_list::is_fingerprint;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SigningSettings {
pub fingerprint: String,
pub prefix: String,
pub channel: String,
}
impl SigningSettings {
pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
let settings: SigningSettings =
serde_json::from_slice(bytes).map_err(|error| invalid(format!("{error}")))?;
settings.validate()?;
if settings.prefix != prefix {
return Err(invalid(format!(
"the settings found for '{prefix}' name prefix '{}'",
settings.prefix
)));
}
Ok(settings)
}
pub fn validate(&self) -> Result<()> {
if !is_fingerprint(&self.fingerprint) {
return Err(invalid(format!(
"fingerprint '{}' is not SHA256:<64 lowercase hex>",
self.fingerprint
)));
}
if !is_prefix(&self.prefix) {
return Err(invalid(format!(
"prefix '{}' is not 1 to 63 of [A-Za-z0-9-] starting with a letter",
self.prefix
)));
}
if !is_name(&self.channel, 63) {
return Err(invalid(format!(
"channel '{}' is not 1 to 63 of [a-z0-9-]",
self.channel
)));
}
Ok(())
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).expect("settings always serialize")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InstallId {
Aws {
account: String,
region: String,
prefix: String,
},
Gcp {
project: String,
prefix: String,
},
Azure {
subscription: String,
resource_group: String,
},
Kubernetes {
cluster: String,
namespace: String,
release: String,
},
Machine {
id: String,
},
}
impl fmt::Display for InstallId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Aws {
account,
region,
prefix,
} => write!(f, "aws:{account}:{region}:{prefix}"),
Self::Gcp { project, prefix } => write!(f, "gcp:{project}:{prefix}"),
Self::Azure {
subscription,
resource_group,
} => write!(f, "azure:{subscription}:{resource_group}"),
Self::Kubernetes {
cluster,
namespace,
release,
} => write!(f, "k8s:{cluster}:{namespace}/{release}"),
Self::Machine { id } => write!(f, "machine:{id}"),
}
}
}
impl InstallId {
pub fn parse(text: &str) -> Result<Self> {
let bad = || invalid_install(text);
let (kind, rest) = text.split_once(':').ok_or_else(bad)?;
let parts: Vec<&str> = rest.split(':').collect();
let id = match (kind, parts.as_slice()) {
("aws", [account, region, prefix]) => Self::Aws {
account: account.to_string(),
region: region.to_string(),
prefix: prefix.to_string(),
},
("gcp", [project, prefix]) => Self::Gcp {
project: project.to_string(),
prefix: prefix.to_string(),
},
("azure", [subscription, resource_group]) => Self::Azure {
subscription: subscription.to_string(),
resource_group: resource_group.to_string(),
},
("k8s", [cluster, scoped]) => {
let (namespace, release) = scoped.split_once('/').ok_or_else(bad)?;
Self::Kubernetes {
cluster: cluster.to_string(),
namespace: namespace.to_string(),
release: release.to_string(),
}
}
("machine", [id]) => Self::Machine { id: id.to_string() },
_ => return Err(bad()),
};
id.validate()?;
Ok(id)
}
pub fn validate(&self) -> Result<()> {
let ok = match self {
Self::Aws {
account,
region,
prefix,
} => {
account.len() == 12
&& account.bytes().all(|byte| byte.is_ascii_digit())
&& is_name(region, 32)
&& is_prefix(prefix)
}
Self::Gcp { project, prefix } => is_name(project, 30) && is_prefix(prefix),
Self::Azure {
subscription,
resource_group,
} => {
is_uuid(subscription)
&& !resource_group.is_empty()
&& resource_group.len() <= 90
&& resource_group.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'_' | b'.' | b'(' | b')')
})
}
Self::Kubernetes {
cluster,
namespace,
release,
} => is_uuid(cluster) && is_name(namespace, 63) && is_name(release, 53),
Self::Machine { id } => is_uuid(id),
};
if ok {
Ok(())
} else {
Err(invalid_install(&self.to_string()))
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lookup {
Found(Vec<u8>),
Absent,
Denied,
}
pub fn discover(candidates: &[(String, Lookup)]) -> Result<Option<SigningSettings>> {
if candidates.is_empty() {
return Err(undecided("there was no place to look for the settings"));
}
let mut found = Vec::new();
let mut any_absent = false;
for (prefix, lookup) in candidates {
match lookup {
Lookup::Found(bytes) => found.push(SigningSettings::parse(bytes, prefix)?),
Lookup::Absent => any_absent = true,
Lookup::Denied => {}
}
}
match found.len() {
0 if any_absent => Ok(None),
0 => Err(undecided(
"every place the settings could be refused the read",
)),
1 => Ok(found.pop()),
count => Err(undecided(format!(
"{count} places hold signing settings: {}",
found
.iter()
.map(|settings| settings.prefix.as_str())
.collect::<Vec<_>>()
.join(", ")
))),
}
}
pub fn candidate_prefixes(name: &str) -> Vec<String> {
let mut prefixes = vec![name.to_string()];
let mut rest = name;
while let Some((head, _)) = rest.rsplit_once('-') {
if !head.is_empty() {
prefixes.push(head.to_string());
}
rest = head;
}
prefixes
}
fn is_name(text: &str, max: usize) -> bool {
(1..=max).contains(&text.len())
&& text
.bytes()
.all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
&& !text.starts_with('-')
}
fn is_prefix(text: &str) -> bool {
(1..=63).contains(&text.len())
&& text.as_bytes()[0].is_ascii_alphabetic()
&& text
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}
fn is_uuid(text: &str) -> bool {
text.len() == 36
&& text.bytes().enumerate().all(|(index, byte)| match index {
8 | 13 | 18 | 23 => byte == b'-',
_ => byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase(),
})
}
fn invalid(reason: impl Into<String>) -> AlienError<ErrorData> {
AlienError::new(ErrorData::SettingsInvalid {
reason: reason.into(),
})
}
fn invalid_install(text: &str) -> AlienError<ErrorData> {
invalid(format!("'{text}' is not an install id"))
}
fn undecided(reason: impl Into<String>) -> AlienError<ErrorData> {
AlienError::new(ErrorData::SettingsUndecided {
reason: reason.into(),
})
}
pub mod names {
pub fn aws_settings(prefix: &str) -> String {
format!("/signed/{prefix}/fingerprint")
}
pub fn aws_ledger(prefix: &str) -> String {
format!("/signed/{prefix}/state")
}
pub fn aws_inputs(prefix: &str) -> String {
format!("/signed/{prefix}/inputs/")
}
pub fn gcp_settings(prefix: &str) -> String {
format!("signed-{prefix}-fingerprint")
}
pub fn gcp_ledger(prefix: &str) -> String {
format!("signed-{prefix}-state")
}
pub fn gcp_input(prefix: &str, name: &str) -> String {
format!("signed-{prefix}-input-{name}")
}
pub const AZURE_SETTINGS_TAG: &str = "signing-fingerprint";
pub fn azure_signing_resource_group(install_group: &str) -> String {
format!("{install_group}-signing")
}
pub const AZURE_LEDGER_SECRET: &str = "signing-state";
pub const AWS_SIGNED_PROFILE_PATH: &str = "/alien-signed/";
pub fn aws_signed_profile_name(base: &str) -> String {
format!("{base}-signed")
}
pub fn aws_signed_profile_arn(account: &str, base: &str) -> String {
format!(
"arn:aws:iam::{account}:instance-profile{AWS_SIGNED_PROFILE_PATH}{}",
aws_signed_profile_name(base)
)
}
pub fn aws_profile_is_signed(arn: &str) -> bool {
arn.split_once(":instance-profile")
.is_some_and(|(head, tail)| {
head.starts_with("arn:")
&& tail.starts_with(AWS_SIGNED_PROFILE_PATH)
&& tail.len() > AWS_SIGNED_PROFILE_PATH.len()
})
}
pub fn kubernetes_settings(release: &str) -> String {
format!("{release}-signing")
}
pub fn aws_workload_roles(prefix: &str, profile: &str) -> Vec<String> {
const MAX: usize = 64;
let full = format!("{prefix}-{profile}-sa");
if full.chars().count() <= MAX {
return vec![full];
}
let readable: String = full.chars().take(MAX - 9).collect();
vec![format!("{readable}-{}", &sha1_hex(&full)[..8])]
}
pub fn gcp_workload_service_accounts(prefix: &str, profile: &str) -> Vec<String> {
let runtime = format!("{prefix}-{profile}-sa");
let normalized = runtime.to_lowercase().replace('_', "-");
let readable: String = format!("a-{normalized}").chars().take(21).collect();
let terraform = format!(
"{}-{}",
readable.trim_matches('-'),
&sha1_hex(&normalized)[..8]
);
if terraform == runtime {
vec![runtime]
} else {
vec![runtime, terraform]
}
}
fn sha1_hex(text: &str) -> String {
use sha1::{Digest, Sha1};
hex::encode(Sha1::digest(text.as_bytes()))
}
}
#[cfg(test)]
mod signed_profile_tests {
use super::names::{aws_profile_is_signed, aws_signed_profile_arn};
#[test]
fn only_the_reserved_path_marks_a_profile() {
let own = aws_signed_profile_arn("111122223333", "acme-prod-compute-general");
assert_eq!(
own,
"arn:aws:iam::111122223333:instance-profile/alien-signed/acme-prod-compute-general-signed"
);
assert!(aws_profile_is_signed(&own));
for unmarked in [
"arn:aws:iam::111122223333:instance-profile/acme-prod-compute-general",
"arn:aws:iam::111122223333:instance-profile/alien-signed-x/p",
"arn:aws:iam::111122223333:instance-profile/x/alien-signed/p",
"arn:aws:iam::111122223333:instance-profile/Alien-Signed/p",
"arn:aws:iam::111122223333:instance-profile/alien-signed/",
"arn:aws:iam::111122223333:role/alien-signed/p",
"instance-profile/alien-signed/p",
"",
] {
assert!(!aws_profile_is_signed(unmarked), "{unmarked}");
}
}
}