fix(mcp): stop repeated keychain prompts and validate upgrade identity
This commit is contained in:
12 files changed
+477
-13
No files matched your search
@@ -15,7 +15,7 @@ sqlite-bundled = ["dbx-core/sqlite-bundled"]
|
||||
# keychain key Desktop provisioned during the data security upgrade; the
|
||||
# Linux zigbuild legs cannot link the dbus Secret Service backend and keep
|
||||
# falling back to the managed .dbx/secret.key file.
|
||||
os-keyring = ["dbx-core/os-keyring"]
|
||||
os-keyring = ["dbx-core/os-keyring", "dep:security-framework"]
|
||||
transaction-test-hooks = []
|
||||
|
||||
[[bin]]
|
||||
@@ -45,6 +45,9 @@ tower-http = { version = "0.6", features = ["cors"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
url = "2"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
security-framework = { version = "3.7", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rmcp = { version = "2.2.0", features = ["transport-streamable-http-client-reqwest"] }
|
||||
rustls-pemfile = "2.2"
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
pub struct BackgroundCredentialGuard {
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
_interaction: security_framework::os::macos::keychain::KeychainUserInteractionLock,
|
||||
}
|
||||
|
||||
pub fn disable_background_interaction() -> Result<BackgroundCredentialGuard, String> {
|
||||
Ok(BackgroundCredentialGuard {
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
_interaction: security_framework::os::macos::keychain::SecKeychain::disable_user_interaction().map_err(
|
||||
|error| format!("KEYRING_ACCESS_FAILED: cannot disable background Keychain interaction: {error}"),
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn startup_error(error: String) -> String {
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
if error.contains("KEYRING_ACCESS_FAILED") {
|
||||
return format!(
|
||||
"{error} Unlock the user Keychain, then run the same official dbx-mcp executable with \
|
||||
--authorize-keychain once in a terminal and restart your MCP client. \
|
||||
Do not add that command to MCP client arguments."
|
||||
);
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "macos", feature = "os-keyring")))]
|
||||
pub fn authorize_keychain() -> Result<(), String> {
|
||||
Err("KEYCHAIN_AUTHORIZATION_UNSUPPORTED: this command requires an official macOS build with OS keyring support"
|
||||
.to_string())
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
pub fn authorize_keychain() -> Result<(), String> {
|
||||
use security_framework::os::macos::{
|
||||
code_signing::{Flags, SecCode, SecRequirement},
|
||||
keychain::{SecKeychain, SecPreferencesDomain},
|
||||
passwords::find_generic_password,
|
||||
};
|
||||
|
||||
let untrusted = |error| format!("KEYCHAIN_AUTHORIZATION_UNTRUSTED: {error}");
|
||||
let requirement: SecRequirement = RELEASE_REQUIREMENT.parse().map_err(|error| untrusted(format!("{error}")))?;
|
||||
// Validate the running code, not just a possibly replaced file at its path.
|
||||
SecCode::for_self(Flags::NONE)
|
||||
.and_then(|code| code.check_validity(Flags::STRICT_VALIDATE, &requirement))
|
||||
.map_err(|error| untrusted(format!("expected the official DBX Developer ID identity: {error}")))?;
|
||||
let executable = std::env::current_exe().map_err(|error| untrusted(format!("{error}")))?;
|
||||
let signature = std::process::Command::new("/usr/bin/codesign")
|
||||
.args(["--display", "--verbose=4", "--requirements", "-"])
|
||||
.arg(executable)
|
||||
.output()
|
||||
.map_err(|error| untrusted(format!("cannot inspect signing identity: {error}")))?;
|
||||
if !signature.status.success() {
|
||||
return Err(untrusted("cannot inspect signing identity".to_string()));
|
||||
}
|
||||
let info =
|
||||
format!("{}\n{}", String::from_utf8_lossy(&signature.stdout), String::from_utf8_lossy(&signature.stderr));
|
||||
validate_signature_info(&info).map_err(|error| untrusted(error.to_string()))?;
|
||||
|
||||
// Match keyring's User-domain lookup exactly; never authorize a same-name
|
||||
// item from another keychain, provision a new key, or rewrite an ACL.
|
||||
let keychain = SecKeychain::default_for_domain(SecPreferencesDomain::User)
|
||||
.map_err(|error| format!("KEYRING_ACCESS_FAILED: cannot open the user Keychain: {error}"))?;
|
||||
let (_password, _item) =
|
||||
find_generic_password(Some(&[keychain]), "com.dbx.app.secret-store.v1", "local-data-encryption-key").map_err(
|
||||
|error| {
|
||||
if error.code() == -25300 {
|
||||
"SECRET_KEY_UNAVAILABLE: no existing DBX Keychain key; use Desktop data-security setup".to_string()
|
||||
} else {
|
||||
format!("KEYRING_ACCESS_FAILED: existing DBX Keychain key cannot be authorized: {error}")
|
||||
}
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "os-keyring"), test))]
|
||||
const RELEASE_REQUIREMENT: &str = "identifier \"com.dbx.app.mcp\" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = \"TVDM965TDL\"";
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "os-keyring"), test))]
|
||||
fn validate_signature_info(info: &str) -> Result<(), &'static str> {
|
||||
let has_line = |expected| info.lines().any(|line| line == expected);
|
||||
if !has_line("Identifier=com.dbx.app.mcp")
|
||||
|| !has_line("TeamIdentifier=TVDM965TDL")
|
||||
|| has_line("Signature=adhoc")
|
||||
|| !info
|
||||
.lines()
|
||||
.any(|line| line.strip_prefix("Timestamp=").is_some_and(|value| !value.is_empty() && value != "none"))
|
||||
{
|
||||
return Err("missing official release identity or secure timestamp");
|
||||
}
|
||||
let normalize = |value: &str| -> String {
|
||||
value.replace("/* exists */", "exists").chars().filter(|c| !c.is_whitespace() && *c != '"').collect()
|
||||
};
|
||||
let mut designated = info.lines().filter_map(|line| line.strip_prefix("designated => "));
|
||||
if !designated.next().is_some_and(|value| normalize(value) == normalize(RELEASE_REQUIREMENT))
|
||||
|| designated.next().is_some()
|
||||
{
|
||||
return Err("a stable Developer ID designated requirement is required");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn signature() -> String {
|
||||
format!(
|
||||
"Identifier=com.dbx.app.mcp\nTeamIdentifier=TVDM965TDL\nTimestamp=Oct 3, 2026\ndesignated => {}\n",
|
||||
RELEASE_REQUIREMENT.replace("exists", "/* exists */")
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_the_stable_release_designated_requirement() {
|
||||
assert!(validate_signature_info(&signature()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unstable_or_incomplete_signatures() {
|
||||
let valid = signature();
|
||||
for invalid in [
|
||||
valid.replace("Identifier=com.dbx.app.mcp", "Identifier=com.dbx.other"),
|
||||
valid.replace("TeamIdentifier=TVDM965TDL", "TeamIdentifier=OTHERTEAM1"),
|
||||
valid.replace("Timestamp=Oct 3, 2026", "Timestamp=none"),
|
||||
valid.replace("Timestamp=Oct 3, 2026", "Timestamp="),
|
||||
valid.replace("Timestamp=Oct 3, 2026\n", ""),
|
||||
format!("{valid}Signature=adhoc\n"),
|
||||
valid.replace(&RELEASE_REQUIREMENT.replace("exists", "/* exists */"), "cdhash H\"abcd\""),
|
||||
valid.replace("designated => ", "missing => "),
|
||||
format!("{valid}designated => cdhash H\"abcd\"\n"),
|
||||
] {
|
||||
assert!(validate_signature_info(&invalid).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_guidance_preserves_the_provider_error() {
|
||||
let error = "SECRET_KEY_UNAVAILABLE: KEYRING_ACCESS_FAILED".to_string();
|
||||
let result = startup_error(error.clone());
|
||||
assert!(result.starts_with(&error));
|
||||
assert_eq!(result.contains("--authorize-keychain"), cfg!(all(target_os = "macos", feature = "os-keyring")));
|
||||
assert_eq!(startup_error("DATA_MIGRATION_REQUIRED".to_string()), "DATA_MIGRATION_REQUIRED");
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "macos", feature = "os-keyring")))]
|
||||
#[test]
|
||||
fn unsupported_platform_policy_does_not_attempt_keychain_authorization() {
|
||||
assert!(authorize_keychain().unwrap_err().starts_with("KEYCHAIN_AUTHORIZATION_UNSUPPORTED"));
|
||||
assert!(disable_background_interaction().is_ok());
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,35 @@ use dbx_mcp::{
|
||||
};
|
||||
use rmcp::ServiceExt;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
mod credentials;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
if std::env::args_os().nth(1).is_some_and(|argument| argument == "--version") {
|
||||
println!("dbx-mcp {}", env!("CARGO_PKG_VERSION"));
|
||||
return Ok(());
|
||||
}
|
||||
if std::env::args_os().nth(1).is_some_and(|argument| argument == "--authorize-keychain") {
|
||||
if std::env::args_os().len() != 2 {
|
||||
return Err("Usage: dbx-mcp --authorize-keychain".into());
|
||||
}
|
||||
credentials::authorize_keychain()?;
|
||||
println!("DBX Keychain access authorized. Restart your MCP client.");
|
||||
return Ok(());
|
||||
}
|
||||
run_noninteractive(run())
|
||||
}
|
||||
|
||||
fn run_noninteractive(
|
||||
future: impl std::future::Future<Output = Result<(), Box<dyn std::error::Error>>>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// This process-wide policy belongs only to the standalone binary and must
|
||||
// outlive the runtime, including credential reads during task shutdown.
|
||||
let _credential_guard = credentials::disable_background_interaction().map_err(std::io::Error::other)?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
||||
runtime.block_on(future)
|
||||
}
|
||||
|
||||
async fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Diagnostics (plugin-tool discovery, bridge fallbacks) go to stderr,
|
||||
// which is safe under the stdio transport. RUST_LOG controls the level;
|
||||
// warnings are on by default so silent degradation stays visible.
|
||||
@@ -24,7 +47,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
)
|
||||
} else {
|
||||
let db_path = dbx_mcp::paths::storage_db_path().map_err(std::io::Error::other)?;
|
||||
Arc::new(LocalBackend::open(&db_path).await.map_err(std::io::Error::other)?)
|
||||
Arc::new(
|
||||
LocalBackend::open(&db_path)
|
||||
.await
|
||||
.map_err(|error| std::io::Error::other(credentials::startup_error(error)))?,
|
||||
)
|
||||
};
|
||||
match runtime.transport {
|
||||
McpTransport::Stdio => {
|
||||
@@ -40,3 +67,39 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos", feature = "os-keyring"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use security_framework::os::macos::keychain::SecKeychain;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
struct ShutdownProbe(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for ShutdownProbe {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(matches!(SecKeychain::user_interaction_allowed(), Ok(false)), Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_interaction_is_disabled_through_runtime_shutdown() {
|
||||
let original = SecKeychain::user_interaction_allowed().unwrap();
|
||||
let shutdown_was_noninteractive = Arc::new(AtomicBool::new(false));
|
||||
let observed = Arc::clone(&shutdown_was_noninteractive);
|
||||
run_noninteractive(async move {
|
||||
assert!(!SecKeychain::user_interaction_allowed().unwrap());
|
||||
let (started, ready) = tokio::sync::oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let _probe = ShutdownProbe(observed);
|
||||
started.send(()).unwrap();
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
ready.await.unwrap();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(shutdown_was_noninteractive.load(Ordering::SeqCst));
|
||||
assert_eq!(SecKeychain::user_interaction_allowed().unwrap(), original);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#include <Security/Security.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
static void record(const char *operation) {
|
||||
Boolean allowed = true;
|
||||
SecKeychainGetUserInteractionAllowed(&allowed);
|
||||
const char *path = getenv("DBX_TEST_KEYCHAIN_POLICY_LOG");
|
||||
FILE *log = path ? fopen(path, "a") : NULL;
|
||||
if (log) {
|
||||
fprintf(log, "%s interaction=%d\n", operation, (int)allowed);
|
||||
fclose(log);
|
||||
}
|
||||
}
|
||||
|
||||
static OSStatus denied_read(CFTypeRef keychain, UInt32 service_len, const char *service,
|
||||
UInt32 account_len, const char *account, UInt32 *length, void **password, SecKeychainItemRef *item) {
|
||||
record("read");
|
||||
return errSecInteractionNotAllowed;
|
||||
}
|
||||
|
||||
static OSStatus denied_lookup(SecPreferencesDomain domain, SecKeychainRef *keychain) {
|
||||
record("lookup");
|
||||
return errSecInteractionNotAllowed;
|
||||
}
|
||||
|
||||
static OSStatus denied_add(SecKeychainRef keychain, UInt32 service_len, const char *service,
|
||||
UInt32 account_len, const char *account, UInt32 length, const void *password, SecKeychainItemRef *item) {
|
||||
record("write");
|
||||
return errSecInteractionNotAllowed;
|
||||
}
|
||||
|
||||
static OSStatus denied_modify(SecKeychainItemRef item, const SecKeychainAttributeList *attributes,
|
||||
UInt32 length, const void *password) {
|
||||
record("write");
|
||||
return errSecInteractionNotAllowed;
|
||||
}
|
||||
|
||||
// Interpose only inside the test child; no real credential reads or writes reach Security.framework.
|
||||
#define INTERPOSE(replacement, original) \
|
||||
__attribute__((used)) static struct { const void *new_function; const void *old_function; } \
|
||||
interpose_##original __attribute__((section("__DATA,__interpose"))) = \
|
||||
{ (const void *)(replacement), (const void *)(original) }
|
||||
|
||||
INTERPOSE(denied_read, SecKeychainFindGenericPassword);
|
||||
INTERPOSE(denied_lookup, SecKeychainCopyDomainDefault);
|
||||
INTERPOSE(denied_add, SecKeychainAddGenericPassword);
|
||||
INTERPOSE(denied_modify, SecKeychainItemModifyAttributesAndData);
|
||||
@@ -14,3 +14,96 @@ fn version_exits_without_initializing_storage_or_transport() {
|
||||
assert!(output.stderr.is_empty());
|
||||
assert!(!directory.path().join("must-not-exist").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keychain_authorization_rejects_extra_arguments_without_opening_storage() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let data_dir = directory.path().join("must-not-exist");
|
||||
let output = std::process::Command::new(env!("CARGO_BIN_EXE_dbx-mcp"))
|
||||
.args(["--authorize-keychain", "--transport", "stdio"])
|
||||
.env("DBX_DATA_DIR", &data_dir)
|
||||
.env("DBX_WEB_URL", "not a URL")
|
||||
.env("DBX_MCP_TRANSPORT", "invalid")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Usage: dbx-mcp --authorize-keychain"));
|
||||
assert!(!data_dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keychain_authorization_rejects_untrusted_or_unsupported_builds_before_storage() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let data_dir = directory.path().join("must-not-exist");
|
||||
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_dbx-mcp"));
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
let log = intercept_keychain(&mut command, directory.path());
|
||||
let output = command
|
||||
.arg("--authorize-keychain")
|
||||
.env("DBX_DATA_DIR", &data_dir)
|
||||
.env("DBX_WEB_URL", "not a URL")
|
||||
.env("DBX_MCP_TRANSPORT", "invalid")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
if cfg!(all(target_os = "macos", feature = "os-keyring")) {
|
||||
assert!(error.contains("KEYCHAIN_AUTHORIZATION_UNTRUSTED"), "{error}");
|
||||
} else {
|
||||
assert!(error.contains("KEYCHAIN_AUTHORIZATION_UNSUPPORTED"), "{error}");
|
||||
}
|
||||
assert!(!data_dir.exists());
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
assert!(!log.exists(), "untrusted recovery must not query the Keychain");
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
fn intercept_keychain(command: &mut std::process::Command, directory: &std::path::Path) -> std::path::PathBuf {
|
||||
let library = directory.join("keychain-policy.dylib");
|
||||
let log = directory.join("keychain-policy.log");
|
||||
let build = std::process::Command::new("/usr/bin/clang")
|
||||
.args(["-dynamiclib", "-Wno-deprecated-declarations", "-framework", "Security", "-o"])
|
||||
.arg(&library)
|
||||
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/macos-keychain-policy.c"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(build.status.success(), "{}", String::from_utf8_lossy(&build.stderr));
|
||||
command.env("DYLD_INSERT_LIBRARIES", &library).env("DBX_TEST_KEYCHAIN_POLICY_LOG", &log);
|
||||
log
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "macos", feature = "os-keyring"))]
|
||||
#[test]
|
||||
fn background_keychain_denial_is_noninteractive_and_never_provisions_a_key() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_dbx-mcp"));
|
||||
let log = intercept_keychain(&mut command, directory.path());
|
||||
let output = command
|
||||
.env("HOME", directory.path())
|
||||
.env("DBX_DATA_DIR", directory.path().join("data"))
|
||||
.env_remove("DBX_WEB_URL")
|
||||
.env_remove("DBX_SECRET_KEY")
|
||||
.env_remove("DBX_SECRET_KEY_FILE")
|
||||
.env_remove("DBX_MCP_TRANSPORT")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
let reads = std::fs::read_to_string(&log).unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"the child must probe the intercepted credential provider: {error}; {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)
|
||||
});
|
||||
assert!(reads.contains("lookup interaction=0"), "{reads}");
|
||||
assert!(!reads.contains("interaction=1"), "{reads}");
|
||||
assert!(!reads.contains("write"), "{reads}");
|
||||
let error = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(error.contains("KEYRING_ACCESS_FAILED"), "{error}");
|
||||
assert!(error.contains("--authorize-keychain"), "{error}");
|
||||
assert!(!directory.path().join(".dbx/secret.key").exists());
|
||||
}
|
||||
Reference in new issue
Block a user