jamjet-api 0.3.2

JamJet REST API server — control plane for workflow management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Secret management — env-var backed with `${SECRET_NAME}` expansion (G2.3).
//!
//! Secrets are referenced in workflow payloads as `${MY_SECRET}`. At execution
//! time, the worker or API resolves them from environment variables. A pluggable
//! `SecretBackend` trait allows future integration with Vault, AWS Secrets Manager, etc.
//!
//! ## Redaction (G2.4)
//! `redact_value()` replaces resolved secret values with `[REDACTED]` before
//! they appear in logs or traces.

// ── Secret backend trait ──────────────────────────────────────────────────────

pub trait SecretBackend: Send + Sync {
    /// Resolve a named secret to its plaintext value.
    fn get(&self, name: &str) -> Option<String>;
}

// ── Env-var backend ───────────────────────────────────────────────────────────

pub struct EnvSecretBackend;

impl SecretBackend for EnvSecretBackend {
    fn get(&self, name: &str) -> Option<String> {
        std::env::var(name).ok()
    }
}

// ── File-based backend (K8s mounted secrets, Docker secrets) ─────────────────

/// Reads secrets from a directory of files (one file per secret).
///
/// Designed for Kubernetes mounted secrets (`/var/run/secrets/`) and Docker
/// secrets (`/run/secrets/`). Each file name is the secret name and the file
/// content is the secret value.
pub struct FileSecretBackend {
    dir: std::path::PathBuf,
}

impl FileSecretBackend {
    pub fn new(dir: impl Into<std::path::PathBuf>) -> Self {
        Self { dir: dir.into() }
    }

    /// Create from `JAMJET_SECRETS_DIR` env var, or return None.
    pub fn from_env() -> Option<Self> {
        std::env::var("JAMJET_SECRETS_DIR").ok().map(Self::new)
    }
}

impl SecretBackend for FileSecretBackend {
    fn get(&self, name: &str) -> Option<String> {
        // Prevent path traversal
        if name.contains('/') || name.contains('\\') || name.contains("..") {
            return None;
        }
        let path = self.dir.join(name);
        std::fs::read_to_string(path)
            .ok()
            .map(|s| s.trim().to_string())
    }
}

// ── HashiCorp Vault backend ──────────────────────────────────────────────────

/// Reads secrets from HashiCorp Vault's KV v2 engine via the `vault` CLI.
///
/// Requires the `vault` CLI to be on PATH and authenticated (e.g., via
/// `VAULT_ADDR` and `VAULT_TOKEN` env vars). Secret names are mapped to
/// Vault paths as `{mount}/{prefix}/{name}`.
pub struct VaultSecretBackend {
    /// KV mount path (e.g., "secret").
    mount: String,
    /// Key prefix within the mount (e.g., "jamjet/production").
    prefix: String,
    /// Field name within the Vault secret. Default: "value".
    field: String,
}

impl VaultSecretBackend {
    pub fn new(mount: impl Into<String>, prefix: impl Into<String>) -> Self {
        Self {
            mount: mount.into(),
            prefix: prefix.into(),
            field: "value".to_string(),
        }
    }

    /// Create from env vars: `VAULT_SECRET_MOUNT`, `VAULT_SECRET_PREFIX`.
    pub fn from_env() -> Option<Self> {
        let mount = std::env::var("VAULT_SECRET_MOUNT").unwrap_or_else(|_| "secret".to_string());
        let prefix = std::env::var("VAULT_SECRET_PREFIX").ok()?;
        Some(Self::new(mount, prefix))
    }
}

impl SecretBackend for VaultSecretBackend {
    fn get(&self, name: &str) -> Option<String> {
        // Prevent path traversal
        if name.contains("..") {
            return None;
        }
        let path = format!("{}/{}/{}", self.mount, self.prefix, name);
        let output = std::process::Command::new("vault")
            .args(["kv", "get", "-field", &self.field, &path])
            .output()
            .ok()?;
        if output.status.success() {
            String::from_utf8(output.stdout)
                .ok()
                .map(|s| s.trim().to_string())
        } else {
            None
        }
    }
}

// ── AWS Secrets Manager backend ──────────────────────────────────────────────

/// Reads secrets from AWS Secrets Manager via the `aws` CLI.
///
/// Requires the `aws` CLI to be configured (credentials, region, etc.).
/// Secret names are used directly as AWS secret IDs, optionally with a prefix.
pub struct AwsSecretBackend {
    /// Optional prefix prepended to all secret names (e.g., "jamjet/production/").
    prefix: String,
}

