Skip to content

Visual Studio Code, rebuilt in Rust

Rust
27.8 KB
Raw Blame
//! The proxy requests of MainThreadWorkspace: `$loadCertificates` (requestService.ts `loadCertificates`, the macOS
//! keychain certificates proxyResolver.ts adds to the host's TLS connections), `$resolveProxy` and
//! `$lookupKerberosAuthorization` (exthost::request), and `$lookupAuthorization` (auth.ts `ProxyAuthService`:
//! credentials for a proxy that answered 407, with window.ts's proxy login dialog).

use std::collections::{HashMap, HashSet, VecDeque};

use base64::Engine;
use futures::channel::oneshot;
use gpui::{Context, Window};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use super::Workbench;
use super::dialog_view::{CustomDialog, DialogButton, DialogInput, DialogResult};
use crate::commands::Outcome;

/// window.ts: the Remember checkbox's last state, in StorageScope.APPLICATION.
const REMEMBER_CREDENTIALS_KEY: &str = "window.rememberProxyCredentials";

/// `ProxyAuthService`'s memory between requests, per auth info hash.
#[derive(Default)]
pub struct ProxyAuth {
    /// The configured credentials last answered and whether the proxy rejected them (`configuredCredentialsStates`).
    configured: HashMap<String, (String, bool)>,
    /// `sessionCredentials`: what the login dialog or the stored credentials last answered.
    session: HashMap<String, Credentials>,
    /// `cancelledAuthInfoHashes`: a login cancelled once shows no dialog again.
    cancelled: HashSet<String>,
    /// `pendingProxyResolves`: the requests answered when the login of their auth info ends.
    pending: HashMap<String, Vec<oneshot::Sender<Result<Value, Value>>>>,
    /// `currentDialog`'s chain: one login dialog at a time, the shown one first.
    logins: VecDeque<Login>,
}

struct Login {
    auth_info: Value,
    key: String,
    stored: Option<Credentials>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Credentials {
    pub username: String,
    pub password: String,
}

/// What `doResolveProxyCredentials` does for a request: answer at once, or ask with the login dialog.
#[derive(Debug, PartialEq)]
pub enum Resolution {
    Answer(Option<Credentials>),
    AskUser { stored: Option<Credentials> },
}

impl Workbench {
    /// `$loadCertificates`: read off the UI thread, answered when `security` is done.
    pub(crate) fn load_certificates(&self, cx: &mut gpui::Context<Self>) -> Outcome {
        let (sender, receiver) = futures::channel::oneshot::channel();
        cx.background_executor()
            .spawn(async move {
                let _ = sender.send(Ok(json!(read_mac_ca_certificates())));
            })
            .detach();
        Outcome::Pending(receiver)
    }

    /// `$resolveProxy(url)`: off the UI thread, as the system settings may name a PAC script to fetch and run.
    pub(crate) fn resolve_proxy(&self, url: &Value, cx: &mut gpui::Context<Self>) -> Outcome {
        let url = url.as_str().unwrap_or_default().to_owned();
        let (sender, receiver) = futures::channel::oneshot::channel();
        cx.background_executor()
            .spawn(async move {
                let _ = sender.send(Ok(json!(exthost::request::resolve_proxy(&url))));
            })
            .detach();
        Outcome::Pending(receiver)
    }

    /// `$lookupKerberosAuthorization(url)`, with requestService.ts `getConfigValue`'s user or default principal.
    pub(crate) fn lookup_kerberos_authorization(&self, url: &Value, cx: &mut gpui::Context<Self>) -> Outcome {
        let url = url.as_str().unwrap_or_default().to_owned();
        let inspected = self.settings.lock().unwrap().configuration.inspect("http.proxyKerberosServicePrincipal", &Default::default());
        let spn = inspected.user_local.value.or(inspected.default_value).and_then(|spn| spn.as_str().map(str::to_owned));
        let (sender, receiver) = futures::channel::oneshot::channel();
        cx.background_executor()
            .spawn(async move {
                let _ = sender.send(Ok(json!(exthost::request::kerberos_authorization(&url, spn.as_deref()))));
            })
            .detach();
        Outcome::Pending(receiver)
    }

