Skip to main content

schedr_model/
secret.rs

1//! Secrets in DAG JSON: which secret a reference names, and the secrets a task declares
2//! (see archive/PROJECT.md, Secret storage).
3//!
4//! A secret is `path#key` in a storage, like a Vault KV v2 secret's key; `path` alone is the
5//! whole secret (every key). The storage is named, or left out for the default one. Only the
6//! names travel: the agent that runs a task fetches the values, never the master.
7
8use std::fmt;
9
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13#[cfg(test)]
14mod tests;
15
16/// A secret in a storage: `path#key`, or `path` for the whole secret.
17#[derive(
18    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
19)]
20#[serde(deny_unknown_fields)]
21pub struct SecretName {
22    /// The storage it comes from; none for the default one.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub storage: Option<String>,
25    /// The secret's path in the storage (`etl/db`).
26    pub path: String,
27    /// The key in the secret (`password`); none for the whole secret, an object of key to
28    /// value.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub key: Option<String>,
31    /// What a reference reads when the secret or its key is missing
32    /// (`secrets['etl/db'].get('password', '')`); a key's only, never declared in `secrets=`.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub default: Option<String>,
35}
36
37impl SecretName {
38    /// A secret of the default storage.
39    #[must_use]
40    pub fn new(path: impl Into<String>, key: Option<&str>) -> Self {
41        Self {
42            storage: None,
43            path: path.into(),
44            key: key.map(str::to_owned),
45            default: None,
46        }
47    }
48
49    /// `path#key`, or `path` for the whole secret.
50    #[must_use]
51    pub fn spec(&self) -> String {
52        match &self.key {
53            Some(key) => format!("{}#{key}", self.path),
54            None => self.path.clone(),
55        }
56    }
57
58    /// What is wrong with it, if anything: its storage name, path and key.
59    ///
60    /// # Errors
61    ///
62    /// Returns a message naming the secret as written (`secrets['etl//db']['password']`).
63    pub fn check(&self) -> Result<(), String> {
64        let problem = |reason: &str| Err(format!("`{self}`: {reason}"));
65        if let Some(storage) = &self.storage
66            && let Err(reason) = check_storage_name(storage)
67        {
68            return problem(&reason);
69        }
70        if self.path.len() > 1 && self.path.ends_with('/') {
71            return problem("a path doesn't end with `/` (a prefix is `SecretPrefix(...)`)");
72        }
73        if let Err(reason) = check_path(&self.path, "path") {
74            return problem(&reason);
75        }
76        if let Some(key) = &self.key {
77            if key.is_empty() {
78                return problem("the key after `#` is empty");
79            }
80            if key.contains('#') || key.contains('\0') {
81                return problem("a key contains neither `#` nor NUL");
82            }
83        } else if self.default.is_some() {
84            return problem("a default is a key's (`.get(key, default)`)");
85        }
86        Ok(())
87    }
88}
89
90impl fmt::Display for SecretName {
91    /// As written in Python (decision 176): `secrets['etl/db']['password']`,
92    /// `secrets.other['etl/db']`, `secrets['etl/db'].get('password', '')`.
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        match &self.storage {
95            Some(storage) if !attribute(storage) => {
96                write!(f, "secrets.storage({})", py_str(storage))?;
97            }
98            Some(storage) => write!(f, "secrets.{storage}")?,
99            None => f.write_str("secrets")?,
100        }
101        write!(f, "[{}]", py_str(&self.path))?;
102        match (&self.key, &self.default) {
103            (None, _) => Ok(()),
104            (Some(key), None) => write!(f, "[{}]", py_str(key)),
105            (Some(key), Some(default)) => {
106                write!(f, ".get({}, {})", py_str(key), py_str(default))
107            }
108        }
109    }
110}
111
112/// Python's keywords: a storage so named can't be written `secrets.<name>`.
113const PYTHON_KEYWORDS: [&str; 35] = [
114    "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
115    "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
116    "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
117    "with", "yield",
118];
119
120/// Whether `secrets.<storage>` reaches the storage (as Python's `storage_label` decides): a
121/// Python name, not a keyword, not `_` first (refused there), not `storage` or `value` (the
122/// methods).
123fn attribute(storage: &str) -> bool {
124    !storage.is_empty()
125        && !storage.starts_with(|c: char| c.is_ascii_digit() || c == '_')
126        && storage
127            .chars()
128            .all(|c| c.is_ascii_alphanumeric() || c == '_')
129        && storage != "storage"
130        && storage != "value"
131        && !PYTHON_KEYWORDS.contains(&storage)
132}
133
134/// A string as Python's `repr` writes it: in single quotes, unless only double quotes avoid
135/// escaping one.
136fn py_str(text: &str) -> String {
137    use std::fmt::Write as _;
138    let quote = if text.contains('\'') && !text.contains('"') {
139        '"'
140    } else {
141        '\''
142    };
143    let mut out = String::with_capacity(text.len() + 2);
144    out.push(quote);
145    for c in text.chars() {
146        match c {
147            '\\' => out.push_str("\\\\"),
148            '\n' => out.push_str("\\n"),
149            '\r' => out.push_str("\\r"),
150            '\t' => out.push_str("\\t"),
151            c if c == quote => {
152                out.push('\\');
153                out.push(c);
154            }
155            c if c.is_control() => {
156                let _ = write!(out, "\\x{:02x}", u32::from(c));
157            }
158            c => out.push(c),
159        }
160    }
161    out.push(quote);
162    out
163}
164
165/// A secret a task declares in `secrets=`: one it may read on demand (`schedr task-ctx
166/// secret get`, `task_ctx.secret(...)`), fetched before its process starts, or a prefix
167/// covering every secret under it, fetched when read.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
169#[serde(tag = "kind", rename_all = "snake_case")]
170pub enum SecretDecl {
171    /// One secret, or a whole one (every key).
172    Secret(SecretName),
173    /// Every secret under a prefix (`SecretPrefix('connections/')`), at any depth.
174    Prefix {
175        /// The storage; none for the default one.
176        #[serde(default, skip_serializing_if = "Option::is_none")]
177        storage: Option<String>,
178        /// The prefix, ending in `/`.
179        prefix: String,
180    },
181}
182
183impl SecretDecl {
184    /// What is wrong with it, if anything.
185    ///
186    /// # Errors
187    ///
188    /// Returns a message naming it as written.
189    pub fn check(&self) -> Result<(), String> {
190        match self {
191            Self::Secret(name) if name.default.is_some() => Err(format!(
192                "`{name}`: a default is for a value passed to a task, not a declaration in \
193                 `secrets=`"
194            )),
195            Self::Secret(name) => name.check(),
196            Self::Prefix { storage, prefix } => {
197                let problem = |reason: &str| Err(format!("`{self}`: {reason}"));
198                if let Some(storage) = storage
199                    && let Err(reason) = check_storage_name(storage)
200                {
201                    return problem(&reason);
202                }
203                let Some(inner) = prefix.strip_suffix('/') else {
204                    return problem("a prefix ends with `/`");
205                };
206                if let Err(reason) = check_path(inner, "prefix") {
207                    return problem(&reason);
208                }
209                Ok(())
210            }
211        }
212    }
213
214    /// Whether it covers `name`, a secret the task reads (the storages as written: none for
215    /// the default one).
216    #[must_use]
217    pub fn covers(&self, name: &SecretName) -> bool {
218        match self {
219            Self::Secret(declared) => {
220                declared.storage == name.storage
221                    && declared.path == name.path
222                    && (declared.key.is_none() || declared.key == name.key)
223            }
224            Self::Prefix { storage, prefix } => {
225                *storage == name.storage && name.path.starts_with(prefix.as_str())
226            }
227        }
228    }
229
230    /// The storage it names; none for the default one.
231    #[must_use]
232    pub fn storage(&self) -> Option<&str> {
233        match self {
234            Self::Secret(name) => name.storage.as_deref(),
235            Self::Prefix { storage, .. } => storage.as_deref(),
236        }
237    }
238}
239
240impl fmt::Display for SecretDecl {
241    /// As written in Python: the secret, or `SecretPrefix('connections/')`.
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        match self {
244            Self::Secret(name) => name.fmt(f),
245            Self::Prefix {
246                storage: Some(storage),
247                prefix,
248            } => write!(
249                f,
250                "SecretPrefix({}, storage={})",
251                py_str(prefix),
252                py_str(storage)
253            ),
254            Self::Prefix {
255                storage: None,
256                prefix,
257            } => write!(f, "SecretPrefix({})", py_str(prefix)),
258        }
259    }
260}
261
262/// Checks a storage's name: the key of its `[secret_storage.<name>]` table.
263///
264/// # Errors
265///
266/// Returns why it can't be one.
267pub fn check_storage_name(name: &str) -> Result<(), String> {
268    if name.is_empty() {
269        return Err("the storage's name is empty".to_owned());
270    }
271    if !name
272        .chars()
273        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
274    {
275        return Err(format!(
276            "storage `{name}`: a name has only letters, digits, `_` and `-`"
277        ));
278    }
279    if name == "default" {
280        return Err("`default` names the default storage's setting, not a storage".to_owned());
281    }
282    Ok(())
283}
284
285/// Checks a path (or a prefix without its last `/`): `/`-separated, no empty part, no `#`.
286fn check_path(path: &str, what: &str) -> Result<(), String> {
287    if path.is_empty() {
288        return Err(format!("the {what} is empty"));
289    }
290    if path.contains('#') {
291        return Err(format!("a {what} contains no `#` (it separates the key)"));
292    }
293    if path.contains('\0') {
294        return Err(format!("a {what} contains no NUL"));
295    }
296    if path.split('/').any(str::is_empty) {
297        return Err(format!(
298            "a {what} has no empty part (no leading `/`, no `//`)"
299        ));
300    }
301    Ok(())
302}