impl AwsSecretBackend {
    pub fn new(prefix: impl Into<String>) -> Self {
        Self {
            prefix: prefix.into(),
        }
    }

    /// Create from `AWS_SECRET_PREFIX` env var.
    pub fn from_env() -> Option<Self> {
        let prefix = std::env::var("AWS_SECRET_PREFIX").unwrap_or_default();
        // Only return if AWS credentials are likely configured
        if std::env::var("AWS_DEFAULT_REGION").is_ok()
            || std::env::var("AWS_REGION").is_ok()
            || std::env::var("AWS_PROFILE").is_ok()
        {
            Some(Self::new(prefix))
        } else {
            None
        }
    }
}

impl SecretBackend for AwsSecretBackend {
    fn get(&self, name: &str) -> Option<String> {
        let secret_id = format!("{}{}", self.prefix, name);
        let output = std::process::Command::new("aws")
            .args([
                "secretsmanager",
                "get-secret-value",
                "--secret-id",
                &secret_id,
                "--query",
                "SecretString",
                "--output",
                "text",
            ])
            .output()
            .ok()?;
        if output.status.success() {
            String::from_utf8(output.stdout)
                .ok()
                .map(|s| s.trim().to_string())
        } else {
            None
        }
    }
}

// ── Composite backend (chaining) ────────────────────────────────────────────

/// Tries multiple backends in order, returning the first match.
pub struct CompositeSecretBackend {
    backends: Vec<Box<dyn SecretBackend>>,
}

impl CompositeSecretBackend {
    pub fn new(backends: Vec<Box<dyn SecretBackend>>) -> Self {
        Self { backends }
    }

    /// Build the default backend stack from environment configuration.
    ///
    /// Priority: Vault > AWS Secrets Manager > File > Env vars (always present).
    pub fn from_env() -> Self {
        let mut backends: Vec<Box<dyn SecretBackend>> = Vec::new();

        if let Some(vault) = VaultSecretBackend::from_env() {
            backends.push(Box::new(vault));
        }
        if let Some(aws) = AwsSecretBackend::from_env() {
            backends.push(Box::new(aws));
        }
        if let Some(file) = FileSecretBackend::from_env() {
            backends.push(Box::new(file));
        }
        backends.push(Box::new(EnvSecretBackend));

        Self { backends }
    }
}

impl SecretBackend for CompositeSecretBackend {
    fn get(&self, name: &str) -> Option<String> {
        for backend in &self.backends {
            if let Some(value) = backend.get(name) {
                return Some(value);
            }
        }
        None
    }
}

// ── Secret expansion ──────────────────────────────────────────────────────────

/// Expand `${SECRET_NAME}` placeholders in a string using the given backend.
/// Unresolvable secrets are left as-is.
pub fn expand(s: &str, backend: &dyn SecretBackend) -> String {
    let mut result = s.to_string();
    let mut pos = 0;

    while let Some(start) = result[pos..].find("${") {
        let abs_start = pos + start;
        if let Some(end) = result[abs_start..].find('}') {
            let abs_end = abs_start + end;
            let name = &result[abs_start + 2..abs_end];
            if let Some(value) = backend.get(name) {
                result = format!(
                    "{}{}{}",
                    &result[..abs_start],
                    value,
                    &result[abs_end + 1..]
                );
                // Don't advance past the substitution — the value itself might contain ${}
                // but to avoid infinite loops just advance past what we replaced.
                pos = abs_start + value.len();
            } else {
                pos = abs_end + 1;
            }
        } else {
            break;
        }
    }

    result
}

/// Expand all string values in a JSON object recursively.
pub fn expand_json(value: &serde_json::Value, backend: &dyn SecretBackend) -> serde_json::Value {
    match value {
        serde_json::Value::String(s) => serde_json::Value::String(expand(s, backend)),
        serde_json::Value::Object(map) => {
            let expanded: serde_json::Map<String, serde_json::Value> = map
                .iter()
                .map(|(k, v)| (k.clone(), expand_json(v, backend)))
                .collect();
            serde_json::Value::Object(expanded)
        }
        serde_json::Value::Array(arr) => {
            serde_json::Value::Array(arr.iter().map(|v| expand_json(v, backend)).collect())
        }
        other => other.clone(),
    }
}

