Skip to main content

schedr_agent/
env.rs

1//! The environment of a task process: clean by default (see archive/PROJECT.md, Worker
2//! environment).
3//!
4//! A task gets only a small allow-list of the agent's variables, those listed in
5//! `[worker] pass_env`, the task's own `env`, and the `SCHEDR_*` run variables. The agent's
6//! own configuration, certificate paths and credentials never reach a task by accident.
7
8use std::collections::BTreeMap;
9
10#[cfg(test)]
11mod tests;
12
13/// The agent's variables every task process gets (plus every `LC_*`).
14pub const ALLOWED: [&str; 5] = ["PATH", "HOME", "LANG", "TZ", "TMPDIR"];
15
16/// The prefix of the run variables, reserved for schedr.
17pub const RESERVED_PREFIX: &str = "SCHEDR_";
18
19/// Why a task's environment can't be built.
20#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
21pub enum EnvError {
22    /// The task's `env` sets a variable reserved for schedr.
23    #[error("environment variable `{0}` is reserved for schedr (names starting with SCHEDR_)")]
24    Reserved(String),
25}
26
27/// The run information every `command` and `script` task gets as `SCHEDR_*` variables.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct RunVars {
30    /// `SCHEDR_DAG_ID`.
31    pub dag_id: String,
32    /// `SCHEDR_RUN_ID`.
33    pub run_id: String,
34    /// `SCHEDR_RUN_KIND`.
35    pub run_kind: String,
36    /// `SCHEDR_TASK_ID`.
37    pub task_id: String,
38    /// `SCHEDR_MAP_INDEX`, for mapped tasks only.
39    pub map_index: Option<u32>,
40    /// `SCHEDR_TRY_NUMBER`.
41    pub try_number: u32,
42    /// `SCHEDR_PLANNED_FOR`, RFC 3339 in UTC.
43    pub planned_for: String,
44    /// `SCHEDR_SINCE`, RFC 3339 in UTC.
45    pub since: String,
46}
47
48impl RunVars {
49    /// The variables, by name.
50    #[must_use]
51    pub fn variables(&self) -> BTreeMap<String, String> {
52        let mut vars = BTreeMap::from([
53            ("SCHEDR_DAG_ID".to_owned(), self.dag_id.clone()),
54            ("SCHEDR_RUN_ID".to_owned(), self.run_id.clone()),
55            ("SCHEDR_RUN_KIND".to_owned(), self.run_kind.clone()),
56            ("SCHEDR_TASK_ID".to_owned(), self.task_id.clone()),
57            ("SCHEDR_TRY_NUMBER".to_owned(), self.try_number.to_string()),
58            ("SCHEDR_PLANNED_FOR".to_owned(), self.planned_for.clone()),
59            ("SCHEDR_SINCE".to_owned(), self.since.clone()),
60        ]);
61        if let Some(index) = self.map_index {
62            vars.insert("SCHEDR_MAP_INDEX".to_owned(), index.to_string());
63        }
64        vars
65    }
66}
67
68/// Whether an agent variable is on the allow-list.
69#[must_use]
70pub fn is_allowed(name: &str) -> bool {
71    ALLOWED.contains(&name) || name.starts_with("LC_")
72}
73
74/// The complete environment of a task process.
75///
76/// Layers, later ones winning: the allow-listed agent variables, the agent variables named in
77/// `pass_env`, the task's own `env`, the run variables.
78///
79/// # Errors
80///
81/// Returns [`EnvError::Reserved`] if the task's `env` sets a `SCHEDR_*` variable.
82pub fn task_environment(
83    agent_env: &BTreeMap<String, String>,
84    pass_env: &[String],
85    task_env: &BTreeMap<String, String>,
86    run: &RunVars,
87) -> Result<BTreeMap<String, String>, EnvError> {
88    if let Some(name) = task_env.keys().find(|n| n.starts_with(RESERVED_PREFIX)) {
89        return Err(EnvError::Reserved(name.clone()));
90    }
91    let mut env: BTreeMap<String, String> = agent_env
92        .iter()
93        .filter(|(name, _)| is_allowed(name) || pass_env.contains(name))
94        .map(|(k, v)| (k.clone(), v.clone()))
95        .collect();
96    env.extend(task_env.iter().map(|(k, v)| (k.clone(), v.clone())));
97    env.extend(run.variables());
98    Ok(env)
99}