From 3561bebdf6a33780bdf09c41f6339e12eaade175 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Mon, 23 Nov 2026 22:35:55 +0100 Subject: [PATCH 1/3] feat(engine): ask which client certificate to send WebKit tabs on macOS failed on servers that require a TLS client certificate: the challenge went to the default handling, which never picks a Keychain identity. Chromium tabs left OnSelectClientCertificate unhandled, so Chromium sent the first certificate without asking. Both engines now raise a tab-modal prompt, only for the page's own origin, listing the certificates the user can send. WebKit lists the Keychain identities valid now and issued by a CA the server accepts, answers challenges that arrive while the prompt is open with the same choice, and asks again on the next page. Cancel, a refused request or a closed prompt sends no certificate, so servers that only ask for one optionally still load. The certificate buttons sit behind the prompt click guard. Linux, iOS and Android are tracked in docs/port-backlog.md. Signed-off-by: rgxdev --- CHANGELOG.md | 3 + crates/app/src/browser/events.rs | 16 ++- crates/app/src/content.rs | 19 ++- crates/browser-core/src/glyphs.rs | 2 +- crates/browser-core/src/prompts.rs | 3 + crates/engine/src/chromium/view.rs | 32 +++++ crates/engine/src/delegates.rs | 133 ++++++++++++++++--- crates/engine/src/prompts.rs | 198 ++++++++++++++++++++++++++++- crates/engine/src/view_policy.rs | 18 +++ docs/port-backlog.md | 22 ++++ docs/threat-model.md | 2 +- docs/windows-plan.md | 6 +- 12 files changed, 428 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0734b7b..b369be63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ All notable changes to Tarn are documented in this file. The format is based on ### Added +- Sites that ask for a client certificate offer the certificates they accept and send only the + one picked; Cancel sends none (macOS and Windows). Chromium tabs no longer send the first + certificate without asking. - An actions page for each command bar row: → with the cursor at the end of the field (⌘K already opens the bar), the row's … button, or on phones its More button lists what the row can do — a tab: Switch, Close, Copy Link, Move to another space; a history page: Open, Open in New Tab, Copy diff --git a/crates/app/src/browser/events.rs b/crates/app/src/browser/events.rs index 9589cf52..161cdb07 100644 --- a/crates/app/src/browser/events.rs +++ b/crates/app/src/browser/events.rs @@ -547,6 +547,16 @@ impl Browser { self.after_prompt(window, cx); } + pub(crate) fn choose_certificate(&mut self, index: usize, window: &mut Window, cx: &mut Context) { + let Some(key) = self.model.active else { return }; + if self.prompt_guarded() { + return; + } + let Some(prompt) = self.prompts.get_mut(&key).and_then(VecDeque::pop_front) else { return }; + prompt.choose(index); + self.after_prompt(window, cx); + } + /// Esc declines the prompt in front, as Cancel or Deny does, without remembering the answer. pub(crate) fn dismiss_prompt(&mut self, window: &mut Window, cx: &mut Context) { self.remember_permission = false; @@ -579,10 +589,12 @@ impl Browser { } } - /// A permission prompt's Allow and Remember, and Keep Anyway on a malware warning, ignore clicks for a + /// A permission prompt's Allow and Remember, Keep Anyway on a malware warning and a certificate choice ignore clicks for a /// moment after they appear, so a page cannot time a click to land on them. pub(crate) fn prompt_guarded(&self) -> bool { - self.active_prompt().is_some_and(|p| p.kind.is_permission() || matches!(p.kind, PromptKind::MaliciousDownload { .. })) && !self.layout_stable() + self.active_prompt() + .is_some_and(|p| p.kind.is_permission() || matches!(p.kind, PromptKind::MaliciousDownload { .. } | PromptKind::ClientCertificate { .. })) + && !self.layout_stable() } pub(super) fn on_prompt_input_event(&mut self, input: &Entity, event: &TextInputEvent, window: &mut Window, cx: &mut Context) { diff --git a/crates/app/src/content.rs b/crates/app/src/content.rs index c2fd9033..b996ece0 100644 --- a/crates/app/src/content.rs +++ b/crates/app/src/content.rs @@ -393,6 +393,7 @@ fn kind_name(kind: &PromptKind) -> &'static str { PromptKind::Microphone => "microphone", PromptKind::CameraAndMicrophone => "camera+microphone", PromptKind::Credentials { .. } => "credentials", + PromptKind::ClientCertificate { .. } => "certificate", PromptKind::ExtensionAccess { .. } => "extension", PromptKind::MaliciousDownload { .. } => "malicious download", } @@ -416,6 +417,7 @@ fn prompt_card(b: &Browser, window: &Window, cx: &mut Context) -> Optio PromptKind::Credentials { realm } => { (origin, format!("asks you to sign in{}", if realm.is_empty() { String::new() } else { format!(" ({})", ui::text::bounded_title(realm)) })) } + PromptKind::ClientCertificate { .. } => (origin, "asks for a certificate to identify you".into()), PromptKind::ExtensionAccess { extension, key } => ( format!("The extension \u{201C}{}\u{201D}", crate::extensions::shown(extension)), format!("({}) wants to read and change {origin}", b.extension_badge(key)), @@ -464,6 +466,7 @@ fn prompt_card(b: &Browser, window: &Window, cx: &mut Context) -> Optio PromptKind::MaliciousDownload { .. } => buttons .child(secure_button("prompt-accept", "Keep Anyway", false).text_color(Secure::danger()).on_click(answer(false, true))) .child(secure_button("prompt-decline", "Cancel Download", true).on_click(answer(false, false))), + PromptKind::ClientCertificate { .. } => buttons.child(silence()).child(secure_ghost_button("prompt-decline", "Cancel").on_click(answer(false, false))), PromptKind::Credentials { .. } => buttons .child(silence()) .child(secure_ghost_button("prompt-decline", "Cancel").on_click(answer(false, false))) @@ -473,6 +476,10 @@ fn prompt_card(b: &Browser, window: &Window, cx: &mut Context) -> Optio .child(secure_ghost_button("prompt-decline", "Cancel").on_click(answer(false, false))) .child(secure_button("prompt-accept", "OK", true).on_click(answer(false, true))), }; + let certificates = match &prompt.kind { + PromptKind::ClientCertificate { names } => Some(names.clone()), + _ => None, + }; let card = floating() .px_3() .py_2p5() @@ -497,9 +504,17 @@ fn prompt_card(b: &Browser, window: &Window, cx: &mut Context) -> Optio ) .child(buttons), ) - .when(prompt.insecure, |d| d.child(div().text_color(Secure::warning()).child("This connection is not secure: the password would be sent unencrypted."))) + .when(prompt.insecure && matches!(prompt.kind, PromptKind::Credentials { .. }), |d| { + d.child(div().text_color(Secure::warning()).child("This connection is not secure: the password would be sent unencrypted.")) + }) .when(matches!(prompt.kind, PromptKind::Text { .. }), |d| d.child(field(b.prompt_input.clone()))) - .when(matches!(prompt.kind, PromptKind::Credentials { .. }), |d| d.child(field(b.auth_user.clone())).child(field(b.auth_pass.clone()))); + .when(matches!(prompt.kind, PromptKind::Credentials { .. }), |d| d.child(field(b.auth_user.clone())).child(field(b.auth_pass.clone()))) + .when_some(certificates, |d, names| { + d.children(names.iter().enumerate().map(|(i, name)| { + secure_button(("prompt-certificate", i), ui::text::bounded_title(name), false) + .on_click(cx.listener(move |b: &mut Browser, _, w, cx| b.choose_certificate(i, w, cx))) + })) + }); Some((title, card)) } diff --git a/crates/browser-core/src/glyphs.rs b/crates/browser-core/src/glyphs.rs index e6b6b8af..50db02f5 100644 --- a/crates/browser-core/src/glyphs.rs +++ b/crates/browser-core/src/glyphs.rs @@ -4,7 +4,7 @@ pub fn glyph(kind: &str) -> &'static str { "microphone" => "mic", "location" | "geolocation" => "map-pin", "notifications" => "bell", - "credentials" => "key-round", + "credentials" | "certificate" => "key-round", "extension" => "shield", "alert" | "confirm" | "download" | "malicious download" => "triangle-alert", "external" => "external-link", diff --git a/crates/browser-core/src/prompts.rs b/crates/browser-core/src/prompts.rs index 71ada4f1..56f639b9 100644 --- a/crates/browser-core/src/prompts.rs +++ b/crates/browser-core/src/prompts.rs @@ -31,6 +31,7 @@ pub fn meaning(kind: &str) -> Option<&'static str> { "location" | "geolocation" => "The site sees where you are while this tab is open.", "notifications" => "The site can show notifications while Tarn runs.", "credentials" => "Your name and password go to this site only.", + "certificate" => "The certificate you pick goes to this site only and tells it who you are.", "extension" => "The extension can read and change pages on this site.", "malicious download" => "The file comes from a site on the malware list.", "external" => "Tarn hands the link to the app that opens it.", @@ -61,6 +62,7 @@ impl Prompt { None => "asks you to sign in".to_owned(), }, "camera+microphone" | "camera and microphone" => "wants to use your camera and microphone".to_owned(), + "certificate" => "asks for a certificate to identify you".to_owned(), kind => format!("wants to use your {kind}"), } } @@ -190,6 +192,7 @@ mod tests { assert_eq!(ask("camera+microphone", None), "wants to use your camera and microphone"); assert_eq!(ask("credentials", Some("")), "asks you to sign in"); assert_eq!(ask("credentials", Some("Admin")), "asks you to sign in (Admin)"); + assert_eq!(ask("certificate", None), "asks for a certificate to identify you"); assert!(ask("credentials", Some(&"r".repeat(5000))).len() < 600); } } diff --git a/crates/engine/src/chromium/view.rs b/crates/engine/src/chromium/view.rs index ff516c10..26a9dd59 100644 --- a/crates/engine/src/chromium/view.rs +++ b/crates/engine/src/chromium/view.rs @@ -900,6 +900,18 @@ wrap_request_handler! { 1 } + // CEF's UI thread. Left unanswered, Chromium would send the first certificate unasked. + fn on_select_client_certificate(&self, _browser: Option<&mut Browser>, is_proxy: i32, host: Option<&CefString>, port: i32, certificates: Option<&[Option]>, callback: Option<&mut SelectClientCertificateCallback>) -> i32 { + let Some(callback) = callback else { return 1 }; + let certificates: Vec = certificates.unwrap_or_default().iter().flatten().cloned().collect(); + if is_proxy == 1 || certificates.is_empty() { + callback.select(None); + return 1; + } + ask_certificate(self.id, &string(host), port, certificates, callback.clone()); + 1 + } + fn on_certificate_error(&self, _browser: Option<&mut Browser>, _cert_error: Errorcode, _request_url: Option<&CefString>, _ssl_info: Option<&mut Sslinfo>, callback: Option<&mut Callback>) -> i32 { if let Some(callback) = callback { callback.cancel(); @@ -1272,6 +1284,26 @@ fn ask_credentials(id: u64, origin_url: &str, realm: &str, callback: &AuthCallba emit(&tab, Event::Prompt(crate::Prompt::answered(origin, None, insecure, String::new(), kind, reply, tab.silenced.clone()))); } +/// As for credentials, only the page's own origin, or the one its main frame is navigating to, +/// may ask; any other request, and Cancel, go on without a certificate. +fn ask_certificate(id: u64, host: &str, port: i32, certificates: Vec, callback: SelectClientCertificateCallback) { + let challenge = crate::view_policy::tls_challenge(host, port); + let origin = challenge.as_ref().and_then(crate::page::serialized_origin); + let (Some(tab), Some(challenge), Some(origin)) = (tab(id), challenge, origin) else { return callback.select(None) }; + let (page, navigating) = (page_url(tab.browser.borrow().as_ref()), tab.navigating.borrow().as_deref().and_then(|o| Url::parse(o).ok())); + let own = [page, navigating].iter().any(|p| crate::view_policy::may_ask_credentials(&challenge, p.as_ref(), 0)); + if !own || tab.silenced.get() || !crate::page::within_burst(&tab.recent_prompts, crate::page::PROMPT_BURST) { + return callback.select(None); + } + let names = certificates.iter().map(|c| c.subject().map(|s| CefString::from(&s.display_name()).to_string()).unwrap_or_default()).collect(); + let reply = Box::new(move |answer: Option<(String, Option<(String, String)>)>| { + let mut chosen = answer.and_then(|(index, _)| index.parse::().ok()).and_then(|i| certificates.get(i).cloned()); + callback.select(chosen.as_mut()); + }); + let kind = crate::PromptKind::ClientCertificate { names }; + emit(&tab, Event::Prompt(crate::Prompt::answered(origin, None, false, String::new(), kind, reply, tab.silenced.clone()))); +} + /// Drops a step into the restored list that did not navigate, and the marks it set for its load. #[cfg(windows)] fn abandon_step(tab: &Tab) { diff --git a/crates/engine/src/delegates.rs b/crates/engine/src/delegates.rs index 271c3d8d..7bf768a3 100644 --- a/crates/engine/src/delegates.rs +++ b/crates/engine/src/delegates.rs @@ -7,8 +7,14 @@ use std::rc::Rc; use std::time::{Instant, SystemTime}; use block2::{DynBlock, RcBlock}; +use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::base::{CFType, CFTypeRef, TCFType}; +use core_foundation::boolean::CFBoolean; +use core_foundation::date::CFDate; +use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; +use core_foundation::string::{CFString, CFStringRef}; use objc2::rc::{Retained, Weak}; -use objc2::runtime::{AnyObject, Bool, NSObjectProtocol, ProtocolObject, Sel}; +use objc2::runtime::{AnyClass, AnyObject, Bool, NSObjectProtocol, ProtocolObject, Sel}; use objc2::sel; use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send}; use objc2_app_kit::{ @@ -16,14 +22,15 @@ use objc2_app_kit::{ }; use objc2_foundation::{ NSArray, NSData, NSDictionary, NSError, NSHTTPURLResponse, NSObject, NSProgressReporting, NSRect, NSString, NSTimer, NSURL, NSURLAuthenticationChallenge, - NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLCredential, NSURLProtectionSpace, NSURLQuarantinePropertiesKey, - NSURLResponse, NSURLSessionAuthChallengeDisposition, + NSURLAuthenticationMethodClientCertificate, NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLCredential, + NSURLCredentialPersistence, NSURLProtectionSpace, NSURLQuarantinePropertiesKey, NSURLResponse, NSURLSessionAuthChallengeDisposition, }; use objc2_web_kit::{ WKDownload, WKDownloadDelegate, WKFrameInfo, WKMediaCaptureType, WKNavigation, WKNavigationAction, WKNavigationActionPolicy, WKNavigationDelegate, WKNavigationResponse, WKNavigationResponsePolicy, WKNavigationType, WKOpenPanelParameters, WKPermissionDecision, WKSecurityOrigin, WKUIDelegate, WKWebView, WKWebViewConfiguration, WKWebpagePreferences, WKWebsiteDataStore, WKWindowFeatures, }; +use security_framework::identity::SecIdentity; use shield::ShieldLevel; use url::Url; @@ -58,6 +65,63 @@ fn previous_failures(challenge: &NSURLAuthenticationChallenge) -> isize { } } +/// The Keychain identities (certificate plus private key) valid now and, when the server names +/// the issuers it accepts, issued by one of them; each named by its certificate's subject. +fn keychain_identities(issuers: Option>>) -> (Vec, Vec) { + #[link(name = "Security", kind = "framework")] + unsafe extern "C" { + static kSecClass: CFStringRef; + static kSecClassIdentity: CFStringRef; + static kSecReturnRef: CFStringRef; + static kSecMatchLimit: CFStringRef; + static kSecMatchLimitAll: CFStringRef; + static kSecMatchIssuers: CFStringRef; + static kSecMatchValidOnDate: CFStringRef; + fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> i32; + } + // SAFETY: the Security framework's constant keys are valid for the life of the process; + // NSArray is toll-free bridged to a CFArray of CFData, retained by `issuers` while the + // query is built; SecItemCopyMatching returns a +1 CFArray of SecIdentityRef for a + // kSecReturnRef, kSecMatchLimitAll identity query, or nothing on failure. + unsafe { + let key = |k: CFStringRef| CFString::wrap_under_get_rule(k); + let mut query = vec![ + (key(kSecClass), key(kSecClassIdentity).into_CFType()), + (key(kSecReturnRef), CFBoolean::true_value().into_CFType()), + (key(kSecMatchLimit), key(kSecMatchLimitAll).into_CFType()), + (key(kSecMatchValidOnDate), CFDate::now().into_CFType()), + ]; + if let Some(issuers) = issuers.filter(|i| i.count() > 0) { + query.push((key(kSecMatchIssuers), CFType::wrap_under_get_rule(Retained::as_ptr(&issuers).cast()))); + } + let query = CFDictionary::from_CFType_pairs(&query); + let mut found: CFTypeRef = std::ptr::null(); + if SecItemCopyMatching(query.as_concrete_TypeRef(), &mut found) != 0 || found.is_null() { + return Default::default(); + } + let found = CFArray::::wrap_under_create_rule(found as CFArrayRef); + found.iter().filter_map(|identity| Some((identity.certificate().ok()?.subject_summary(), identity.clone()))).unzip() + } +} + +pub(crate) fn identity_credential(identity: &SecIdentity) -> Option> { + type Make = unsafe extern "C-unwind" fn(*const AnyClass, Sel, *const c_void, *const NSArray, NSURLCredentialPersistence) -> *mut NSURLCredential; + // SAFETY: `objc_msgSend` called with the exact signature of `+[NSURLCredential + // credentialWithIdentity:certificates:persistence:]` and a live SecIdentityRef; it returns a + // +0 credential or nil, which is retained. + unsafe { + let send: Make = std::mem::transmute(objc2::ffi::objc_msgSend as unsafe extern "C-unwind" fn()); + let made = send( + ::class(), + sel!(credentialWithIdentity:certificates:persistence:), + identity.as_concrete_TypeRef().cast(), + std::ptr::null(), + NSURLCredentialPersistence::ForSession, + ); + Retained::retain(made) + } +} + fn navigation_id(navigation: Option<&WKNavigation>) -> usize { navigation.map_or(0, |n| n as *const WKNavigation as usize) } @@ -112,6 +176,8 @@ pub(crate) struct DelegateState { pub recent_downloads: Rc>>, /// Set when the user silences the page's dialogs; cleared on the next committed navigation. pub silenced: Rc>, + /// Client certificate answers of the page being loaded or shown; a new page asks again. + pub certificates: Rc>, /// Address of the main-frame load between its start and its commit or failure; an external-scheme /// request then may come from a server redirect, so its source frame is not named. pub provisional: Cell>, @@ -161,6 +227,7 @@ impl DelegateState { recent_popups: Rc::default(), recent_downloads: Rc::default(), silenced: Rc::default(), + certificates: Rc::default(), committed_origin: RefCell::default(), committed_url: RefCell::default(), web_origin: RefCell::default(), @@ -579,12 +646,14 @@ define_class!( }; let method = space.authenticationMethod(); // SAFETY: reading Foundation's constant strings. - let http_auth = unsafe { - method.isEqualToString(NSURLAuthenticationMethodHTTPBasic) - || method.isEqualToString(NSURLAuthenticationMethodHTTPDigest) + let (http_auth, client_certificate) = unsafe { + ( + method.isEqualToString(NSURLAuthenticationMethodHTTPBasic) || method.isEqualToString(NSURLAuthenticationMethodHTTPDigest), + method.isEqualToString(NSURLAuthenticationMethodClientCertificate), + ) }; - // Server trust and client certificates keep WebKit's default handling (S7). - if !http_auth { + // Server trust keeps WebKit's default handling (S7). + if !http_auth && !client_certificate { handler.call((NSURLSessionAuthChallengeDisposition::PerformDefaultHandling, std::ptr::null_mut())); return; } @@ -598,26 +667,55 @@ define_class!( // other ports of the same host. WebKit moves the URL to a navigation's target before // its challenge arrives. let origin = challenger.as_ref().and_then(serialized_origin); + // A refused certificate request goes on without one, which servers that only ask for + // a certificate optionally accept. + let refuse = if client_certificate { + NSURLSessionAuthChallengeDisposition::PerformDefaultHandling + } else { + NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge + }; let Some(origin) = origin.filter(|o| page.as_ref().and_then(serialized_origin).as_ref() == Some(o)) else { - handler.call((NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge, std::ptr::null_mut())); + handler.call((refuse, std::ptr::null_mut())); return; }; - if previous_failures(challenge) >= MAX_AUTH_ATTEMPTS - || self.ivars().silenced.get() + if previous_failures(challenge) >= MAX_AUTH_ATTEMPTS { + handler.call((refuse, std::ptr::null_mut())); + return; + } + if client_certificate && prompts::Certificates::join(&self.ivars().certificates, &origin, &handler.copy()) { + return; + } + if self.ivars().silenced.get() || !within_burst(&self.ivars().recent_prompts, PROMPT_BURST) { - handler.call((NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge, std::ptr::null_mut())); + handler.call((refuse, std::ptr::null_mut())); return; } - let realm = space.realm().map(|r| r.to_string()).unwrap_or_default(); - let insecure = !space.receivesCredentialSecurely(); + let (kind, reply) = if client_certificate { + let (names, identities) = keychain_identities(space.distinguishedNames()); + if identities.is_empty() { + handler.call((refuse, std::ptr::null_mut())); + return; + } + let state = self.ivars().certificates.clone(); + let page = { + let mut certificates = state.borrow_mut(); + certificates.waiting.insert(origin.clone(), Vec::new()); + certificates.page + }; + let ask = prompts::CertificateAsk { origin: origin.clone(), page, identities, state }; + (PromptKind::ClientCertificate { names }, Reply::Certificate(handler.copy(), ask)) + } else { + let realm = space.realm().map(|r| r.to_string()).unwrap_or_default(); + (PromptKind::Credentials { realm }, Reply::Credentials(handler.copy())) + }; let prompt = Prompt { origin, top_origin: None, - insecure, + insecure: !space.receivesCredentialSecurely(), message: String::new(), - kind: PromptKind::Credentials { realm }, - reply: Some(Reply::Credentials(handler.copy())), + kind, + reply: Some(reply), suppress: self.ivars().silenced.clone(), }; self.emit(Event::Prompt(prompt)); @@ -627,6 +725,7 @@ define_class!( fn did_start_provisional(&self, _web_view: &WKWebView, navigation: Option<&WKNavigation>) { let id = navigation_id(navigation); self.ivars().provisional.set(Some(id)); + self.ivars().certificates.borrow_mut().next_page(); if navigation_id(self.ivars().user_load.borrow().as_deref()) != id { self.ivars().user_load.take(); } diff --git a/crates/engine/src/prompts.rs b/crates/engine/src/prompts.rs index f89a44b7..617e0790 100644 --- a/crates/engine/src/prompts.rs +++ b/crates/engine/src/prompts.rs @@ -11,6 +11,8 @@ use objc2::runtime::Bool; use objc2_foundation::{NSString, NSURLCredential, NSURLCredentialPersistence, NSURLSessionAuthChallengeDisposition}; #[cfg(target_os = "macos")] use objc2_web_kit::WKPermissionDecision; +#[cfg(target_os = "macos")] +use security_framework::identity::SecIdentity; #[derive(Debug, Clone, PartialEq, Eq)] pub enum PromptKind { @@ -26,6 +28,10 @@ pub enum PromptKind { Credentials { realm: String, }, + /// The server asks for a TLS client certificate; `names` are the Keychain identities to pick from. + ClientCertificate { + names: Vec, + }, /// An extension asks to read and change the prompt's origin (a host); `key` is its install /// id or bundle path. Allow without Remember lasts an hour. ExtensionAccess { @@ -69,13 +75,95 @@ pub(crate) enum Reply { #[cfg(target_os = "macos")] Permission(RcBlock), #[cfg(target_os = "macos")] - Credentials(RcBlock), + Credentials(AuthBlock), + #[cfg(target_os = "macos")] + Certificate(AuthBlock, CertificateAsk), /// Whether to allow (`None` dismisses) and whether to remember it. Access(Box, bool)>), #[cfg(any(windows, feature = "chromium"))] Answer(Answer), } +#[cfg(target_os = "macos")] +pub(crate) type AuthBlock = RcBlock; + +/// A view's client certificate answers for the page being loaded or shown, per origin: the +/// identity picked or `None` for none, and the challenges that arrived while the origin's prompt +/// was open. `page` counts main-frame navigations, so an old page's prompt answers no new page. +#[cfg(target_os = "macos")] +#[derive(Default)] +pub(crate) struct Certificates { + pub answers: std::collections::HashMap>, + /// Each waiting challenge with the page it came from. + pub waiting: std::collections::HashMap>, + pub page: u64, +} + +#[cfg(target_os = "macos")] +impl Certificates { + /// A new page asks again. + pub(crate) fn next_page(&mut self) { + self.answers.clear(); + self.page += 1; + } + + /// Answers `done` from what this page already settled for `origin`, or queues it behind the + /// open prompt; `false` when the user still has to be asked. + pub(crate) fn join(state: &std::cell::RefCell, origin: &str, done: &AuthBlock) -> bool { + let known = { + let mut state = state.borrow_mut(); + let page = state.page; + match (state.answers.get(origin).cloned(), state.waiting.get_mut(origin)) { + (Some(answer), _) => Some(answer), + (None, Some(waiting)) => { + waiting.push((page, done.clone())); + return true; + } + (None, None) => None, + } + }; + known.map(|answer| answer_certificate(done, answer.as_ref())).is_some() + } +} + +/// The identities a client certificate prompt offers, and where its answer is kept. +#[cfg(target_os = "macos")] +pub(crate) struct CertificateAsk { + pub origin: String, + pub page: u64, + pub identities: Vec, + pub state: Rc>, +} + +#[cfg(target_os = "macos")] +impl CertificateAsk { + /// Answers the prompt's challenge and every one waiting on it with `index`'s identity, or + /// with none, and keeps the answer for the page shown if it asked. + fn settle(self, done: &AuthBlock, index: Option) { + let identity = index.and_then(|i| self.identities.into_iter().nth(i)); + let waiting = { + let mut state = self.state.borrow_mut(); + let waiting = state.waiting.remove(&self.origin).unwrap_or_default(); + if state.page == self.page || waiting.iter().any(|(page, _)| *page == state.page) { + state.answers.insert(self.origin.clone(), identity.clone()); + } + waiting + }; + for done in std::iter::once(done).chain(waiting.iter().map(|(_, done)| done)) { + answer_certificate(done, identity.as_ref()); + } + } +} + +/// Sends `identity`, or no certificate, which servers that only ask for one optionally accept. +#[cfg(target_os = "macos")] +pub(crate) fn answer_certificate(done: &AuthBlock, identity: Option<&SecIdentity>) { + match identity.and_then(crate::delegates::identity_credential) { + Some(credential) => done.call((NSURLSessionAuthChallengeDisposition::UseCredential, Retained::as_ptr(&credential).cast_mut())), + None => done.call((NSURLSessionAuthChallengeDisposition::PerformDefaultHandling, std::ptr::null_mut())), + } +} + /// A question a page or server asks, shown tab-modally with its origin. Answer it with /// `accept`/`decline`; dropping an unanswered prompt declines it, so WebKit is always answered. pub struct Prompt { @@ -99,6 +187,9 @@ impl std::fmt::Debug for Prompt { impl Prompt { /// `text` answers a text prompt; `credentials` answers an authentication prompt. pub fn accept(mut self, text: &str, credentials: Option<(&str, &str)>) { + if matches!(self.kind, PromptKind::ClientCertificate { .. }) { + return self.decline(); + } match self.reply.take() { #[cfg(target_os = "macos")] Some(Reply::Alert(done)) => done.call(()), @@ -126,10 +217,27 @@ impl Prompt { }, #[cfg(any(windows, feature = "chromium"))] Some(Reply::Answer(done)) => done(Some((text.to_owned(), credentials.map(|(u, p)| (u.to_owned(), p.to_owned()))))), + #[cfg(target_os = "macos")] + other @ Some(Reply::Certificate(..)) => decline(other), None => {} } } + /// Answers a client certificate prompt with the identity at `index` of its `names`; any + /// other index sends none. + pub fn choose(mut self, index: usize) { + match self.reply.take() { + #[cfg(target_os = "macos")] + Some(Reply::Certificate(done, ask)) => ask.settle(&done, Some(index)), + #[cfg(any(windows, feature = "chromium"))] + Some(Reply::Answer(done)) => done(Some((index.to_string(), None))), + other => { + let _ = index; + decline(other) + } + } + } + #[cfg(any(windows, feature = "chromium"))] pub(crate) fn answered( origin: String, @@ -199,6 +307,20 @@ mod tests { prompt(got.clone()).decline(); assert_eq!(*got.borrow(), [None, Some("hi".to_owned()), None]); } + + #[test] + fn a_certificate_prompt_passes_only_the_picked_index() { + let got = Rc::new(std::cell::RefCell::new(Vec::new())); + let prompt = |got: Rc>>>| { + let reply: Answer = Box::new(move |a| got.borrow_mut().push(a.map(|(t, _)| t))); + let kind = PromptKind::ClientCertificate { names: vec!["A".into(), "B".into()] }; + Prompt::answered("https://a.test".into(), None, false, String::new(), kind, reply, Rc::default()) + }; + prompt(got.clone()).choose(1); + prompt(got.clone()).accept("1", None); + prompt(got.clone()).decline(); + assert_eq!(*got.borrow(), [Some("1".to_owned()), None, None]); + } } pub(crate) fn decline(reply: Option) { @@ -213,6 +335,8 @@ pub(crate) fn decline(reply: Option) { Some(Reply::Permission(done)) => done.call((WKPermissionDecision::Deny,)), #[cfg(target_os = "macos")] Some(Reply::Credentials(done)) => done.call((NSURLSessionAuthChallengeDisposition::CancelAuthenticationChallenge, std::ptr::null_mut())), + #[cfg(target_os = "macos")] + Some(Reply::Certificate(done, ask)) => ask.settle(&done, None), Some(Reply::Access(done)) => done(None, false), #[cfg(any(windows, feature = "chromium"))] Some(Reply::Answer(done)) => done(None), @@ -239,3 +363,75 @@ mod access_tests { assert_eq!(*got.borrow(), [(None, false), (Some(true), false), (Some(false), true), (None, false)]); } } + +#[cfg(all(test, target_os = "macos"))] +mod certificate_tests { + use super::*; + + type Got = Rc>>; + + fn recorder(got: &Got) -> AuthBlock { + let got = got.clone(); + RcBlock::new(move |d: NSURLSessionAuthChallengeDisposition, _: *mut NSURLCredential| got.borrow_mut().push(d)) + } + + fn prompt(done: AuthBlock, state: &Rc>) -> Prompt { + state.borrow_mut().waiting.insert("https://a.test".into(), Vec::new()); + let page = state.borrow().page; + let ask = CertificateAsk { origin: "https://a.test".into(), page, identities: Vec::new(), state: state.clone() }; + Prompt { + origin: "https://a.test".into(), + top_origin: None, + insecure: false, + message: String::new(), + kind: PromptKind::ClientCertificate { names: Vec::new() }, + reply: Some(Reply::Certificate(done, ask)), + suppress: Rc::default(), + } + } + + #[test] + fn a_certificate_prompt_answers_once_and_sends_none_unless_one_is_picked() { + let got: Got = Rc::default(); + let answered: [fn(Prompt); 5] = [drop, Prompt::decline, |p| p.accept("", None), |p| p.choose(0), Prompt::decline_and_silence_page]; + for answer in answered { + answer(prompt(recorder(&got), &Rc::default())); + } + assert_eq!(*got.borrow(), [NSURLSessionAuthChallengeDisposition::PerformDefaultHandling; 5]); + } + + #[test] + fn challenges_while_the_prompt_is_open_share_its_answer_and_later_ones_reuse_it() { + let (got, state): (Got, Rc>) = Default::default(); + let open = prompt(recorder(&got), &state); + assert!(Certificates::join(&state, "https://a.test", &recorder(&got))); + assert!(!Certificates::join(&state, "https://b.test", &recorder(&got))); + assert!(got.borrow().is_empty()); + open.decline(); + assert_eq!(got.borrow().len(), 2); + assert!(Certificates::join(&state, "https://a.test", &recorder(&got))); + assert_eq!(*got.borrow(), [NSURLSessionAuthChallengeDisposition::PerformDefaultHandling; 3]); + } + + #[test] + fn an_old_pages_prompt_leaves_no_answer_for_the_next_page() { + let (got, state): (Got, Rc>) = Default::default(); + let open = prompt(recorder(&got), &state); + state.borrow_mut().next_page(); + open.decline(); + assert_eq!(got.borrow().len(), 1); + assert!(!Certificates::join(&state, "https://a.test", &recorder(&got))); + } + + #[test] + fn a_new_page_that_joined_the_open_prompt_keeps_its_answer() { + let (got, state): (Got, Rc>) = Default::default(); + let open = prompt(recorder(&got), &state); + state.borrow_mut().next_page(); + assert!(Certificates::join(&state, "https://a.test", &recorder(&got))); + open.decline(); + assert_eq!(got.borrow().len(), 2); + assert!(Certificates::join(&state, "https://a.test", &recorder(&got))); + assert_eq!(got.borrow().len(), 3); + } +} diff --git a/crates/engine/src/view_policy.rs b/crates/engine/src/view_policy.rs index e4df46ae..f3dadb6d 100644 --- a/crates/engine/src/view_policy.rs +++ b/crates/engine/src/view_policy.rs @@ -242,6 +242,13 @@ pub fn same_origin(challenge: &Url, page: Option<&Url>) -> bool { } /// Sign-in requests are shown only for the page's own origin and only for a few failed tries. +/// The HTTPS origin a TLS client certificate request names by host and port; an IPv6 host comes +/// bare or bracketed. +pub fn tls_challenge(host: &str, port: i32) -> Option { + let host = if host.contains(':') && !host.starts_with('[') { format!("[{host}]") } else { host.to_owned() }; + Url::parse(&format!("https://{host}:{port}")).ok() +} + pub fn may_ask_credentials(challenge: &Url, page: Option<&Url>, failures: u32) -> bool { failures < MAX_AUTH_ATTEMPTS && same_origin(challenge, page) } @@ -560,4 +567,15 @@ mod tests { assert_eq!(without_credentials("https://u:p@a.test/f?x"), "https://a.test/f?x"); assert_eq!(without_credentials("not a url"), ""); } + + #[test] + fn a_certificate_request_names_an_https_origin() { + let origin = |host, port| tls_challenge(host, port).as_ref().and_then(crate::page::serialized_origin); + assert_eq!(origin("a.test", 443).as_deref(), Some("https://a.test")); + assert_eq!(origin("a.test", 8443).as_deref(), Some("https://a.test:8443")); + assert_eq!(origin("::1", 443).as_deref(), Some("https://[::1]")); + assert_eq!(origin("[::1]", 8443).as_deref(), Some("https://[::1]:8443")); + assert!(may_ask_credentials(&tls_challenge("a.test", 443).unwrap(), Some(&u("https://a.test/x")), 0)); + assert!(tls_challenge("a test", 443).is_none()); + } } diff --git a/docs/port-backlog.md b/docs/port-backlog.md index acee1afe..608aba56 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -21,6 +21,28 @@ Reference: . ## Open +### Client certificate picker (2026-11-23) + +What it does: when the page's own site asks for a TLS client certificate, a tab-modal prompt lists +the certificates the user has that the server accepts and sends only the one they pick; Cancel +sends none and the page loads as it would without one. Other sites never get to ask. +Shared API: `engine::PromptKind::ClientCertificate { names }`, `engine::Prompt::choose(index)`; +NSH clients use the `"certificate"` kind with `browser_core::prompts::{Prompt::ask, meaning}` and +`browser_core::glyphs::glyph`, and `view_policy::may_ask_credentials` for the origin check. +Reference: `crates/engine/src/delegates.rs` (`auth_challenge`, `keychain_identities`), +`crates/engine/src/chromium/view.rs` (`on_select_client_certificate`, `ask_certificate`), +`crates/app/src/content.rs` (`prompt_card`), `crates/app/src/browser/events.rs` +(`choose_certificate`). + +- [x] Windows — same code in `crates/app` and the Chromium engine +- [ ] Linux — WebKitGTK raises `AuthenticationScheme::ClientCertificateRequested`, which + `authenticate` in `linux/src/webview/mod.rs` cancels; GTK has no system certificate store, so + answering it needs a way to pick a certificate file and `Credential::for_certificate` +- [ ] iOS — `challenge` in `mobile/ios/src/handler.rs` takes the default handling; an app cannot + read the system's identities, so this needs certificates imported into Tarn's own keychain +- [ ] Android — `onReceivedClientCertRequest` in `TarnWebView` with + `KeyChain.choosePrivateKeyAlias`, behind the same origin check + ### Insert Snippet in the page's context menu (2026-11-22) What it does: right-clicking (long-pressing) a text field on a page offers Insert Snippet…, which diff --git a/docs/threat-model.md b/docs/threat-model.md index a67bbb6b..d97a5d3c 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -14,7 +14,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | S3 | High | API token or page content leaks | Token only in the platform secret store (Keychain, Credential Manager, Secret Service, Android Keystore). Content leaves the device only after an explicit click with a visible indicator. AI is unavailable in the private profile. We never read the CLI's stored credentials. | `ai::Secrets` keeps the API token in the platform store only, with no fallback to a file: the Keychain on macOS and iOS, the Credential Manager on Windows and the Secret Service on Linux (`ai::secrets::Keyring`); on Android it is sealed with AES-GCM under a key that never leaves the Android Keystore (`tarn_mobile_android::Keystore`, `Secrets.java`). `ApiToken`'s `Debug` never shows the value (`token_never_in_debug_output`). On Linux, iOS and Android (`tarn_nsh_shared::assistant`) a request leaves only on Send, a command or Group with Assistant, the chat lists every block a send carries with its size first, Settings › AI and the chat are hidden or refused in a private space, a burner tab and at Lockdown (`tabs::Model::assistant_origin` carries the page's own Shield level: `the_assistant_origin_carries_the_kind_and_the_sites_own_level`), the key typed into Settings › AI goes straight to the platform store, a Claude request without a stored key sends nothing and Ollama never gets the key (`claude_needs_a_stored_key_and_sends_it_only_to_anthropic`, `ollama_answers_on_loopback_without_the_key`), and a build for neither phone has no store and sends nothing; turning the switch off, deleting a profile or clearing its data drops every window's chat. macOS and Windows the assistant column (`crates/app/src/assistant.rs`) sends only on Send, names every block a send carries with its size above the question field, passes the active page's effective Shield level (per-site setting included) with each send, drops the chat when the profile, its data or its AI switch goes, and shows no chat in a private space, burner tab or Lockdown; Settings › AI stores the key through `ai::secrets::Keyring` only.. The core rules in `browser_core::assistant`: no chat in a private space, burner tab, Lockdown or with the profile's AI switch off (`private_burner_and_lockdown_get_no_session`), a send from any of them, from another profile or with the switch off is refused and drops every pill, and a pill whose page went to Lockdown since it was added, or whose address does not parse, is dropped, also after the user removed it, and the answers given while it or a refused send's pills were attached are never sent again (`a_refused_send_forgets_answers_given_while_its_pills_were_attached`, `a_removed_pill_whose_page_went_to_lockdown_still_forgets_its_answers`, `a_send_from_where_the_assistant_is_not_allowed_is_refused_and_drops_the_pills`, `a_send_drops_pills_whose_page_went_to_lockdown_since_they_were_added`, `a_pill_without_a_readable_address_counts_as_lockdown`, `answers_given_while_a_pill_now_in_lockdown_was_attached_are_never_sent_again`), nothing is sent without a send event and every block it would carry is listed with its size (`the_view_lists_every_block_that_would_be_sent`), each block and the whole request are capped (`pills_are_capped_each_and_with_history_in_total`). Local models implement `ai::LocalModel` and run only through `ai::local::stream`, the one place that can make the `local::Checked` token their `respond` takes, after their availability check: `engine::foundation_models::FoundationModel` (macOS and iOS, the `foundation-models` feature) calls only `SystemLanguageModel.default` and takes no transport; `ai::Ollama` is available only when Ollama on loopback answers `/api/show` for the model and reports no remote host, and a `-cloud` or `:cloud` name is refused before anything is asked (`cloud_models_are_never_local`, `an_ollama_that_does_not_answer_needs_setup_and_gets_no_question`). An unavailable model answers `AiError::Unavailable` with its reason instead of another model answering; `ai::local::route` never sends a local choice to the cloud (`a_local_choice_never_routes_to_the_cloud`). A selection or another tab reaches the assistant only by the user's choice: the selection menu has no assistant entry where `tabs::Model::assistant_menu` refuses the page (AI off, private space, burner, Lockdown), the tab picker lists only the current space's other web tabs the assistant may read and never wakes a sleeping one to read it (`the_tab_picker_lists_other_web_tabs_the_assistant_may_read_and_wakes_none`, `a_selection_and_a_loaded_tab_reach_the_assistant_and_a_sleeping_tab_is_never_read` on Linux and mobile), and a send still checks every pill's page level. Commands run on the system's on-device model when it is available and the cloud was chosen; with a local choice that cannot answer the chat says why and asks no cloud, and every answer names the model that gave it (`ai::local::answer`: `commands_stay_on_the_device_when_it_can_answer_and_say_who_answered`; `commands_answer_on_the_device_and_name_it_while_questions_go_where_chosen`). | | S4 | High | Malicious update | EdDSA-signed updates, HTTPS, downgrade protection, signing keys only in the signing environments of the release workflow. On Windows, `platform::updater` reads `windows-update.json` next to the appcast: its Ed25519 signature (the Sparkle key in `packaging/updates.conf`, compiled in) is checked over the exact bytes before anything is parsed; the installer must come over https from this repository's release downloads, match the signed length, SHA-256 and its own Ed25519 signature before it is written, and is hashed again through a handle that bars writes while it starts; only a later version is offered; feeds are capped at 64 KiB and installers at 512 MiB. Windows releases ship the unsigned installer CI built: the release workflow's signing job, which runs no build code, signs that run's installer and its `windows-update.json` with the update key (`scripts/windows-feed.sh`, its URL limited to this repository's release downloads), so installs have no Authenticode signature; `scripts/sign-windows.ps1` (Authenticode) is not part of CI and no certificate is set up. Remaining on Windows: the installer is not Authenticode-checked by the updater, so the Ed25519 key is the only anchor, and a replayed feed that lists the running version still counts as a verified check (as on macOS) until releases carry an expiry. Repository: two-factor login, branch protection, pinned actions, no secrets for fork pull requests. | CI actions pinned by commit hash; no job that pull requests, issues or comments can start runs on a self-hosted runner: enforced only by the runner group's "Selected workflows" limit and fork-approval settings in `release.md`, applied by hand, since a fork pull request runs its own edited workflow; `scripts/check-workflows.sh` in CI is a merge-time lint that keeps such jobs out of `main`, not a control on what a pull request can schedule; `.github/CODEOWNERS` covers the workflows, `codesign-app.sh`, `bundle.sh`, `packaging/`, the lockfiles and manifests and the embedded signing keys (owner `@Quavon-dev/maintainers`), and `main`'s ruleset requires approval of the most recent push and dismisses stale approvals (settings by hand) but does not require an up-to-date branch, so a merge can land a tree CI did not test; Chromium updates are proposed by `chromium-update.yml` as pull requests that run CI and need a maintainer's approval like any other; once merged, it tags them (except one that moves the `cef` crate, which a maintainer releases) and `release.yml` signs and publishes them only after a maintainer approves its `release-signing` deployment. Updater: Sparkle 2.10.1, pinned by SHA-256, verifies the archive's EdDSA signature before extraction, requires a signed feed and refuses older versions; the feed (the latest published GitHub release's `appcast.xml`) and the public key are in `packaging/updates.conf` and only release bundles carry them; the private key, the Developer ID certificate and the notary API key are secrets of the `release-signing` environment (deployments from `main` and `v*` tags, a maintainer's approval) and the `nightly-signing` environment (deployments from `main` only, no approval) and the private key has an offline backup; only the `sign` job enters them, runs no build code, imports the certificate into a temporary keychain and writes the other keys under `RUNNER_TEMP`, and deletes both when it ends. A compromised build job or dependency build script holds none of them, but a workflow or script changed on `main` runs with them on the next nightly without approval and could sign a feed that Release users accept, since both channels share the update key (Sparkle takes one `SUPublicEDKey`); code-owner review of `.github/` and `scripts/` on `main` is what stands in the way, and `scripts/appcast.sh` signs only a notarised Tarn of team CFV35FGSHF whose version matches the tag. The feed URL comes from Info.plist through the updater delegate, never from user defaults; with Settings › General › Nightly builds on it is the same file in the `nightly` release (`platform::updater::nightly_feed`), on macOS and Windows. Nightly builds carry `.` versions and are signed with the same keys: every commit merged to `main`, including engine updates (reviewed, with a CEF archive whose hash only `chromium-update.yml`'s own download checked), reaches users of that channel signed and notarised within a day, with no release review. Nightly feeds carry their channel inside the signed bytes (`sparkle:channel`, the Windows feed's `channel`), and the Release channel refuses them, so a nightly feed uploaded to a release is not offered to Release users. A nightly on the Release channel counts the release feed as current for its release version (`channel_version`) and is offered only a later release. A check counts as verified for the Chromium staleness gate only if the signed appcast lists the running version or a later one, so an old appcast replayed through a release asset no longer keeps Chromium open; one listing the running version still does. A feed that fails verification still offers items in Sparkle's fallback mode (no critical marking); the archive signature still applies. Tampered and older updates not yet tried against a real feed. Windows, Linux and mobile release files are built unsigned from pinned containers and a pinned rustup-init but with unpinned distribution packages and Gradle dependencies; they are attested by a job that runs none of their code, and each build job can add only its own file names to the release. A release run starts from a `v*` tag push (tag creation limited by ruleset), from `start-release.yml` on `main` (any account with write access can start it; it builds every client without keys, and only after a maintainer approves the `release-signing` deployment does the `sign` job create the `v*` tag with the update app, whose key that environment then also holds, so this tag is the app's, not a maintainer's signed tag), a manual `workflow_dispatch` on an existing `v*` tag, which any account with write access can start and which builds macOS alone, or `chromium-update.yml`; it never replaces a published release's files (a re-run of a published tag only marks the highest version latest) and publishes only after the `release-signing` deployment is approved. `nightly.yml` publishes the `nightly` pre-release without approval. The signed zip, disk image and feeds are in `SHA256SUMS` and the attestation. Mobile stores: only `mobile-store.yml` dispatched on `main` enters the separately approved `ios-store` and `android-store` environments. Each runner verifies the published stable release, attested `SHA256SUMS` and its mobile artifact with the release workflow identity, rejects self-hosted provenance, and binds the verified predicate to the current tag commit before exposing signing secrets to a step. Released code is never executed, and credential jobs build nothing or install dependencies. iOS validates the distribution profile, bundle identity/version and permitted signing certificate; ZIP links, traversal and nested code are rejected. Android signs only the AAB with a separate Play upload key and uses GitHub OIDC restricted to this repository, `main`, the store environment and workflow for short-lived Google tokens; Play retains the app signing key. Uploads go only to TestFlight and Play internal testing (draft by default), never a production track or explicit public submission. Play commits fail when an existing review is pending and request review deferral after rejection; required internal-release reviews remain a Console step. Temporary keys and signed bundles are deleted and never become GitHub artifacts. Code-owner review of the trusted workflow and signing script remains essential; compromise of either store environment can publish internal builds for its app. | | S18 | High | Malicious or compromised extension | Per-profile install, per-site permission prompts, hash recorded, no silent updates, off in private mode by default, no access to internal pages or other profiles. | App and Official extensions get every site they list without a prompt while Settings › Extensions › "Allow extensions on every site" is on, which is the default (`Pref::ExtensionsEverySite`); Unverified ones always ask per site and Lockdown hosts stay denied. `tabs.create` from an App extension opens a web page as a normal tab through `nav_policy`, at the pop-up rate (3 in 10 s) and never with a private-network address as its URL (S10). Open: that tab is a user load, so a redirect of its URL to a private address is followed. With the global switch on, an update that asks for more sites is not held back. Only Safari web extensions bundled with apps in `/Applications` are offered (`engine::extensions`); nothing runs until the user turns an extension on for the current profile in Settings › Extensions, which lists every requested permission and site pattern. Turning it on grants all of them (no per-site prompts). Each profile has its own `WKWebExtensionController`: storage is keyed by the profile's own data-store UUID, also when it shares website data with another profile, the private space gets an in-memory controller with nothing enabled, Lockdown profiles and Lockdown-level views get no controller, and hosts with a Lockdown override are denied to every extension (checked: the content script stops answering), because a link into such a host keeps its view. An extension sees only the tabs of its own profile. Its `safari-web-extension://` origin (Safari's scheme, which Bitwarden's inline menu requires), which pages can see, is derived from the profile's data-store UUID, so it differs per user and profile; sites that probe for Bitwarden's Safari pages find it as they would in Safari. `windows.create` opens a window only for the extension's own pages (Bitwarden's unlock, passkey and edit popouts), at most four per extension, each side between 200 and 1000 points and the height kept on screen; the window's top-level navigations are held to the extension's own pages, because it has no navigation policy or Shield, and it closes when the extension is turned off or its data is removed. Only the extension that opened it sees it. Frames inside it are not restricted and it shows no origin chip, as with the extension's toolbar popup. Native messages and native ports are answered only while Settings › Extensions › "Bitwarden integration" is on, which it is not by default (`Pref::ExtensionsBitwarden`; switching it reloads Bitwarden with or without them, and off it runs like any other app extension), and only for an app extension whose code signature is Bitwarden's (`com.bitwarden.desktop.safari`, signed by team `LTZ2PFU5D6`, or by Apple for the Mac App Store with that team's entitlement), checked when extensions are discovered, and only for the four Bitwarden uses (`copyToClipboard`, `readFromClipboard`, `sleep` with at most 16 pending, `showPopover`); a native port (`connectNative`) is accepted only for Bitwarden's app id, at most four per extension, closed with the extension, and answers only Bitwarden's biometrics questions as its Safari app extension does: Touch ID through LocalAuthentication, then the user key the Bitwarden desktop app keeps in the login keychain (`Bitwarden_biometric`, account `_user_biometric`), read off the main thread after Touch ID succeeded and handed only to that port; one Touch ID prompt at a time, naming the extension; while Bitwarden runs in a profile with that integration on (turned off, pages already open keep this until they reload), pages there (not at Lockdown) are told that passkeys and conditional mediation are available, as in Safari, but only in frames where `navigator.credentials.get` has been replaced again, by Bitwarden's page script or the page itself; WebKit says no without Apple's browser entitlement and refuses conditional requests at once, so in those frames such a refusal of a request with an abort signal stays pending until the page aborts it, as Safari's conditional UI does, and Bitwarden's answer is not cut short; elsewhere WebKit's own answers are returned, the availability one after waiting while the document still parses, at most 40 checks 50 ms apart; clipboard writes need the granted `clipboardWrite` permission and reads also need `clipboardRead` in the manifest, which Settings then lists. Deleting a profile removes its extensions' data through WebKit and then WebKit's folder for it, whose `State.plist` names each extension; "Delete everything" removes the data and restarts the profile's extensions. Tarn has no internal web pages to reach. Extensions can also be installed from a GitHub repository, the signed official catalog (own ed25519 key, domain-separated signature, rollback and 30-day freshness checks, a revoked set that only grows) and `.zip`/`.crx` files: archives are unpacked with strict name, size, depth and type checks into read-only per-install directories; storage is keyed by a random install id; the tree hash is recorded at install and checked before every load, `.appex` bundles included, and a mismatch turns the extension off and drops its site grants; trust labels and the Bitwarden privileges (native messages, clipboard read, passkey script, pop-out windows) follow the install source, never the manifest; unpacked extensions show a popup only after a toolbar click. Host access is per site: the grant-all loop is gone, WebKit's own URL prompt becomes a tab-modal Allow/Deny with Remember (Once lasts an hour), decisions are stored per install and profile, and App and Official sources may be switched to "Allow on every site", which turns off when an update asks for more sites (without effect while the global switch is on). Extension pages, workers and popups get the profile's private-network and HTTPS rule lists. `Tab` refuses `loadURL`, reload, back, forward and zoom without access to the tab's page. Updates are a new install with the same prompt, never automatic. Tarn extensions (`manifest_version` 3 with `browser_specific_settings.tarn.runtime` 1) run on Tarn's own runtime (`browser_core::tarn_ext`, contract `engine::tarn_ext`), the same on every engine: a package using any manifest key, permission (only `storage`, `activeTab`, `declarativeNetRequest`), content-script option or network-rule action outside the subset is refused at install with the key named, and `redirect`, `modifyHeaders` and `allowAllRequests` rules always are, as are a `priority` other than 1, a port in a site pattern and more than 1000 `regexFilter` rules; content scripts and their CSS run only in the install's isolated world `tarn-ext-`, only in http and https frames, only where the engine's synchronous gate (`frame_decision`) allows them, which needs a grant for the frame's host from the same per-site machinery (App and Official may use every site, Unverified always ask, Lockdown hosts denied, Once one hour or until the tab closes, one prompt per site and session); nothing runs in private spaces, burner tabs, Lockdown profiles or Lockdown-level views: no extension page opens in a Lockdown profile, the pages already open close when a profile moves into Lockdown (`Runtime::level_changed`, called by every shell), and its messages and action clicks are refused. Messages travel only between the install's isolated worlds, its own pages and the shell's router (`tarn_ext::router`): the engine defines the transport only in that world or page and reports where a call arrived, so the sender (install, tab, frame, page) never comes from the message; a main frame's message counts only while the install holds a grant for the tab's host (and, where the engine reports the main frame's origin, only when it is the tab's) and a subframe's only while it holds one for the frame's own origin as the engine reported it, a plain `http` document's only when one of the install's site patterns also covers `http`, and no frame inside a page of a Lockdown host runs a script or sends a message; each message is JSON of at most 1 MiB, at most 200 per second per install and tab, malformed ones dropped; a reply counts only from a receiver the message went to; `tabs.query` shows the URL and title only of tabs whose host the install holds a grant for or that `activeTab` gave it; `tabs.sendMessage` reaches only such tabs; `tabs.create` opens web pages only through `nav_policy`, at most 3 in 10 s, never a private-network address (S10); `storage.local` holds JSON per profile and install, at most 5 MiB with keys up to 1 KiB, in memory for a private profile, and is deleted with the install. Static network rules (at most 5 files of 4 MiB, 30,000 rules) compile into one content rule list per install whose block and upgrade rules act only on top-level sites the install holds a grant for (every site only with the trusted switch, minus the hosts the user denied for the install and Lockdown hosts); the grant is the host's whatever the scheme, so they also act on a plain `http` page of a granted host, also for an install whose site patterns name only `https` (WebKit's `if-domain` names no scheme, and the `if-top-url` that could cannot share a list with it); a rule without `resourceTypes` leaves out top-level documents as in Chrome, and one for only main or only sub frames is kept to them (`load-context`); `excludedRequestDomains`, and `excludedInitiatorDomains` together with `initiatorDomains` or `domains`, are refused, because a content rule list can only lift every earlier rule; `allow` rules lift only the same install's rules, never Shield's, and no list is attached in private spaces, Lockdown profiles or Lockdown-level views. Extension pages are served from `tarn-extension:///`, the origin id the first 32 hex digits of SHA-256 of the profile's data-store seed and the install id, only from the install's read-only directory, whose tree hash is checked when the install loads (files are read on request; a change after that check is found at the next load, which turns the install off), with paths that leave it refused, with `script-src 'self'; frame-src 'self'; object-src 'none'`, so its frames are only its own pages or `about:` ones; web pages cannot load the scheme (no `web_accessible_resources`). The background page is started on its first event and closed after 30 s idle; one that does not get ready within 30 s is closed and its waiting callers get an error, and at most 64 messages wait for a page; a reply not given within 30 s ends with an error, at most 256 replies wait per install, and the background page's own calls do not keep it running. The tree hash is checked before every load and a mismatch turns the install off and drops its grants; Tarn extensions get none of the Bitwarden privileges whatever their source. On macOS and Windows the gate is asked in the navigation callback of every frame before the engine is answered, and its answer travels in the world's scripts (`tarn_ext::injections`); a document whose answer did not arrive first runs nothing, and on WebKit a view without a gate (the link peek) holds an empty answer for each of its documents, so no tab can let that document run, until it gets a gate or closes. WebKit (macOS) runs the scripts in a `WKContentWorld` named after the install with a script message handler added only to that world, and takes the frame from WebKit's own message (subframes by WebKit's private `_handle.frameID`; without it a subframe cannot send), each subframe document numbered on its own per install and holding a random value the install's world draws at document start and sends with every message (a message with another value from a frame that has a newer document is dropped); WebKit runs a reply in whatever document the frame shows, so the reply runs only where that value matches, never in the frame's next document, and a fragment navigation or a load that never commits keeps the document and its replies; extension pages are views of their own with the bootstrap in their main world, a handler that answers only the main frame of the install's origin and a `tarn-extension` scheme handler that serves only that origin. Chromium (macOS and Windows) does the same over the in-process DevTools channel only (S22): new-document scripts in an isolated world named after the install, a `Runtime.addBinding` limited to that world's name and taken out of its global before any content script runs, each context's frame and origin taken from DevTools' own `Runtime.executionContextCreated` (never from what a script sends), replies by `Runtime.evaluate` into those contexts. Frames in another process (cross-site iframes) are attached over the same channel (`Target.setAutoAttach` for iframes only, flattened, each waiting before its first document): a frame gets the same binding and scripts in its own session before it is resumed, an install added later gets them in every attached frame, and its contexts are known by session and context id, so its identity comes from the session DevTools reported, never from a script. The Runtime and Page domains are on in tabs of a profile with Tarn extensions, so a page there can tell that a DevTools client is attached (console argument previews); they stay on because without the Runtime domain no binding reaches a new document's context (checked: no `Runtime.bindingCalled` from any new document), and `Page.createIsolatedWorld` with a binding by context id reaches a frame only after its document has started, too late for `document_start` scripts. Checked at run time in a signed debug bundle on macOS (`engine/tests/tarn_extension_chromium.rs`, `app/tests/tarn_extension.rs`) and in WebKit (`engine/tests/tarn_extension.rs`): the isolated world, messages both ways, storage, the network rule only with a grant, no extension file loads from a web page, frame identity in same-site and cross-site frames after reloads and navigations, an install added after a cross-site frame was attached, nothing in a Lockdown view or profile, and an extension page framing only its own origin. The Runtime domain and auto-attach are turned off again in a view when its last install is removed, which detaches its frames' sessions; an install added later attaches them again. An install added (or added back) while a cross-site frame's navigation is in flight does not run in the document that navigation commits: DevTools holds the commands for that frame's session until the commit, after the document's contexts exist, so nothing runs or is heard there (it fails closed) and the frame's next document runs the install. Open on Chromium: not confirmed against Blink whether `Page.addScriptToEvaluateOnNewDocument` with a `worldName` creates that world with universal access; if it does, content scripts there can reach more than in a WebKit content world. `document_end` scripts start after a round trip to the shell, so they can run after the page's `load` event; extension pages register the scheme per request context on Windows only, where it is a standard, secure, display-isolated scheme in every process; the request context is the profile's, so its handler serves only the browser of the page view of that origin and refuses every other one. Store install link (new boundary: a web page leads to an install prompt): only a main-frame navigation the user started (a typed or other shell load that is not a link or pop-up the shell loads for a page, or a link click with a user gesture; `nav_policy::store_link_asks`) to exactly `https://extensions.tarnbrowser.com/install/` (`engine::tarn_ext::store_install`: https, that host, no port, no user info, a valid catalog id, query and fragment ignored) is cancelled before any request; the page passes nothing but the id and gets no channel into the browser. The link itself makes no request: if Tarn already holds a fresh (at most 30 days old) verified copy of the signed catalog, Settings › Extensions shows a confirmation built only from that entry (name, description, version, permissions, optional permissions, sites; `extensions::install::store_step`, `store_sheet`), otherwise a notice points to Settings › Extensions, where the user can load the catalog, and nothing else happens. Requests start only when the user presses Install there: Tarn first checks everything again (`store_confirm`: the same entry in a fresh catalog, not revoked or installed, no install in progress, and `Core::store_link_allowed` for the tab), then downloads, verifies and unpacks the package as for Settings › Extensions › Official; a package whose manifest stays within that entry (`vet`, as always) installs without a second prompt. A page cannot swap what the user confirms: a new store link replaces the sheet under a new token (`install::StoreToken`: a sequence number, the entry's id and SHA-256), the Install button carries the token of the sheet it was drawn for and `StoreSheet::take` refuses any other, and Install clicks within 700 ms of a sheet appearing or being replaced are ignored (`STORE_CONFIRM_DELAY`; on macOS and Windows also while the window layout is not stable, as for the S5 hand-off rule); closing Settings › Extensions drops an unanswered sheet. An unknown, revoked or already installed id or an install in progress gets a notice, and nothing is offered in a private space, a burner tab, a Lockdown profile, from a page at Lockdown or while the store's host is at Lockdown. Every client takes at most one store link per 10 s and ignores the rest without a sheet (`Core::admit_store_link`). Redirects into the address, subframes and script navigations without a gesture load normally. A script that navigates while handling the user's click counts as the user's, as for pop-ups. WebKit on macOS tells a user's click from a script's `a.click()` only through WebKit's private `_isUserInitiated`, and redirects through `_isRedirect`; where they are missing only shell loads ask. Chromium uses CEF's user gesture, Android WebView `hasGesture`, WebKitGTK `is_user_gesture`. iOS uses no private WebKit API and has no public user-gesture or redirect flag: a shell load or any main-frame `linkActivated` navigation asks, so a page's own script-started link click (and a redirect after a link click) can raise the confirmation there, at most once per 10 s; it requests and installs nothing without the user's confirmation. Open: on Linux the user's own click on an install link inside a frame also opens the consent (WebKitGTK does not say which frame a navigation targets). | -| S5 | High | Origin spoofing; a sidebar-only UI hides the URL | Origin chip always visible; registrable domain emphasised; punycode for mixed-script names. Prompts and dialogs show the origin and are tab-modal. | Origin chip shows the host as parsed by `url` (IDNA to punycode); a `blob:` page shows the host of the URL it wraps and a page without a host (an opener-filled `about:blank`, `data:`) shows only its scheme (`about:blank`, `data:`), as does its tab title when the page set none, so the chip is empty only when no page is loaded. While a navigation the page started is pending, WebKit's `URL` already names its target over the old content; `WebView::url` then returns the committed URL (`Delegate::shown_url`; `about:blank` for a pop-up before its first commit), so chip, peek header and site settings keep naming the page on screen. Only a server redirect (WebKit's private `_isRedirect`) of the navigation the shell itself started with `load` continues the user's load (`Delegate::user_load`); a navigation the old document starts while that load is pending, and its redirects, are the page's own for S10. Without the selector no hop counts as the user's. For the chip, `user_navigation` still covers the time until the user's load commits or any load fails. The link peek header uses the chip's label (`toolbar::site_of`). Dialogs, permission and sign-in requests are tab-modal cards naming the origin (shortened from the left so the registrable domain stays visible) and the embedding page for frames; a permission card's Allow and Remember ignore clicks for 700 ms after the card becomes visible, a banner above it appears or leaves, or the window becomes active (which also covers leaving element fullscreen). All guarded controls (this one, S6's "Open", S25's "Visit Anyway", a notice's offer) share one timer (`Browser::layout_stable_since`), restarted when any of them appears or changes in the active tab, a banner appears or leaves, the tab or overlay changes, the window becomes active or the sidebar is resized, and when the sidebar is shown or hidden it runs from the end of the slide (Linux: Visit Anyway's `guard_since`; mobile: Keep in the downloads pop-over, which hangs from the sidebar). Clean Up never names a group after a site, so a group name says nothing about the origin of the tabs in it; the origin chip stays the trust signal. A page on a site no rule knows can pick its own topic group through its address and title, but never outvotes a known site and never lands in Money or Mail and Chat, which take known sites only, and a group named after a category never learns a host from the tabs in it, so a lookalike is not filed next to the real bank or mail tab; only loose tabs move, and the store never moves a tab from one group into another. A page-requested hand-off to another app names the requesting site ("A page" when its origin is opaque or while a main-frame load is in flight, as in S6), is rate-limited like other prompts, is not replaced while shown, ignores clicks for 700 ms after it appears and shows only in its own tab, hidden while the user is on another tab. A Shift-click link peek follows the pop-up rules and their rate limit. | +| S5 | High | Origin spoofing; a sidebar-only UI hides the URL | Origin chip always visible; registrable domain emphasised; punycode for mixed-script names. Prompts and dialogs show the origin and are tab-modal. | Origin chip shows the host as parsed by `url` (IDNA to punycode); a `blob:` page shows the host of the URL it wraps and a page without a host (an opener-filled `about:blank`, `data:`) shows only its scheme (`about:blank`, `data:`), as does its tab title when the page set none, so the chip is empty only when no page is loaded. While a navigation the page started is pending, WebKit's `URL` already names its target over the old content; `WebView::url` then returns the committed URL (`Delegate::shown_url`; `about:blank` for a pop-up before its first commit), so chip, peek header and site settings keep naming the page on screen. Only a server redirect (WebKit's private `_isRedirect`) of the navigation the shell itself started with `load` continues the user's load (`Delegate::user_load`); a navigation the old document starts while that load is pending, and its redirects, are the page's own for S10. Without the selector no hop counts as the user's. For the chip, `user_navigation` still covers the time until the user's load commits or any load fails. The link peek header uses the chip's label (`toolbar::site_of`). Dialogs, permission, sign-in and client certificate requests are tab-modal cards naming the origin (shortened from the left so the registrable domain stays visible) and the embedding page for frames; a permission card's Allow and Remember ignore clicks for 700 ms after the card becomes visible, a banner above it appears or leaves, or the window becomes active (which also covers leaving element fullscreen). A client certificate request comes only from the page's own origin (or, in Chromium tabs, the one its main frame is navigating to), never for a proxy, and lists only certificates valid now that the server accepts (WebKit: `kSecMatchIssuers`, `kSecMatchValidOnDate`); its certificate buttons are guarded the same way, none is the default, and Cancel, a refused request or a closed card sends no certificate (Chromium remembers that for the host until Tarn restarts). All guarded controls (this one, a certificate choice, S6's "Open", S25's "Visit Anyway", a notice's offer) share one timer (`Browser::layout_stable_since`), restarted when any of them appears or changes in the active tab, a banner appears or leaves, the tab or overlay changes, the window becomes active or the sidebar is resized, and when the sidebar is shown or hidden it runs from the end of the slide (Linux: Visit Anyway's `guard_since`; mobile: Keep in the downloads pop-over, which hangs from the sidebar). Clean Up never names a group after a site, so a group name says nothing about the origin of the tabs in it; the origin chip stays the trust signal. A page on a site no rule knows can pick its own topic group through its address and title, but never outvotes a known site and never lands in Money or Mail and Chat, which take known sites only, and a group named after a category never learns a host from the tabs in it, so a lookalike is not filed next to the real bank or mail tab; only loose tabs move, and the store never moves a tab from one group into another. A page-requested hand-off to another app names the requesting site ("A page" when its origin is opaque or while a main-frame load is in flight, as in S6), is rate-limited like other prompts, is not replaced while shown, ignores clicks for 700 ms after it appears and shows only in its own tab, hidden while the user is on another tab. A Shift-click link peek follows the pop-up rules and their rate limit. | | S6 | High | Dangerous schemes and untrusted URL sources | Allowlist `http`, `https`, `about:blank`, `blob`. `data:` not at top level. `file:` only by explicit user action. `javascript:` rejected in the command bar and on paste. External schemes prompt each time. URLs from other apps, drops and sync pass the same policy. | `nav_policy::decide` with table test; applied to typed input, Open File (`load_file` is the only load that reaches `file:`, decided as `Source::FileOpen` through `nav_policy::file_open`, which also admits only the user's Back, Forward and Reload onto a file that view itself opened, never a restored history; an opened page loads `file:` subresources and frames only from its own folder, or only itself when that folder is a root, a mounted volume's top or holds the home folder, with symlinks resolved and `file:` URLs naming a host refused before any lookup (macOS WebKit's read-access grant and `nav_policy::file_subresource_allowed` for frames, Chromium's request filter (not yet verified at runtime that CEF hands it `file:` subresources; macOS opens files in WebKit), iOS's grant, Android's `shouldInterceptRequest`; Linux gap in `docs/nsh-plan.md` §4), so its images and styles load, and file pages cannot read other files with scripts; the address shows `File:` and the file's name; iOS and Android copy the picked file into a folder of its own under a staging directory cleared at launch), command-line URLs, restored tabs and session snapshots, main-frame navigations, redirects and popups. A page's external-scheme request shows a banner naming the origin of the frame that started it ("A page" when opaque or while a main-frame load is in flight, so a server redirect is never credited to the page or frame that linked to it), only in its own tab, until that tab's next commit or close; while it shows, further requests are dropped, and "Open" ignores clicks for 700 ms after it, or any banner above it, appears, and again when the window becomes active. Links other apps send (the default-browser case, `shared::open_urls` through GPUI's `on_open_urls`) pass `decide(ExternalApp)`, at most 10 in 10 s across the app (the rest are dropped with a toast), and load as a page's link (`WebView::load_link` with no opener), so S10 refuses a local target or any redirect hop into the local network with its usual notice; typing the address opens it. A loopback link (`localhost`, 127.0.0.0/8, `::1`) opens as typed while Settings › Privacy › Open localhost links from other apps is on (the default), since developers open local servers from terminals and editors; the accepted risk is that a link from a remote sender (a mail) can then reach a service on this computer, as a typed address could. Off, it gets the notice. Other local addresses always get it. The notice offers Open Anyway, which loads the address as the user's own navigation. Chromium tabs do the same: their `load_link` sets no shell mark, also for a load held until the view is ready, so `on_before_browse` credits the page (a Chromium integration test is not written yet); such a load is not a user's, so it does not bridge WebKit's cookies first and the site may open signed out in Chromium. Open: public names that resolve to private addresses (`nip.io`-style) are not recognised. | | S19 | High | Sync storage is read or tampered with | Client-side authenticated encryption; remote data validated as untrusted input; secrets and cookies never synced. | Not built. | | S7 | Medium | TLS downgrade or click-through | WebKit's default trust evaluation, never custom acceptance, and no bypass at any level. Chromium tabs cancel certificate errors and turn Chrome's override off, so its certificate page has no way through. | No custom trust handling exists. Plain-HTTP page navigations into an HTTPS-only site are blocked (a URL with an explicit port loads when the view was built HTTPS-only, because `make-https` leaves ports alone; Chromium tabs, which have no per-level view, upgrade such a link without a port and refuse one with a port unless the page being left is HTTPS-only). | diff --git a/docs/windows-plan.md b/docs/windows-plan.md index 6835b26d..0231dd68 100644 --- a/docs/windows-plan.md +++ b/docs/windows-plan.md @@ -66,7 +66,9 @@ WebView2 plan and are kept for the security mapping; where they disagree, this s - **Page requests:** camera and microphone ask with the page's origin as in WebKit tabs (screen capture is refused); HTTP Basic and Digest ask only for the page's own origin or the one its main frame is navigating to, three times at most per page load (proxy and integrated - authentication are refused); a link to another app's scheme (`mailto:`, `tel:`) asks before it + authentication are refused); a client certificate is asked for under the same origin rule, + never for a proxy, and Cancel sends none, which Chromium then keeps for that host until Tarn + restarts; a link to another app's scheme (`mailto:`, `tel:`) asks before it is handed to Windows. Shift-click opens a link in a peek; Ctrl- and middle-click and the page menu's Open Link in New Tab open a tab under the pop-up rules, its first load judged as the page's link (S10). The page menu keeps Chrome's editing, link, image and media items; saving @@ -275,7 +277,7 @@ If item 1 fails, the fallback is a sidebar in its own WebView2 with the stricter | `WKContentRuleList` (Shield, private-network rule, HTTPS upgrade) | `AddWebResourceRequestedFilter("*", ALL)` + `WebResourceRequested` handler that evaluates the `adblock-rust` engine in-process | No compile step and no per-list limit; cost is a callback per request, so the engine must answer in microseconds (bench gate). HTTPS-only: cancel and re-navigate main-frame HTTP; subresources blocked. | | `interactionState` | No equivalent | The back list cannot be restored; only the URL is. Documented loss. | | Navigation delegate (`decidePolicyForNavigationAction`) | `NavigationStarting` (cancel), `FrameNavigationStarting`, `NewWindowRequested` (popups, gesture via `IsUserInitiated`) | `nav_policy::decide` called from the same places; `Source` mapping unchanged. | -| JS dialogs, permissions, HTTP auth | `ScriptDialogOpening` (deferral, tab-modal GPUI prompt), `PermissionRequested`, `BasicAuthenticationRequested` | Origin shown in every prompt (S5). | +| JS dialogs, permissions, HTTP auth, client certificates | `ScriptDialogOpening` (deferral, tab-modal GPUI prompt), `PermissionRequested`, `BasicAuthenticationRequested`, CEF `OnSelectClientCertificate` | Origin shown in every prompt (S5). | | TLS errors | `ServerCertificateErrorDetected` | Never `AlwaysAllow`; no bypass at any level (S7). | | Content-process crash reload | `ProcessFailed` | Same rate limit. | | Script message handlers (none) | `AreHostObjectsAllowed = FALSE`, `IsWebMessageEnabled = FALSE`, no `AddHostObjectToScript` | S1 holds. Also `AreDevToolsEnabled` only in the dev profile; `AreDefaultContextMenusEnabled` reviewed. | From 32be1ed5946c960410ca151226a2d13aaf60b2c0 Mon Sep 17 00:00:00 2001 From: rgxdev Date: Mon, 23 Nov 2026 22:43:06 +0100 Subject: [PATCH 2/3] test(linux): give the split partner a distinct last use Two tabs opened within the same millisecond tie on last use, and the split partner then depends on list order, which made the split test flaky in CI. Signed-off-by: rgxdev --- linux/src/browser/feature_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/linux/src/browser/feature_tests.rs b/linux/src/browser/feature_tests.rs index 73f6e136..49a9b1e6 100644 --- a/linux/src/browser/feature_tests.rs +++ b/linux/src/browser/feature_tests.rs @@ -454,6 +454,8 @@ fn a_split_shows_its_panes_and_a_closed_pane_hands_the_focus_on() { visit(&mut b, first, "https://a.test/"); let second = b.new_tab("https://b.test/").unwrap(); let third = b.new_tab("https://c.test/").unwrap(); + // Both tabs can open within the same millisecond; the later one is the more recent. + b.model.touch(&b.core, third, browser_core::now() + 1); b.activate(first); b.open_split(); assert_eq!(b.shown_split().map(|s| s.panes().to_vec()), Some(vec![first, third]), "the most recently used tab joins"); From 41325e78d1bb3a606d082c596d7fd824f87aae3f Mon Sep 17 00:00:00 2001 From: rgxdev Date: Mon, 23 Nov 2026 22:52:18 +0100 Subject: [PATCH 3/3] docs(threat-model): state when the certificate list is issuer-filtered Signed-off-by: rgxdev --- docs/threat-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/threat-model.md b/docs/threat-model.md index d97a5d3c..9c54ffaa 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -14,7 +14,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | S3 | High | API token or page content leaks | Token only in the platform secret store (Keychain, Credential Manager, Secret Service, Android Keystore). Content leaves the device only after an explicit click with a visible indicator. AI is unavailable in the private profile. We never read the CLI's stored credentials. | `ai::Secrets` keeps the API token in the platform store only, with no fallback to a file: the Keychain on macOS and iOS, the Credential Manager on Windows and the Secret Service on Linux (`ai::secrets::Keyring`); on Android it is sealed with AES-GCM under a key that never leaves the Android Keystore (`tarn_mobile_android::Keystore`, `Secrets.java`). `ApiToken`'s `Debug` never shows the value (`token_never_in_debug_output`). On Linux, iOS and Android (`tarn_nsh_shared::assistant`) a request leaves only on Send, a command or Group with Assistant, the chat lists every block a send carries with its size first, Settings › AI and the chat are hidden or refused in a private space, a burner tab and at Lockdown (`tabs::Model::assistant_origin` carries the page's own Shield level: `the_assistant_origin_carries_the_kind_and_the_sites_own_level`), the key typed into Settings › AI goes straight to the platform store, a Claude request without a stored key sends nothing and Ollama never gets the key (`claude_needs_a_stored_key_and_sends_it_only_to_anthropic`, `ollama_answers_on_loopback_without_the_key`), and a build for neither phone has no store and sends nothing; turning the switch off, deleting a profile or clearing its data drops every window's chat. macOS and Windows the assistant column (`crates/app/src/assistant.rs`) sends only on Send, names every block a send carries with its size above the question field, passes the active page's effective Shield level (per-site setting included) with each send, drops the chat when the profile, its data or its AI switch goes, and shows no chat in a private space, burner tab or Lockdown; Settings › AI stores the key through `ai::secrets::Keyring` only.. The core rules in `browser_core::assistant`: no chat in a private space, burner tab, Lockdown or with the profile's AI switch off (`private_burner_and_lockdown_get_no_session`), a send from any of them, from another profile or with the switch off is refused and drops every pill, and a pill whose page went to Lockdown since it was added, or whose address does not parse, is dropped, also after the user removed it, and the answers given while it or a refused send's pills were attached are never sent again (`a_refused_send_forgets_answers_given_while_its_pills_were_attached`, `a_removed_pill_whose_page_went_to_lockdown_still_forgets_its_answers`, `a_send_from_where_the_assistant_is_not_allowed_is_refused_and_drops_the_pills`, `a_send_drops_pills_whose_page_went_to_lockdown_since_they_were_added`, `a_pill_without_a_readable_address_counts_as_lockdown`, `answers_given_while_a_pill_now_in_lockdown_was_attached_are_never_sent_again`), nothing is sent without a send event and every block it would carry is listed with its size (`the_view_lists_every_block_that_would_be_sent`), each block and the whole request are capped (`pills_are_capped_each_and_with_history_in_total`). Local models implement `ai::LocalModel` and run only through `ai::local::stream`, the one place that can make the `local::Checked` token their `respond` takes, after their availability check: `engine::foundation_models::FoundationModel` (macOS and iOS, the `foundation-models` feature) calls only `SystemLanguageModel.default` and takes no transport; `ai::Ollama` is available only when Ollama on loopback answers `/api/show` for the model and reports no remote host, and a `-cloud` or `:cloud` name is refused before anything is asked (`cloud_models_are_never_local`, `an_ollama_that_does_not_answer_needs_setup_and_gets_no_question`). An unavailable model answers `AiError::Unavailable` with its reason instead of another model answering; `ai::local::route` never sends a local choice to the cloud (`a_local_choice_never_routes_to_the_cloud`). A selection or another tab reaches the assistant only by the user's choice: the selection menu has no assistant entry where `tabs::Model::assistant_menu` refuses the page (AI off, private space, burner, Lockdown), the tab picker lists only the current space's other web tabs the assistant may read and never wakes a sleeping one to read it (`the_tab_picker_lists_other_web_tabs_the_assistant_may_read_and_wakes_none`, `a_selection_and_a_loaded_tab_reach_the_assistant_and_a_sleeping_tab_is_never_read` on Linux and mobile), and a send still checks every pill's page level. Commands run on the system's on-device model when it is available and the cloud was chosen; with a local choice that cannot answer the chat says why and asks no cloud, and every answer names the model that gave it (`ai::local::answer`: `commands_stay_on_the_device_when_it_can_answer_and_say_who_answered`; `commands_answer_on_the_device_and_name_it_while_questions_go_where_chosen`). | | S4 | High | Malicious update | EdDSA-signed updates, HTTPS, downgrade protection, signing keys only in the signing environments of the release workflow. On Windows, `platform::updater` reads `windows-update.json` next to the appcast: its Ed25519 signature (the Sparkle key in `packaging/updates.conf`, compiled in) is checked over the exact bytes before anything is parsed; the installer must come over https from this repository's release downloads, match the signed length, SHA-256 and its own Ed25519 signature before it is written, and is hashed again through a handle that bars writes while it starts; only a later version is offered; feeds are capped at 64 KiB and installers at 512 MiB. Windows releases ship the unsigned installer CI built: the release workflow's signing job, which runs no build code, signs that run's installer and its `windows-update.json` with the update key (`scripts/windows-feed.sh`, its URL limited to this repository's release downloads), so installs have no Authenticode signature; `scripts/sign-windows.ps1` (Authenticode) is not part of CI and no certificate is set up. Remaining on Windows: the installer is not Authenticode-checked by the updater, so the Ed25519 key is the only anchor, and a replayed feed that lists the running version still counts as a verified check (as on macOS) until releases carry an expiry. Repository: two-factor login, branch protection, pinned actions, no secrets for fork pull requests. | CI actions pinned by commit hash; no job that pull requests, issues or comments can start runs on a self-hosted runner: enforced only by the runner group's "Selected workflows" limit and fork-approval settings in `release.md`, applied by hand, since a fork pull request runs its own edited workflow; `scripts/check-workflows.sh` in CI is a merge-time lint that keeps such jobs out of `main`, not a control on what a pull request can schedule; `.github/CODEOWNERS` covers the workflows, `codesign-app.sh`, `bundle.sh`, `packaging/`, the lockfiles and manifests and the embedded signing keys (owner `@Quavon-dev/maintainers`), and `main`'s ruleset requires approval of the most recent push and dismisses stale approvals (settings by hand) but does not require an up-to-date branch, so a merge can land a tree CI did not test; Chromium updates are proposed by `chromium-update.yml` as pull requests that run CI and need a maintainer's approval like any other; once merged, it tags them (except one that moves the `cef` crate, which a maintainer releases) and `release.yml` signs and publishes them only after a maintainer approves its `release-signing` deployment. Updater: Sparkle 2.10.1, pinned by SHA-256, verifies the archive's EdDSA signature before extraction, requires a signed feed and refuses older versions; the feed (the latest published GitHub release's `appcast.xml`) and the public key are in `packaging/updates.conf` and only release bundles carry them; the private key, the Developer ID certificate and the notary API key are secrets of the `release-signing` environment (deployments from `main` and `v*` tags, a maintainer's approval) and the `nightly-signing` environment (deployments from `main` only, no approval) and the private key has an offline backup; only the `sign` job enters them, runs no build code, imports the certificate into a temporary keychain and writes the other keys under `RUNNER_TEMP`, and deletes both when it ends. A compromised build job or dependency build script holds none of them, but a workflow or script changed on `main` runs with them on the next nightly without approval and could sign a feed that Release users accept, since both channels share the update key (Sparkle takes one `SUPublicEDKey`); code-owner review of `.github/` and `scripts/` on `main` is what stands in the way, and `scripts/appcast.sh` signs only a notarised Tarn of team CFV35FGSHF whose version matches the tag. The feed URL comes from Info.plist through the updater delegate, never from user defaults; with Settings › General › Nightly builds on it is the same file in the `nightly` release (`platform::updater::nightly_feed`), on macOS and Windows. Nightly builds carry `.` versions and are signed with the same keys: every commit merged to `main`, including engine updates (reviewed, with a CEF archive whose hash only `chromium-update.yml`'s own download checked), reaches users of that channel signed and notarised within a day, with no release review. Nightly feeds carry their channel inside the signed bytes (`sparkle:channel`, the Windows feed's `channel`), and the Release channel refuses them, so a nightly feed uploaded to a release is not offered to Release users. A nightly on the Release channel counts the release feed as current for its release version (`channel_version`) and is offered only a later release. A check counts as verified for the Chromium staleness gate only if the signed appcast lists the running version or a later one, so an old appcast replayed through a release asset no longer keeps Chromium open; one listing the running version still does. A feed that fails verification still offers items in Sparkle's fallback mode (no critical marking); the archive signature still applies. Tampered and older updates not yet tried against a real feed. Windows, Linux and mobile release files are built unsigned from pinned containers and a pinned rustup-init but with unpinned distribution packages and Gradle dependencies; they are attested by a job that runs none of their code, and each build job can add only its own file names to the release. A release run starts from a `v*` tag push (tag creation limited by ruleset), from `start-release.yml` on `main` (any account with write access can start it; it builds every client without keys, and only after a maintainer approves the `release-signing` deployment does the `sign` job create the `v*` tag with the update app, whose key that environment then also holds, so this tag is the app's, not a maintainer's signed tag), a manual `workflow_dispatch` on an existing `v*` tag, which any account with write access can start and which builds macOS alone, or `chromium-update.yml`; it never replaces a published release's files (a re-run of a published tag only marks the highest version latest) and publishes only after the `release-signing` deployment is approved. `nightly.yml` publishes the `nightly` pre-release without approval. The signed zip, disk image and feeds are in `SHA256SUMS` and the attestation. Mobile stores: only `mobile-store.yml` dispatched on `main` enters the separately approved `ios-store` and `android-store` environments. Each runner verifies the published stable release, attested `SHA256SUMS` and its mobile artifact with the release workflow identity, rejects self-hosted provenance, and binds the verified predicate to the current tag commit before exposing signing secrets to a step. Released code is never executed, and credential jobs build nothing or install dependencies. iOS validates the distribution profile, bundle identity/version and permitted signing certificate; ZIP links, traversal and nested code are rejected. Android signs only the AAB with a separate Play upload key and uses GitHub OIDC restricted to this repository, `main`, the store environment and workflow for short-lived Google tokens; Play retains the app signing key. Uploads go only to TestFlight and Play internal testing (draft by default), never a production track or explicit public submission. Play commits fail when an existing review is pending and request review deferral after rejection; required internal-release reviews remain a Console step. Temporary keys and signed bundles are deleted and never become GitHub artifacts. Code-owner review of the trusted workflow and signing script remains essential; compromise of either store environment can publish internal builds for its app. | | S18 | High | Malicious or compromised extension | Per-profile install, per-site permission prompts, hash recorded, no silent updates, off in private mode by default, no access to internal pages or other profiles. | App and Official extensions get every site they list without a prompt while Settings › Extensions › "Allow extensions on every site" is on, which is the default (`Pref::ExtensionsEverySite`); Unverified ones always ask per site and Lockdown hosts stay denied. `tabs.create` from an App extension opens a web page as a normal tab through `nav_policy`, at the pop-up rate (3 in 10 s) and never with a private-network address as its URL (S10). Open: that tab is a user load, so a redirect of its URL to a private address is followed. With the global switch on, an update that asks for more sites is not held back. Only Safari web extensions bundled with apps in `/Applications` are offered (`engine::extensions`); nothing runs until the user turns an extension on for the current profile in Settings › Extensions, which lists every requested permission and site pattern. Turning it on grants all of them (no per-site prompts). Each profile has its own `WKWebExtensionController`: storage is keyed by the profile's own data-store UUID, also when it shares website data with another profile, the private space gets an in-memory controller with nothing enabled, Lockdown profiles and Lockdown-level views get no controller, and hosts with a Lockdown override are denied to every extension (checked: the content script stops answering), because a link into such a host keeps its view. An extension sees only the tabs of its own profile. Its `safari-web-extension://` origin (Safari's scheme, which Bitwarden's inline menu requires), which pages can see, is derived from the profile's data-store UUID, so it differs per user and profile; sites that probe for Bitwarden's Safari pages find it as they would in Safari. `windows.create` opens a window only for the extension's own pages (Bitwarden's unlock, passkey and edit popouts), at most four per extension, each side between 200 and 1000 points and the height kept on screen; the window's top-level navigations are held to the extension's own pages, because it has no navigation policy or Shield, and it closes when the extension is turned off or its data is removed. Only the extension that opened it sees it. Frames inside it are not restricted and it shows no origin chip, as with the extension's toolbar popup. Native messages and native ports are answered only while Settings › Extensions › "Bitwarden integration" is on, which it is not by default (`Pref::ExtensionsBitwarden`; switching it reloads Bitwarden with or without them, and off it runs like any other app extension), and only for an app extension whose code signature is Bitwarden's (`com.bitwarden.desktop.safari`, signed by team `LTZ2PFU5D6`, or by Apple for the Mac App Store with that team's entitlement), checked when extensions are discovered, and only for the four Bitwarden uses (`copyToClipboard`, `readFromClipboard`, `sleep` with at most 16 pending, `showPopover`); a native port (`connectNative`) is accepted only for Bitwarden's app id, at most four per extension, closed with the extension, and answers only Bitwarden's biometrics questions as its Safari app extension does: Touch ID through LocalAuthentication, then the user key the Bitwarden desktop app keeps in the login keychain (`Bitwarden_biometric`, account `_user_biometric`), read off the main thread after Touch ID succeeded and handed only to that port; one Touch ID prompt at a time, naming the extension; while Bitwarden runs in a profile with that integration on (turned off, pages already open keep this until they reload), pages there (not at Lockdown) are told that passkeys and conditional mediation are available, as in Safari, but only in frames where `navigator.credentials.get` has been replaced again, by Bitwarden's page script or the page itself; WebKit says no without Apple's browser entitlement and refuses conditional requests at once, so in those frames such a refusal of a request with an abort signal stays pending until the page aborts it, as Safari's conditional UI does, and Bitwarden's answer is not cut short; elsewhere WebKit's own answers are returned, the availability one after waiting while the document still parses, at most 40 checks 50 ms apart; clipboard writes need the granted `clipboardWrite` permission and reads also need `clipboardRead` in the manifest, which Settings then lists. Deleting a profile removes its extensions' data through WebKit and then WebKit's folder for it, whose `State.plist` names each extension; "Delete everything" removes the data and restarts the profile's extensions. Tarn has no internal web pages to reach. Extensions can also be installed from a GitHub repository, the signed official catalog (own ed25519 key, domain-separated signature, rollback and 30-day freshness checks, a revoked set that only grows) and `.zip`/`.crx` files: archives are unpacked with strict name, size, depth and type checks into read-only per-install directories; storage is keyed by a random install id; the tree hash is recorded at install and checked before every load, `.appex` bundles included, and a mismatch turns the extension off and drops its site grants; trust labels and the Bitwarden privileges (native messages, clipboard read, passkey script, pop-out windows) follow the install source, never the manifest; unpacked extensions show a popup only after a toolbar click. Host access is per site: the grant-all loop is gone, WebKit's own URL prompt becomes a tab-modal Allow/Deny with Remember (Once lasts an hour), decisions are stored per install and profile, and App and Official sources may be switched to "Allow on every site", which turns off when an update asks for more sites (without effect while the global switch is on). Extension pages, workers and popups get the profile's private-network and HTTPS rule lists. `Tab` refuses `loadURL`, reload, back, forward and zoom without access to the tab's page. Updates are a new install with the same prompt, never automatic. Tarn extensions (`manifest_version` 3 with `browser_specific_settings.tarn.runtime` 1) run on Tarn's own runtime (`browser_core::tarn_ext`, contract `engine::tarn_ext`), the same on every engine: a package using any manifest key, permission (only `storage`, `activeTab`, `declarativeNetRequest`), content-script option or network-rule action outside the subset is refused at install with the key named, and `redirect`, `modifyHeaders` and `allowAllRequests` rules always are, as are a `priority` other than 1, a port in a site pattern and more than 1000 `regexFilter` rules; content scripts and their CSS run only in the install's isolated world `tarn-ext-`, only in http and https frames, only where the engine's synchronous gate (`frame_decision`) allows them, which needs a grant for the frame's host from the same per-site machinery (App and Official may use every site, Unverified always ask, Lockdown hosts denied, Once one hour or until the tab closes, one prompt per site and session); nothing runs in private spaces, burner tabs, Lockdown profiles or Lockdown-level views: no extension page opens in a Lockdown profile, the pages already open close when a profile moves into Lockdown (`Runtime::level_changed`, called by every shell), and its messages and action clicks are refused. Messages travel only between the install's isolated worlds, its own pages and the shell's router (`tarn_ext::router`): the engine defines the transport only in that world or page and reports where a call arrived, so the sender (install, tab, frame, page) never comes from the message; a main frame's message counts only while the install holds a grant for the tab's host (and, where the engine reports the main frame's origin, only when it is the tab's) and a subframe's only while it holds one for the frame's own origin as the engine reported it, a plain `http` document's only when one of the install's site patterns also covers `http`, and no frame inside a page of a Lockdown host runs a script or sends a message; each message is JSON of at most 1 MiB, at most 200 per second per install and tab, malformed ones dropped; a reply counts only from a receiver the message went to; `tabs.query` shows the URL and title only of tabs whose host the install holds a grant for or that `activeTab` gave it; `tabs.sendMessage` reaches only such tabs; `tabs.create` opens web pages only through `nav_policy`, at most 3 in 10 s, never a private-network address (S10); `storage.local` holds JSON per profile and install, at most 5 MiB with keys up to 1 KiB, in memory for a private profile, and is deleted with the install. Static network rules (at most 5 files of 4 MiB, 30,000 rules) compile into one content rule list per install whose block and upgrade rules act only on top-level sites the install holds a grant for (every site only with the trusted switch, minus the hosts the user denied for the install and Lockdown hosts); the grant is the host's whatever the scheme, so they also act on a plain `http` page of a granted host, also for an install whose site patterns name only `https` (WebKit's `if-domain` names no scheme, and the `if-top-url` that could cannot share a list with it); a rule without `resourceTypes` leaves out top-level documents as in Chrome, and one for only main or only sub frames is kept to them (`load-context`); `excludedRequestDomains`, and `excludedInitiatorDomains` together with `initiatorDomains` or `domains`, are refused, because a content rule list can only lift every earlier rule; `allow` rules lift only the same install's rules, never Shield's, and no list is attached in private spaces, Lockdown profiles or Lockdown-level views. Extension pages are served from `tarn-extension:///`, the origin id the first 32 hex digits of SHA-256 of the profile's data-store seed and the install id, only from the install's read-only directory, whose tree hash is checked when the install loads (files are read on request; a change after that check is found at the next load, which turns the install off), with paths that leave it refused, with `script-src 'self'; frame-src 'self'; object-src 'none'`, so its frames are only its own pages or `about:` ones; web pages cannot load the scheme (no `web_accessible_resources`). The background page is started on its first event and closed after 30 s idle; one that does not get ready within 30 s is closed and its waiting callers get an error, and at most 64 messages wait for a page; a reply not given within 30 s ends with an error, at most 256 replies wait per install, and the background page's own calls do not keep it running. The tree hash is checked before every load and a mismatch turns the install off and drops its grants; Tarn extensions get none of the Bitwarden privileges whatever their source. On macOS and Windows the gate is asked in the navigation callback of every frame before the engine is answered, and its answer travels in the world's scripts (`tarn_ext::injections`); a document whose answer did not arrive first runs nothing, and on WebKit a view without a gate (the link peek) holds an empty answer for each of its documents, so no tab can let that document run, until it gets a gate or closes. WebKit (macOS) runs the scripts in a `WKContentWorld` named after the install with a script message handler added only to that world, and takes the frame from WebKit's own message (subframes by WebKit's private `_handle.frameID`; without it a subframe cannot send), each subframe document numbered on its own per install and holding a random value the install's world draws at document start and sends with every message (a message with another value from a frame that has a newer document is dropped); WebKit runs a reply in whatever document the frame shows, so the reply runs only where that value matches, never in the frame's next document, and a fragment navigation or a load that never commits keeps the document and its replies; extension pages are views of their own with the bootstrap in their main world, a handler that answers only the main frame of the install's origin and a `tarn-extension` scheme handler that serves only that origin. Chromium (macOS and Windows) does the same over the in-process DevTools channel only (S22): new-document scripts in an isolated world named after the install, a `Runtime.addBinding` limited to that world's name and taken out of its global before any content script runs, each context's frame and origin taken from DevTools' own `Runtime.executionContextCreated` (never from what a script sends), replies by `Runtime.evaluate` into those contexts. Frames in another process (cross-site iframes) are attached over the same channel (`Target.setAutoAttach` for iframes only, flattened, each waiting before its first document): a frame gets the same binding and scripts in its own session before it is resumed, an install added later gets them in every attached frame, and its contexts are known by session and context id, so its identity comes from the session DevTools reported, never from a script. The Runtime and Page domains are on in tabs of a profile with Tarn extensions, so a page there can tell that a DevTools client is attached (console argument previews); they stay on because without the Runtime domain no binding reaches a new document's context (checked: no `Runtime.bindingCalled` from any new document), and `Page.createIsolatedWorld` with a binding by context id reaches a frame only after its document has started, too late for `document_start` scripts. Checked at run time in a signed debug bundle on macOS (`engine/tests/tarn_extension_chromium.rs`, `app/tests/tarn_extension.rs`) and in WebKit (`engine/tests/tarn_extension.rs`): the isolated world, messages both ways, storage, the network rule only with a grant, no extension file loads from a web page, frame identity in same-site and cross-site frames after reloads and navigations, an install added after a cross-site frame was attached, nothing in a Lockdown view or profile, and an extension page framing only its own origin. The Runtime domain and auto-attach are turned off again in a view when its last install is removed, which detaches its frames' sessions; an install added later attaches them again. An install added (or added back) while a cross-site frame's navigation is in flight does not run in the document that navigation commits: DevTools holds the commands for that frame's session until the commit, after the document's contexts exist, so nothing runs or is heard there (it fails closed) and the frame's next document runs the install. Open on Chromium: not confirmed against Blink whether `Page.addScriptToEvaluateOnNewDocument` with a `worldName` creates that world with universal access; if it does, content scripts there can reach more than in a WebKit content world. `document_end` scripts start after a round trip to the shell, so they can run after the page's `load` event; extension pages register the scheme per request context on Windows only, where it is a standard, secure, display-isolated scheme in every process; the request context is the profile's, so its handler serves only the browser of the page view of that origin and refuses every other one. Store install link (new boundary: a web page leads to an install prompt): only a main-frame navigation the user started (a typed or other shell load that is not a link or pop-up the shell loads for a page, or a link click with a user gesture; `nav_policy::store_link_asks`) to exactly `https://extensions.tarnbrowser.com/install/` (`engine::tarn_ext::store_install`: https, that host, no port, no user info, a valid catalog id, query and fragment ignored) is cancelled before any request; the page passes nothing but the id and gets no channel into the browser. The link itself makes no request: if Tarn already holds a fresh (at most 30 days old) verified copy of the signed catalog, Settings › Extensions shows a confirmation built only from that entry (name, description, version, permissions, optional permissions, sites; `extensions::install::store_step`, `store_sheet`), otherwise a notice points to Settings › Extensions, where the user can load the catalog, and nothing else happens. Requests start only when the user presses Install there: Tarn first checks everything again (`store_confirm`: the same entry in a fresh catalog, not revoked or installed, no install in progress, and `Core::store_link_allowed` for the tab), then downloads, verifies and unpacks the package as for Settings › Extensions › Official; a package whose manifest stays within that entry (`vet`, as always) installs without a second prompt. A page cannot swap what the user confirms: a new store link replaces the sheet under a new token (`install::StoreToken`: a sequence number, the entry's id and SHA-256), the Install button carries the token of the sheet it was drawn for and `StoreSheet::take` refuses any other, and Install clicks within 700 ms of a sheet appearing or being replaced are ignored (`STORE_CONFIRM_DELAY`; on macOS and Windows also while the window layout is not stable, as for the S5 hand-off rule); closing Settings › Extensions drops an unanswered sheet. An unknown, revoked or already installed id or an install in progress gets a notice, and nothing is offered in a private space, a burner tab, a Lockdown profile, from a page at Lockdown or while the store's host is at Lockdown. Every client takes at most one store link per 10 s and ignores the rest without a sheet (`Core::admit_store_link`). Redirects into the address, subframes and script navigations without a gesture load normally. A script that navigates while handling the user's click counts as the user's, as for pop-ups. WebKit on macOS tells a user's click from a script's `a.click()` only through WebKit's private `_isUserInitiated`, and redirects through `_isRedirect`; where they are missing only shell loads ask. Chromium uses CEF's user gesture, Android WebView `hasGesture`, WebKitGTK `is_user_gesture`. iOS uses no private WebKit API and has no public user-gesture or redirect flag: a shell load or any main-frame `linkActivated` navigation asks, so a page's own script-started link click (and a redirect after a link click) can raise the confirmation there, at most once per 10 s; it requests and installs nothing without the user's confirmation. Open: on Linux the user's own click on an install link inside a frame also opens the consent (WebKitGTK does not say which frame a navigation targets). | -| S5 | High | Origin spoofing; a sidebar-only UI hides the URL | Origin chip always visible; registrable domain emphasised; punycode for mixed-script names. Prompts and dialogs show the origin and are tab-modal. | Origin chip shows the host as parsed by `url` (IDNA to punycode); a `blob:` page shows the host of the URL it wraps and a page without a host (an opener-filled `about:blank`, `data:`) shows only its scheme (`about:blank`, `data:`), as does its tab title when the page set none, so the chip is empty only when no page is loaded. While a navigation the page started is pending, WebKit's `URL` already names its target over the old content; `WebView::url` then returns the committed URL (`Delegate::shown_url`; `about:blank` for a pop-up before its first commit), so chip, peek header and site settings keep naming the page on screen. Only a server redirect (WebKit's private `_isRedirect`) of the navigation the shell itself started with `load` continues the user's load (`Delegate::user_load`); a navigation the old document starts while that load is pending, and its redirects, are the page's own for S10. Without the selector no hop counts as the user's. For the chip, `user_navigation` still covers the time until the user's load commits or any load fails. The link peek header uses the chip's label (`toolbar::site_of`). Dialogs, permission, sign-in and client certificate requests are tab-modal cards naming the origin (shortened from the left so the registrable domain stays visible) and the embedding page for frames; a permission card's Allow and Remember ignore clicks for 700 ms after the card becomes visible, a banner above it appears or leaves, or the window becomes active (which also covers leaving element fullscreen). A client certificate request comes only from the page's own origin (or, in Chromium tabs, the one its main frame is navigating to), never for a proxy, and lists only certificates valid now that the server accepts (WebKit: `kSecMatchIssuers`, `kSecMatchValidOnDate`); its certificate buttons are guarded the same way, none is the default, and Cancel, a refused request or a closed card sends no certificate (Chromium remembers that for the host until Tarn restarts). All guarded controls (this one, a certificate choice, S6's "Open", S25's "Visit Anyway", a notice's offer) share one timer (`Browser::layout_stable_since`), restarted when any of them appears or changes in the active tab, a banner appears or leaves, the tab or overlay changes, the window becomes active or the sidebar is resized, and when the sidebar is shown or hidden it runs from the end of the slide (Linux: Visit Anyway's `guard_since`; mobile: Keep in the downloads pop-over, which hangs from the sidebar). Clean Up never names a group after a site, so a group name says nothing about the origin of the tabs in it; the origin chip stays the trust signal. A page on a site no rule knows can pick its own topic group through its address and title, but never outvotes a known site and never lands in Money or Mail and Chat, which take known sites only, and a group named after a category never learns a host from the tabs in it, so a lookalike is not filed next to the real bank or mail tab; only loose tabs move, and the store never moves a tab from one group into another. A page-requested hand-off to another app names the requesting site ("A page" when its origin is opaque or while a main-frame load is in flight, as in S6), is rate-limited like other prompts, is not replaced while shown, ignores clicks for 700 ms after it appears and shows only in its own tab, hidden while the user is on another tab. A Shift-click link peek follows the pop-up rules and their rate limit. | +| S5 | High | Origin spoofing; a sidebar-only UI hides the URL | Origin chip always visible; registrable domain emphasised; punycode for mixed-script names. Prompts and dialogs show the origin and are tab-modal. | Origin chip shows the host as parsed by `url` (IDNA to punycode); a `blob:` page shows the host of the URL it wraps and a page without a host (an opener-filled `about:blank`, `data:`) shows only its scheme (`about:blank`, `data:`), as does its tab title when the page set none, so the chip is empty only when no page is loaded. While a navigation the page started is pending, WebKit's `URL` already names its target over the old content; `WebView::url` then returns the committed URL (`Delegate::shown_url`; `about:blank` for a pop-up before its first commit), so chip, peek header and site settings keep naming the page on screen. Only a server redirect (WebKit's private `_isRedirect`) of the navigation the shell itself started with `load` continues the user's load (`Delegate::user_load`); a navigation the old document starts while that load is pending, and its redirects, are the page's own for S10. Without the selector no hop counts as the user's. For the chip, `user_navigation` still covers the time until the user's load commits or any load fails. The link peek header uses the chip's label (`toolbar::site_of`). Dialogs, permission, sign-in and client certificate requests are tab-modal cards naming the origin (shortened from the left so the registrable domain stays visible) and the embedding page for frames; a permission card's Allow and Remember ignore clicks for 700 ms after the card becomes visible, a banner above it appears or leaves, or the window becomes active (which also covers leaving element fullscreen). A client certificate request comes only from the page's own origin (or, in Chromium tabs, the one its main frame is navigating to), never for a proxy, and lists the certificates that may answer it (WebKit: Keychain identities valid now, `kSecMatchValidOnDate`, and issued by one of the server's named issuers, `kSecMatchIssuers`, when it names any; Chromium: the list Chromium filtered); its certificate buttons are guarded the same way, none is the default, and Cancel, a refused request or a closed card sends no certificate (Chromium remembers that for the host until Tarn restarts). All guarded controls (this one, a certificate choice, S6's "Open", S25's "Visit Anyway", a notice's offer) share one timer (`Browser::layout_stable_since`), restarted when any of them appears or changes in the active tab, a banner appears or leaves, the tab or overlay changes, the window becomes active or the sidebar is resized, and when the sidebar is shown or hidden it runs from the end of the slide (Linux: Visit Anyway's `guard_since`; mobile: Keep in the downloads pop-over, which hangs from the sidebar). Clean Up never names a group after a site, so a group name says nothing about the origin of the tabs in it; the origin chip stays the trust signal. A page on a site no rule knows can pick its own topic group through its address and title, but never outvotes a known site and never lands in Money or Mail and Chat, which take known sites only, and a group named after a category never learns a host from the tabs in it, so a lookalike is not filed next to the real bank or mail tab; only loose tabs move, and the store never moves a tab from one group into another. A page-requested hand-off to another app names the requesting site ("A page" when its origin is opaque or while a main-frame load is in flight, as in S6), is rate-limited like other prompts, is not replaced while shown, ignores clicks for 700 ms after it appears and shows only in its own tab, hidden while the user is on another tab. A Shift-click link peek follows the pop-up rules and their rate limit. | | S6 | High | Dangerous schemes and untrusted URL sources | Allowlist `http`, `https`, `about:blank`, `blob`. `data:` not at top level. `file:` only by explicit user action. `javascript:` rejected in the command bar and on paste. External schemes prompt each time. URLs from other apps, drops and sync pass the same policy. | `nav_policy::decide` with table test; applied to typed input, Open File (`load_file` is the only load that reaches `file:`, decided as `Source::FileOpen` through `nav_policy::file_open`, which also admits only the user's Back, Forward and Reload onto a file that view itself opened, never a restored history; an opened page loads `file:` subresources and frames only from its own folder, or only itself when that folder is a root, a mounted volume's top or holds the home folder, with symlinks resolved and `file:` URLs naming a host refused before any lookup (macOS WebKit's read-access grant and `nav_policy::file_subresource_allowed` for frames, Chromium's request filter (not yet verified at runtime that CEF hands it `file:` subresources; macOS opens files in WebKit), iOS's grant, Android's `shouldInterceptRequest`; Linux gap in `docs/nsh-plan.md` §4), so its images and styles load, and file pages cannot read other files with scripts; the address shows `File:` and the file's name; iOS and Android copy the picked file into a folder of its own under a staging directory cleared at launch), command-line URLs, restored tabs and session snapshots, main-frame navigations, redirects and popups. A page's external-scheme request shows a banner naming the origin of the frame that started it ("A page" when opaque or while a main-frame load is in flight, so a server redirect is never credited to the page or frame that linked to it), only in its own tab, until that tab's next commit or close; while it shows, further requests are dropped, and "Open" ignores clicks for 700 ms after it, or any banner above it, appears, and again when the window becomes active. Links other apps send (the default-browser case, `shared::open_urls` through GPUI's `on_open_urls`) pass `decide(ExternalApp)`, at most 10 in 10 s across the app (the rest are dropped with a toast), and load as a page's link (`WebView::load_link` with no opener), so S10 refuses a local target or any redirect hop into the local network with its usual notice; typing the address opens it. A loopback link (`localhost`, 127.0.0.0/8, `::1`) opens as typed while Settings › Privacy › Open localhost links from other apps is on (the default), since developers open local servers from terminals and editors; the accepted risk is that a link from a remote sender (a mail) can then reach a service on this computer, as a typed address could. Off, it gets the notice. Other local addresses always get it. The notice offers Open Anyway, which loads the address as the user's own navigation. Chromium tabs do the same: their `load_link` sets no shell mark, also for a load held until the view is ready, so `on_before_browse` credits the page (a Chromium integration test is not written yet); such a load is not a user's, so it does not bridge WebKit's cookies first and the site may open signed out in Chromium. Open: public names that resolve to private addresses (`nip.io`-style) are not recognised. | | S19 | High | Sync storage is read or tampered with | Client-side authenticated encryption; remote data validated as untrusted input; secrets and cookies never synced. | Not built. | | S7 | Medium | TLS downgrade or click-through | WebKit's default trust evaluation, never custom acceptance, and no bypass at any level. Chromium tabs cancel certificate errors and turn Chrome's override off, so its certificate page has no way through. | No custom trust handling exists. Plain-HTTP page navigations into an HTTPS-only site are blocked (a URL with an explicit port loads when the view was built HTTPS-only, because `make-https` leaves ports alone; Chromium tabs, which have no per-level view, upgrade such a link without a port and refuse one with a port unless the page being left is HTTPS-only). |