product-os-proxy 0.0.19

Product OS : Proxy builds on the work of hudsucker, taking it to the next level with a man-in-the-middle proxy server that can tunnel traffic through a VPN utilising Product OS : VPN.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! Programmatic CA trust probe, setup prompts, and install for agent tooling.

use product_os_security::certificates::ManagedCa;
use product_os_utilities::ProductOSError;
use serde::{Deserialize, Serialize};

use crate::ca::install::TrustInstaller;
use crate::ca::probe::active_platform_https_self_test;
use crate::ca::trust::{needs_reinstall, needs_uninstall_before_install, TrustProbe, TrustStatus};
use crate::config::{NetworkProxyCertificateAuthorityTrust, NetworkProxyTrustTarget};

/// Default trust store targets for browser automation.
#[must_use]
pub fn default_browser_trust_targets() -> Vec<String> {
    let mut targets = vec!["system".to_string(), "chromium-profile".to_string()];
    #[cfg(target_os = "macos")]
    targets.push("macos-user".to_string());
    targets
}

/// Trust stores required before starting a browser session.
///
/// On macOS, Chrome requires the MITM root in the **System** keychain. `ca_ensure_trust` with
/// `auto_install: true` prompts for the macOS administrator password via a GUI dialog.
#[must_use]
pub fn session_trust_targets() -> Vec<String> {
    #[cfg(target_os = "macos")]
    {
        // Install login keychain first (no admin), then System (admin GUI prompt).
        vec!["macos-user".to_string(), "system".to_string()]
    }
    #[cfg(not(target_os = "macos"))]
    {
        default_browser_trust_targets()
    }
}

/// Serialize [`TrustStatus`] for JSON APIs.
#[must_use]
pub fn trust_status_str(status: &TrustStatus) -> &'static str {
    match status {
        TrustStatus::Trusted => "trusted",
        TrustStatus::InstalledNotTrusted => "installed-not-trusted",
        TrustStatus::NotInstalled => "not-installed",
        TrustStatus::FingerprintMismatch => "fingerprint-mismatch",
        TrustStatus::BypassedViaFlag => "bypassed-via-flag",
        TrustStatus::Unknown(_) => "unknown",
    }
}

/// Per-target trust probe result.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetTrustStatus {
    /// Trust store target name (e.g. `system`, `chromium-profile`).
    pub name: String,
    /// Serialized [`TrustStatus`] for this target.
    pub status: String,
}

/// Full trust probe report for a managed CA.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaTrustReport {
    /// Whether every probed target is trusted (platform-aware via [`effective_all_trusted`]).
    pub all_trusted: bool,
    /// Per-target probe results.
    pub targets: Vec<TargetTrustStatus>,
    /// Path to the managed CA certificate on disk.
    pub ca_path: String,
    /// SHA-256 fingerprint of the managed CA.
    pub fingerprint: String,
}

/// Setup details embedded in agent-facing prompts.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaTrustSetup {
    /// Whether every probed target is trusted.
    pub all_trusted: bool,
    /// Per-target probe results.
    pub targets: Vec<TargetTrustStatus>,
    /// Path to the managed CA certificate on disk.
    pub ca_path: String,
    /// SHA-256 fingerprint of the managed CA.
    pub fingerprint: String,
    /// URL the user can open for guided setup.
    pub setup_url: String,
    /// Manual steps when automatic install is unavailable.
    pub manual_steps: Vec<String>,
}

/// Agent-facing setup-required envelope.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaSetupPrompt {
    /// `false` when setup is required before automation can proceed.
    pub ok: bool,
    /// Machine-readable status code for agents.
    pub code: &'static str,
    /// Human-readable explanation.
    pub message: String,
    /// Trust probe details for the setup UI.
    pub setup: CaTrustSetup,
    /// Suggested follow-up API operation.
    pub next_operation: &'static str,
    /// Whether the user must approve installation.
    pub requires_user_consent: bool,
}