    /// `$lookupAuthorization(authInfo)`.
    pub(crate) fn lookup_authorization(&mut self, auth_info: &Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        if auth_info["isProxy"] != true {
            return Outcome::Ready(Ok(Value::Null));
        }
        // `hash({ scheme, host, port })`: any stable key of the three serves.
        let key = json!([auth_info["scheme"], auth_info["host"], auth_info["port"]]).to_string();
        let (sender, receiver) = oneshot::channel();
        if let Some(waiting) = self.proxy_auth.pending.get_mut(&key) {
            waiting.push(sender);
            return Outcome::Pending(receiver);
        }
        let proxy = self.setting("http.proxy").as_str().unwrap_or_default().trim().to_owned();
        let output = &self.output;
        let mut stored = || stored_credentials::read(&key).unwrap_or_else(|error| {
            output.log_window(5, &format!("auth#doResolveProxyCredentials (proxy) - {error}"));
            None
        });
        match resolve_proxy_credentials(&mut self.proxy_auth, auth_info, &key, self.skip_dialogs, &proxy, &|name| std::env::var(name).ok(), &mut stored) {
            Resolution::Answer(credentials) => Outcome::Ready(Ok(credentials_value(credentials.as_ref()))),
            Resolution::AskUser { stored } => {
                self.proxy_auth.pending.insert(key.clone(), vec![sender]);
                self.proxy_auth.logins.push_back(Login { auth_info: auth_info.clone(), key, stored });
                if self.proxy_auth.logins.len() == 1 {
                    self.show_proxy_login(window, cx);
                }
                Outcome::Pending(receiver)
            }
        }
    }

    /// `showProxyCredentialsDialog` for the first waiting login, with window.ts's `vscode:openProxyAuthenticationDialog`
    /// handler; a login cancelled before answers without a dialog.
    fn show_proxy_login(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        while let Some(login) = self.proxy_auth.logins.front() {
            if !self.proxy_auth.cancelled.contains(&login.key) {
                break;
            }
            let key = login.key.clone();
            self.proxy_auth.logins.pop_front();
            self.answer_proxy_login(&key, None);
        }
        let Some(login) = self.proxy_auth.logins.front() else { return };
        let shown = self.proxy_auth.session.get(&login.key).or(login.stored.as_ref());
        let username = shown.map(|credentials| credentials.username.clone()).unwrap_or_default();
        let password = shown.map(|credentials| credentials.password.clone()).unwrap_or_default();
        let text = |value: &Value| value.as_str().map_or_else(|| value.to_string(), str::to_owned);
        let detail = format!("The proxy {}:{} requires a username and password.", text(&login.auth_info["host"]), text(&login.auth_info["port"]));
        let remember = self.application_storage.lock().unwrap().get(REMEMBER_CREDENTIALS_KEY) == Some("true");
        let dialog = CustomDialog {
            icon: "warning",
            message: "Proxy Authentication Required".into(),
            detail: Some(detail),
            details: Vec::new(),
            inputs: vec![DialogInput { placeholder: "Username".into(), password: false, value: username }, DialogInput { placeholder: "Password".into(), password: true, value: password }],
            checkbox: Some("Remember my credentials".into()),
            checkbox_checked: remember,
            buttons: ["Log In", "Cancel"].map(|label| DialogButton { label: label.into(), detail: None }).into(),
            cancel: Some(1),
        };
        let answer = self.show_input_dialog(dialog, window, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            let result = answer.await.ok();
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.end_proxy_login(result, window, cx));
        })
        .detach();
    }

    /// The dialog's reply: window.ts keeps the Remember state, auth.ts stores or forgets the credentials, keeps them
    /// for the session, and a cancel marks the login cancelled.
    fn end_proxy_login(&mut self, result: Option<DialogResult>, window: &mut Window, cx: &mut Context<Self>) {
        let login = self.proxy_auth.logins.pop_front().expect("the shown login");
        let confirmed = result.filter(|result| result.button == 0 && result.values.len() == 2);
        let credentials = confirmed.map(|result| {
            let mut storage = self.application_storage.lock().unwrap();
            match result.checkbox_checked {
                true => storage.set(REMEMBER_CREDENTIALS_KEY, "true".into()),
                false => storage.delete(REMEMBER_CREDENTIALS_KEY),
            }
            drop(storage);
            let [username, password] = <[String; 2]>::try_from(result.values).expect("two inputs");
            let credentials = Credentials { username, password };
            let stored = match result.checkbox_checked {
                true => stored_credentials::write(&login.key, &credentials),
                false => stored_credentials::delete(&login.key),
            };
            if let Err(error) = stored {
                self.output.log_window(5, &format!("auth#doResolveProxyCredentials (proxy) - {error}"));
            }
            credentials
        });
        match &credentials {
            Some(credentials) => self.proxy_auth.session.insert(login.key.clone(), credentials.clone()),
            None => {
                self.proxy_auth.cancelled.insert(login.key.clone());
                self.proxy_auth.session.remove(&login.key)
            }
        };
        self.answer_proxy_login(&login.key, credentials.as_ref());
        self.show_proxy_login(window, cx);
    }

    fn answer_proxy_login(&mut self, key: &str, credentials: Option<&Credentials>) {
        for sender in self.proxy_auth.pending.remove(key).unwrap_or_default() {
            let _ = sender.send(Ok(credentials_value(credentials)));
        }
    }
}

