1use std::fmt;
10
11use alien_error::AlienError;
12use serde::{Deserialize, Serialize};
13
14use crate::error::{ErrorData, Result};
15use crate::signer_list::is_fingerprint;
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase", deny_unknown_fields)]
20pub struct SigningSettings {
21 pub fingerprint: String,
23 pub prefix: String,
26 pub channel: String,
29}
30
31impl SigningSettings {
32 pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
34 let settings: SigningSettings =
35 serde_json::from_slice(bytes).map_err(|error| invalid(format!("{error}")))?;
36 settings.validate()?;
37 if settings.prefix != prefix {
38 return Err(invalid(format!(
39 "the settings found for '{prefix}' name prefix '{}'",
40 settings.prefix
41 )));
42 }
43 Ok(settings)
44 }
45
46 pub fn validate(&self) -> Result<()> {
48 if !is_fingerprint(&self.fingerprint) {
49 return Err(invalid(format!(
50 "fingerprint '{}' is not SHA256:<64 lowercase hex>",
51 self.fingerprint
52 )));
53 }
54 if !is_prefix(&self.prefix) {
55 return Err(invalid(format!(
56 "prefix '{}' is not 1 to 63 of [A-Za-z0-9-] starting with a letter",
57 self.prefix
58 )));
59 }
60 if !is_name(&self.channel, 63) {
61 return Err(invalid(format!(
62 "channel '{}' is not 1 to 63 of [a-z0-9-]",
63 self.channel
64 )));
65 }
66 Ok(())
67 }
68
69 pub fn to_json(&self) -> String {
71 serde_json::to_string(self).expect("settings always serialize")
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum InstallId {
80 Aws {
82 account: String,
84 region: String,
86 prefix: String,
88 },
89 Gcp {
91 project: String,
93 prefix: String,
95 },
96 Azure {
98 subscription: String,
100 resource_group: String,
102 },
103 Kubernetes {
105 cluster: String,
107 namespace: String,
109 release: String,
111 },
112 Machine {
114 id: String,
116 },
117}
118
119impl fmt::Display for InstallId {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 match self {
122 Self::Aws {
123 account,
124 region,
125 prefix,
126 } => write!(f, "aws:{account}:{region}:{prefix}"),
127 Self::Gcp { project, prefix } => write!(f, "gcp:{project}:{prefix}"),
128 Self::Azure {
129 subscription,
130 resource_group,
131 } => write!(f, "azure:{subscription}:{resource_group}"),
132 Self::Kubernetes {
133 cluster,
134 namespace,
135 release,
136 } => write!(f, "k8s:{cluster}:{namespace}/{release}"),
137 Self::Machine { id } => write!(f, "machine:{id}"),
138 }
139 }
140}
141
142impl InstallId {
143 pub fn parse(text: &str) -> Result<Self> {
146 let bad = || invalid_install(text);
147 let (kind, rest) = text.split_once(':').ok_or_else(bad)?;
148 let parts: Vec<&str> = rest.split(':').collect();
149 let id = match (kind, parts.as_slice()) {
150 ("aws", [account, region, prefix]) => Self::Aws {
151 account: account.to_string(),
152 region: region.to_string(),
153 prefix: prefix.to_string(),
154 },
155 ("gcp", [project, prefix]) => Self::Gcp {
156 project: project.to_string(),
157 prefix: prefix.to_string(),
158 },
159 ("azure", [subscription, resource_group]) => Self::Azure {
160 subscription: subscription.to_string(),
161 resource_group: resource_group.to_string(),
162 },
163 ("k8s", [cluster, scoped]) => {
164 let (namespace, release) = scoped.split_once('/').ok_or_else(bad)?;
165 Self::Kubernetes {
166 cluster: cluster.to_string(),
167 namespace: namespace.to_string(),
168 release: release.to_string(),
169 }
170 }
171 ("machine", [id]) => Self::Machine { id: id.to_string() },
172 _ => return Err(bad()),
173 };
174 id.validate()?;
175 Ok(id)
176 }
177
178 pub fn validate(&self) -> Result<()> {
180 let ok = match self {
181 Self::Aws {
182 account,
183 region,
184 prefix,
185 } => {
186 account.len() == 12
187 && account.bytes().all(|byte| byte.is_ascii_digit())
188 && is_name(region, 32)
189 && is_prefix(prefix)
190 }
191 Self::Gcp { project, prefix } => is_name(project, 30) && is_prefix(prefix),
192 Self::Azure {
193 subscription,
194 resource_group,
195 } => {
196 is_uuid(subscription)
197 && !resource_group.is_empty()
198 && resource_group.len() <= 90
199 && resource_group.bytes().all(|byte| {
200 byte.is_ascii_alphanumeric()
201 || matches!(byte, b'-' | b'_' | b'.' | b'(' | b')')
202 })
203 }
204 Self::Kubernetes {
205 cluster,
206 namespace,
207 release,
208 } => is_uuid(cluster) && is_name(namespace, 63) && is_name(release, 53),
209 Self::Machine { id } => is_uuid(id),
210 };
211 if ok {
212 Ok(())
213 } else {
214 Err(invalid_install(&self.to_string()))
215 }
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum Lookup {
222 Found(Vec<u8>),
224 Absent,
226 Denied,
228}
229
230pub fn discover(candidates: &[(String, Lookup)]) -> Result<Option<SigningSettings>> {
239 if candidates.is_empty() {
240 return Err(undecided("there was no place to look for the settings"));
241 }
242 let mut found = Vec::new();
243 let mut any_absent = false;
244 for (prefix, lookup) in candidates {
245 match lookup {
246 Lookup::Found(bytes) => found.push(SigningSettings::parse(bytes, prefix)?),
247 Lookup::Absent => any_absent = true,
248 Lookup::Denied => {}
249 }
250 }
251 match found.len() {
252 0 if any_absent => Ok(None),
253 0 => Err(undecided(
254 "every place the settings could be refused the read",
255 )),
256 1 => Ok(found.pop()),
257 count => Err(undecided(format!(
258 "{count} places hold signing settings: {}",
259 found
260 .iter()
261 .map(|settings| settings.prefix.as_str())
262 .collect::<Vec<_>>()
263 .join(", ")
264 ))),
265 }
266}
267
268pub fn candidate_prefixes(name: &str) -> Vec<String> {
273 let mut prefixes = vec![name.to_string()];
274 let mut rest = name;
275 while let Some((head, _)) = rest.rsplit_once('-') {
276 if !head.is_empty() {
277 prefixes.push(head.to_string());
278 }
279 rest = head;
280 }
281 prefixes
282}
283
284fn is_name(text: &str, max: usize) -> bool {
285 (1..=max).contains(&text.len())
286 && text
287 .bytes()
288 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
289 && !text.starts_with('-')
290}
291
292fn is_prefix(text: &str) -> bool {
294 (1..=63).contains(&text.len())
295 && text.as_bytes()[0].is_ascii_alphabetic()
296 && text
297 .bytes()
298 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
299}
300
301fn is_uuid(text: &str) -> bool {
302 text.len() == 36
303 && text.bytes().enumerate().all(|(index, byte)| match index {
304 8 | 13 | 18 | 23 => byte == b'-',
305 _ => byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase(),
306 })
307}
308
309fn invalid(reason: impl Into<String>) -> AlienError<ErrorData> {
310 AlienError::new(ErrorData::SettingsInvalid {
311 reason: reason.into(),
312 })
313}
314
315fn invalid_install(text: &str) -> AlienError<ErrorData> {
316 invalid(format!("'{text}' is not an install id"))
317}
318
319fn undecided(reason: impl Into<String>) -> AlienError<ErrorData> {
320 AlienError::new(ErrorData::SettingsUndecided {
321 reason: reason.into(),
322 })
323}
324
325pub mod names {
331 pub fn aws_settings(prefix: &str) -> String {
333 format!("/signed/{prefix}/fingerprint")
334 }
335
336 pub fn aws_ledger(prefix: &str) -> String {
338 format!("/signed/{prefix}/state")
339 }
340
341 pub fn aws_inputs(prefix: &str) -> String {
343 format!("/signed/{prefix}/inputs/")
344 }
345
346 pub fn gcp_settings(prefix: &str) -> String {
348 format!("signed-{prefix}-fingerprint")
349 }
350
351 pub fn gcp_ledger(prefix: &str) -> String {
353 format!("signed-{prefix}-state")
354 }
355
356 pub fn gcp_input(prefix: &str, name: &str) -> String {
358 format!("signed-{prefix}-input-{name}")
359 }
360
361 pub const AZURE_SETTINGS_TAG: &str = "signing-fingerprint";
363
364 pub fn azure_signing_resource_group(install_group: &str) -> String {
370 format!("{install_group}-signing")
371 }
372
373 pub const AZURE_LEDGER_SECRET: &str = "signing-state";
375
376 pub const AWS_SIGNED_PROFILE_PATH: &str = "/alien-signed/";
378
379 pub fn aws_signed_profile_name(base: &str) -> String {
383 format!("{base}-signed")
384 }
385
386 pub fn aws_signed_profile_arn(account: &str, base: &str) -> String {
388 format!(
389 "arn:aws:iam::{account}:instance-profile{AWS_SIGNED_PROFILE_PATH}{}",
390 aws_signed_profile_name(base)
391 )
392 }
393
394 pub fn aws_profile_is_signed(arn: &str) -> bool {
398 arn.split_once(":instance-profile")
399 .is_some_and(|(head, tail)| {
400 head.starts_with("arn:")
401 && tail.starts_with(AWS_SIGNED_PROFILE_PATH)
402 && tail.len() > AWS_SIGNED_PROFILE_PATH.len()
403 })
404 }
405
406 pub fn kubernetes_settings(release: &str) -> String {
408 format!("{release}-signing")
409 }
410
411 pub fn aws_workload_roles(prefix: &str, profile: &str) -> Vec<String> {
416 const MAX: usize = 64;
417 let full = format!("{prefix}-{profile}-sa");
418 if full.chars().count() <= MAX {
419 return vec![full];
420 }
421 let readable: String = full.chars().take(MAX - 9).collect();
422 vec![format!("{readable}-{}", &sha1_hex(&full)[..8])]
423 }
424
425 pub fn gcp_workload_service_accounts(prefix: &str, profile: &str) -> Vec<String> {
430 let runtime = format!("{prefix}-{profile}-sa");
431 let normalized = runtime.to_lowercase().replace('_', "-");
432 let readable: String = format!("a-{normalized}").chars().take(21).collect();
433 let terraform = format!(
434 "{}-{}",
435 readable.trim_matches('-'),
436 &sha1_hex(&normalized)[..8]
437 );
438 if terraform == runtime {
439 vec![runtime]
440 } else {
441 vec![runtime, terraform]
442 }
443 }
444
445 fn sha1_hex(text: &str) -> String {
446 use sha1::{Digest, Sha1};
447 hex::encode(Sha1::digest(text.as_bytes()))
448 }
449}
450
451#[cfg(test)]
452mod signed_profile_tests {
453 use super::names::{aws_profile_is_signed, aws_signed_profile_arn};
454
455 #[test]
456 fn only_the_reserved_path_marks_a_profile() {
457 let own = aws_signed_profile_arn("111122223333", "acme-prod-compute-general");
458 assert_eq!(
459 own,
460 "arn:aws:iam::111122223333:instance-profile/alien-signed/acme-prod-compute-general-signed"
461 );
462 assert!(aws_profile_is_signed(&own));
463 for unmarked in [
464 "arn:aws:iam::111122223333:instance-profile/acme-prod-compute-general",
465 "arn:aws:iam::111122223333:instance-profile/alien-signed-x/p",
466 "arn:aws:iam::111122223333:instance-profile/x/alien-signed/p",
467 "arn:aws:iam::111122223333:instance-profile/Alien-Signed/p",
468 "arn:aws:iam::111122223333:instance-profile/alien-signed/",
469 "arn:aws:iam::111122223333:role/alien-signed/p",
470 "instance-profile/alien-signed/p",
471 "",
472 ] {
473 assert!(!aws_profile_is_signed(unmarked), "{unmarked}");
474 }
475 }
476}