/// Options for [`ensure_ca_trust`].
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnsureTrustOptions {
    /// Attempt automatic installation when targets are not trusted.
    pub auto_install: bool,
    /// Optional subset of trust targets; defaults to [`default_browser_trust_targets`].
    #[serde(default)]
    pub targets: Option<Vec<String>>,
    /// Run an active HTTPS probe after install.
    #[serde(default)]
    pub active_probe: bool,
}

/// Per-target install outcome.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TargetInstallResult {
    /// Trust store target name.
    pub name: String,
    /// Whether installation succeeded for this target.
    pub ok: bool,
    /// Error message when installation failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Action taken (install, reinstall, skip).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
}

/// Result of an ensure-trust operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EnsureTrustResult {
    /// Whether trust is sufficient for browser automation.
    pub all_trusted: bool,
    /// Full probe report after install attempts.
    pub report: CaTrustReport,
    /// Per-target install outcomes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub install_results: Vec<TargetInstallResult>,
    /// Active HTTPS probe result, when requested.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_probe_ok: Option<bool>,
    /// Active probe error message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_probe_error: Option<String>,
}

/// Probe configured trust stores for a managed CA.
#[must_use]
pub fn probe_trust_report(managed: &ManagedCa, targets: &[String]) -> CaTrustReport {
    let effective = if targets.is_empty() {
        default_browser_trust_targets()
    } else {
        targets.to_vec()
    };
    let target_statuses: Vec<TargetTrustStatus> = effective
        .iter()
        .map(|name| TargetTrustStatus {
            name: name.clone(),
            status: trust_status_str(&TrustProbe::check_target(managed, name)).to_string(),
        })
        .collect();
    let all_trusted = effective_all_trusted(&target_statuses);
    CaTrustReport {
        all_trusted,
        targets: target_statuses,
        ca_path: managed.cert_path().display().to_string(),
        fingerprint: managed
            .fingerprint_sha256()
            .unwrap_or_else(|_| "unknown".into()),
    }
}

/// Whether every target in a probe report is explicitly `trusted`.
#[must_use]
pub fn strict_all_trusted(targets: &[TargetTrustStatus]) -> bool {
    targets.iter().all(|t| t.status == "trusted")
}

/// Whether trust is sufficient for browser automation (platform-specific fallbacks).
///
/// Prefer [`session_trust_targets`] + [`strict_all_trusted`] for session gates.
#[must_use]
pub fn effective_all_trusted(targets: &[TargetTrustStatus]) -> bool {
    if targets.iter().all(|t| t.status == "trusted") {
        return true;
    }
    #[cfg(target_os = "macos")]
    {
        let system_ok = targets
            .iter()
            .any(|t| t.name == "system" && t.status == "trusted");
        let user_ok = targets.iter().any(|t| {
            (t.name == "macos-user" || t.name == "user-keychain") && t.status == "trusted"
        });
        if system_ok && user_ok {
            return targets
                .iter()
                .all(|t| t.status == "trusted" || ignorable_macos_nss_target(t));
        }
    }
    false
}

#[cfg(target_os = "macos")]
fn ignorable_macos_nss_target(t: &TargetTrustStatus) -> bool {
    matches!(t.name.as_str(), "chromium-profile" | "chromium" | "firefox") && t.status == "unknown"
}

#[cfg(not(target_os = "macos"))]
fn ignorable_macos_nss_target(_t: &TargetTrustStatus) -> bool {
    false
}