fn credentials_value(credentials: Option<&Credentials>) -> Value {
    credentials.map_or(Value::Null, |credentials| json!({ "username": credentials.username, "password": credentials.password }))
}

/// `doResolveProxyCredentials`: extension tests read the credentials from the realm; otherwise the credentials of
/// `http.proxy` or the proxy environment variables until the proxy rejects them, then those of the session, then the
/// stored ones, each only on a first attempt; else the login dialog asks.
pub fn resolve_proxy_credentials(state: &mut ProxyAuth, auth_info: &Value, key: &str, extension_tests: bool, proxy_setting: &str, env: &dyn Fn(&str) -> Option<String>, stored: &mut dyn FnMut() -> Option<Credentials>) -> Resolution {
    if extension_tests {
        return Resolution::Answer(realm_credentials(auth_info));
    }
    let mut attempt = auth_info["attempt"].as_u64().unwrap_or(1);
    if let Some(configured) = configured_proxy_credentials(proxy_setting, env) {
        let credentials_key = json!([configured.username, configured.password]).to_string();
        match state.configured.get_mut(key) {
            Some((last, rejected)) if *last == credentials_key => {
                if !*rejected {
                    if attempt == 1 {
                        return Resolution::Answer(Some(configured));
                    }
                    *rejected = true;
                    attempt = 1;
                }
            }
            _ => {
                state.configured.insert(key.to_owned(), (credentials_key, false));
                return Resolution::Answer(Some(configured));
            }
        }
    }
    if attempt == 1
        && let Some(session) = state.session.get(key)
    {
        return Resolution::Answer(Some(session.clone()));
    }
    let stored = stored();
    if attempt == 1
        && let Some(stored) = &stored
    {
        state.session.insert(key.to_owned(), stored.clone());
        return Resolution::Answer(Some(stored.clone()));
    }
    Resolution::AskUser { stored }
}

/// The extension tests' proxy puts the credentials in the realm, base64 JSON.
fn realm_credentials(auth_info: &Value) -> Option<Credentials> {
    let realm = base64::engine::general_purpose::STANDARD.decode(auth_info["realm"].as_str()?).ok()?;
    let realm = String::from_utf8(realm).ok().filter(|realm| realm.starts_with('{'))?;
    serde_json::from_str(&realm).ok()
}

/// auth.ts's `proxy-credentials://<hash>` entries, encrypted with safeStorage in application storage upstream: Keychain
/// items here, as the secret storage keeps its secrets (port/notes.md).
#[cfg(all(target_os = "macos", not(test)))]
mod stored_credentials {
    use super::Credentials;

    const SERVICE: &str = "Code - OSS Proxy Credentials";
    /// errSecItemNotFound.
    const ITEM_NOT_FOUND: i32 = -25300;

