Skip to main content

alien_signing/
settings.rs

1//! What setup pins for a protected install, how an enforcer finds it, and
2//! the install id every enforcer derives from its own identity.
3//!
4//! Setup writes three values: the signer list fingerprint, the install's
5//! prefix and the release channel it follows. The project is the one signer
6//! list version 1 names. Nothing else comes from setup, and nothing at all
7//! from the control plane.
8
9use 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/// The signing settings of one install.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase", deny_unknown_fields)]
20pub struct SigningSettings {
21    /// `SHA256:<hex>` fingerprint of the project's signer list version 1.
22    pub fingerprint: String,
23    /// The install's resource prefix. It must equal the place the settings
24    /// were found, so a value copied from a neighbor is refused.
25    pub prefix: String,
26    /// Release channel the install follows. A release for another channel is
27    /// refused.
28    pub channel: String,
29}
30
31impl SigningSettings {
32    /// Parse settings found at `prefix` and check each field.
33    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    /// Check each field.
47    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    /// The JSON setup writes.
70    pub fn to_json(&self) -> String {
71        serde_json::to_string(self).expect("settings always serialize")
72    }
73}
74
75/// The install id. Enforcers derive it from their own identity and never
76/// read it from anywhere the control plane writes, so a statement signed for
77/// one customer's install is refused by another's.
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum InstallId {
80    /// `aws:<account>:<region>:<prefix>`.
81    Aws {
82        /// 12-digit account id.
83        account: String,
84        /// Region.
85        region: String,
86        /// Stack prefix.
87        prefix: String,
88    },
89    /// `gcp:<project>:<prefix>`.
90    Gcp {
91        /// Project id.
92        project: String,
93        /// Resource prefix.
94        prefix: String,
95    },
96    /// `azure:<subscription>:<resource-group>`.
97    Azure {
98        /// Subscription id.
99        subscription: String,
100        /// Resource group.
101        resource_group: String,
102    },
103    /// `k8s:<kube-system namespace uid>:<namespace>/<release>`.
104    Kubernetes {
105        /// UID of the cluster's `kube-system` namespace.
106        cluster: String,
107        /// Install namespace.
108        namespace: String,
109        /// Helm release name.
110        release: String,
111    },
112    /// `machine:<uuid>`, generated by `join` on the machine itself.
113    Machine {
114        /// UUID.
115        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    /// Parse the printed form, checking each part, so an id the CLI shows an
144    /// admin is the one an enforcer would derive.
145    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    /// Check each part.
179    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/// What an enforcer got when it read one place the settings could be.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum Lookup {
222    /// The value was there.
223    Found(Vec<u8>),
224    /// The place is empty.
225    Absent,
226    /// The enforcer may not read it.
227    Denied,
228}
229
230/// Decide whether an install is protected from every place its settings
231/// could be, keyed by the prefix each place belongs to.
232///
233/// Every candidate must be read; this never stops at the first answer. The
234/// install is protected if exactly one place holds settings and they name
235/// that place's prefix. Two or more, or settings that don't parse, are an
236/// error. It is unprotected only if every place is absent or denied and at
237/// least one is absent: when every place is denied, nothing was learned.
238pub 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
268/// The prefixes a resource name could belong to, longest first: the name
269/// itself, then every part of it ending before a `-`. An enforcer whose role
270/// is `acme-prod-verifier` looks for settings of `acme-prod-verifier`,
271/// `acme-prod` and `acme`.
272pub 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
292/// Resource prefixes: CloudFormation stack names allow upper case.
293fn 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
325/// Where setup writes the signing settings, the ledger and deployer inputs.
326///
327/// Every name sits under a root no management grant reaches: grants are on
328/// `<prefix>-*`, and these start with `/signed/` or `signed-`, so a neighbor
329/// install whose prefix overlaps this one's can't write them.
330pub mod names {
331    /// AWS SSM parameter holding the signing settings.
332    pub fn aws_settings(prefix: &str) -> String {
333        format!("/signed/{prefix}/fingerprint")
334    }
335
336    /// AWS SSM parameter holding the ledger.
337    pub fn aws_ledger(prefix: &str) -> String {
338        format!("/signed/{prefix}/state")
339    }
340
341    /// AWS SSM path under which each deployer input is one parameter.
342    pub fn aws_inputs(prefix: &str) -> String {
343        format!("/signed/{prefix}/inputs/")
344    }
345
346    /// GCP Parameter Manager parameter holding the signing settings.
347    pub fn gcp_settings(prefix: &str) -> String {
348        format!("signed-{prefix}-fingerprint")
349    }
350
351    /// GCP Secret Manager secret holding the ledger.
352    pub fn gcp_ledger(prefix: &str) -> String {
353        format!("signed-{prefix}-state")
354    }
355
356    /// GCP Secret Manager secret holding deployer input `name`.
357    pub fn gcp_input(prefix: &str, name: &str) -> String {
358        format!("signed-{prefix}-input-{name}")
359    }
360
361    /// Azure resource-group tag holding the signing settings.
362    pub const AZURE_SETTINGS_TAG: &str = "signing-fingerprint";
363
364    /// Azure resource group holding the install's signing vault: `<install group>-signing`.
365    ///
366    /// The vault is not in the install's own group. Management holds role-assignment rights in
367    /// that group, so a vault there could be opened to an identity the vendor holds; this group
368    /// is setup's alone.
369    pub fn azure_signing_resource_group(install_group: &str) -> String {
370        format!("{install_group}-signing")
371    }
372
373    /// Azure Key Vault secret, in the install's signing vault, holding the ledger.
374    pub const AZURE_LEDGER_SECRET: &str = "signing-state";
375
376    /// IAM path of the instance profiles setup creates for machines the verifier launches.
377    pub const AWS_SIGNED_PROFILE_PATH: &str = "/alien-signed/";
378
379    /// Name of the marked instance profile for capacity group profile `base`
380    /// (`<prefix>-<cluster>-<group>`). The name differs from the unmarked profile because IAM
381    /// instance profile names are unique per account whatever the path.
382    pub fn aws_signed_profile_name(base: &str) -> String {
383        format!("{base}-signed")
384    }
385
386    /// ARN of the marked instance profile for `base` in `account`.
387    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    /// Whether an instance profile ARN names a profile under the reserved path. The check is
395    /// case-sensitive and covers the whole `instance-profile/alien-signed/` prefix, so
396    /// `/alien-signed-x/` and `/x/alien-signed/` are not marked.
397    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    /// Kubernetes ConfigMap holding the signing settings of Helm release `release`.
407    pub fn kubernetes_settings(release: &str) -> String {
408        format!("{release}-signing")
409    }
410
411    /// IAM role names setup may give the cloud identity of permission
412    /// profile `profile`. Setup at runtime names it `<prefix>-<profile>-sa`;
413    /// Terraform keeps that while it fits IAM's 64 characters and otherwise
414    /// cuts it to 55 and appends 8 hex of its SHA-1.
415    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    /// GCP service account ids setup may give the cloud identity of
426    /// permission profile `profile`: `<prefix>-<profile>-sa` at runtime, and
427    /// Terraform's id (lowercase, `_` as `-`, `a-` in front, cut to 21 and
428    /// trimmed of `-`, then 8 hex of the SHA-1 of the full name).
429    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}