Skip to main content

stackless_core/
security.rs

1//! Public secret references, controlled child environments, and output redaction.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::ffi::{OsStr, OsString};
5
6use serde::{Deserialize, Serialize};
7
8/// A selector for controller-side injection. It contains no credential value.
9/// The immutable owner must match the target workload before it is resolved.
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct SecretRef {
13    kind: SecretRefKind,
14    pub instance_id: String,
15    pub integration: String,
16    pub output: String,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20enum SecretRefKind {
21    #[serde(rename = "secret_ref")]
22    Reference,
23}
24
25impl SecretRef {
26    pub fn new(instance_id: &str, integration: &str, output: &str) -> Self {
27        Self {
28            kind: SecretRefKind::Reference,
29            instance_id: instance_id.into(),
30            integration: integration.into(),
31            output: output.into(),
32        }
33    }
34}
35
36/// These credentials authorize infrastructure operations. They are not an app's
37/// secret namespace, even when a definition requests them under another name.
38pub fn controller_credential(key: &str) -> bool {
39    let upper = key.to_ascii_uppercase();
40    matches!(
41        upper.as_str(),
42        "STRIPE_API_KEY"
43            | "STRIPE_SECRET_KEY"
44            | "STRIPE_API_TOKEN"
45            | "RENDER_API_KEY"
46            | "VERCEL_TOKEN"
47            | "VERCEL_API_TOKEN"
48            | "FLY_API_TOKEN"
49            | "FLY_ACCESS_TOKEN"
50            | "NETLIFY_AUTH_TOKEN"
51            | "NETLIFY_ACCESS_TOKEN"
52            | "RAILWAY_TOKEN"
53            | "RAILWAY_API_TOKEN"
54            | "CLOUDFLARE_API_TOKEN"
55            | "CLOUDFLARE_API_KEY"
56            | "CF_API_TOKEN"
57            | "LARAVEL_CLOUD_API_TOKEN"
58            | "GITLAB_TOKEN"
59            | "GITLAB_ACCESS_TOKEN"
60            | "WORDPRESS_ACCESS_TOKEN"
61            | "WORDPRESS_API_TOKEN"
62            | "STACKLESS_STATE_TOKEN"
63            | "STACKLESS_CONTROLLER_TOKEN"
64            | "AWS_ACCESS_KEY_ID"
65            | "AWS_SECRET_ACCESS_KEY"
66            | "AWS_SESSION_TOKEN"
67            | "GOOGLE_APPLICATION_CREDENTIALS"
68            | "AZURE_CLIENT_SECRET"
69    )
70}
71
72pub fn sensitive_key(key: &str) -> bool {
73    let key = key.to_ascii_lowercase();
74    [
75        "secret",
76        "password",
77        "token",
78        "credential",
79        "authorization",
80        "cookie",
81        "private_key",
82        "api_key",
83        "connection_string",
84    ]
85    .iter()
86    .any(|part| key.contains(part))
87        || key.ends_with("_dsn")
88        || key.ends_with("database_url")
89}
90
91pub fn controller_values(secrets: &BTreeMap<String, String>) -> BTreeSet<String> {
92    std::env::vars_os()
93        .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
94        .chain(secrets.iter().map(|(k, v)| (k.clone(), v.clone())))
95        .filter(|(key, value)| controller_credential(key) && !value.is_empty())
96        .map(|(_, value)| value)
97        .collect()
98}
99
100pub fn application_secrets(secrets: &BTreeMap<String, String>) -> BTreeMap<String, String> {
101    let privileged = controller_values(secrets);
102    secrets
103        .iter()
104        .filter(|(key, value)| {
105            !controller_credential(key) && !privileged.iter().any(|secret| value.contains(secret))
106        })
107        .map(|(key, value)| (key.clone(), value.clone()))
108        .collect()
109}
110
111/// Call after interpolation too: literal values and renamed aliases do not
112/// grant a workload access to a controller credential.
113pub fn validate_environment<'a>(
114    env: impl IntoIterator<Item = (&'a str, &'a str)>,
115    secrets: &BTreeMap<String, String>,
116) -> Result<(), String> {
117    let privileged = controller_values(secrets);
118    if env.into_iter().any(|(key, value)| {
119        controller_credential(key) || privileged.iter().any(|secret| value.contains(secret))
120    }) {
121        return Err("workload environment requests an infrastructure credential".into());
122    }
123    Ok(())
124}
125
126/// Logs may contain raw app output on disk. Restrict access before writing.
127pub fn private_log(path: &std::path::Path, append: bool) -> std::io::Result<std::fs::File> {
128    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
129    if let Some(parent) = path.parent() {
130        std::fs::create_dir_all(parent)?;
131        std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
132    }
133    let file = std::fs::OpenOptions::new()
134        .create(true)
135        .write(true)
136        .append(append)
137        .truncate(!append)
138        .mode(0o600)
139        .custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32)
140        .open(path)?;
141    file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
142    Ok(file)
143}
144
145const CHILD_ENV: &[&str] = &[
146    "PATH",
147    "HOME",
148    "USER",
149    "LOGNAME",
150    "TMPDIR",
151    "TMP",
152    "TEMP",
153    "LANG",
154    "LC_ALL",
155    "LC_CTYPE",
156    "LC_MESSAGES",
157    "TERM",
158    "COLORTERM",
159    "TZ",
160    "CARGO_HOME",
161    "RUSTUP_HOME",
162    "MISE_DATA_DIR",
163    "MISE_CACHE_DIR",
164    "SYSTEMROOT",
165    "COMSPEC",
166    "PATHEXT",
167];
168
169fn allowed_child_key(key: &OsStr) -> bool {
170    key.to_str().is_some_and(|key| CHILD_ENV.contains(&key))
171}
172
173/// Call `env_clear` before applying this list and explicitly resolved app env.
174pub fn child_environment() -> Vec<(OsString, OsString)> {
175    std::env::vars_os()
176        .filter(|(key, _)| allowed_child_key(key))
177        .collect()
178}
179
180#[derive(Clone, Default)]
181pub struct Redactor {
182    values: BTreeSet<String>,
183}
184
185impl std::fmt::Debug for Redactor {
186    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        f.debug_struct("Redactor")
188            .field("value_count", &self.values.len())
189            .finish()
190    }
191}
192
193impl Redactor {
194    pub fn new(values: impl IntoIterator<Item = String>) -> Self {
195        let mut redactor = Self::default();
196        for value in values {
197            redactor.register(&value);
198        }
199        redactor
200    }
201
202    pub fn register(&mut self, value: &str) {
203        if value.is_empty() || value == "[redacted]" {
204            return;
205        }
206        self.values.insert(value.into());
207        // Provider credential blobs and connection URLs can be logged by field.
208        if let Ok(json) = serde_json::from_str::<serde_json::Value>(value) {
209            self.register_json_leaves(&json);
210        }
211        if let Some((_, rest)) = value.split_once("://") {
212            let authority = rest.split('/').next().unwrap_or_default();
213            if let Some((userinfo, _)) = authority.rsplit_once('@')
214                && let Some((_, password)) = userinfo.split_once(':')
215                && !password.is_empty()
216            {
217                self.values.insert(password.into());
218            }
219        }
220    }
221
222    fn register_json_leaves(&mut self, value: &serde_json::Value) {
223        match value {
224            serde_json::Value::String(value) => {
225                if !value.is_empty() {
226                    self.values.insert(value.clone());
227                }
228            }
229            serde_json::Value::Array(values) => {
230                for value in values {
231                    self.register_json_leaves(value);
232                }
233            }
234            serde_json::Value::Object(values) => {
235                for value in values.values() {
236                    self.register_json_leaves(value);
237                }
238            }
239            _ => {}
240        }
241    }
242
243    pub fn text(&self, text: &str) -> String {
244        let mut values: Vec<_> = self.values.iter().collect();
245        values.sort_by_key(|value| std::cmp::Reverse(value.len()));
246        values.into_iter().fold(text.into(), |text: String, value| {
247            text.replace(value, "[redacted]")
248        })
249    }
250
251    /// Metadata fields retain their protocol meaning. Free text and sensitive
252    /// provider fields are redacted before entering a public envelope.
253    pub fn value(&self, value: &mut serde_json::Value) {
254        match value {
255            serde_json::Value::String(text) => *text = self.text(text),
256            serde_json::Value::Array(values) => {
257                for value in values {
258                    self.value(value);
259                }
260            }
261            serde_json::Value::Object(values) => {
262                if serde_json::from_value::<SecretRef>(serde_json::Value::Object(values.clone()))
263                    .is_ok()
264                {
265                    return;
266                }
267                for (key, value) in values {
268                    if sensitive_key(key)
269                        && serde_json::from_value::<SecretRef>(value.clone()).is_err()
270                    {
271                        *value = serde_json::Value::String("[redacted]".into());
272                    } else if !matches!(
273                        key.as_str(),
274                        "code"
275                            | "status"
276                            | "verb"
277                            | "id"
278                            | "instance_id"
279                            | "instance"
280                            | "step_kind"
281                            | "schema_version"
282                    ) {
283                        self.value(value);
284                    }
285                }
286            }
287            _ => {}
288        }
289    }
290}
291
292/// The application cannot authorize host execution by declaring configuration.
293pub fn host_grant_required() -> crate::substrate::SubstrateFault {
294    crate::substrate::SubstrateFault {
295        code: "execution.host_grant_required".into(),
296        message: "host execution requires an explicit caller grant".into(),
297        remediation: "use a container image or pass --allow-host-execution for code you trust with the controller host".into(),
298        context: Box::default(),
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    #[test]
307    fn child_environment_excludes_credentials_and_code_injection() {
308        for key in [
309            "STRIPE_API_KEY",
310            "AWS_SESSION_TOKEN",
311            "SSH_AUTH_SOCK",
312            "NODE_OPTIONS",
313            "PYTHONPATH",
314            "BASH_ENV",
315            "DYLD_INSERT_LIBRARIES",
316        ] {
317            assert!(!allowed_child_key(OsStr::new(key)));
318        }
319        assert!(allowed_child_key(OsStr::new("PATH")));
320    }
321
322    #[test]
323    fn redacts_credential_fields_and_values_without_corrupting_handles_or_error_codes() {
324        let redactor = Redactor::new([
325            "secret-canary".into(),
326            "postgres://user:database-password@db/one".into(),
327        ]);
328        let reference = SecretRef::new("owner", "database", "password");
329        let mut value = serde_json::json!({"code":"state.query_failed","message":"secret-canary / database-password","token":"unseen-token","password":reference});
330        redactor.value(&mut value);
331        assert_eq!(value["message"], "[redacted] / [redacted]");
332        assert_eq!(value["token"], "[redacted]");
333        assert_eq!(value["password"]["kind"], "secret_ref");
334        assert_eq!(value["code"], "state.query_failed");
335        assert!(!format!("{redactor:?}").contains("secret-canary"));
336    }
337}