    pub fn read(key: &str) -> Result<Option<Credentials>, String> {
        match security_framework::passwords::get_generic_password(SERVICE, key) {
            Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| error.to_string()),
            Err(error) if error.code() == ITEM_NOT_FOUND => Ok(None),
            Err(error) => Err(error.to_string()),
        }
    }

    pub fn write(key: &str, credentials: &Credentials) -> Result<(), String> {
        let bytes = serde_json::to_vec(credentials).map_err(|error| error.to_string())?;
        security_framework::passwords::set_generic_password(SERVICE, key, &bytes).map_err(|error| error.to_string())
    }

    pub fn delete(key: &str) -> Result<(), String> {
        match security_framework::passwords::delete_generic_password(SERVICE, key) {
            Err(error) if error.code() != ITEM_NOT_FOUND => Err(error.to_string()),
            _ => Ok(()),
        }
    }
}

/// Tests keep the stored credentials in memory, so the login keychain is never touched; Linux does too, as its secret
/// storage does.
#[cfg(any(test, not(target_os = "macos")))]
mod stored_credentials {
    use std::cell::RefCell;
    use std::collections::HashMap;

    use super::Credentials;

    thread_local! {
        static STORED: RefCell<HashMap<String, Credentials>> = RefCell::default();
    }

    pub fn read(key: &str) -> Result<Option<Credentials>, String> {
        Ok(STORED.with_borrow(|stored| stored.get(key).cloned()))
    }

    pub fn write(key: &str, credentials: &Credentials) -> Result<(), String> {
        STORED.with_borrow_mut(|stored| stored.insert(key.to_owned(), credentials.clone()));
        Ok(())
    }

    pub fn delete(key: &str) -> Result<(), String> {
        STORED.with_borrow_mut(|stored| stored.remove(key));
        Ok(())
    }
}

/// `readConfiguredProxyCredentials`: the user info of `http.proxy`, else of the https or http proxy variable.
fn configured_proxy_credentials(proxy_setting: &str, env: &dyn Fn(&str) -> Option<String>) -> Option<Credentials> {
    let proxy = match proxy_setting.is_empty() {
        false => proxy_setting.to_owned(),
        true => ["https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"].iter().find_map(|key| env(key).filter(|value| !value.is_empty())).unwrap_or_default().trim().to_owned(),
    };
    let authority = proxy.split_once("://").map_or(proxy.as_str(), |(_, rest)| rest);
    let authority = authority.split(['/', '?', '#']).next().unwrap_or_default();
    let (userinfo, _) = authority.split_once('@')?;
    Some(match userinfo.split_once(':') {
        Some((username, password)) => Credentials { username: username.into(), password: password.into() },
        None => Credentials { username: userinfo.into(), password: String::new() },
    })
}

/// @vscode/proxy-agent `loadSystemCertificates` without `http.systemCertificatesNode`, the only case the extension
/// host asks the window (proxyResolver.ts `loadAdditionalCertificates`): `readMacCaCertificates`, then
/// `filterExpiredCertificates`.
fn read_mac_ca_certificates() -> Vec<String> {
    let Ok(output) = std::process::Command::new("/usr/bin/security").args(["find-certificate", "-a", "-p"]).output() else { return Vec::new() };
    unexpired_certificates(&String::from_utf8_lossy(&output.stdout), chrono::Utc::now().naive_utc())
}

fn unexpired_certificates(dump: &str, now: chrono::NaiveDateTime) -> Vec<String> {
    split_pem_certificates(dump).into_iter().filter(|pem| is_unexpired(pem, now)).collect()
}