/// Platform-specific manual trust steps for agents to relay to users.
#[must_use]
pub fn manual_trust_steps(managed: &ManagedCa) -> Vec<String> {
    let mut steps = vec![
        format!("CA file: {}", managed.cert_path().display()),
        format!(
            "Fingerprint: {}",
            managed
                .fingerprint_sha256()
                .unwrap_or_else(|_| "unknown".into())
        ),
    ];
    #[cfg(target_os = "macos")]
    {
        steps.push(
            "Call ca_ensure_trust with auto_install: true — macOS will show an administrator \
             password dialog to install into the System keychain (required for Chrome)."
                .into(),
        );
        steps.push(
            "Login keychain (no admin): pos-proxy cert install --target macos-user --trust".into(),
        );
    }
    #[cfg(target_os = "windows")]
    steps.push("certmgr.msc → Trusted Root Certification Authorities → Import".into());
    #[cfg(target_os = "linux")]
    steps.push("Copy to /usr/local/share/ca-certificates/ and run update-ca-certificates".into());
    steps.push(
        "Firefox (persistent profiles): pos-proxy cert install --target firefox --trust".into(),
    );
    steps.push(
        "Firefox (agent ephemeral profiles): the browser engine seeds each --profile directory \
         via distribution/certs + policies.Certificates.Install before launch — global NSS \
         install is optional."
            .into(),
    );
    steps.push("Chromium profile: pos-proxy cert install --target chromium-profile --trust".into());
    steps
}

/// Build the agent-facing setup-required prompt from a probe report.
#[must_use]
pub fn build_setup_prompt(
    report: &CaTrustReport,
    proxy_host: &str,
    proxy_port: u16,
) -> CaSetupPrompt {
    let setup_url = format!("http://{proxy_host}:{proxy_port}/_product-os/setup");
    let manual_steps = manual_trust_steps_from_path(&report.ca_path, &report.fingerprint);
    CaSetupPrompt {
        ok: false,
        code: "ca_setup_required",
        message: setup_required_message(report),
        setup: CaTrustSetup {
            all_trusted: report.all_trusted,
            targets: report.targets.clone(),
            ca_path: report.ca_path.clone(),
            fingerprint: report.fingerprint.clone(),
            setup_url,
            manual_steps,
        },
        next_operation: "ca_ensure_trust",
        requires_user_consent: true,
    }
}

fn setup_required_message(report: &CaTrustReport) -> String {
    let mismatched: Vec<&str> = report
        .targets
        .iter()
        .filter(|t| t.status == "fingerprint-mismatch")
        .map(|t| t.name.as_str())
        .collect();
    if !mismatched.is_empty() {
        return format!(
            "Stale MITM proxy root CA fingerprint in {}. Ask the user for permission to \
             reinstall it, then call ca_ensure_trust with auto_install: true.",
            mismatched.join(", ")
        );
    }
    #[cfg(target_os = "macos")]
    {
        if report
            .targets
            .iter()
            .any(|t| t.name == "system" && t.status == "not-installed")
        {
            return "Chrome requires the MITM root CA in the macOS System keychain. Ask the \
                    user for permission, then call ca_ensure_trust with auto_install: true — \
                    a macOS administrator password dialog will appear for System keychain install."
                .into();
        }
    }
    "MITM proxy root CA is not trusted. Ask the user for permission to install it, \
     then call ca_ensure_trust with auto_install: true."
        .into()
}

/// One-line sudo command to trust the managed CA in the macOS System keychain (Chrome).
#[must_use]
pub fn system_trust_install_command(ca_path: &str) -> String {
    format!(
        "sudo security add-trusted-cert -d -r trustRoot -p ssl -k /Library/Keychains/System.keychain {ca_path}"
    )
}

fn manual_trust_steps_from_path(ca_path: &str, fingerprint: &str) -> Vec<String> {
    let mut steps = vec![
        format!("CA file: {ca_path}"),
        format!("Fingerprint: {fingerprint}"),
    ];
    #[cfg(target_os = "macos")]
    {
        steps.push(
            "Call ca_ensure_trust with auto_install: true — macOS will show an administrator \
             password dialog to install into the System keychain (required for Chrome)."
                .into(),
        );
        steps.push(
            "Login keychain (no admin): pos-proxy cert install --target macos-user --trust".into(),
        );
    }
    #[cfg(target_os = "windows")]
    steps.push("certmgr.msc → Trusted Root Certification Authorities → Import".into());
    #[cfg(target_os = "linux")]
    steps.push("Copy to /usr/local/share/ca-certificates/ and run update-ca-certificates".into());
    steps.push(
        "Firefox (persistent profiles): pos-proxy cert install --target firefox --trust".into(),
    );
    steps.push(
        "Firefox (agent ephemeral profiles): the browser engine seeds each --profile directory \
         via distribution/certs + policies.Certificates.Install before launch — global NSS \
         install is optional."
            .into(),
    );
    steps.push("Chromium profile: pos-proxy cert install --target chromium-profile --trust".into());
    steps
}

