aKode: rimosso il provider OpenAI dal credential broker

- Il broker delle credenziali del proxy di rete non conosce più OpenAI:
  restano GitHub e i provider configurati dall'utente.
- Test del loader adattati: le protezioni di sicurezza restano, ora
  verificate con GitHub e con un provider personalizzato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 16:40:26 +01:00
parent e1ce139a80
commit f366db7f29
14 changed files with 228 additions and 658 deletions

View File

@@ -170,9 +170,6 @@ pub struct NetworkProxyConfig {
pub credential_broker_enabled_mitm: bool,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub credential_providers: BTreeMap<String, crate::CredentialProviderConfig>,
/// Trusted OpenAI endpoint derived from local configuration, never sent to remote executors.
#[serde(skip)]
pub credential_broker_openai_host: Option<String>,
/// Trusted local destination context, never sent to remote executors or child environments.
#[serde(skip)]
pub credential_broker_context: crate::CredentialBrokerContext,
@@ -203,7 +200,6 @@ impl Default for NetworkProxyConfig {
credential_broker: false,
credential_broker_enabled_mitm: false,
credential_providers: BTreeMap::new(),
credential_broker_openai_host: None,
credential_broker_context: crate::CredentialBrokerContext::default(),
dangerously_allow_plaintext_credential_injection: false,
mitm_hooks: Vec::new(),
@@ -227,10 +223,6 @@ impl NetworkProxyConfig {
}
}
pub fn set_credential_broker_openai_base_url(&mut self, base_url: Option<&str>) {
self.credential_broker_openai_host = base_url.and_then(trusted_credential_broker_host);
}
/// Retains trusted destination context without changing child environment policy. Conflicting
/// case-insensitive provider overrides disable brokerage on Windows.
pub fn configure_credential_broker_environment(
@@ -405,15 +397,6 @@ impl NetworkProxyConfig {
}
}
pub(crate) fn trusted_credential_broker_host(base_url: &str) -> Option<String> {
Url::parse(base_url)
.ok()
.filter(|url| {
url.scheme() == "https" && url.username().is_empty() && url.password().is_none()
})
.and_then(|url| url.host_str().map(normalize_host))
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum NetworkMode {
@@ -768,7 +751,6 @@ mod tests {
credential_broker: false,
credential_broker_enabled_mitm: false,
credential_providers: BTreeMap::new(),
credential_broker_openai_host: None,
credential_broker_context: crate::CredentialBrokerContext::default(),
dangerously_allow_plaintext_credential_injection: false,
mitm_hooks: Vec::new(),
@@ -882,33 +864,6 @@ mod tests {
assert!(config.credential_broker);
}
#[test]
fn credential_broker_only_accepts_trusted_https_openai_endpoints() {
let mut config = NetworkProxyConfig::default();
for (base_url, expected_host) in [
(
Some("https://gateway.example.com/v1"),
Some("gateway.example.com"),
),
(
Some("https://gateway.example.com./v1"),
Some("gateway.example.com"),
),
(Some("https://[2001:db8::1]/v1"), Some("2001:db8::1")),
(Some("http://gateway.example.com/v1"), None),
(Some("https://user@gateway.example.com/v1"), None),
(Some("not-a-url"), None),
(None, None),
] {
config.set_credential_broker_openai_base_url(base_url);
assert_eq!(
config.credential_broker_openai_host.as_deref(),
expected_host
);
}
}
#[test]
fn managed_proxy_ports_reject_ephemeral_ports() {
let mut config = NetworkProxyConfig {

View File

@@ -66,7 +66,6 @@ struct CredentialBrokerState {
config_revision: u64,
enabled: bool,
allow_local_binding: bool,
openai_api_host: Option<String>,
context: CredentialBrokerContext,
configured_provider_configs: BTreeMap<String, CredentialProviderConfig>,
configured_providers: Vec<Arc<configured::ConfiguredCredentialProvider>>,
@@ -297,7 +296,6 @@ impl CredentialBroker {
let previous_context_sources = (state.context != config.credential_broker_context)
.then(|| active_credential_sources(&state, &HashMap::new()));
if state.enabled != config.credential_broker
|| state.openai_api_host != config.credential_broker_openai_host
|| state.allow_local_binding != config.allow_local_binding()
|| state.configured_provider_configs != config.credential_providers
|| previous_context_sources.is_some()
@@ -312,18 +310,6 @@ impl CredentialBroker {
state.credential_owners.clear();
state.credential_aliases.clear();
}
if state.openai_api_host != config.credential_broker_openai_host {
state
.openai_api_host
.clone_from(&config.credential_broker_openai_host);
state.credentials.retain(|credential| {
!matches!(
&credential.provider,
BrokeredCredentialProvider::Builtin(provider)
if provider.reset_on_configuration_change
)
});
}
if state.configured_provider_configs != config.credential_providers {
let mut configured_providers: Vec<Arc<configured::ConfiguredCredentialProvider>> =
Vec::new();
@@ -804,8 +790,7 @@ impl CredentialBroker {
for provider in providers::credential_providers() {
let brokered_provider = BrokeredCredentialProvider::Builtin(provider);
let Some((source, host_binding)) = provider.sources().iter().rev().find_map(|source| {
(source.host_binding)(&binding_env, state.openai_api_host.as_deref())
.map(|binding| (source, binding))
(source.host_binding)(&binding_env).map(|binding| (source, binding))
}) else {
continue;
};
@@ -883,11 +868,7 @@ impl CredentialBroker {
.env_vars
.iter()
.any(|key| env_value(env, key) == Some(credential))
&& (candidate.host_binding)(
&binding_env,
state.openai_api_host.as_deref(),
)
.is_none()
&& (candidate.host_binding)(&binding_env).is_none()
})
{
continue;

View File

@@ -676,8 +676,8 @@ fn configured_provider_does_not_guess_ambiguous_alias_destinations() {
false,
),
(
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
"^sk-proj-[A-Za-z0-9]+$",
"ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
"^ghp_[A-Za-z0-9]+$",
true,
),
] {
@@ -713,7 +713,7 @@ fn configured_provider_does_not_guess_ambiguous_alias_destinations() {
assert!(!broker.host_requires_mitm("first.example", /*port*/ 443));
assert!(!broker.host_requires_mitm("second.example", /*port*/ 443));
if overlaps_builtin {
assert!(!broker.host_requires_mitm("api.openai.com", /*port*/ 443));
assert!(!broker.host_requires_mitm("api.github.com", /*port*/ 443));
}
env.insert("FIRST_TOKEN".to_string(), token.to_string());
@@ -747,19 +747,15 @@ fn configured_owner_keeps_prefixed_builtin_shaped_aliases_scoped() {
),
];
for (pattern, token_length, dummy_prefix) in [
(r"\bsk-proj-[a-z]{64}\b", 64, Some("sk-proj-")),
(r"\bghp_[a-z]{64}\b", 64, Some("ghp_")),
// The fixed real branch forces an independently generated vendor-shaped dummy.
(
r"\b(?:sk-proj-a{64}|vendor_[a-z]{64})\b",
64,
Some("vendor_"),
),
(r"\b(?:ghp_a{64}|vendor_[a-z]{64})\b", 64, Some("vendor_")),
// With no distinct long alternative, registration must remain fail-open.
(r"\b(?:sk-proj-a{64}|pin)\b", 64, None),
(r"\b(?:sk-proj-[a-z]{64}|pin)\b", 64, Some("sk-proj-")),
(r"^sk-proj-[a-z]{7}$", 7, Some("sk-proj-")),
(r"\b(?:ghp_a{64}|pin)\b", 64, None),
(r"\b(?:ghp_[a-z]{64}|pin)\b", 64, Some("ghp_")),
(r"^ghp_[a-z]{7}$", 7, Some("ghp_")),
] {
let token = format!("sk-proj-{}", "a".repeat(token_length));
let token = format!("ghp_{}", "a".repeat(token_length));
for (environment_id, retain_source) in [
(None, true),
(Some("local"), true),
@@ -815,7 +811,7 @@ fn configured_owner_keeps_prefixed_builtin_shaped_aliases_scoped() {
assert!(
!broker
.host_protocols_for_environment(
"api.openai.com",
"api.github.com",
/*port*/ 443,
environment_id,
)
@@ -828,7 +824,7 @@ fn configured_owner_keeps_prefixed_builtin_shaped_aliases_scoped() {
)])
};
for target in [
"https://api.openai.com/v1/models",
"https://github.com/v1/models",
"https://api.github.com/v1/models",
"https://configured.example/v2/models",
"https://configured.example/v1/models",
@@ -862,7 +858,7 @@ fn configured_owner_keeps_prefixed_builtin_shaped_aliases_scoped() {
&original_env[key],
&env[key],
&original_env,
|source| source == "OPENAI_API_KEY"
|source| source == "GH_TOKEN"
));
let mut snapshot_alias = original_env[key].clone();
if brokered || token.len() >= super::MIN_EMBEDDED_CREDENTIAL_LENGTH {
@@ -912,7 +908,7 @@ fn configured_owner_keeps_prefixed_builtin_shaped_aliases_scoped() {
#[test]
fn known_credential_spans_preserve_overlaps_and_uncovered_adjacent_credentials() {
let short = format!("sk-proj-{}", "a".repeat(64));
let short = format!("ghp_{}", "a".repeat(64));
let long = format!("{short}bbbbbbbb");
let known = format!(":known_{}", "b".repeat(24));
let github = "ghp_spinningabcdefghijklmnopqrstuvwxyz0123456789";
@@ -937,7 +933,7 @@ fn known_credential_spans_preserve_overlaps_and_uncovered_adjacent_credentials()
"PIN_KEY".to_string(),
],
patterns: vec![
r"\bsk-proj-[ab]{64,72}\b".to_string(),
r"\bghp_[ab]{64,72}\b".to_string(),
"^:known_[a-z]{24}$".to_string(),
r"\bpin\b".to_string(),
],
@@ -1055,21 +1051,21 @@ fn known_credential_spans_preserve_overlaps_and_uncovered_adjacent_credentials()
#[test]
fn configured_provider_does_not_claim_embedded_builtin_credentials() {
let github_token = "ghp_abcdefghijklmnopqrstuvwxyz1234567890";
let openai_token = "sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let oauth_token = "gho_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let broker = broker_for(CredentialProviderConfig {
env: vec!["COMBINED_TOKEN".to_string()],
patterns: vec!["^combo_[A-Za-z0-9_-]{80,180}$".to_string()],
url_prefixes: vec!["combo.example".to_string()],
..CredentialProviderConfig::default()
});
let combined = format!("combo_{github_token}_{openai_token}");
let combined = format!("combo_{github_token}_{oauth_token}");
let mut env = HashMap::from([("AUTH_HEADER".to_string(), combined.clone())]);
broker.virtualize_child_env(&mut env);
assert_ne!(env["AUTH_HEADER"], combined);
assert!(!env["AUTH_HEADER"].contains(github_token));
assert!(!env["AUTH_HEADER"].contains(openai_token));
assert!(!env["AUTH_HEADER"].contains(oauth_token));
assert!(!broker.host_requires_mitm("combo.example", /*port*/ 443));
let mut headers = HeaderMap::new();
headers.insert(
@@ -1088,7 +1084,7 @@ fn configured_provider_does_not_claim_embedded_builtin_credentials() {
#[test]
fn configured_discovery_does_not_claim_overlapping_credential_spans() {
let suffix = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV";
for token in [format!("sk-{suffix}"), format!("sk-proj-{suffix}{suffix}")] {
for token in [format!("ghp_{suffix}"), format!("gho_{suffix}{suffix}")] {
for patterns in [
vec!["^[A-Za-z0-9]{48}$".to_string()],
vec![
@@ -1202,10 +1198,6 @@ fn discovered_credential_aliases_rebind_when_the_destination_changes() {
for (token, host_key) in [
("stripe_live_abcdefghijklmnopqrstuvwx", "STRIPE_HOST"),
("ghp_abcdefghijklmnopqrstuvwxyz1234567890", "GH_HOST"),
(
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
"OPENAI_BASE_URL",
),
] {
let broker = broker_for(CredentialProviderConfig {
env: vec!["STRIPE_API_KEY".to_string()],
@@ -1215,13 +1207,8 @@ fn discovered_credential_aliases_rebind_when_the_destination_changes() {
});
let authorization_header = format!("Bearer {token}");
for host in ["first.example", "second.example"] {
let host_value = if host_key == "OPENAI_BASE_URL" {
format!("https://{host}/v1")
} else {
host.to_string()
};
let mut env = HashMap::from([
(host_key.to_string(), host_value),
(host_key.to_string(), host.to_string()),
("AUTH_HEADER".to_string(), authorization_header.clone()),
]);
@@ -1245,12 +1232,8 @@ fn discovered_credential_aliases_rebind_when_the_destination_changes() {
let mut unbound =
HashMap::from([("AUTH_HEADER".to_string(), authorization_header.clone())]);
broker.virtualize_child_env(&mut unbound);
if host_key == "OPENAI_BASE_URL" {
assert_ne!(unbound["AUTH_HEADER"], authorization_header);
} else {
assert_eq!(unbound["AUTH_HEADER"], authorization_header);
assert!(!broker.host_requires_mitm("api.github.com", /*port*/ 443));
}
assert_eq!(unbound["AUTH_HEADER"], authorization_header);
assert!(!broker.host_requires_mitm("api.github.com", /*port*/ 443));
}
}
@@ -1292,13 +1275,6 @@ fn credential_rotation_preserves_alias_destination_ownership() {
"ghp_",
None,
),
(
"OPENAI_API_KEY",
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"sk-proj-",
Some("api.openai.com"),
),
] {
for (environment, real_aliases, discover_parent) in [
("parent", false, false),
@@ -1321,10 +1297,9 @@ fn credential_rotation_preserves_alias_destination_ownership() {
url_prefix_from_env: Some("PROVIDER_URL".to_string()),
..CredentialProviderConfig::default()
});
let suffix_len = if key == "OPENAI_API_KEY" { 64 } else { 36 };
let first = format!("{prefix}{}", "a".repeat(suffix_len));
let second = format!("{prefix}{}", "b".repeat(suffix_len));
let auxiliary = format!("{prefix}{}", "c".repeat(suffix_len));
let first = format!("{prefix}{}", "a".repeat(36));
let second = format!("{prefix}{}", "b".repeat(36));
let auxiliary = format!("{prefix}{}", "c".repeat(36));
let endpoint = |host: &str| {
if host_key == "GH_HOST" {
host.to_string()
@@ -2839,12 +2814,6 @@ fn explicit_invalid_destinations_clear_previous_dynamic_bindings() {
"ghp_abcdefghijklmnopqrstuvwxyz0123456789",
None,
),
(
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789",
Some("api.openai.com"),
),
(
"PROVIDER_TOKEN",
"PROVIDER_ENDPOINT",

View File

@@ -1,5 +1,4 @@
mod github;
mod openai;
use super::destination::CredentialDestination;
use rama_http::HeaderMap;
@@ -23,7 +22,6 @@ pub(super) struct CredentialProvider {
pub(super) credential_watermark: Option<&'static str>,
pub(super) minimum_credential_len: usize,
sources: &'static [CredentialSource],
pub(super) reset_on_configuration_change: bool,
dummy_value: fn(&str) -> String,
translate_request_header: TranslateRequestHeader,
request_header_value: fn(&str) -> Option<HeaderValue>,
@@ -33,7 +31,6 @@ pub(super) struct CredentialProvider {
#[derive(Clone, PartialEq, Eq)]
pub(super) enum CredentialHostBinding {
ExactHost(String),
ExactHosts(Vec<String>),
HostPattern {
exact_hosts: &'static [&'static str],
suffixes: &'static [&'static str],
@@ -46,11 +43,10 @@ pub(super) struct CredentialSource {
pub(super) binding_env_vars: &'static [&'static str],
// An explicit invalid hint can clear dynamic destinations while leaving a static fallback.
pub(super) invalidates_host_binding: fn(&HashMap<String, String>) -> bool,
pub(super) host_binding:
fn(&HashMap<String, String>, Option<&str>) -> Option<CredentialHostBinding>,
pub(super) host_binding: fn(&HashMap<String, String>) -> Option<CredentialHostBinding>,
}
const CREDENTIAL_PROVIDERS: &[&CredentialProvider] = &[&github::PROVIDER, &openai::PROVIDER];
const CREDENTIAL_PROVIDERS: &[&CredentialProvider] = &[&github::PROVIDER];
impl CredentialProvider {
pub(super) fn sources(&self) -> &[CredentialSource] {
@@ -85,7 +81,6 @@ impl CredentialHostBinding {
match self {
Self::ExactHost(host) => is_default_proxy_bypass_host(host),
Self::ExactHosts(hosts) => hosts.iter().any(|host| is_default_proxy_bypass_host(host)),
Self::HostPattern { exact_hosts, .. } => exact_hosts
.iter()
.any(|host| is_default_proxy_bypass_host(host)),
@@ -98,9 +93,6 @@ impl CredentialHostBinding {
pub(super) fn matches_host(&self, host: &str, port: u16) -> bool {
match self {
Self::ExactHost(expected_host) => host == expected_host,
Self::ExactHosts(expected_hosts) => {
expected_hosts.iter().any(|expected| host == expected)
}
Self::HostPattern {
exact_hosts,
suffixes,
@@ -119,7 +111,7 @@ impl CredentialHostBinding {
Self::ConfiguredHosts(destinations) => destinations
.iter()
.any(|destination| destination.matches_hostname(host)),
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
Self::ExactHost(_) | Self::HostPattern { .. } => {
self.matches_host(host, /*port*/ 443)
}
}
@@ -130,9 +122,7 @@ impl CredentialHostBinding {
Self::ConfiguredHosts(destinations) => destinations
.iter()
.any(|destination| destination.requires_mitm(host, port)),
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
self.matches_host(host, port)
}
Self::ExactHost(_) | Self::HostPattern { .. } => self.matches_host(host, port),
}
}
@@ -141,7 +131,7 @@ impl CredentialHostBinding {
Self::ConfiguredHosts(destinations) => destinations
.iter()
.any(|destination| destination.matches_request(host, request)),
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
Self::ExactHost(_) | Self::HostPattern { .. } => {
request.is_none_or(|request| request.scheme() == "https")
&& self.matches_host(
host,

View File

@@ -42,7 +42,6 @@ pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
host_binding: github_enterprise_binding,
},
],
reset_on_configuration_change: false,
dummy_value,
translate_request_header,
request_header_value,
@@ -110,20 +109,14 @@ pub(super) fn translate_request_header(
}
}
fn github_cloud_binding(
_: &HashMap<String, String>,
_: Option<&str>,
) -> Option<CredentialHostBinding> {
fn github_cloud_binding(_: &HashMap<String, String>) -> Option<CredentialHostBinding> {
Some(CredentialHostBinding::HostPattern {
exact_hosts: GITHUB_CLOUD_HOSTS,
suffixes: GITHUB_CLOUD_HOST_SUFFIXES,
})
}
fn github_enterprise_binding(
env: &HashMap<String, String>,
_: Option<&str>,
) -> Option<CredentialHostBinding> {
fn github_enterprise_binding(env: &HashMap<String, String>) -> Option<CredentialHostBinding> {
github_host_hint(env)
.filter(|host| !github_cloud_host(host))
.map(CredentialHostBinding::ExactHost)

View File

@@ -1,95 +0,0 @@
use super::super::env_value;
use super::CredentialHostBinding;
use super::CredentialProvider;
use super::CredentialSource;
use super::shaped_dummy_value;
use crate::config::trusted_credential_broker_host;
use rama_http::HeaderMap;
use rama_http::HeaderValue;
use rama_http::header::AUTHORIZATION;
use std::collections::HashMap;
const OPENAI_API_KEY_ENV_VARS: &[&str] = &["OPENAI_API_KEY"];
const OPENAI_API_KEY_PREFIXES: &[&str] = &["sk-proj-", "sk-svcacct-", "sk-admin-", "sk-"];
const OPENAI_BASE_URL_ENV_VAR: &str = "OPENAI_BASE_URL";
const OPENAI_API_KEY_MIN_LEN: usize = 51;
const OPENAI_API_HOST: &str = "api.openai.com";
pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
context_env_vars: &[OPENAI_BASE_URL_ENV_VAR],
credential_prefixes: OPENAI_API_KEY_PREFIXES,
ignored_credential_prefixes: &["sk-ant-", "sk-or-"],
credential_watermark: Some("T3BlbkFJ"),
minimum_credential_len: OPENAI_API_KEY_MIN_LEN,
sources: &[CredentialSource {
env_vars: OPENAI_API_KEY_ENV_VARS,
binding_env_vars: &[OPENAI_BASE_URL_ENV_VAR],
invalidates_host_binding: |env| {
env_value(env, OPENAI_BASE_URL_ENV_VAR)
.is_some_and(|value| trusted_credential_broker_host(value).is_none())
},
host_binding,
}],
reset_on_configuration_change: true,
dummy_value,
translate_request_header,
request_header_value,
insert_request_header,
};
fn dummy_value(real_value: &str) -> String {
shaped_dummy_value(
real_value,
openai_api_key_prefix(real_value),
OPENAI_API_KEY_MIN_LEN,
)
}
fn translate_request_header(
headers: &HeaderMap,
expected_value: &str,
replacement_value: &str,
) -> Option<HeaderValue> {
headers
.get(AUTHORIZATION)
.and_then(|header| header.to_str().ok())
.filter(|header| header.contains(expected_value))?;
request_header_value(replacement_value)
}
fn request_header_value(value: &str) -> Option<HeaderValue> {
HeaderValue::from_str(&format!("Bearer {value}")).ok()
}
fn insert_request_header(headers: &mut HeaderMap, value: HeaderValue) {
headers.insert(AUTHORIZATION, value);
}
fn host_binding(
env: &HashMap<String, String>,
configured_host: Option<&str>,
) -> Option<CredentialHostBinding> {
let mut hosts = vec![OPENAI_API_HOST.to_string()];
for host in configured_host
.map(str::to_string)
.into_iter()
.chain(env_value(env, OPENAI_BASE_URL_ENV_VAR).and_then(trusted_credential_broker_host))
{
if !hosts.contains(&host) {
hosts.push(host);
}
}
Some(match hosts.as_slice() {
[host] => CredentialHostBinding::ExactHost(host.clone()),
_ => CredentialHostBinding::ExactHosts(hosts),
})
}
fn openai_api_key_prefix(value: &str) -> &str {
OPENAI_API_KEY_PREFIXES
.iter()
.copied()
.find(|prefix| value.starts_with(prefix))
.unwrap_or("sk-")
}

View File

@@ -349,9 +349,7 @@ pub(super) fn active_credential_sources(
let mut sources = Vec::new();
for provider in providers::credential_providers() {
for source in provider.sources() {
if let Some(host_binding) =
(source.host_binding)(&binding_env, state.openai_api_host.as_deref())
{
if let Some(host_binding) = (source.host_binding)(&binding_env) {
sources.push(ActiveCredentialSource {
provider: BrokeredCredentialProvider::Builtin(provider),
host_binding,
@@ -448,7 +446,7 @@ pub(super) fn prioritized_credentials<'a>(
BrokeredCredentialProvider::Builtin(provider) => {
provider.sources().iter().any(|source| {
!source.binding_env_vars.is_empty()
&& (source.host_binding)(&binding_env, state.openai_api_host.as_deref())
&& (source.host_binding)(&binding_env)
.is_some_and(|binding| binding == credential.host_binding)
})
}

View File

@@ -45,15 +45,10 @@ fn assert_credential_shape(real_value: &str, dummy_value: &str, prefix: &str) {
#[test]
fn unmasked_credentials_follow_the_selected_failure_mode() {
for (enabled, source, base_url, expected) in [
for (enabled, source, host_hint, expected) in [
(true, "GH_TOKEN", None, true),
(true, "GH_ENTERPRISE_TOKEN", None, false),
(
true,
"OPENAI_API_KEY",
Some("https://localhost:1234/v1"),
false,
),
(true, "GH_ENTERPRISE_TOKEN", Some("localhost"), false),
(false, "GH_TOKEN", None, false),
] {
let broker = CredentialBroker::new(enabled);
@@ -66,8 +61,8 @@ fn unmasked_credentials_follow_the_selected_failure_mode() {
(source, "opaque-executor-credential"),
("AUTH_HEADER", "Bearer opaque-executor-credential"),
]);
if let Some(base_url) = base_url {
env.insert("OPENAI_BASE_URL".to_string(), base_url.to_string());
if let Some(host_hint) = host_hint {
env.insert("GH_HOST".to_string(), host_hint.to_string());
}
broker.virtualize_child_env(&mut env);
for alias_only in [false, true] {
@@ -99,147 +94,80 @@ fn unmasked_credentials_follow_the_selected_failure_mode() {
}
}
fn vendor_broker() -> CredentialBroker {
let broker = CredentialBroker::new(/*enabled*/ true);
broker.configure(&NetworkProxyConfig {
credential_broker: true,
credential_providers: BTreeMap::from([(
"vendor".to_string(),
CredentialProviderConfig {
env: vec!["VENDOR_API_KEY".to_string()],
patterns: vec![r"\bvendor_[A-Za-z0-9]{40}\b".to_string()],
url_prefixes: vec!["https://api.vendor.example/v1".to_string()],
..CredentialProviderConfig::default()
},
)]),
..NetworkProxyConfig::default()
});
broker
}
#[test]
fn virtualize_child_env_replaces_supported_credentials() {
let broker = CredentialBroker::new(/*enabled*/ true);
let broker = vendor_broker();
let github_token = "github_pat_11AA0bbCC_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH";
let openai_api_key = "sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
let vendor_api_key = "vendor_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN";
let authorization = format!("Bearer {github_token}");
let mut env = env_map([
("GH_TOKEN", github_token),
("HOMEBREW_GITHUB_API_TOKEN", github_token),
("AUTH_HEADER", authorization.as_str()),
("OPENAI_API_KEY", openai_api_key),
("VENDOR_API_KEY", vendor_api_key),
("GH_ENTERPRISE_TOKEN", github_token),
]);
broker.virtualize_child_env(&mut env);
let github_dummy = env.get("GH_TOKEN").expect("dummy GitHub token");
let openai_dummy = env.get("OPENAI_API_KEY").expect("dummy OpenAI API key");
let vendor_dummy = env.get("VENDOR_API_KEY").expect("dummy vendor API key");
assert_credential_shape(github_token, github_dummy, "github_pat_");
assert_credential_shape(openai_api_key, openai_dummy, "sk-proj-");
assert_ne!(vendor_dummy, vendor_api_key);
assert_eq!(env.get("HOMEBREW_GITHUB_API_TOKEN"), Some(github_dummy));
assert_eq!(env.get("GH_ENTERPRISE_TOKEN"), Some(github_dummy));
assert_eq!(
env.get("AUTH_HEADER"),
Some(&format!("Bearer {github_dummy}"))
);
let mut persisted_credentials = format!("{github_token}\n{openai_api_key}");
let mut persisted_credentials = format!("{github_token}\n{vendor_api_key}");
assert!(broker.virtualize_text(&mut persisted_credentials, &env));
assert_eq!(
persisted_credentials,
format!("{github_dummy}\n{openai_dummy}")
format!("{github_dummy}\n{vendor_dummy}")
);
let mut filtered_env = env.clone();
filtered_env.remove("OPENAI_API_KEY");
let mut excluded_credentials = format!("{github_token}\n{openai_api_key}");
filtered_env.remove("VENDOR_API_KEY");
let mut excluded_credentials = format!("{github_token}\n{vendor_api_key}");
assert!(!broker.virtualize_text(&mut excluded_credentials, &filtered_env));
assert_eq!(excluded_credentials, format!("{github_dummy}\n"));
let mut excluded_dummies = format!("{github_dummy}\n{openai_dummy}");
let mut excluded_dummies = format!("{github_dummy}\n{vendor_dummy}");
assert!(!broker.virtualize_text(&mut excluded_dummies, &filtered_env));
assert_eq!(excluded_dummies, format!("{github_dummy}\n"));
let unknown_github_token = "ghp_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh";
let unknown_openai_key = "sk-proj-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh";
let unknown_legacy_openai_key = format!("sk-{}", "a".repeat(48));
let mut unregistered = format!(
"{unknown_github_token}\n{unknown_openai_key}\n{unknown_legacy_openai_key}\nghp_x sk-proj-x"
);
let unknown_oauth_token = "gho_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh";
let mut unregistered = format!("{unknown_github_token}\n{unknown_oauth_token}\nghp_x gho_x");
assert!(!broker.virtualize_text(&mut unregistered, &env));
assert_eq!(unregistered, "\n\n\nghp_x sk-proj-x");
for key in [
"sk-ant-api03-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno",
"sk-ant-oat01-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno",
"sk-or-v1-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno",
] {
let mut unrelated_provider = key.to_string();
assert!(broker.virtualize_text(&mut unrelated_provider, &env));
assert_eq!(unrelated_provider, key);
assert!(!credential_broker_provider_sources_allowed(
key,
key,
&HashMap::new(),
|_| true,
));
}
let mut embedded_tokens = format!("v1{unknown_github_token}\n/opt/ta{unknown_openai_key}/bin");
assert_eq!(unregistered, "\n\nghp_x gho_x");
let mut embedded_tokens = format!("v1{unknown_github_token}\n/opt/ta{unknown_oauth_token}/bin");
assert!(!broker.virtualize_text(&mut embedded_tokens, &env));
assert_eq!(embedded_tokens, "v1\n/opt/ta/bin");
let qualified_legacy = format!(
"sk-{}-{}T3BlbkFJ{}",
"a".repeat(20),
"b".repeat(19),
"c".repeat(20)
);
let legacy_broker = CredentialBroker::new(/*enabled*/ true);
let mut legacy_env = env_map([("OPENAI_API_KEY", qualified_legacy.as_str())]);
legacy_broker.virtualize_child_env(&mut legacy_env);
assert_credential_shape(&qualified_legacy, &legacy_env["OPENAI_API_KEY"], "sk-");
let unmarked_legacy = format!("sk-{}-{}", "a".repeat(15), "b".repeat(35));
let mut unmarked_legacy_alias = format!("Bearer {unmarked_legacy}");
assert!(!broker.virtualize_text(&mut unmarked_legacy_alias, &env));
assert_eq!(unmarked_legacy_alias, "Bearer ");
let collision = format!(
"sk-{}-sk-{}T3BlbkFJ{}",
"a".repeat(20),
"b".repeat(16),
"c".repeat(20)
);
let mut collision_alias = format!("Bearer {collision}");
assert!(!broker.virtualize_text(&mut collision_alias, &env));
assert_eq!(collision_alias, "Bearer ");
let unrelated_collision = format!("sk-ant-api03-{}-sk-{}", "a".repeat(40), "b".repeat(48));
let mut redacted_collision = unrelated_collision.clone();
assert!(!broker.virtualize_text(&mut redacted_collision, &env));
assert_eq!(
redacted_collision,
format!("sk-ant-api03-{}-", "a".repeat(40))
);
assert!(credential_broker_provider_sources_allowed(
&unrelated_collision,
&redacted_collision,
&HashMap::new(),
|_| true,
));
let unrelated = "sk-ant-api03-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno";
let mut known_provider_env = env.clone();
known_provider_env.insert("ANTHROPIC_API_KEY".to_string(), unrelated.to_string());
for separator in ["_", "__", "--", "-_", "_-", "", "_openai_", "_Bearer_"] {
let mut known_adjacent = format!("{unrelated}{separator}{unknown_legacy_openai_key}");
assert!(!broker.virtualize_text(&mut known_adjacent, &known_provider_env));
assert_eq!(known_adjacent, format!("{unrelated}{separator}"));
}
let first_bundle = format!("{unrelated}_{unknown_legacy_openai_key}");
known_provider_env.insert("FIRST_BUNDLE".to_string(), first_bundle.clone());
let openrouter = "sk-or-v1-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno";
for ignored in [unrelated, openrouter] {
for separator in ["_", "-", "__", "--", "", "_openai_", "_Bearer_"] {
let mut unknown_adjacent = format!("{ignored}{separator}{unknown_legacy_openai_key}");
assert!(!broker.virtualize_text(&mut unknown_adjacent, &env));
assert_eq!(unknown_adjacent, format!("{ignored}{separator}"));
}
}
let mut nested_bundle = format!("{first_bundle}_{openrouter}");
assert!(!broker.virtualize_text(&mut nested_bundle, &known_provider_env));
assert_eq!(nested_bundle, format!("{unrelated}__{openrouter}"));
let mixed_providers = format!("{unknown_github_token}_{unrelated_collision}");
let mut virtualized_providers = mixed_providers.clone();
assert!(!broker.virtualize_text(&mut virtualized_providers, &env));
assert!(!credential_broker_provider_sources_allowed(
&mixed_providers,
&virtualized_providers,
&HashMap::new(),
|source| source != "OPENAI_API_KEY",
));
let mixed_credentials =
format!("{unknown_github_token}_{unknown_legacy_openai_key}_{unrelated}");
let mixed_credentials = format!("{unknown_github_token}_{unknown_oauth_token}");
let mut virtualized_credentials = mixed_credentials.clone();
assert!(!broker.virtualize_text(&mut virtualized_credentials, &env));
assert!(!credential_broker_provider_sources_allowed(
&mixed_credentials,
&virtualized_credentials,
&HashMap::new(),
|source| source != "OPENAI_API_KEY",
|source| source != "GITHUB_TOKEN",
));
let equivalent_sources = env_map([
("GH_TOKEN", unknown_github_token),
@@ -262,144 +190,52 @@ fn virtualize_child_env_replaces_supported_credentials() {
&distinct_sources,
|source| source == "GH_TOKEN",
));
for unrelated in [
unrelated,
"sk-or-v1-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno",
] {
for separator in ['_', '-'] {
for (mut adjacent, expected) in [
(
format!("{unrelated}{separator}{qualified_legacy}"),
format!("{unrelated}{separator}"),
),
(
format!("{unknown_legacy_openai_key}{separator}{unrelated}"),
format!("{separator}{unrelated}"),
),
] {
assert!(!broker.virtualize_text(&mut adjacent, &env));
assert_eq!(adjacent, expected);
}
}
}
let hash = "a".repeat(64);
let copied_openai_key = format!("sk-proj-{hash}");
let mut copied_credential = format!("ta{copied_openai_key}");
let copied_github_token = format!("ghp_{hash}");
let mut copied_credential = format!("ta{copied_github_token}");
assert!(!broker.virtualize_text(&mut copied_credential, &env));
assert_eq!(copied_credential, "ta");
let mut path_embedded_credentials =
format!("/prefix/{unknown_legacy_openai_key}:/next\n/prefix/sk-proj-{hash}");
format!("/prefix/{unknown_github_token}:/next\n/prefix/ghp_{hash}");
assert!(!broker.virtualize_text(&mut path_embedded_credentials, &env));
assert_eq!(path_embedded_credentials, "/prefix/:/next\n/prefix/");
for separator in ['-', '_'] {
let mut embedded_path = format!("/workspace/token{separator}sk-proj-{hash}/bin");
let mut embedded_path = format!("/workspace/token{separator}ghp_{hash}/bin");
assert!(!broker.virtualize_text(&mut embedded_path, &env));
assert_eq!(embedded_path, format!("/workspace/token{separator}/bin"));
}
let mut adjacent_path = format!("/workspace/tokensk-proj-{hash}/bin");
let mut adjacent_path = format!("/workspace/tokenghp_{hash}/bin");
assert!(!broker.virtualize_text(&mut adjacent_path, &env));
assert_eq!(adjacent_path, "/workspace/token/bin");
let mut word_adjacent_path = format!("/workspace/datask-proj-{hash}/bin");
assert!(!broker.virtualize_text(&mut word_adjacent_path, &env));
assert_eq!(word_adjacent_path, "/workspace/data/bin");
for prefix in ["a", "di", "ma", "ri", "bri"] {
let mut embedded_credential = format!("Bearer {prefix}sk-{hash}");
assert!(!broker.virtualize_text(&mut embedded_credential, &env));
assert_eq!(embedded_credential, format!("Bearer {prefix}"));
}
for component in ["\u{e9}task", "e\u{301}task"] {
let mut unicode_adjacent_path = format!("/workspace/{component}-proj-{hash}/bin");
assert!(!broker.virtualize_text(&mut unicode_adjacent_path, &env));
assert_eq!(
unicode_adjacent_path,
format!("/workspace/{}/bin", component.strip_suffix("sk").unwrap())
);
}
let mut hashed_credential_path =
format!("/workspace/task-proj-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh-{hash}/bin");
assert!(!broker.virtualize_text(&mut hashed_credential_path, &env));
assert_eq!(hashed_credential_path, "/workspace/ta/bin");
let mut watermarked_path = format!("/workspace/tokensk-proj-{hash}-T3BlbkFJsuffix/bin");
assert!(!broker.virtualize_text(&mut watermarked_path, &env));
assert_eq!(watermarked_path, "/workspace/token/bin");
for suffix in ["build-", "", "proj-", "admin-", "svcacct-"] {
let path_value =
format!("/task-{suffix}{hash}:/task-{suffix}{hash}/x:/task-{suffix}{hash}");
for path in [
path_value,
format!("declare -x PATH=\"/task-{suffix}{hash}-build:/task-{suffix}{hash}-release\""),
format!("export -UT PATH path=(/task-{suffix}{hash} /usr/bin)"),
format!("alias activate='source /task-{suffix}{hash}/bin/activate'"),
format!(r"C:\task-{suffix}{hash}\Scripts"),
] {
let mut virtualized_path = path.clone();
assert!(broker.virtualize_text(&mut virtualized_path, &env));
assert_eq!(virtualized_path, path);
}
}
for component in [
"my_task",
"flask",
"disk",
"mask",
"risk",
"brisk",
"subtask",
"mytask",
"devtask",
"multitask",
"buildtask",
"mydisk",
"harddisk",
"MY_Task",
"Flask",
"\u{e9}_task",
"e\u{301}_task",
] {
for suffix in ["", "proj-", "admin-", "svcacct-"] {
for path in [
format!("/workspace/{component}-{suffix}{hash}/bin"),
format!("VIRTUAL_ENV=/workspace/{component}-{suffix}{hash}"),
format!(
"alias activate='source /workspace/{component}-{suffix}{hash}/bin/activate'"
),
format!(r"C:\\workspace\\{component}-{suffix}{hash}\\Scripts"),
] {
let mut virtualized_path = path.clone();
assert!(broker.virtualize_text(&mut virtualized_path, &env));
assert_eq!(virtualized_path, path);
}
}
}
let registered_hex_credential = format!("sk-{hash}");
let registered_hex_credential = format!("ghp_{hash}");
let registered_broker = CredentialBroker::new(/*enabled*/ true);
let mut registered_env = env_map([("OPENAI_API_KEY", registered_hex_credential.as_str())]);
let mut registered_env = env_map([("GH_TOKEN", registered_hex_credential.as_str())]);
registered_broker.virtualize_child_env(&mut registered_env);
let registered_dummy = &registered_env["OPENAI_API_KEY"];
let registered_dummy = &registered_env["GH_TOKEN"];
let mut credential_path = format!("/workspace/multita{registered_hex_credential}/bin");
assert!(registered_broker.virtualize_text(&mut credential_path, &registered_env));
assert_eq!(
credential_path,
format!("/workspace/multita{registered_dummy}/bin")
);
for (key, placeholder, credential) in [
("GH_TOKEN", "ghp_", unknown_github_token),
("OPENAI_API_KEY", "sk-", unknown_legacy_openai_key.as_str()),
] {
{
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([(key, placeholder)]);
let mut env = env_map([("GH_TOKEN", "ghp_")]);
broker.virtualize_child_env(&mut env);
let mut alias = format!("Bearer {credential}");
let mut alias = format!("Bearer {unknown_github_token}");
assert!(!broker.virtualize_text(&mut alias, &env));
assert!(!alias.contains(credential));
assert!(!alias.contains(unknown_github_token));
}
let mut command = vec![
format!("Authorization: Bearer {github_dummy}"),
format!("Authorization: Bearer {openai_dummy}"),
format!("Authorization: Bearer {vendor_dummy}"),
];
let github_dummy = github_dummy.clone();
let openai_dummy = openai_dummy.clone();
env.insert("OPENAI_API_KEY".to_string(), "sk-user-override".to_string());
let vendor_dummy = vendor_dummy.clone();
env.insert(
"VENDOR_API_KEY".to_string(),
"vendor-user-override".to_string(),
);
env.insert(
"GIT_CONFIG_VALUE_0".to_string(),
format!("Authorization: Bearer {github_dummy}"),
@@ -421,8 +257,8 @@ fn virtualize_child_env_replaces_supported_credentials() {
);
assert_eq!(env.get("AUTH_HEADER"), Some(&authorization));
assert_eq!(
env.get("OPENAI_API_KEY").map(String::as_str),
Some("sk-user-override")
env.get("VENDOR_API_KEY").map(String::as_str),
Some("vendor-user-override")
);
assert_eq!(
env.get("GIT_CONFIG_VALUE_0"),
@@ -432,15 +268,15 @@ fn virtualize_child_env_replaces_supported_credentials() {
command,
vec![
format!("Authorization: Bearer {github_dummy}"),
format!("Authorization: Bearer {openai_dummy}"),
format!("Authorization: Bearer {vendor_dummy}"),
]
);
env.insert("GH_TOKEN".to_string(), openai_dummy.clone());
env.insert("OPENAI_API_KEY".to_string(), github_dummy.clone());
env.insert("GH_TOKEN".to_string(), vendor_dummy.clone());
env.insert("VENDOR_API_KEY".to_string(), github_dummy.clone());
broker.restore_child_env(&mut env, &mut []);
assert_eq!(env.get("GH_TOKEN"), Some(&openai_dummy));
assert_eq!(env.get("OPENAI_API_KEY"), Some(&github_dummy));
assert_eq!(env.get("GH_TOKEN"), Some(&vendor_dummy));
assert_eq!(env.get("VENDOR_API_KEY"), Some(&github_dummy));
}
#[test]
@@ -623,16 +459,17 @@ fn virtualize_child_env_replaces_aliases_of_filtered_parent_credentials() {
assert_eq!(child_env["AUTH_HEADER"], authorization_header);
assert!(!child_env.contains_key("GH_TOKEN"));
let openai_token = "sk-proj-abcdefghijklmnopqrstuvwxyz1234567890";
let mixed_bundle = format!("GitHub {github_token}\nOpenAI {openai_token}");
let broker = vendor_broker();
let vendor_token = "vendor_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN";
let mixed_bundle = format!("GitHub {github_token}\nVendor {vendor_token}");
let mut mixed_env = env_map([
("GH_TOKEN", github_token),
("OPENAI_API_KEY", openai_token),
("VENDOR_API_KEY", vendor_token),
("AUTH_BUNDLE", mixed_bundle.as_str()),
]);
broker.virtualize_child_env(&mut mixed_env);
let mut mixed_alias = mixed_env["AUTH_BUNDLE"].clone();
let excluded_dummy = mixed_env.remove("OPENAI_API_KEY").expect("OpenAI dummy");
let excluded_dummy = mixed_env.remove("VENDOR_API_KEY").expect("vendor dummy");
assert!(!broker.virtualize_text(&mut mixed_alias, &mixed_env));
assert!(!mixed_alias.contains(&excluded_dummy));
}
@@ -640,7 +477,7 @@ fn virtualize_child_env_replaces_aliases_of_filtered_parent_credentials() {
#[test]
fn virtualize_child_env_preserves_paths_unless_the_credential_is_known() {
let broker = CredentialBroker::new(/*enabled*/ true);
let real = format!("sk-proj-{}", "a".repeat(64));
let real = format!("ghp_{}", "a".repeat(64));
let path = format!("/workspace/my_ta{real}/bin");
let mut env = env_map([("VIRTUAL_ENV", &path)]);
@@ -659,9 +496,9 @@ fn virtualize_child_env_preserves_paths_unless_the_credential_is_known() {
let mut copied_env = env_map([("COPIED", &copied)]);
broker.virtualize_child_env(&mut copied_env);
let dummy = copied_env["COPIED"].strip_prefix("ta").unwrap();
assert_credential_shape(&real, dummy, "sk-proj-");
assert_credential_shape(&real, dummy, "ghp_");
let mut headers = headers_with_bearer(dummy);
broker.inject_request_headers("api.openai.com", &mut headers);
broker.inject_request_headers("api.github.com", &mut headers);
assert_eq!(
authorization(&headers),
Some(format!("Bearer {real}").as_str())
@@ -680,9 +517,9 @@ fn virtualize_child_env_discovers_credentials_without_canonical_variables() {
"api.github.com",
),
(
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
"OPENAI_API_KEY",
"api.openai.com",
"github_pat_11AA0bbCC_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH",
"GITHUB_TOKEN",
"uploads.github.com",
),
] {
let broker = CredentialBroker::new(/*enabled*/ true);
@@ -719,9 +556,9 @@ fn virtualize_child_env_discovers_credentials_without_canonical_variables() {
fn virtualize_child_env_preserves_operational_paths_during_credential_discovery() {
let broker = CredentialBroker::new(/*enabled*/ true);
let hash = "a".repeat(64);
let virtual_env = format!("/workspace/multitask-proj-{hash}/bin");
let github_host = format!("multitask-proj-{hash}.enterprise.example");
let token = "sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let virtual_env = format!("/workspace/multitaghp_{hash}/bin");
let github_host = format!("multitaghp-{hash}.enterprise.example");
let token = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let authorization_header = format!("Bearer {token}");
let mut env = env_map([
("VIRTUAL_ENV", virtual_env.as_str()),
@@ -741,22 +578,35 @@ fn virtualize_child_env_preserves_operational_paths_during_credential_discovery(
#[test]
fn virtualize_child_env_keeps_adjacent_provider_credentials_separate() {
let broker = CredentialBroker::new(/*enabled*/ true);
broker.configure(&NetworkProxyConfig {
credential_broker: true,
credential_providers: BTreeMap::from([(
"vendor".to_string(),
CredentialProviderConfig {
env: vec!["VENDOR_API_KEY".to_string()],
patterns: vec!["vendor_[A-Za-z0-9]{40}".to_string()],
url_prefixes: vec!["https://api.vendor.example/v1".to_string()],
..CredentialProviderConfig::default()
},
)]),
..NetworkProxyConfig::default()
});
let github_token = "ghp_abcdefghijklmnopqrstuvwxyz1234567890ABCD";
let openai_token = "sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let real_bundle = format!("{github_token}_{openai_token}");
let vendor_token = "vendor_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN";
let real_bundle = format!("{github_token}_{vendor_token}");
let mut env = env_map([("AUTH_BUNDLE", real_bundle.as_str())]);
broker.virtualize_child_env(&mut env);
let dummy_bundle = env["AUTH_BUNDLE"].clone();
assert!(!dummy_bundle.contains(github_token));
assert!(!dummy_bundle.contains(openai_token));
let (github_dummy, openai_suffix) = dummy_bundle
.split_once("_sk-proj-")
assert!(!dummy_bundle.contains(vendor_token));
let (github_dummy, vendor_suffix) = dummy_bundle
.split_once("_vendor_")
.expect("separate provider credentials");
let openai_dummy = format!("sk-proj-{openai_suffix}");
let vendor_dummy = format!("vendor_{vendor_suffix}");
assert_credential_shape(github_token, github_dummy, "ghp_");
assert_credential_shape(openai_token, &openai_dummy, "sk-proj-");
assert_ne!(vendor_dummy, vendor_token);
let mut github_headers = headers_with_bearer(github_dummy);
broker.inject_request_headers("api.github.com", &mut github_headers);
@@ -765,11 +615,11 @@ fn virtualize_child_env_keeps_adjacent_provider_credentials_separate() {
Some(format!("Bearer {github_token}").as_str())
);
let mut openai_headers = headers_with_bearer(&openai_dummy);
broker.inject_request_headers("api.openai.com", &mut openai_headers);
let mut vendor_headers = headers_with_bearer(&vendor_dummy);
broker.inject_request_headers("https://api.vendor.example/v1/models", &mut vendor_headers);
assert_eq!(
authorization(&openai_headers),
Some(format!("Bearer {openai_token}").as_str())
authorization(&vendor_headers),
Some(format!("Bearer {vendor_token}").as_str())
);
let mut bundled_headers = headers_with_bearer(&dummy_bundle);
@@ -826,31 +676,35 @@ fn virtualize_child_env_binds_filtered_enterprise_credentials_to_child_host() {
#[test]
fn brokered_credential_env_keys_only_include_registered_credentials() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([
("OPENAI_API_KEY", "sk-real"),
("GH_TOKEN", ""),
("GH_HOST", "github.example.com"),
]);
for (registered, expected) in [
(Some("GITHUB_TOKEN"), vec!["GITHUB_TOKEN", "GH_HOST"]),
(None, Vec::new()),
] {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([("GH_TOKEN", ""), ("GH_HOST", "github.example.com")]);
if let Some(registered) = registered {
env.insert(registered.to_string(), "ghp-real".to_string());
}
broker.virtualize_child_env(&mut env);
env.insert(
"GH_TOKEN".to_string(),
"ghp_added_after_brokerage".to_string(),
);
broker.virtualize_child_env(&mut env);
env.insert(
"GH_TOKEN".to_string(),
"ghp_added_after_brokerage".to_string(),
);
assert_eq!(
brokered_credential_env_keys(&env).collect::<Vec<_>>(),
vec!["OPENAI_API_KEY"]
);
assert_eq!(
brokered_credential_env_keys(&env).collect::<Vec<_>>(),
expected
);
}
}
#[test]
fn brokered_credential_value_env_keys_include_dummy_aliases() {
let broker = CredentialBroker::new(/*enabled*/ true);
let real = "sk-proj-abcdefghijklmnopqrstuvwxyz";
let real = "ghp_abcdefghijklmnopqrstuvwxyz";
let alias = format!("Bearer {real}");
let mut env = env_map([("OPENAI_API_KEY", real), ("AUTH_HEADER", alias.as_str())]);
let mut env = env_map([("GH_TOKEN", real), ("AUTH_HEADER", alias.as_str())]);
broker.virtualize_child_env(&mut env);
@@ -859,21 +713,15 @@ fn brokered_credential_value_env_keys_include_dummy_aliases() {
assert_eq!(
marker,
vec![
(
"@alias:AUTH_HEADER".to_string(),
env["OPENAI_API_KEY"].clone()
),
(
"@alias:OPENAI_API_KEY".to_string(),
env["OPENAI_API_KEY"].clone()
),
("OPENAI_API_KEY".to_string(), env["OPENAI_API_KEY"].clone()),
("@alias:AUTH_HEADER".to_string(), env["GH_TOKEN"].clone()),
("@alias:GH_TOKEN".to_string(), env["GH_TOKEN"].clone()),
("GH_TOKEN".to_string(), env["GH_TOKEN"].clone()),
]
);
assert_eq!(
brokered_credential_value_env_keys(&env),
vec!["AUTH_HEADER".to_string(), "OPENAI_API_KEY".to_string()]
vec!["AUTH_HEADER".to_string(), "GH_TOKEN".to_string()]
);
let mut absent_alias_env = env.clone();
@@ -881,15 +729,15 @@ fn brokered_credential_value_env_keys_include_dummy_aliases() {
broker.virtualize_child_env(&mut absent_alias_env);
assert_eq!(
brokered_credential_marker_env_keys(&absent_alias_env),
vec!["AUTH_HEADER".to_string(), "OPENAI_API_KEY".to_string()]
vec!["AUTH_HEADER".to_string(), "GH_TOKEN".to_string()]
);
env.remove("OPENAI_API_KEY");
env.remove("GH_TOKEN");
broker.virtualize_child_env(&mut env);
assert!(brokered_credential_dummy_env_keys(&env).is_empty());
assert_eq!(
brokered_credential_marker_env_keys(&env),
vec!["AUTH_HEADER".to_string(), "OPENAI_API_KEY".to_string()]
vec!["AUTH_HEADER".to_string(), "GH_TOKEN".to_string()]
);
assert_eq!(
brokered_credential_value_env_keys(&env),
@@ -902,9 +750,6 @@ fn virtualize_child_env_uses_fresh_dummy_capabilities() {
for (source, real_value, prefix) in [
("GH_TOKEN", "ghp_short", "ghp_"),
("GH_TOKEN", "opaque:.credential/🦀", "ghp_"),
("OPENAI_API_KEY", "sk-proj-short", "sk-proj-"),
("OPENAI_API_KEY", "sk-svcacct-short", "sk-svcacct-"),
("OPENAI_API_KEY", "opaque:.credential/🦀", "sk-"),
] {
let mut first_env = env_map([(source, real_value)]);
let mut second_env = first_env.clone();
@@ -917,11 +762,7 @@ fn virtualize_child_env_uses_fresh_dummy_capabilities() {
"custom".to_string(),
CredentialProviderConfig {
env: vec!["CUSTOM_TOKEN".to_string()],
patterns: vec![
"^ghp_[A-Za-z0-9]+$".to_string(),
"^sk-proj-[A-Za-z0-9]+$".to_string(),
"^[a-z]{4}$".to_string(),
],
patterns: vec!["^ghp_[A-Za-z0-9]+$".to_string(), "^[a-z]{4}$".to_string()],
url_prefixes: vec!["https://custom.example".to_string()],
..CredentialProviderConfig::default()
},
@@ -940,14 +781,14 @@ fn virtualize_child_env_uses_fresh_dummy_capabilities() {
#[test]
fn child_without_dummy_cannot_use_previous_child_credential() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut first_env = env_map([("OPENAI_API_KEY", "sk-real")]);
let mut first_env = env_map([("GH_TOKEN", "ghp-real")]);
let mut second_env = HashMap::new();
broker.virtualize_child_env(&mut first_env);
broker.virtualize_child_env(&mut second_env);
let mut headers = HeaderMap::new();
broker.inject_request_headers("api.openai.com", &mut headers);
broker.inject_request_headers("api.github.com", &mut headers);
assert_eq!(authorization(&headers), None);
}
@@ -1094,24 +935,24 @@ fn request_translation_preserves_provider_scheme_and_host_binding() {
#[test]
fn inject_request_headers_requires_dummy_and_preserves_explicit_authorization() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([("OPENAI_API_KEY", "sk-real")]);
let mut env = env_map([("GH_TOKEN", "ghp-real")]);
broker.virtualize_child_env(&mut env);
let openai_api_key = env.get("OPENAI_API_KEY").expect("dummy OpenAI API key");
let github_token = env.get("GH_TOKEN").expect("dummy GitHub token");
let mut headers = HeaderMap::new();
broker.inject_request_headers("api.openai.com", &mut headers);
broker.inject_request_headers("api.github.com", &mut headers);
assert_eq!(authorization(&headers), None);
headers = headers_with_bearer(openai_api_key);
broker.inject_request_headers("api.openai.com", &mut headers);
assert_eq!(authorization(&headers), Some("Bearer sk-real"));
headers = headers_with_bearer(github_token);
broker.inject_request_headers("api.github.com", &mut headers);
assert_eq!(authorization(&headers), Some("Bearer ghp-real"));
for explicit_value in [
"sk-explicit",
"sk-masked000000000000000000000000000000000000000000",
"ghp-explicit",
"ghp_masked000000000000000000000000000000000000000000",
] {
let mut explicit_headers = headers_with_bearer(explicit_value);
broker.inject_request_headers("api.openai.com", &mut explicit_headers);
broker.inject_request_headers("api.github.com", &mut explicit_headers);
assert_eq!(explicit_headers, headers_with_bearer(explicit_value));
}
}
@@ -1124,11 +965,6 @@ fn concurrent_commands_preserve_discovered_credential_destinations() {
"GH_HOST",
"ghp_abcdefghijklmnopqrstuvwxyz1234567890",
),
(
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
),
(
"PROVIDER_TOKEN",
"PROVIDER_ENDPOINT",
@@ -1234,30 +1070,21 @@ fn builtin_credentials_use_private_destination_context() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut config = NetworkProxyConfig::default();
config.set_credential_broker_enabled(/*enabled*/ true);
config.configure_credential_broker_environment(&env_map([
("GH_HOST", "github.enterprise.example"),
("OPENAI_BASE_URL", "https://gateway.example/v1"),
]));
config.configure_credential_broker_environment(&env_map([(
"GH_HOST",
"github.enterprise.example",
)]));
broker.configure(&config);
for (key, context_key, token, host) in [
(
"GH_ENTERPRISE_TOKEN",
"GH_HOST",
"ghp-real",
"github.enterprise.example",
),
(
"OPENAI_API_KEY",
"OPENAI_BASE_URL",
"sk-real",
"gateway.example",
),
] {
for (key, context_key, token, host) in [(
"GH_ENTERPRISE_TOKEN",
"GH_HOST",
"ghp-real",
"github.enterprise.example",
)] {
let mut env = env_map([(key, token)]);
broker.virtualize_child_env(&mut env);
assert_ne!(env[key], token);
assert!(!env.contains_key("GH_HOST"));
assert!(!env.contains_key("OPENAI_BASE_URL"));
let mut headers = headers_with_bearer(&env[key]);
broker.inject_request_headers(host, &mut headers);
assert_eq!(
@@ -1310,7 +1137,6 @@ fn builtin_credentials_use_private_destination_context() {
fn private_destination_updates_reconcile_registered_fallbacks() {
for ((key, context_key, token), previously_used_fallback) in [
("GH_ENTERPRISE_TOKEN", "GH_HOST", "ghp-real"),
("OPENAI_API_KEY", "OPENAI_BASE_URL", "sk-real"),
(
"VENDOR_TOKEN",
"VENDOR_HOST",
@@ -1391,7 +1217,7 @@ fn private_destination_updates_reconcile_registered_fallbacks() {
}
};
let unrelated_key = if context_key == "GH_HOST" {
"OPENAI_BASE_URL"
"VENDOR_HOST"
} else {
"GH_HOST"
};
@@ -1499,78 +1325,25 @@ fn private_destination_updates_reconcile_registered_fallbacks() {
}
#[test]
fn openai_credentials_bind_only_to_default_and_configured_trusted_hosts() {
fn selected_credential_matches_ipv6_alias_with_plaintext_fallback() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut config = NetworkProxyConfig::default();
config.set_credential_broker_enabled(/*enabled*/ true);
config.set_credential_broker_openai_base_url(
/*base_url*/ Some("https://gateway.example.com./v1"),
);
broker.configure(&config);
let mut env = env_map([
("OPENAI_API_KEY", "sk-real"),
("OPENAI_BASE_URL", "https://sdk.example.com./v1"),
("GH_TOKEN", "ghp-real"),
("GH_ENTERPRISE_TOKEN", "ghp-real"),
("GH_HOST", "hooked.example"),
]);
broker.virtualize_child_env(&mut env);
assert!(brokered_credential_env_keys(&env).any(|key| key == "OPENAI_BASE_URL"));
assert!(brokered_credential_binding_env_keys(&env).any(|key| key == "OPENAI_BASE_URL"));
let dummy = &env["OPENAI_API_KEY"];
for (host, expected_credential) in [
("api.openai.com", "sk-real"),
("gateway.example.com", "sk-real"),
("sdk.example.com", "sk-real"),
("attacker.example", dummy.as_str()),
] {
let mut headers = headers_with_bearer(dummy);
assert_eq!(
env.insert("GH_HOST".to_string(), "fd00::1".to_string());
broker.virtualize_child_env(&mut env);
for destination in ["https://[fd00::1]/api/v3/user", "fd00::1"] {
assert!(
broker.request_matches_hooked_host_alias(
host,
&headers,
&["api.openai.com".to_string()],
destination,
&headers_with_bearer(&env["GH_ENTERPRISE_TOKEN"]),
&["hooked.example".to_string()],
/*environment_id*/ None,
),
host != "api.openai.com" && expected_credential == "sk-real",
"{destination}"
);
broker.inject_request_headers(host, &mut headers);
let expected = format!("Bearer {expected_credential}");
assert_eq!(authorization(&headers), Some(expected.as_str()), "{host}");
}
config.set_credential_broker_openai_base_url(
/*base_url*/ Some("https://replacement.example/v1"),
);
broker.configure(&config);
let mut github_headers = headers_with_bearer(&env["GH_TOKEN"]);
broker.inject_request_headers("api.github.com", &mut github_headers);
assert_eq!(authorization(&github_headers), Some("Bearer ghp-real"));
let mut openai_headers = headers_with_bearer(dummy);
broker.inject_request_headers("gateway.example.com", &mut openai_headers);
assert_eq!(
authorization(&openai_headers),
Some(format!("Bearer {dummy}").as_str())
);
}
#[test]
fn selected_openai_credential_matches_ipv6_alias_with_plaintext_fallback() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([
("OPENAI_API_KEY", "sk-real"),
("OPENAI_BASE_URL", "https://[fd00::1]/v1"),
]);
broker.virtualize_child_env(&mut env);
for destination in ["https://[fd00::1]/v1/models", "fd00::1"] {
assert!(broker.request_matches_hooked_host_alias(
destination,
&headers_with_bearer(&env["OPENAI_API_KEY"]),
&["api.openai.com".to_string()],
/*environment_id*/ None,
));
}
}

View File

@@ -259,12 +259,24 @@ async fn mitm_policy_enforces_brokered_aliases_without_blocking_unrelated_creden
hook
})
.collect(),
credential_providers: std::collections::BTreeMap::from([(
"other".to_string(),
CredentialProviderConfig {
env: vec!["OTHER_TOKEN".to_string()],
patterns: vec!["other_[a-z]{24}".to_string()],
url_prefixes: vec!["https://api.other.example/v1".to_string()],
..CredentialProviderConfig::default()
},
)]),
..NetworkProxyConfig::default()
};
let app_state = Arc::new(network_proxy_state_for_policy(network));
let mut env = HashMap::from([
("GH_TOKEN".to_string(), "ghp-real".to_string()),
("OPENAI_API_KEY".to_string(), "sk-real".to_string()),
(
"OTHER_TOKEN".to_string(),
format!("other_{}", "a".repeat(24)),
),
("GH_HOST".to_string(), "enterprise.example".to_string()),
(
"GH_ENTERPRISE_TOKEN".to_string(),
@@ -278,7 +290,7 @@ async fn mitm_policy_enforces_brokered_aliases_without_blocking_unrelated_creden
"Basic {}",
STANDARD.encode(format!("x-access-token:{}", env["GH_TOKEN"]))
);
let openai = format!("Bearer {}", env["OPENAI_API_KEY"]);
let other = format!("Bearer {}", env["OTHER_TOKEN"]);
let enterprise = format!("Bearer {}", env["GH_ENTERPRISE_TOKEN"]);
for (host, authorization, uses_cloud_credential) in [
("github.com", Some(github.as_str()), true),
@@ -287,7 +299,7 @@ async fn mitm_policy_enforces_brokered_aliases_without_blocking_unrelated_creden
("github.com", Some(basic.as_str()), true),
("github.com", None, false),
("github.com", Some("Bearer unrelated-token"), false),
("github.com", Some(openai.as_str()), false),
("github.com", Some(other.as_str()), false),
("enterprise.example", Some(enterprise.as_str()), false),
] {
let ctx = policy_ctx(

View File

@@ -973,7 +973,6 @@ impl NetworkProxy {
enabled: config.enabled,
allow_local_binding: config.allow_local_binding.filter(|binding| !binding),
credential_providers: config.credential_providers.clone(),
credential_broker_openai_host: config.credential_broker_openai_host.clone(),
credential_broker_context: config.credential_broker_context.clone(),
dangerously_allow_plaintext_credential_injection: config
.dangerously_allow_plaintext_credential_injection,

View File

@@ -44,7 +44,6 @@ impl RemoteCredentialBrokerCache {
let config = NetworkProxyConfig {
credential_broker: config.credential_broker,
allow_local_binding: Some(config.allow_local_binding()),
credential_broker_openai_host: config.credential_broker_openai_host.clone(),
credential_broker_context: config.credential_broker_context.clone(),
credential_providers: config.credential_providers.clone(),
..NetworkProxyConfig::default()

View File

@@ -1548,9 +1548,9 @@ mod tests {
.force_reload()
.await
.expect("enable credential broker");
let mut env = HashMap::from([("OPENAI_API_KEY".to_string(), "sk-real".to_string())]);
let mut env = HashMap::from([("GH_TOKEN".to_string(), "ghp-real".to_string())]);
state.virtualize_child_credentials(&mut env);
assert_ne!(env["OPENAI_API_KEY"], "sk-real");
assert_ne!(env["GH_TOKEN"], "ghp-real");
}
#[test]
@@ -1567,11 +1567,11 @@ mod tests {
)
.expect("managed-disabled credential broker should fail open");
let state = NetworkProxyState::with_reloader(config_state, Arc::new(NoopReloader));
let mut env = HashMap::from([("OPENAI_API_KEY".to_string(), "sk-real".to_string())]);
let mut env = HashMap::from([("GH_TOKEN".to_string(), "ghp-real".to_string())]);
state.virtualize_child_credentials(&mut env);
assert_eq!(env["OPENAI_API_KEY"], "sk-real");
assert_eq!(env["GH_TOKEN"], "ghp-real");
}
#[tokio::test]

View File

@@ -1038,12 +1038,12 @@ mod tests {
credential_broker: true,
..NetworkProxyConfig::default()
};
settings.set_allowed_domains(vec!["api.openai.com".to_string()]);
settings.set_allowed_domains(vec!["api.github.com".to_string()]);
let state = state_for_settings(settings);
let mut env = HashMap::from([("OPENAI_API_KEY".to_string(), "sk-real".to_string())]);
let mut env = HashMap::from([("GH_TOKEN".to_string(), "ghp-real".to_string())]);
state.virtualize_child_credentials(&mut env);
let mut request = TcpRequest::new(
HostWithPort::try_from("api.openai.com:8443").expect("valid authority"),
HostWithPort::try_from("api.github.com:8443").expect("valid authority"),
);
request.extensions_mut().insert(state.clone());