/// `filterExpiredCertificates`: a certificate that does not parse is dropped; one whose `validTo` does not parse as a
/// date is kept.
fn is_unexpired(pem: &str, now: chrono::NaiveDateTime) -> bool {
    let body: String = pem.lines().filter(|line| !line.starts_with("-----")).collect();
    let Ok(der) = base64::engine::general_purpose::STANDARD.decode(body.trim()) else { return false };
    let Some((tag, not_after)) = certificate_not_after(&der) else { return false };
    let text = String::from_utf8_lossy(not_after);
    let text = match tag {
        // UTCTime: years 50 to 99 are 19xx (RFC 5280 4.1.2.5.1).
        0x17 if text.len() >= 2 => format!("{}{text}", if text[..2] >= *"50" { "19" } else { "20" }),
        _ => text.into_owned(),
    };
    chrono::NaiveDateTime::parse_from_str(&text, "%Y%m%d%H%M%SZ").map_or(true, |valid_to| valid_to > now)
}

/// The `notAfter` time of a DER certificate, with its tag: Certificate > TBSCertificate > [version], serialNumber,
/// signature, issuer, validity.
fn certificate_not_after(der: &[u8]) -> Option<(u8, &[u8])> {
    let (_, certificate, _) = der_element(der)?;
    let (_, mut tbs, _) = der_element(certificate)?;
    let (tag, _, rest) = der_element(tbs)?;
    if tag == 0xA0 {
        tbs = rest;
    }
    for _ in 0..3 {
        tbs = der_element(tbs)?.2;
    }
    let (_, validity, _) = der_element(tbs)?;
    let (_, _, after_not_before) = der_element(validity)?;
    let (tag, not_after, _) = der_element(after_not_before)?;
    Some((tag, not_after))
}

