Skip to main content

surjection_core/model/
ids.rs

1//! Identifier rules (SPEC 5.1). Store files keep ids as plain strings so a
2//! bad id survives a rewrite and is reported by validation with
3//! [`ErrorCode::InvalidId`] instead of failing to load.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use crate::error::{CoreError, ErrorCode};
8
9/// Longest server, skill, project id or secret alias, in bytes.
10pub const MAX_ID_LEN: usize = 64;
11
12/// JSON Schema pattern for server, skill and project ids.
13pub const SLUG_PATTERN: &str = "^[a-z0-9][a-z0-9._-]{0,63}$";
14/// JSON Schema pattern for machine and apply ids.
15pub const ULID_PATTERN: &str = "^[0-7][0-9A-HJKMNP-TV-Z]{25}$";
16
17/// Which identifier rule applies.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum IdKind {
20    /// Server id: `^[a-z0-9][a-z0-9._-]{0,63}$`.
21    Server,
22    /// Skill id, same rule as servers.
23    Skill,
24    /// Project id, same rule as servers.
25    Project,
26    /// Secret alias: `^[A-Za-z_][A-Za-z0-9_]{0,63}$`, so it doubles as an
27    /// environment variable name.
28    SecretAlias,
29    /// Environment variable name: `^[A-Za-z_][A-Za-z0-9_]*$`.
30    EnvVar,
31    /// Machine id: a ULID (26 Crockford base32 characters, upper case).
32    Machine,
33    /// Apply id: a ULID, as for machines.
34    Apply,
35    /// Store id (`loadout.toml`): a ULID, as for machines.
36    Store,
37}
38
39impl IdKind {
40    /// Short English noun for messages ("server id", "secret alias").
41    pub const fn noun(self) -> &'static str {
42        match self {
43            IdKind::Server => "server id",
44            IdKind::Skill => "skill id",
45            IdKind::Project => "project id",
46            IdKind::SecretAlias => "secret alias",
47            IdKind::EnvVar => "environment variable name",
48            IdKind::Machine => "machine id",
49            IdKind::Apply => "apply id",
50            IdKind::Store => "store id",
51        }
52    }
53
54    const fn rule(self) -> &'static str {
55        match self {
56            IdKind::Server | IdKind::Skill | IdKind::Project => {
57                "1 to 64 characters from a-z, 0-9, '.', '_', '-', starting with a letter or digit"
58            }
59            IdKind::SecretAlias => {
60                "1 to 64 characters from A-Z, a-z, 0-9, '_', not starting with a digit"
61            }
62            IdKind::EnvVar => "characters from A-Z, a-z, 0-9, '_', not starting with a digit",
63            IdKind::Machine | IdKind::Apply | IdKind::Store => {
64                "a ULID: 26 upper-case Crockford base32 characters"
65            }
66        }
67    }
68}
69
70/// Whether `value` satisfies the rule for `kind`.
71pub fn is_valid(kind: IdKind, value: &str) -> bool {
72    match kind {
73        IdKind::Server | IdKind::Skill | IdKind::Project => is_slug(value),
74        IdKind::SecretAlias => value.len() <= MAX_ID_LEN && is_env_name(value),
75        IdKind::EnvVar => is_env_name(value),
76        IdKind::Machine | IdKind::Apply | IdKind::Store => is_ulid(value),
77    }
78}
79
80/// Checks `value` against the rule for `kind`.
81pub fn check(kind: IdKind, value: &str) -> Result<(), CoreError> {
82    if is_valid(kind, value) {
83        Ok(())
84    } else {
85        Err(CoreError::new(
86            ErrorCode::InvalidId,
87            invalid_message(kind, value),
88        ))
89    }
90}
91
92/// English message for an id that breaks its rule.
93pub(crate) fn invalid_message(kind: IdKind, value: &str) -> String {
94    format!(
95        "invalid {} {value:?}: expected {}",
96        kind.noun(),
97        kind.rule()
98    )
99}
100
101fn is_slug(value: &str) -> bool {
102    let bytes = value.as_bytes();
103    let Some(first) = bytes.first() else {
104        return false;
105    };
106    bytes.len() <= MAX_ID_LEN
107        && (first.is_ascii_lowercase() || first.is_ascii_digit())
108        && bytes.iter().all(|&b| {
109            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
110        })
111}
112
113fn is_env_name(value: &str) -> bool {
114    let bytes = value.as_bytes();
115    let Some(first) = bytes.first() else {
116        return false;
117    };
118    (first.is_ascii_alphabetic() || *first == b'_')
119        && bytes
120            .iter()
121            .all(|&b| b.is_ascii_alphanumeric() || b == b'_')
122}
123
124/// Crockford base32 alphabet used by ULIDs.
125const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
126
127fn is_ulid(value: &str) -> bool {
128    let bytes = value.as_bytes();
129    // The first character carries 3 bits of a 128-bit value, so it is 0-7.
130    bytes.len() == 26 && bytes[0] <= b'7' && bytes.iter().all(|b| CROCKFORD.contains(b))
131}
132
133/// A new ULID for `time` (from [`crate::Env::now`]): 48 bits of Unix
134/// milliseconds, then 80 bits from the operating system's random source.
135pub fn new_ulid(time: SystemTime) -> Result<String, CoreError> {
136    let mut random = [0u8; 10];
137    getrandom::fill(&mut random).map_err(|err| {
138        CoreError::new(
139            ErrorCode::IoError,
140            format!("cannot read random bytes for a new id: {err}"),
141        )
142    })?;
143    Ok(encode_ulid(time, random))
144}
145
146/// An unguessable handle: 16 bytes from the operating system's random
147/// source, in lower-case hex (32 characters).
148pub fn new_token() -> Result<String, CoreError> {
149    let mut random = [0u8; 16];
150    getrandom::fill(&mut random).map_err(|err| {
151        CoreError::new(
152            ErrorCode::IoError,
153            format!("cannot read random bytes for a token: {err}"),
154        )
155    })?;
156    Ok(random.iter().map(|byte| format!("{byte:02x}")).collect())
157}
158
159fn encode_ulid(time: SystemTime, random: [u8; 10]) -> String {
160    let millis = time
161        .duration_since(UNIX_EPOCH)
162        .map_or(0, |elapsed| elapsed.as_millis())
163        & ((1 << 48) - 1);
164    let value = random
165        .iter()
166        .fold(millis, |value, &byte| (value << 8) | u128::from(byte));
167    (0..26)
168        .map(|index| char::from(CROCKFORD[((value >> (125 - 5 * index)) & 31) as usize]))
169        .collect()
170}
171
172/// Abbreviated or full lower-case hex git object id (SHA-1 or SHA-256).
173pub fn is_commit_id(value: &str) -> bool {
174    (7..=64).contains(&value.len())
175        && value
176            .bytes()
177            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
178}