// ── Secret redaction ──────────────────────────────────────────────────────────

/// Build a redaction map from known secret names (reads them to find their values,
/// then replaces those values with `[REDACTED]` in any string).
pub struct Redactor {
    known_values: Vec<String>,
}

impl Redactor {
    /// Create a redactor that will mask the values of all listed secret names.
    pub fn from_names(names: &[&str], backend: &dyn SecretBackend) -> Self {
        let known_values = names
            .iter()
            .filter_map(|n| backend.get(n))
            .filter(|v| v.len() >= 8) // don't redact very short values (false positives)
            .collect();
        Self { known_values }
    }

    /// Redact all known secret values from a string.
    pub fn redact_str(&self, s: &str) -> String {
        let mut result = s.to_string();
        for secret in &self.known_values {
            result = result.replace(secret.as_str(), "[REDACTED]");
        }
        result
    }

    /// Redact all known secret values from a JSON value.
    pub fn redact_json(&self, value: &serde_json::Value) -> serde_json::Value {
        match value {
            serde_json::Value::String(s) => serde_json::Value::String(self.redact_str(s)),
            serde_json::Value::Object(map) => {
                let redacted = map
                    .iter()
                    .map(|(k, v)| (k.clone(), self.redact_json(v)))
                    .collect();
                serde_json::Value::Object(redacted)
            }
            serde_json::Value::Array(arr) => {
                serde_json::Value::Array(arr.iter().map(|v| self.redact_json(v)).collect())
            }
            other => other.clone(),
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    struct MapBackend(HashMap<String, String>);
    impl SecretBackend for MapBackend {
        fn get(&self, name: &str) -> Option<String> {
            self.0.get(name).cloned()
        }
    }

    fn backend(pairs: &[(&str, &str)]) -> MapBackend {
        MapBackend(
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        )
    }

    #[test]
    fn test_expand_simple() {
        let b = backend(&[("MY_KEY", "secret123")]);
        assert_eq!(expand("Bearer ${MY_KEY}", &b), "Bearer secret123");
    }

    #[test]
    fn test_expand_missing() {
        let b = backend(&[]);
        assert_eq!(expand("Bearer ${MISSING}", &b), "Bearer ${MISSING}");
    }

    #[test]
    fn test_expand_json() {
        let b = backend(&[("DB_PASS", "pa$$word")]);
        let v = serde_json::json!({ "password": "${DB_PASS}", "user": "admin" });
        let expanded = expand_json(&v, &b);
        assert_eq!(expanded["password"], "pa$$word");
        assert_eq!(expanded["user"], "admin");
    }

    #[test]
    fn test_redactor() {
        let b = backend(&[("API_KEY", "super-secret-value")]);
        let r = Redactor::from_names(&["API_KEY"], &b);
        assert_eq!(
            r.redact_str("key is super-secret-value!"),
            "key is [REDACTED]!"
        );
    }

    #[test]
    fn test_file_backend() {
        let dir = std::env::temp_dir().join("jamjet-secrets-test");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("DB_PASSWORD"), "hunter2\n").unwrap();
        std::fs::write(dir.join("API_KEY"), "  sk-abc123  ").unwrap();

        let b = FileSecretBackend::new(&dir);
        assert_eq!(b.get("DB_PASSWORD"), Some("hunter2".to_string()));
        assert_eq!(b.get("API_KEY"), Some("sk-abc123".to_string()));
        assert_eq!(b.get("MISSING"), None);

        // Path traversal prevention
        assert_eq!(b.get("../etc/passwd"), None);
        assert_eq!(b.get("foo/bar"), None);

        // Cleanup
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn test_composite_backend_priority() {
        let high = backend(&[("SHARED", "from-high"), ("HIGH_ONLY", "h")]);
        let low = backend(&[("SHARED", "from-low"), ("LOW_ONLY", "l")]);
        let composite = CompositeSecretBackend::new(vec![Box::new(high), Box::new(low)]);

        // High-priority backend wins for shared key
        assert_eq!(composite.get("SHARED"), Some("from-high".to_string()));
        // Falls through to low-priority for unique keys
        assert_eq!(composite.get("LOW_ONLY"), Some("l".to_string()));
        assert_eq!(composite.get("HIGH_ONLY"), Some("h".to_string()));
        assert_eq!(composite.get("MISSING"), None);
    }
}