envseal 0.3.12

Write-only secret vault with process-level access control — post-agent secret management
Documentation
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Security configuration — per-vault security tier settings.
//!
//! Configured on first vault access, modifiable only by authenticating
//! at the current highest tier. This prevents security downgrades by
//! attackers who have partial access.
//!
//! # Invariant
//!
//! To modify security settings, the user must authenticate using the
//! **currently configured** authentication method. An attacker who
//! obtains the passphrase but not the TOTP device cannot downgrade
//! from Lockdown to Standard.
//!
//! # File Format
//!
//! Stored as `security.toml` in the vault root, HMAC-signed with the
//! master key (same mechanism as `policy.toml`).

use serde::{Deserialize, Serialize};

/// The authentication method for passphrase entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InputMethod {
    /// Standard keyboard input via zenity/kdialog/osascript.
    /// Vulnerable to X11 keyloggers on X11 sessions.
    Keyboard,

    /// Randomized on-screen virtual keyboard (mouse-click input).
    /// Defeats keyloggers since key positions are shuffled per session.
    VirtualKeyboard,
}

/// The overall security tier for the vault.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SecurityTier {
    /// GUI popup only. Suitable for development API keys.
    Standard = 0,

    /// GUI popup with virtual keyboard. Defeats X11 keyloggers.
    Hardened = 1,

    /// GUI popup + virtual keyboard + TOTP. For production credentials.
    Lockdown = 2,
}