fn resolve_targets(
    trust_config: &NetworkProxyCertificateAuthorityTrust,
    override_targets: Option<Vec<String>>,
) -> Vec<String> {
    override_targets.unwrap_or_else(|| {
        if trust_config.targets.is_empty() {
            default_browser_trust_targets()
        } else {
            trust_config.targets.clone()
        }
    })
}

/// Install CA to all given targets (used by guide and ensure API).
pub(crate) fn auto_install_targets_internal(
    managed: &ManagedCa,
    targets: &[String],
) -> Vec<TargetInstallResult> {
    let mut results = Vec::new();
    for target in targets {
        match NetworkProxyTrustTarget::parse(target) {
            Some(parsed) => match TrustInstaller::install(managed, parsed, true) {
                Ok(()) => results.push(TargetInstallResult {
                    name: target.clone(),
                    ok: true,
                    error: None,
                    action: Some("install".into()),
                }),
                Err(e) => results.push(TargetInstallResult {
                    name: target.clone(),
                    ok: false,
                    error: Some(format!("{e}")),
                    action: Some("install".into()),
                }),
            },
            None => results.push(TargetInstallResult {
                name: target.clone(),
                ok: false,
                error: Some(format!("unknown trust target: {target}")),
                action: None,
            }),
        }
    }
    results
}

fn reinstall_target(
    managed: &ManagedCa,
    target: &str,
    prior_status: TrustStatus,
) -> TargetInstallResult {
    let Some(parsed) = NetworkProxyTrustTarget::parse(target) else {
        return TargetInstallResult {
            name: target.to_string(),
            ok: false,
            error: Some(format!("unknown trust target: {target}")),
            action: None,
        };
    };

    if needs_uninstall_before_install(&prior_status) {
        let _ = TrustInstaller::uninstall(managed, parsed);
    }
    match TrustInstaller::install(managed, parsed, true) {
        Ok(()) => TargetInstallResult {
            name: target.to_string(),
            ok: true,
            error: None,
            action: Some("reinstall".into()),
        },
        Err(e) => TargetInstallResult {
            name: target.to_string(),
            ok: false,
            error: Some(format!("{e}")),
            action: Some("reinstall".into()),
        },
    }
}