/// One DER element: its tag, its content and the bytes after it.
fn der_element(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> {
    let (&tag, rest) = bytes.split_first()?;
    let (&first, mut rest) = rest.split_first()?;
    let length = if first < 0x80 {
        first as usize
    } else {
        let count = (first & 0x7F) as usize;
        if count == 0 || count > 4 || rest.len() < count {
            return None;
        }
        let length = rest[..count].iter().fold(0usize, |length, byte| length << 8 | *byte as usize);
        rest = &rest[count..];
        length
    };
    (rest.len() >= length).then(|| (tag, &rest[..length], &rest[length..]))
}

/// `stdout.split(/(?=-----BEGIN CERTIFICATE-----)/g)` without empty parts, duplicates dropped in first-seen order.
pub fn split_pem_certificates(text: &str) -> Vec<String> {
    const BEGIN: &str = "-----BEGIN CERTIFICATE-----";
    let mut certificates: Vec<String> = Vec::new();
    let starts: Vec<usize> = text.match_indices(BEGIN).map(|(index, _)| index).collect();
    let mut bounds = vec![0];
    bounds.extend(starts.iter().copied().filter(|start| *start > 0));
    bounds.push(text.len());
    for pair in bounds.windows(2) {
        let part = &text[pair[0]..pair[1]];
        if !part.is_empty() && !certificates.iter().any(|known| known == part) {
            certificates.push(part.to_owned());
        }
    }
    certificates
}

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

    fn info(realm: &str, attempt: u64) -> Value {
        json!({ "isProxy": true, "scheme": "basic", "host": "127.0.0.1", "port": 8080, "realm": realm, "attempt": attempt })
    }

    fn workbench(cx: &mut gpui::TestAppContext) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext) {
        let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
        let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
        let (sender, _messages) = std::sync::mpsc::channel();
        cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx))
    }

    /// requestService.ts `resolveProxy` behind `MainThreadWorkspace.$resolveProxy`: the host's request answers with
    /// the system's PAC result for the URL.
    #[gpui::test]
    fn the_host_request_resolves_the_proxy(cx: &mut gpui::TestAppContext) {
        let (workbench, cx) = workbench(cx);
        let url = "https://example.com/";
        let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadWorkspace", method: "$resolveProxy".into(), args: vec![json!(url)] };
        let Outcome::Pending(mut answer) = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx)) else {
            panic!("the proxy resolves off the UI thread")
        };
        cx.run_until_parked();
        assert_eq!(answer.try_recv().unwrap(), Some(Ok(json!(exthost::request::resolve_proxy(url)))));
    }

    /// window.ts `vscode:openProxyAuthenticationDialog` and auth.ts `showProxyCredentialsDialog`: the typed
    /// credentials answer every request for the proxy, are remembered, and a cancel answers without a dialog after.
    #[gpui::test]
    fn the_login_dialog_answers_with_the_typed_credentials(cx: &mut gpui::TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update(cx, |workbench, _| workbench.application_storage.lock().unwrap().set(REMEMBER_CREDENTIALS_KEY, "true".into()));
        let lookup = |attempt| exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadWorkspace", method: "$lookupAuthorization".into(), args: vec![info("", attempt)] };
        let ask = |attempt, cx: &mut gpui::VisualTestContext| match workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(lookup(attempt), window, cx)) {
            Outcome::Pending(answer) => answer,
            Outcome::Ready(_) => panic!("the login waits on the dialog"),
        };
        let mut first = ask(1, cx);
        let mut second = ask(1, cx);
        cx.run_until_parked();
        workbench.read_with(cx, |workbench, _| {
            let dialog = &workbench.dialogs[0].dialog;
            assert_eq!(workbench.dialogs.len(), 1, "requests for one proxy share the login");
            assert_eq!((dialog.message.as_str(), dialog.detail.as_deref()), ("Proxy Authentication Required", Some("The proxy 127.0.0.1:8080 requires a username and password.")));
            assert_eq!(dialog.buttons.iter().map(|button| button.label.as_str()).collect::<Vec<_>>(), ["Log In", "Cancel"]);
            assert_eq!((dialog.checkbox.as_deref(), dialog.checkbox_checked), (Some("Remember my credentials"), true));
        });
        cx.simulate_input("ann");
        cx.simulate_keystrokes("tab");
        cx.simulate_input("s3cret");
        cx.simulate_keystrokes("enter");
        cx.run_until_parked();
        let typed = Credentials { username: "ann".into(), password: "s3cret".into() };
        for answer in [&mut first, &mut second] {
            assert_eq!(answer.try_recv().unwrap(), Some(Ok(credentials_value(Some(&typed)))));
        }
        let key = json!(["basic", "127.0.0.1", 8080]).to_string();
        assert_eq!(stored_credentials::read(&key), Ok(Some(typed.clone())));
        let again = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(lookup(1), window, cx));
        assert!(matches!(again, Outcome::Ready(Ok(ref value)) if *value == credentials_value(Some(&typed))), "the session's credentials answer a first attempt");

        let mut rejected = ask(2, cx);
        cx.run_until_parked();
        let shown = workbench.read_with(cx, |workbench, _| workbench.dialogs[0].inputs.iter().map(|input| input.input.value.clone()).collect::<Vec<_>>());
        assert_eq!(shown, ["ann", "s3cret"], "the dialog shows the session's credentials");
        cx.simulate_keystrokes("escape");
        cx.run_until_parked();
        assert_eq!(rejected.try_recv().unwrap(), Some(Ok(Value::Null)));
        let mut after_cancel = ask(2, cx);
        cx.run_until_parked();
        assert_eq!(after_cancel.try_recv().unwrap(), Some(Ok(Value::Null)));
        assert!(workbench.read_with(cx, |workbench, _| workbench.dialogs.is_empty()), "no dialog after a cancel");
    }

    #[test]
    fn extension_tests_read_the_credentials_from_the_realm() {
        let realm = base64::engine::general_purpose::STANDARD.encode(r#"{"username":"testuser","password":"testpassword"}"#);
        let resolve = |info: &Value| resolve_proxy_credentials(&mut ProxyAuth::default(), info, "key", true, "", &|_| None, &mut || None);
        assert_eq!(resolve(&info(&realm, 1)), Resolution::Answer(Some(Credentials { username: "testuser".into(), password: "testpassword".into() })));
        assert_eq!(resolve(&info("", 1)), Resolution::Answer(None));
    }

    #[test]
    fn configured_credentials_answer_until_the_proxy_rejects_them() {
        let mut state = ProxyAuth::default();
        let expected = Resolution::Answer(Some(Credentials { username: "ann".into(), password: "p:w".into() }));
        let proxy = "http://ann:p:w@proxy:3128";
        let mut resolve = |attempt, proxy: &str| resolve_proxy_credentials(&mut state, &info("", attempt), "key", false, proxy, &|_| None, &mut || None);
        assert_eq!(resolve(1, proxy), expected);
        assert_eq!(resolve(1, proxy), expected);
        assert_eq!(resolve(2, proxy), Resolution::AskUser { stored: None }, "rejected: the dialog asks");
        assert_eq!(resolve(1, proxy), Resolution::AskUser { stored: None });
        let changed = "http://ann:new@proxy:3128";
        assert_eq!(resolve(2, changed), Resolution::Answer(Some(Credentials { username: "ann".into(), password: "new".into() })));
        let env = |key: &str| (key == "HTTP_PROXY").then(|| "http://bob@proxy:3128".to_owned());
        assert_eq!(configured_proxy_credentials("", &env), Some(Credentials { username: "bob".into(), password: String::new() }));
        assert_eq!(configured_proxy_credentials("http://proxy:3128", &env), None);
    }

    #[test]
    fn stored_credentials_answer_a_first_attempt_and_fill_the_dialog_after() {
        let mut state = ProxyAuth::default();
        let stored = Credentials { username: "ann".into(), password: "kept".into() };
        let resolve = |attempt, state: &mut ProxyAuth| resolve_proxy_credentials(state, &info("", attempt), "key", false, "", &|_| None, &mut || Some(stored.clone()));
        assert_eq!(resolve(1, &mut state), Resolution::Answer(Some(stored.clone())));
        assert_eq!(state.session.get("key"), Some(&stored), "kept for the session");
        assert_eq!(resolve(2, &mut state), Resolution::AskUser { stored: Some(stored.clone()) });
    }

    #[test]
    fn the_keychain_dump_splits_into_unique_certificates() {
        let a = "-----BEGIN CERTIFICATE-----\nAAA\n-----END CERTIFICATE-----\n";
        let b = "-----BEGIN CERTIFICATE-----\nBBB\n-----END CERTIFICATE-----\n";
        assert_eq!(split_pem_certificates(&format!("{a}{b}{a}")), [a, b]);
        assert!(split_pem_certificates("").is_empty());
    }

    /// A self-signed certificate valid from 2020-01-01 to 2021-01-01.
    const EXPIRED_2021: &str = "-----BEGIN CERTIFICATE-----
MIIBbDCCARKgAwIBAgIUcivtsfK+ZFst+LUbPMc3fAmF+bwwCgYIKoZIzj0EAwIw
HDEaMBgGA1UEAwwRRXhwaXJlZCBUZXN0IFJvb3QwHhcNMjAwMTAxMDAwMDAwWhcN
MjEwMTAxMDAwMDAwWjAcMRowGAYDVQQDDBFFeHBpcmVkIFRlc3QgUm9vdDBZMBMG
ByqGSM49AgEGCCqGSM49AwEHA0IABAPPngxW8ukvVWAh2udx6E2IsabdIzc3qb9m
UhJNyR8yzKUNFva8y7NilKtedkjG3PAMxszfQJCw8lWwr+3bRdSjMjAwMB0GA1Ud
DgQWBBTRnToPdHw+TZMim3ObaMJxJoQ4DzAPBgNVHRMBAf8EBTADAQH/MAoGCCqG
SM49BAMCA0gAMEUCIQChCi8NOMOiM1hEv97D8vnjtc9K/jplWN8XuCJRG6yeMQIg
XacgzMwmcNxJhVsTlz3QCWMOuqFE8HWdmF2uwKaxnW4=
-----END CERTIFICATE-----
";

    #[test]
    fn expired_and_unparsable_certificates_are_dropped() {
        let at = |date: &str| chrono::NaiveDateTime::parse_from_str(date, "%Y-%m-%d %H:%M:%S").unwrap();
        let broken = "-----BEGIN CERTIFICATE-----\nAAA\n-----END CERTIFICATE-----\n";
        let dump = format!("{EXPIRED_2021}{broken}");
        assert_eq!(unexpired_certificates(&dump, at("2020-12-31 23:59:59")), [EXPIRED_2021]);
        assert!(unexpired_certificates(&dump, at("2021-01-01 00:00:00")).is_empty());
    }
}