/// Security configuration for a vault.
///
/// Every field is individually toggleable for full granularity.
/// The `tier` field selects a preset, but each setting can be
/// overridden independently. Use `apply_preset()` to reset all
/// fields to a tier's defaults.
///
/// # Day-to-day developer experience
///
/// **Standard** (default): GUI popup appears, click allow, done.
/// Zero friction — the popup is the only thing between the agent
/// and the secret. This is what developers use for development keys.
///
/// **Hardened**: adds virtual keyboard + 2s delay. For staging/prod
/// keys where X11 keylogger risk matters.
///
/// **Lockdown**: adds challenge code + 5s delay + hard-blocks hostile
/// environments. For production infrastructure credentials.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct SecurityConfig {
    /// The active preset tier. Individual fields below can override.
    pub tier: SecurityTier,

    // -- Input method --
    /// How the passphrase is entered.
    pub input_method: InputMethod,

    /// Whether to auto-detect X11 and upgrade input method.
    /// When true, if the session is X11, `input_method` is automatically
    /// promoted to `VirtualKeyboard` regardless of the configured value.
    #[serde(default = "default_true")]
    pub x11_auto_upgrade: bool,

    // -- Challenge & delay --
    /// Whether a 4-digit challenge code is required before approval.
    /// Default: false (Standard), false (Hardened), true (Lockdown).
    #[serde(default)]
    pub challenge_required: bool,

    /// Approval delay in seconds before the popup appears.
    /// Prevents automated click-through. 0 = immediate.
    /// Default: 0 (Standard), 2 (Hardened), 5 (Lockdown).
    #[serde(default)]
    pub approval_delay_secs: u32,

    // -- Idle auto-lock (desktop GUI) --
    /// Seconds of GUI inactivity after which the cached unlocked
    /// vault is dropped, forcing the next operation to re-prompt
    /// for the passphrase. Tightens the window in which a
    /// background script can drive the GUI to peek/revoke secrets
    /// while the user is away.
    /// 0 = never auto-lock. Default: 60 (Standard), 30 (Hardened),
    /// 15 (Lockdown).
    #[serde(default = "default_auto_lock")]
    pub auto_lock_secs: u32,

    // -- TOTP --
    /// Whether TOTP is required for vault unlock.
    pub totp_required: bool,

    /// TOTP secret (encrypted with master key, stored as hex).
    /// None if TOTP is not configured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub totp_secret_encrypted: Option<String>,

    // -- Audit --
    /// Whether to log all approval events to the audit log.
    /// Default: true for all tiers.
    #[serde(default = "default_true")]
    pub audit_logging: bool,

    // -- Relay auth --
    /// Whether to require phone/relay confirmation for vault operations.
    /// When enabled, approval requests are forwarded to a paired device.
    /// Default: false for all tiers.
    #[serde(default)]
    pub relay_required: bool,

    /// Relay endpoint URL (set during pairing).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relay_endpoint: Option<String>,

    // -- Custom UI --
    /// Optional absolute path to a custom UI binary/script for prompts.
    ///
    /// This allows users on unsupported environments (e.g. Sway, i3, TUI over SSH)
    /// to provide their own prompt handler (like `rofi` or `fzf`). The custom
    /// binary is guaranteed by the master key's HMAC signature, preventing
    /// attacker tampering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_ui_cmd: Option<String>,

    /// Relay device ID (set during pairing).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relay_device_id: Option<String>,
    /// Pairing key (hex) used to verify relay approvals.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relay_pairing_key: Option<String>,

    // -- Rate limiting (anti-fatigue / anti-spam) --
    /// Minimum seconds between approval popups. Prevents agents from
    /// spamming the user with requests hoping they click "Allow" reflexively.
    /// 0 = no cooldown (Standard), 3 (Hardened), 10 (Lockdown).
    #[serde(default)]
    pub approval_cooldown_secs: u32,

    /// Maximum approval requests per minute. After this limit, all requests
    /// are auto-denied for the remainder of the minute.
    /// 0 = unlimited (Standard), 10 (Hardened), 5 (Lockdown).
    #[serde(default)]
    pub max_approvals_per_minute: u32,

    // -- Social engineering defenses --
    /// Show a prominent warning when the binary requesting access is in
    /// a user-writable directory (/tmp, /home, /var/tmp).
    /// Default: true for all tiers.
    #[serde(default = "default_true")]
    pub warn_untrusted_binary: bool,

    // -- Detector / policy overrides (signal taxonomy, see `guard::signal`) --
    /// Per-signal policy overrides keyed by stable
    /// [`crate::guard::SignalId`] string (e.g. `gui.input_injector.xdotool`,
    /// `env.preload.ld_preload`). The action string must be one of
    /// `ignore` / `log` / `warn` / `warn_with_challenge` / `block`.
    ///
    /// Stronger than `tier_overrides` — a per-signal entry wins
    /// against the (severity, tier) table for that one signal.
    ///
    /// Example `security.toml`:
    ///
    /// ```toml
    /// [signal_overrides]
    /// "gui.screen_recorder.obs_studio" = "ignore"
    /// "env.suspicious_loader_var.ld_library_path" = "warn"
    /// ```
    #[serde(default)]
    pub signal_overrides: std::collections::BTreeMap<String, String>,

    /// Per-(severity, tier) policy overrides. Severity is one of
    /// `info` / `warn` / `degraded` / `hostile` / `critical`. Tier
    /// is the active tier this override applies under
    /// (`standard` / `hardened` / `lockdown`). The action string
    /// uses the same vocabulary as `signal_overrides`.
    ///
    /// Example: a corporate deployment that wants `Warn`-severity
    /// signals to *block* under Hardened (default would just warn):
    ///
    /// ```toml
    /// [tier_overrides]
    /// "warn:hardened" = "block"
    /// ```
    #[serde(default)]
    pub tier_overrides: std::collections::BTreeMap<String, String>,

    // -- Allow Always rule lifetime --
    /// Default expiry (seconds since rule creation) applied when
    /// the operator picks "Allow Always" without specifying a
    /// duration. `None` = forever. Per-tier defaults:
    ///
    /// - Standard: `None`     (the operator's call)
    /// - Hardened: 30 days
    /// - Lockdown: 1 hour
    ///
    /// Configurable in the desktop GUI Settings tab; advanced users
    /// can also edit `security.sealed` indirectly via `envseal
    /// security set default_rule_expiry_secs <n>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_rule_expiry_secs: Option<u64>,

    /// Hard cap on the longest expiry the operator can pick at the
    /// approval popup. Even if the user clicks "Allow Forever",
    /// the rule is silently downgraded to `min(forever, this cap)`.
    /// Used by CTF mode to force every CTF-period approval to be
    /// short-lived (10 min) regardless of operator preference.
    /// `None` = no cap.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_rule_expiry_secs: Option<u64>,

    /// Generation counter of the policy file at the time this config
    /// was last saved. Used to detect policy rollback attacks: if the
    /// loaded policy has a lower generation than recorded here, the
    /// policy file was swapped for an older snapshot.
    #[serde(default)]
    pub policy_generation: u64,
}