/// Probe trust, optionally uninstall+reinstall stale CAs, re-probe, and run platform HTTPS probe.
pub async fn ensure_ca_trust(
    managed: &ManagedCa,
    trust_config: &NetworkProxyCertificateAuthorityTrust,
    proxy_host: &str,
    proxy_port: u16,
    opts: &EnsureTrustOptions,
) -> Result<EnsureTrustResult, ProductOSError> {
    let targets = resolve_targets(trust_config, opts.targets.clone());
    let mut install_results = Vec::new();

    if opts.auto_install && trust_config.allow_auto_install {
        for target in &targets {
            let status = TrustProbe::check_target(managed, target);
            if needs_reinstall(&status) {
                install_results.push(reinstall_target(managed, target, status));
            }
        }
    }

    let report = probe_trust_report(managed, &targets);
    let mut active_probe_ok = None;
    let mut active_probe_error = None;

    if opts.active_probe && report.all_trusted {
        match active_platform_https_self_test(proxy_host, proxy_port).await {
            Ok(()) => active_probe_ok = Some(true),
            Err(err) => {
                active_probe_ok = Some(false);
                active_probe_error = Some(err);
            }
        }
    } else if opts.active_probe && !report.all_trusted {
        active_probe_ok = Some(false);
        active_probe_error = Some(
            "skipped platform HTTPS probe because fingerprint-matched trust is incomplete".into(),
        );
    }

    let all_trusted = report.all_trusted && active_probe_ok.unwrap_or(true);

    Ok(EnsureTrustResult {
        all_trusted,
        report,
        install_results,
        active_probe_ok,
        active_probe_error,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_targets_include_chromium_profile() {
        let t = default_browser_trust_targets();
        assert!(t.iter().any(|x| x == "chromium-profile"));
        assert!(t.iter().any(|x| x == "system"));
    }

    #[test]
    fn session_trust_targets_macos_require_system_and_login() {
        let t = session_trust_targets();
        #[cfg(target_os = "macos")]
        {
            assert!(t.iter().any(|x| x == "system"));
            assert!(t.iter().any(|x| x == "macos-user"));
            assert!(!t.iter().any(|x| x == "chromium-profile"));
        }
    }

    #[test]
    fn strict_all_trusted_requires_every_target_trusted() {
        let targets = vec![
            TargetTrustStatus {
                name: "system".into(),
                status: "trusted".into(),
            },
            TargetTrustStatus {
                name: "macos-user".into(),
                status: "unknown".into(),
            },
        ];
        assert!(!strict_all_trusted(&targets));
    }

    #[test]
    fn trust_status_str_maps_fingerprint_mismatch() {
        assert_eq!(trust_status_str(&TrustStatus::Trusted), "trusted");
        assert_eq!(
            trust_status_str(&TrustStatus::NotInstalled),
            "not-installed"
        );
        assert_eq!(
            trust_status_str(&TrustStatus::FingerprintMismatch),
            "fingerprint-mismatch"
        );
    }

    #[test]
    fn needs_uninstall_before_install_skips_not_installed() {
        assert!(!needs_uninstall_before_install(&TrustStatus::NotInstalled));
        assert!(needs_uninstall_before_install(
            &TrustStatus::FingerprintMismatch
        ));
    }

    #[test]
    fn needs_reinstall_detects_mismatch() {
        assert!(needs_reinstall(&TrustStatus::FingerprintMismatch));
        assert!(needs_reinstall(&TrustStatus::NotInstalled));
        assert!(!needs_reinstall(&TrustStatus::Trusted));
    }

    #[test]
    fn effective_all_trusted_macos_ignores_unknown_nss_when_keychains_trusted() {
        let targets = vec![
            TargetTrustStatus {
                name: "system".into(),
                status: "trusted".into(),
            },
            TargetTrustStatus {
                name: "macos-user".into(),
                status: "trusted".into(),
            },
            TargetTrustStatus {
                name: "chromium-profile".into(),
                status: "unknown".into(),
            },
        ];
        assert!(effective_all_trusted(&targets));
    }

    #[test]
    fn effective_all_trusted_requires_all_when_keychains_missing() {
        let targets = vec![
            TargetTrustStatus {
                name: "system".into(),
                status: "trusted".into(),
            },
            TargetTrustStatus {
                name: "macos-user".into(),
                status: "not-installed".into(),
            },
            TargetTrustStatus {
                name: "chromium-profile".into(),
                status: "unknown".into(),
            },
        ];
        assert!(!effective_all_trusted(&targets));
    }

    #[test]
    fn setup_required_message_mentions_fingerprint_mismatch() {
        let report = CaTrustReport {
            all_trusted: false,
            targets: vec![TargetTrustStatus {
                name: "system".into(),
                status: "fingerprint-mismatch".into(),
            }],
            ca_path: "/tmp/ca.pem".into(),
            fingerprint: "aa:bb".into(),
        };
        let msg = setup_required_message(&report);
        assert!(msg.contains("Stale MITM proxy root CA fingerprint"));
        assert!(msg.contains("system"));
    }
}