fn default_true() -> bool {
    true
}

fn default_auto_lock() -> u32 {
    60
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self::preset_standard()
    }
}

impl SecurityConfig {
    /// Standard preset — zero friction.
    ///
    /// GUI popup appears, click allow, done. No delay, no challenge,
    /// no environment blocking. This is what the average AI developer
    /// uses day-to-day for development API keys.
    pub fn preset_standard() -> Self {
        Self {
            tier: SecurityTier::Standard,
            input_method: InputMethod::Keyboard,
            x11_auto_upgrade: true,
            challenge_required: false,
            approval_delay_secs: 0,
            auto_lock_secs: 60,
            totp_required: false,
            totp_secret_encrypted: None,
            audit_logging: true,
            relay_required: false,
            relay_endpoint: None,
            relay_device_id: None,
            relay_pairing_key: None,
            custom_ui_cmd: None,
            approval_cooldown_secs: 0,
            max_approvals_per_minute: 0, // unlimited
            warn_untrusted_binary: true,
            signal_overrides: std::collections::BTreeMap::new(),
            tier_overrides: std::collections::BTreeMap::new(),
            default_rule_expiry_secs: None, // Standard: forever (operator's call)
            max_rule_expiry_secs: None,
            policy_generation: 0,
        }
    }

    /// Hardened preset — defeats keyloggers and automation.
    ///
    /// Adds virtual keyboard for passphrase entry (defeats X11 keyloggers),
    /// 2-second approval delay (defeats automated click-through),
    /// and blocks hostile environments (remote desktop, input injection).
    pub fn preset_hardened() -> Self {
        Self {
            tier: SecurityTier::Hardened,
            input_method: InputMethod::VirtualKeyboard,
            x11_auto_upgrade: true,
            challenge_required: false,
            approval_delay_secs: 2,
            auto_lock_secs: 30,
            totp_required: false,
            totp_secret_encrypted: None,
            audit_logging: true,
            relay_required: false,
            relay_endpoint: None,
            relay_device_id: None,
            relay_pairing_key: None,
            custom_ui_cmd: None,
            approval_cooldown_secs: 3,
            max_approvals_per_minute: 10,
            warn_untrusted_binary: true,
            signal_overrides: std::collections::BTreeMap::new(),
            tier_overrides: std::collections::BTreeMap::new(),
            default_rule_expiry_secs: Some(30 * 24 * 3600), // Hardened: 30 days
            max_rule_expiry_secs: Some(90 * 24 * 3600),     // 90-day cap
            policy_generation: 0,
        }
    }

    /// Lockdown preset — maximum security for production credentials.
    ///
    /// Adds 4-digit challenge code (proves physical presence),
    /// 5-second approval delay, blocks both degraded and hostile
    /// environments. For production infrastructure tokens.
    pub fn preset_lockdown() -> Self {
        Self {
            tier: SecurityTier::Lockdown,
            input_method: InputMethod::VirtualKeyboard,
            x11_auto_upgrade: true,
            challenge_required: true,
            approval_delay_secs: 5,
            auto_lock_secs: 15,
            totp_required: false,
            totp_secret_encrypted: None,
            audit_logging: true,
            relay_required: false,
            relay_endpoint: None,
            relay_device_id: None,
            relay_pairing_key: None,
            custom_ui_cmd: None,
            approval_cooldown_secs: 10,
            max_approvals_per_minute: 5,
            warn_untrusted_binary: true,
            signal_overrides: std::collections::BTreeMap::new(),
            tier_overrides: std::collections::BTreeMap::new(),
            default_rule_expiry_secs: Some(3600), // Lockdown: 1 hour
            max_rule_expiry_secs: Some(24 * 3600),
            policy_generation: 0,
        }
    }

    /// Apply a preset, resetting all granular fields to that tier's defaults.
    ///
    /// Preserves TOTP, relay configuration, and any per-signal /
    /// per-tier policy overrides — those are user-authored
    /// customizations that survive a tier preset switch.
    pub fn apply_preset(&mut self, tier: SecurityTier) {
        let fresh = match tier {
            SecurityTier::Standard => Self::preset_standard(),
            SecurityTier::Hardened => Self::preset_hardened(),
            SecurityTier::Lockdown => Self::preset_lockdown(),
        };
        // Preserve pairing state, custom UI configuration, and TOTP
        let totp_enc = self.totp_secret_encrypted.take();
        let totp_req = self.totp_required;
        let relay_ep = self.relay_endpoint.take();
        let relay_id = self.relay_device_id.take();
        let relay_pairing_key = self.relay_pairing_key.take();
        let relay_require = self.relay_required;
        let custom_ui = self.custom_ui_cmd.take();
        let signal_ov = std::mem::take(&mut self.signal_overrides);
        let tier_ov = std::mem::take(&mut self.tier_overrides);
        let policy_gen = self.policy_generation;

        *self = fresh;
        self.totp_secret_encrypted = totp_enc;
        self.totp_required = totp_req;
        self.relay_endpoint = relay_ep;
        self.relay_device_id = relay_id;
        self.relay_pairing_key = relay_pairing_key;
        self.relay_required = relay_require;
        self.custom_ui_cmd = custom_ui;
        self.signal_overrides = signal_ov;
        self.tier_overrides = tier_ov;
        self.policy_generation = policy_gen;
    }

    /// Resolve the effective input method based on runtime environment.
    ///
    /// If `x11_auto_upgrade` is enabled and the current session is X11,
    /// the input method is promoted to `VirtualKeyboard` even if configured
    /// as `Keyboard`. This is a defense-in-depth measure.
    pub fn effective_input_method(&self) -> InputMethod {
        if self.x11_auto_upgrade && is_x11_session() {
            InputMethod::VirtualKeyboard
        } else {
            self.input_method
        }
    }

    /// Tier that must be authenticated against to modify config.
    pub fn required_auth_tier(&self) -> SecurityTier {
        self.tier
    }

    /// Validate a proposed tier change.
    ///
    /// Returns the authentication tier required to perform the change.
    /// Downgrades require authentication at the current (higher) tier;
    /// upgrades are always allowed after standard authentication.
    pub fn validate_tier_change(&self, new_tier: SecurityTier) -> SecurityTier {
        if new_tier < self.tier {
            self.tier
        } else {
            SecurityTier::Standard
        }
    }
}

/// Detect if the current session is X11 (vs Wayland or other).
fn is_x11_session() -> bool {
    #[cfg(target_os = "linux")]
    {
        if let Ok(session_type) = std::env::var("XDG_SESSION_TYPE") {
            return session_type == "x11";
        }
        // Fallback: DISPLAY set but no WAYLAND_DISPLAY = likely X11
        std::env::var("DISPLAY").is_ok() && std::env::var("WAYLAND_DISPLAY").is_err()
    }

    #[cfg(not(target_os = "linux"))]
    {
        false
    }
}