Harden network proxy credential brokerage (#38049)

## What changed

- Bind OpenAI credentials to `api.openai.com` and trusted HTTPS hosts derived from local configuration or `OPENAI_BASE_URL`.
- Support GitHub credentials for `uploads.github.com` and translate Bearer, token, and Basic authorization forms while preserving their schemes.
- Apply credential broker configuration changes without restarting the proxy, including clearing affected credential mappings when trusted OpenAI hosts change.
- Restore brokered credentials in environments and command arguments that intentionally leave managed networking, while preserving user overrides and handling Windows environment keys case-insensitively.
- Keep local credential brokerage out of remote proxy launch configuration and avoid launching a remote proxy when brokerage alone enabled the local proxy.

## Testing

Added coverage for trusted host binding, authorization translation, live reconfiguration, credential restoration, managed-disabled behavior, remote launch configuration, and Windows environment key matching.

GitOrigin-RevId: 8d8bd3aaf6e581849cb622b2faec62cee4e13e52
This commit is contained in:
Winston Howes authored and copyberry committed 2026-08-11 18:21:34 +00:00
1 parent d6ca19d99b
commit eea28321ad
9 files changed
+626 -115

No files matched your search

+46
View File
@@ -14,6 +14,7 @@ use tracing::warn;
use url::Url; use url::Url;
use crate::mitm_hook::MitmHookConfig; use crate::mitm_hook::MitmHookConfig;
use crate::policy::normalize_host;
/// Variant order encodes effective precedence for duplicate patterns: /// Variant order encodes effective precedence for duplicate patterns:
/// `None < Allow < Deny`, so deny wins over allow when entries conflict. /// `None < Allow < Deny`, so deny wins over allow when entries conflict.
@@ -137,6 +138,9 @@ pub struct NetworkProxyConfig {
pub mitm: bool, pub mitm: bool,
#[serde(default)] #[serde(default)]
pub credential_broker: bool, pub credential_broker: bool,
/// Trusted OpenAI endpoint derived from local configuration, never sent to remote executors.
#[serde(skip)]
pub credential_broker_openai_host: Option<String>,
#[serde(default)] #[serde(default)]
pub dangerously_allow_plaintext_credential_injection: bool, pub dangerously_allow_plaintext_credential_injection: bool,
#[serde(default)] #[serde(default)]
@@ -160,6 +164,7 @@ impl Default for NetworkProxyConfig {
allow_local_binding: false, allow_local_binding: false,
mitm: false, mitm: false,
credential_broker: false, credential_broker: false,
credential_broker_openai_host: None,
dangerously_allow_plaintext_credential_injection: false, dangerously_allow_plaintext_credential_injection: false,
mitm_hooks: Vec::new(), mitm_hooks: Vec::new(),
} }
@@ -172,6 +177,10 @@ impl NetworkProxyConfig {
self.mitm |= enabled; self.mitm |= enabled;
} }
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);
}
pub fn allowed_domains(&self) -> Option<Vec<String>> { pub fn allowed_domains(&self) -> Option<Vec<String>> {
self.domain_entries(NetworkDomainPermission::Allow) self.domain_entries(NetworkDomainPermission::Allow)
} }
@@ -276,6 +285,15 @@ 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)] #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum NetworkMode { pub enum NetworkMode {
@@ -619,12 +637,40 @@ mod tests {
allow_local_binding: false, allow_local_binding: false,
mitm: false, mitm: false,
credential_broker: false, credential_broker: false,
credential_broker_openai_host: None,
dangerously_allow_plaintext_credential_injection: false, dangerously_allow_plaintext_credential_injection: false,
mitm_hooks: Vec::new(), mitm_hooks: Vec::new(),
} }
); );
} }
#[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] #[test]
fn managed_proxy_ports_reject_ephemeral_ports() { fn managed_proxy_ports_reject_ephemeral_ports() {
let mut config = NetworkProxyConfig { let mut config = NetworkProxyConfig {
+122 -44
View File
@@ -1,5 +1,6 @@
mod providers; mod providers;
use crate::config::NetworkProxyConfig;
use crate::policy::normalize_host; use crate::policy::normalize_host;
use rama_http::HeaderMap; use rama_http::HeaderMap;
use std::collections::HashMap; use std::collections::HashMap;
@@ -17,6 +18,7 @@ pub(crate) struct CredentialBroker {
#[derive(Default)] #[derive(Default)]
struct CredentialBrokerState { struct CredentialBrokerState {
enabled: bool, enabled: bool,
openai_api_host: Option<String>,
credentials: Vec<CredentialRecord>, credentials: Vec<CredentialRecord>,
} }
@@ -28,6 +30,39 @@ struct CredentialRecord {
dummy_value: String, dummy_value: String,
} }
fn env_key_matches(candidate: &str, expected: &str) -> bool {
if cfg!(windows) {
candidate.eq_ignore_ascii_case(expected)
} else {
candidate == expected
}
}
fn env_entry<'a>(env: &'a HashMap<String, String>, key: &str) -> Option<(&'a str, &'a str)> {
env.iter()
.find(|(candidate, _)| env_key_matches(candidate, key))
.map(|(key, value)| (key.as_str(), value.as_str()))
}
pub(super) fn env_value<'a>(env: &'a HashMap<String, String>, key: &str) -> Option<&'a str> {
env_entry(env, key).map(|(_, value)| value)
}
fn set_env_value(env: &mut HashMap<String, String>, key: &str, value: String) {
if cfg!(windows) {
env.retain(|candidate, _| !env_key_matches(candidate, key));
}
env.insert(key.to_string(), value);
}
fn remove_env_value(env: &mut HashMap<String, String>, key: &str) {
if cfg!(windows) {
env.retain(|candidate, _| !env_key_matches(candidate, key));
} else {
env.remove(key);
}
}
impl CredentialBroker { impl CredentialBroker {
pub(crate) fn new(enabled: bool) -> Self { pub(crate) fn new(enabled: bool) -> Self {
Self { Self {
@@ -38,25 +73,36 @@ impl CredentialBroker {
} }
} }
pub(crate) fn enabled(&self) -> bool { pub(crate) fn configure(&self, config: &NetworkProxyConfig) {
self.read_state().enabled let mut state = self.write_state();
if state.enabled != config.credential_broker {
state.enabled = config.credential_broker;
state.credentials.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| !credential.provider.reset_on_configuration_change);
}
} }
pub(crate) fn virtualize_child_env(&self, env: &mut HashMap<String, String>) { pub(crate) fn virtualize_child_env(&self, env: &mut HashMap<String, String>) {
let mut state = self.write_state(); let mut state = self.write_state();
if !state.enabled { if !state.enabled {
env.remove(CREDENTIAL_BROKER_ACTIVE_ENV_KEY); remove_env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY);
env.remove(BROKERED_CREDENTIALS_ENV_KEY); remove_env_value(env, BROKERED_CREDENTIALS_ENV_KEY);
return; return;
} }
env.insert( set_env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY, "1".to_string());
CREDENTIAL_BROKER_ACTIVE_ENV_KEY.to_string(),
"1".to_string(),
);
for provider in providers::credential_providers() { for provider in providers::credential_providers() {
for source in provider.sources() { for source in provider.sources() {
if let Some(host_binding) = (source.host_binding)(env) { if let Some(host_binding) =
(source.host_binding)(env, state.openai_api_host.as_deref())
{
for env_var in source.env_vars { for env_var in source.env_vars {
virtualize_env_var( virtualize_env_var(
env, env,
@@ -72,6 +118,31 @@ impl CredentialBroker {
update_brokered_credentials_marker(&state, env); update_brokered_credentials_marker(&state, env);
} }
pub(crate) fn restore_child_env(
&self,
env: &mut HashMap<String, String>,
command: &mut [String],
) {
let state = self.read_state();
if !state.enabled || env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY) != Some("1") {
return;
}
for (key, value) in env {
if let Some(credential) = state.credentials.iter().find(|credential| {
env_key_matches(key, &credential.env_var) && value == &credential.dummy_value
}) {
for argument in command.iter_mut() {
if argument.contains(&credential.dummy_value) {
*argument =
argument.replace(&credential.dummy_value, &credential.real_value);
}
}
*value = credential.real_value.clone();
}
}
}
pub(crate) fn host_requires_mitm(&self, host: &str) -> bool { pub(crate) fn host_requires_mitm(&self, host: &str) -> bool {
let normalized_host = normalize_host(host); let normalized_host = normalize_host(host);
let state = self.read_state(); let state = self.read_state();
@@ -94,12 +165,7 @@ impl CredentialBroker {
.iter() .iter()
.filter(|credential| credential.matches_host(&normalized_host)) .filter(|credential| credential.matches_host(&normalized_host))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let Some(credential) = select_credential(headers, &matching_credentials) else { let Some((credential, header_value)) = select_credential(headers, &matching_credentials)
return;
};
let Some(header_value) = credential
.provider
.request_header_value(&credential.real_value)
else { else {
return; return;
}; };
@@ -133,7 +199,7 @@ fn virtualize_env_var(
}; };
let dummy_value = state.register(env_var, provider, host_binding, real_value); let dummy_value = state.register(env_var, provider, host_binding, real_value);
env.insert(env_var.to_string(), dummy_value); set_env_value(env, env_var, dummy_value);
} }
fn brokerable_credential_value<'a>( fn brokerable_credential_value<'a>(
@@ -142,7 +208,7 @@ fn brokerable_credential_value<'a>(
env_var: &str, env_var: &str,
provider: &providers::CredentialProvider, provider: &providers::CredentialProvider,
) -> Option<&'a str> { ) -> Option<&'a str> {
let real_value = env.get(env_var)?.trim(); let real_value = env_value(env, env_var)?.trim();
(!real_value.is_empty() (!real_value.is_empty()
&& !state.is_dummy_value(real_value) && !state.is_dummy_value(real_value)
&& provider.request_header_value(real_value).is_some()) && provider.request_header_value(real_value).is_some())
@@ -198,40 +264,36 @@ impl CredentialRecord {
fn select_credential<'a>( fn select_credential<'a>(
headers: &HeaderMap, headers: &HeaderMap,
matching_credentials: &[&'a CredentialRecord], matching_credentials: &[&'a CredentialRecord],
) -> Option<&'a CredentialRecord> { ) -> Option<(&'a CredentialRecord, rama_http::HeaderValue)> {
let dummy_matches = matching_credentials let mut translated_matches = matching_credentials
.iter() .iter()
.copied() .copied()
.filter(|credential| { .filter_map(|credential| {
credential credential
.provider .provider
.request_header(headers) .translate_request_header(headers, &credential.dummy_value, &credential.real_value)
.and_then(|value| value.to_str().ok()) .map(|header_value| (credential, header_value))
.is_some_and(|value| value.contains(&credential.dummy_value)) });
}) let matched = translated_matches.next()?;
.collect::<Vec<_>>(); translated_matches.next().is_none().then_some(matched)
match dummy_matches.as_slice() {
[credential] => Some(*credential),
[] | [_, _, ..] => None,
}
} }
fn update_brokered_credentials_marker( fn update_brokered_credentials_marker(
state: &CredentialBrokerState, state: &CredentialBrokerState,
env: &mut HashMap<String, String>, env: &mut HashMap<String, String>,
) { ) {
let brokered = providers::credential_broker_env_keys() let brokered = providers::credential_env_keys()
.filter_map(|key| { .filter_map(|key| {
let value = env.get(key)?; let (actual_key, value) = env_entry(env, key)?;
state.is_dummy_value(value).then_some((key, value.as_str())) state.is_dummy_value(value).then_some((actual_key, value))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
match serde_json::to_string(&brokered) { match serde_json::to_string(&brokered) {
Ok(marker) => { Ok(marker) => {
env.insert(BROKERED_CREDENTIALS_ENV_KEY.to_string(), marker); set_env_value(env, BROKERED_CREDENTIALS_ENV_KEY, marker);
} }
Err(_) => { Err(_) => {
env.remove(BROKERED_CREDENTIALS_ENV_KEY); remove_env_value(env, BROKERED_CREDENTIALS_ENV_KEY);
} }
} }
} }
@@ -243,26 +305,42 @@ fn update_brokered_credentials_marker(
/// replaced by the user are ignored. The environment is not mutated; callers own the decision to /// replaced by the user are ignored. The environment is not mutated; callers own the decision to
/// remove the returned keys. /// remove the returned keys.
pub fn brokered_credential_dummy_env_keys(env: &HashMap<String, String>) -> Vec<String> { pub fn brokered_credential_dummy_env_keys(env: &HashMap<String, String>) -> Vec<String> {
env.get(BROKERED_CREDENTIALS_ENV_KEY) let mut keys = env_value(env, BROKERED_CREDENTIALS_ENV_KEY)
.and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok()) .and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok())
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.filter_map(|(key, dummy_value)| { .filter_map(|(key, dummy_value)| {
(providers::credential_broker_env_keys().any(|candidate| candidate == key.as_str()) providers::credential_env_keys()
&& env.get(&key) == Some(&dummy_value)) .any(|candidate| env_key_matches(&key, candidate))
.then_some(key) .then_some(())?;
let (actual_key, actual_value) = env_entry(env, &key)?;
(actual_value == dummy_value.as_str()).then(|| actual_key.to_string())
}) })
.collect() .collect::<Vec<_>>();
keys.sort_unstable();
keys
} }
/// Returns supported credential keys only for an environment with an active broker. /// Returns credential keys plus provider context keys already present in an environment with an
/// active broker.
pub fn brokered_credential_env_keys( pub fn brokered_credential_env_keys(
env: &HashMap<String, String>, env: &HashMap<String, String>,
) -> impl Iterator<Item = &'static str> { ) -> impl Iterator<Item = &'static str> {
let active = env let active = env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY).is_some_and(|value| value == "1");
.get(CREDENTIAL_BROKER_ACTIVE_ENV_KEY) let mut keys = Vec::new();
.is_some_and(|value| value == "1"); if active {
providers::credential_broker_env_keys().filter(move |_| active) let brokered_keys = brokered_credential_dummy_env_keys(env);
keys.extend(providers::credential_env_keys().filter(|key| {
brokered_keys
.iter()
.any(|brokered_key| env_key_matches(brokered_key, key))
}));
keys.extend(
providers::credential_context_env_keys(&brokered_keys)
.filter(|key| env_value(env, key).is_some()),
);
}
keys.into_iter()
} }
#[cfg(test)] #[cfg(test)]
@@ -8,7 +8,7 @@ use std::collections::HashMap;
const DUMMY_ALPHANUMERIC: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const DUMMY_ALPHANUMERIC: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
type RequestHeader = for<'a> fn(&'a HeaderMap) -> Option<&'a HeaderValue>; type TranslateRequestHeader = fn(&HeaderMap, &str, &str) -> Option<HeaderValue>;
/// Describes how one credential family is recognized and injected. /// Describes how one credential family is recognized and injected.
/// ///
@@ -17,8 +17,9 @@ type RequestHeader = for<'a> fn(&'a HeaderMap) -> Option<&'a HeaderValue>;
pub(super) struct CredentialProvider { pub(super) struct CredentialProvider {
context_env_vars: &'static [&'static str], context_env_vars: &'static [&'static str],
sources: &'static [CredentialSource], sources: &'static [CredentialSource],
pub(super) reset_on_configuration_change: bool,
dummy_value: fn(&str) -> String, dummy_value: fn(&str) -> String,
request_header: RequestHeader, translate_request_header: TranslateRequestHeader,
request_header_value: fn(&str) -> Option<HeaderValue>, request_header_value: fn(&str) -> Option<HeaderValue>,
insert_request_header: fn(&mut HeaderMap, HeaderValue), insert_request_header: fn(&mut HeaderMap, HeaderValue),
} }
@@ -26,6 +27,7 @@ pub(super) struct CredentialProvider {
#[derive(Clone, PartialEq, Eq)] #[derive(Clone, PartialEq, Eq)]
pub(super) enum CredentialHostBinding { pub(super) enum CredentialHostBinding {
ExactHost(String), ExactHost(String),
ExactHosts(Vec<String>),
HostPattern { HostPattern {
exact_hosts: &'static [&'static str], exact_hosts: &'static [&'static str],
suffixes: &'static [&'static str], suffixes: &'static [&'static str],
@@ -34,7 +36,8 @@ pub(super) enum CredentialHostBinding {
pub(super) struct CredentialSource { pub(super) struct CredentialSource {
pub(super) env_vars: &'static [&'static str], pub(super) env_vars: &'static [&'static str],
pub(super) host_binding: fn(&HashMap<String, String>) -> Option<CredentialHostBinding>, pub(super) host_binding:
fn(&HashMap<String, String>, Option<&str>) -> Option<CredentialHostBinding>,
} }
const CREDENTIAL_PROVIDERS: &[&CredentialProvider] = &[&github::PROVIDER, &openai::PROVIDER]; const CREDENTIAL_PROVIDERS: &[&CredentialProvider] = &[&github::PROVIDER, &openai::PROVIDER];
@@ -48,8 +51,13 @@ impl CredentialProvider {
(self.dummy_value)(real_value) (self.dummy_value)(real_value)
} }
pub(super) fn request_header<'a>(&self, headers: &'a HeaderMap) -> Option<&'a HeaderValue> { pub(super) fn translate_request_header(
(self.request_header)(headers) &self,
headers: &HeaderMap,
expected_value: &str,
replacement_value: &str,
) -> Option<HeaderValue> {
(self.translate_request_header)(headers, expected_value, replacement_value)
} }
pub(super) fn request_header_value(&self, value: &str) -> Option<HeaderValue> { pub(super) fn request_header_value(&self, value: &str) -> Option<HeaderValue> {
@@ -65,6 +73,9 @@ impl CredentialHostBinding {
pub(super) fn matches_host(&self, host: &str) -> bool { pub(super) fn matches_host(&self, host: &str) -> bool {
match self { match self {
Self::ExactHost(expected_host) => host == expected_host, Self::ExactHost(expected_host) => host == expected_host,
Self::ExactHosts(expected_hosts) => {
expected_hosts.iter().any(|expected| host == expected)
}
Self::HostPattern { Self::HostPattern {
exact_hosts, exact_hosts,
suffixes, suffixes,
@@ -75,14 +86,26 @@ impl CredentialHostBinding {
} }
} }
pub(super) fn credential_broker_env_keys() -> impl Iterator<Item = &'static str> { pub(super) fn credential_context_env_keys(
brokered_keys: &[String],
) -> impl Iterator<Item = &'static str> + '_ {
credential_providers() credential_providers()
.filter(move |provider| {
provider.sources().iter().any(|source| {
source.env_vars.iter().any(|key| {
brokered_keys
.iter()
.any(|brokered_key| super::env_key_matches(brokered_key, key))
})
})
})
.flat_map(|provider| provider.context_env_vars.iter().copied()) .flat_map(|provider| provider.context_env_vars.iter().copied())
.chain( }
credential_providers()
.flat_map(CredentialProvider::sources) pub(super) fn credential_env_keys() -> impl Iterator<Item = &'static str> {
.flat_map(|source| source.env_vars.iter().copied()), credential_providers()
) .flat_map(CredentialProvider::sources)
.flat_map(|source| source.env_vars.iter().copied())
} }
pub(super) fn credential_providers() -> impl Iterator<Item = &'static CredentialProvider> { pub(super) fn credential_providers() -> impl Iterator<Item = &'static CredentialProvider> {
@@ -1,8 +1,10 @@
use super::super::env_value;
use super::CredentialHostBinding; use super::CredentialHostBinding;
use super::CredentialProvider; use super::CredentialProvider;
use super::CredentialSource; use super::CredentialSource;
use super::shaped_dummy_value; use super::shaped_dummy_value;
use crate::policy::normalize_host; use crate::policy::normalize_host;
use base64::Engine as _;
use rama_http::HeaderMap; use rama_http::HeaderMap;
use rama_http::HeaderValue; use rama_http::HeaderValue;
use rama_http::header::AUTHORIZATION; use rama_http::header::AUTHORIZATION;
@@ -14,7 +16,7 @@ const GITHUB_TOKEN_MIN_LEN: usize = 40;
const GITHUB_CLOUD_TOKEN_ENV_VARS: &[&str] = &["GH_TOKEN", "GITHUB_TOKEN"]; const GITHUB_CLOUD_TOKEN_ENV_VARS: &[&str] = &["GH_TOKEN", "GITHUB_TOKEN"];
const GITHUB_ENTERPRISE_TOKEN_ENV_VARS: &[&str] = const GITHUB_ENTERPRISE_TOKEN_ENV_VARS: &[&str] =
&["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]; &["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
const GITHUB_CLOUD_HOSTS: &[&str] = &["api.github.com", "github.com"]; const GITHUB_CLOUD_HOSTS: &[&str] = &["api.github.com", "github.com", "uploads.github.com"];
const GITHUB_CLOUD_HOST_SUFFIXES: &[&str] = &[".ghe.com"]; const GITHUB_CLOUD_HOST_SUFFIXES: &[&str] = &[".ghe.com"];
pub(super) static PROVIDER: CredentialProvider = CredentialProvider { pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
@@ -29,8 +31,9 @@ pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
host_binding: github_enterprise_binding, host_binding: github_enterprise_binding,
}, },
], ],
reset_on_configuration_change: false,
dummy_value, dummy_value,
request_header, translate_request_header,
request_header_value, request_header_value,
insert_request_header, insert_request_header,
}; };
@@ -43,10 +46,6 @@ fn dummy_value(real_value: &str) -> String {
) )
} }
fn request_header(headers: &HeaderMap) -> Option<&HeaderValue> {
headers.get(AUTHORIZATION)
}
fn request_header_value(value: &str) -> Option<HeaderValue> { fn request_header_value(value: &str) -> Option<HeaderValue> {
HeaderValue::from_str(&format!("Bearer {value}")).ok() HeaderValue::from_str(&format!("Bearer {value}")).ok()
} }
@@ -55,14 +54,54 @@ fn insert_request_header(headers: &mut HeaderMap, value: HeaderValue) {
headers.insert(AUTHORIZATION, value); headers.insert(AUTHORIZATION, value);
} }
fn github_cloud_binding(_: &HashMap<String, String>) -> Option<CredentialHostBinding> { fn translate_request_header(
headers: &HeaderMap,
expected_value: &str,
replacement_value: &str,
) -> Option<HeaderValue> {
let header = headers.get(AUTHORIZATION)?.to_str().ok()?;
let (scheme, value) = header.split_once(' ')?;
let value = value.trim();
if scheme.eq_ignore_ascii_case("basic") {
let decoded = base64::engine::general_purpose::STANDARD
.decode(value)
.ok()?;
let separator = decoded.iter().position(|byte| *byte == b':')?;
let mut translated = Vec::with_capacity(decoded.len() + replacement_value.len());
if &decoded[..separator] == expected_value.as_bytes() {
translated.extend_from_slice(replacement_value.as_bytes());
translated.extend_from_slice(&decoded[separator..]);
} else if &decoded[separator + 1..] == expected_value.as_bytes() {
translated.extend_from_slice(&decoded[..=separator]);
translated.extend_from_slice(replacement_value.as_bytes());
} else {
return None;
}
let encoded = base64::engine::general_purpose::STANDARD.encode(translated);
HeaderValue::from_str(&format!("{scheme} {encoded}")).ok()
} else if (scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token"))
&& value == expected_value
{
HeaderValue::from_str(&format!("{scheme} {replacement_value}")).ok()
} else {
None
}
}
fn github_cloud_binding(
_: &HashMap<String, String>,
_: Option<&str>,
) -> Option<CredentialHostBinding> {
Some(CredentialHostBinding::HostPattern { Some(CredentialHostBinding::HostPattern {
exact_hosts: GITHUB_CLOUD_HOSTS, exact_hosts: GITHUB_CLOUD_HOSTS,
suffixes: GITHUB_CLOUD_HOST_SUFFIXES, suffixes: GITHUB_CLOUD_HOST_SUFFIXES,
}) })
} }
fn github_enterprise_binding(env: &HashMap<String, String>) -> Option<CredentialHostBinding> { fn github_enterprise_binding(
env: &HashMap<String, String>,
_: Option<&str>,
) -> Option<CredentialHostBinding> {
github_host_hint(env) github_host_hint(env)
.filter(|host| !github_cloud_host(host)) .filter(|host| !github_cloud_host(host))
.map(CredentialHostBinding::ExactHost) .map(CredentialHostBinding::ExactHost)
@@ -84,8 +123,7 @@ fn github_token_prefix(value: &str) -> &str {
} }
fn github_host_hint(env: &HashMap<String, String>) -> Option<String> { fn github_host_hint(env: &HashMap<String, String>) -> Option<String> {
env.get(GH_HOST_ENV_VAR) env_value(env, GH_HOST_ENV_VAR)
.map(String::as_str)
.map(normalize_host) .map(normalize_host)
.filter(|host| !host.is_empty()) .filter(|host| !host.is_empty())
} }
@@ -1,24 +1,28 @@
use super::super::env_value;
use super::CredentialHostBinding; use super::CredentialHostBinding;
use super::CredentialProvider; use super::CredentialProvider;
use super::CredentialSource; use super::CredentialSource;
use super::shaped_dummy_value; use super::shaped_dummy_value;
use crate::config::trusted_credential_broker_host;
use rama_http::HeaderMap; use rama_http::HeaderMap;
use rama_http::HeaderValue; use rama_http::HeaderValue;
use rama_http::header::AUTHORIZATION; use rama_http::header::AUTHORIZATION;
use std::collections::HashMap; use std::collections::HashMap;
const OPENAI_API_KEY_ENV_VARS: &[&str] = &["OPENAI_API_KEY"]; const OPENAI_API_KEY_ENV_VARS: &[&str] = &["OPENAI_API_KEY"];
const OPENAI_BASE_URL_ENV_VAR: &str = "OPENAI_BASE_URL";
const OPENAI_API_KEY_MIN_LEN: usize = 51; const OPENAI_API_KEY_MIN_LEN: usize = 51;
const OPENAI_API_HOST: &str = "api.openai.com"; const OPENAI_API_HOST: &str = "api.openai.com";
pub(super) static PROVIDER: CredentialProvider = CredentialProvider { pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
context_env_vars: &[], context_env_vars: &[OPENAI_BASE_URL_ENV_VAR],
sources: &[CredentialSource { sources: &[CredentialSource {
env_vars: OPENAI_API_KEY_ENV_VARS, env_vars: OPENAI_API_KEY_ENV_VARS,
host_binding, host_binding,
}], }],
reset_on_configuration_change: true,
dummy_value, dummy_value,
request_header, translate_request_header,
request_header_value, request_header_value,
insert_request_header, insert_request_header,
}; };
@@ -31,8 +35,16 @@ fn dummy_value(real_value: &str) -> String {
) )
} }
fn request_header(headers: &HeaderMap) -> Option<&HeaderValue> { fn translate_request_header(
headers.get(AUTHORIZATION) 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> { fn request_header_value(value: &str) -> Option<HeaderValue> {
@@ -43,10 +55,25 @@ fn insert_request_header(headers: &mut HeaderMap, value: HeaderValue) {
headers.insert(AUTHORIZATION, value); headers.insert(AUTHORIZATION, value);
} }
fn host_binding(_: &HashMap<String, String>) -> Option<CredentialHostBinding> { fn host_binding(
Some(CredentialHostBinding::ExactHost( env: &HashMap<String, String>,
OPENAI_API_HOST.to_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 { fn openai_api_key_prefix(value: &str) -> &str {
@@ -1,5 +1,7 @@
use super::*; use super::*;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use rama_http::HeaderValue; use rama_http::HeaderValue;
use rama_http::header::AUTHORIZATION; use rama_http::header::AUTHORIZATION;
@@ -12,10 +14,14 @@ fn env_map<const N: usize>(entries: [(&str, &str); N]) -> HashMap<String, String
} }
fn headers_with_bearer(value: &str) -> HeaderMap { fn headers_with_bearer(value: &str) -> HeaderMap {
headers_with_authorization(&format!("Bearer {value}"))
}
fn headers_with_authorization(value: &str) -> HeaderMap {
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
headers.insert( headers.insert(
AUTHORIZATION, AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {value}")).expect("valid bearer header"), HeaderValue::from_str(value).expect("valid authorization header"),
); );
headers headers
} }
@@ -57,11 +63,53 @@ fn virtualize_child_env_replaces_supported_credentials() {
let openai_dummy = env.get("OPENAI_API_KEY").expect("dummy OpenAI API key"); let openai_dummy = env.get("OPENAI_API_KEY").expect("dummy OpenAI API key");
assert_credential_shape(github_token, github_dummy, "github_pat_"); assert_credential_shape(github_token, github_dummy, "github_pat_");
assert_credential_shape(openai_api_key, openai_dummy, "sk-proj-"); assert_credential_shape(openai_api_key, openai_dummy, "sk-proj-");
let mut command = vec![
format!("Authorization: Bearer {github_dummy}"),
format!("Authorization: Bearer {openai_dummy}"),
];
let openai_dummy = openai_dummy.clone();
env.insert("OPENAI_API_KEY".to_string(), "sk-user-override".to_string()); env.insert("OPENAI_API_KEY".to_string(), "sk-user-override".to_string());
assert_eq!( assert_eq!(
brokered_credential_dummy_env_keys(&env), brokered_credential_dummy_env_keys(&env),
vec!["GH_TOKEN".to_string()] vec!["GH_TOKEN".to_string()]
); );
broker.restore_child_env(&mut env, &mut command);
assert_eq!(env.get("GH_TOKEN").map(String::as_str), Some(github_token));
assert_eq!(
env.get("OPENAI_API_KEY").map(String::as_str),
Some("sk-user-override")
);
assert_eq!(
command,
vec![
format!("Authorization: Bearer {github_token}"),
format!("Authorization: Bearer {openai_dummy}"),
]
);
}
#[cfg(windows)]
#[test]
fn brokered_credentials_match_environment_keys_case_insensitively_on_windows() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([
("gh_host", "github.example.com"),
("gh_enterprise_token", "ghp-enterprise-real"),
]);
broker.virtualize_child_env(&mut env);
let dummy = env
.get("GH_ENTERPRISE_TOKEN")
.expect("dummy GitHub enterprise token");
let mut headers = headers_with_bearer(dummy);
broker.inject_request_headers("github.example.com", &mut headers);
assert_eq!(
brokered_credential_dummy_env_keys(&env),
vec!["GH_ENTERPRISE_TOKEN".to_string()]
);
assert_eq!(authorization(&headers), Some("Bearer ghp-enterprise-real"));
} }
#[test] #[test]
@@ -84,6 +132,27 @@ fn virtualize_child_env_preserves_live_dummy_mappings() {
assert_eq!(authorization(&second_headers), Some("Bearer ghp-real-two")); assert_eq!(authorization(&second_headers), Some("Bearer ghp-real-two"));
} }
#[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"),
]);
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"]
);
}
#[test] #[test]
fn virtualize_child_env_uses_fresh_dummy_capabilities() { fn virtualize_child_env_uses_fresh_dummy_capabilities() {
let mut first_env = env_map([("OPENAI_API_KEY", "sk-proj-abcdefghijklmnopqrstuvwxyz")]); let mut first_env = env_map([("OPENAI_API_KEY", "sk-proj-abcdefghijklmnopqrstuvwxyz")]);
@@ -146,6 +215,47 @@ fn inject_request_headers_requires_dummy_to_select_ambiguous_github_credential()
assert_eq!(authorization(&headers), Some("Bearer ghp-real-two")); assert_eq!(authorization(&headers), Some("Bearer ghp-real-two"));
} }
#[test]
fn request_translation_preserves_provider_scheme_and_host_binding() {
let broker = CredentialBroker::new(/*enabled*/ true);
let mut env = env_map([("GH_TOKEN", "ghp-real")]);
broker.virtualize_child_env(&mut env);
let gh = &env["GH_TOKEN"];
let basic_dummy = STANDARD.encode(format!("x-access-token:{gh}"));
let basic_real = STANDARD.encode("x-access-token:ghp-real");
let basic_username_dummy = STANDARD.encode(format!("{gh}:x-oauth-basic"));
let basic_username_real = STANDARD.encode("ghp-real:x-oauth-basic");
let basic_dummy = basic_dummy.as_str();
let basic_real = basic_real.as_str();
let basic_username_dummy = basic_username_dummy.as_str();
let basic_username_real = basic_username_real.as_str();
for (host, scheme, input, expected) in [
("github.com", "Basic", basic_dummy, basic_real),
("example.com", "Basic", basic_dummy, basic_dummy),
(
"github.com",
"Basic",
basic_username_dummy,
basic_username_real,
),
(
"example.com",
"Basic",
basic_username_dummy,
basic_username_dummy,
),
("api.github.com", "Bearer", gh.as_str(), "ghp-real"),
("uploads.github.com", "Bearer", gh.as_str(), "ghp-real"),
("api.github.com", "token", gh.as_str(), "ghp-real"),
] {
let mut headers = headers_with_authorization(&format!("{scheme} {input}"));
broker.inject_request_headers(host, &mut headers);
let expected = format!("{scheme} {expected}");
assert_eq!(authorization(&headers), Some(expected.as_str()), "{host}");
}
}
#[test] #[test]
fn inject_request_headers_requires_dummy_and_preserves_explicit_authorization() { fn inject_request_headers_requires_dummy_and_preserves_explicit_authorization() {
let broker = CredentialBroker::new(/*enabled*/ true); let broker = CredentialBroker::new(/*enabled*/ true);
@@ -167,6 +277,54 @@ fn inject_request_headers_requires_dummy_and_preserves_explicit_authorization()
assert_eq!(authorization(&explicit_headers), Some("Bearer sk-explicit")); assert_eq!(authorization(&explicit_headers), Some("Bearer sk-explicit"));
} }
#[test]
fn openai_credentials_bind_only_to_default_and_configured_trusted_hosts() {
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"),
]);
broker.virtualize_child_env(&mut env);
assert!(brokered_credential_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);
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] #[test]
fn github_cloud_credentials_match_ghe_com_host_hint() { fn github_cloud_credentials_match_ghe_com_host_hint() {
let broker = CredentialBroker::new(/*enabled*/ true); let broker = CredentialBroker::new(/*enabled*/ true);
@@ -207,6 +365,7 @@ fn github_enterprise_credentials_bind_to_gh_host() {
("GH_ENTERPRISE_TOKEN", "ghp-enterprise-real"), ("GH_ENTERPRISE_TOKEN", "ghp-enterprise-real"),
]); ]);
broker.virtualize_child_env(&mut env); broker.virtualize_child_env(&mut env);
assert!(brokered_credential_env_keys(&env).any(|key| key == "GH_HOST"));
let github_token = env let github_token = env
.get("GH_ENTERPRISE_TOKEN") .get("GH_ENTERPRISE_TOKEN")
.expect("dummy GitHub enterprise token"); .expect("dummy GitHub enterprise token");
+74 -5
View File
@@ -603,7 +603,11 @@ pub fn is_managed_proxy_env_var(key: &str, value: &str) -> bool {
} }
pub fn strip_managed_proxy_env(env: &mut HashMap<String, String>) { pub fn strip_managed_proxy_env(env: &mut HashMap<String, String>) {
env.retain(|key, value| !is_managed_proxy_env_var(key, value)); let brokered_credential_dummy_env_keys =
crate::credential_broker::brokered_credential_dummy_env_keys(env);
env.retain(|key, value| {
!brokered_credential_dummy_env_keys.contains(key) && !is_managed_proxy_env_var(key, value)
});
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@@ -828,9 +832,27 @@ impl NetworkProxy {
/// Captures the static inputs needed to launch a matching executor-local proxy. /// Captures the static inputs needed to launch a matching executor-local proxy.
pub async fn remote_launch_config(&self) -> Result<crate::RemoteNetworkProxyLaunchConfig> { pub async fn remote_launch_config(&self) -> Result<crate::RemoteNetworkProxyLaunchConfig> {
let proxy = crate::RemoteNetworkProxyConfig::from_effective_config( let (mut config, brokerage_created_default_allowlist) =
&self.state.current_cfg().await?, self.state.current_cfg_with_brokerage_provenance().await?;
)?; let mut broker_only_config = config::NetworkProxyConfig {
enabled: config.enabled,
credential_broker_openai_host: config.credential_broker_openai_host.clone(),
dangerously_allow_plaintext_credential_injection: config
.dangerously_allow_plaintext_credential_injection,
..config::NetworkProxyConfig::default()
};
broker_only_config.set_credential_broker_enabled(/*enabled*/ true);
broker_only_config.set_allowed_domains(vec!["*".to_string()]);
let broker_only = brokerage_created_default_allowlist && config == broker_only_config;
if config.credential_broker {
config.enabled &= !broker_only;
config.credential_broker = false;
config.dangerously_allow_plaintext_credential_injection = false;
if config.mitm && config.mitm_hooks.is_empty() {
config.mitm = false;
}
}
let proxy = crate::RemoteNetworkProxyConfig::from_effective_config(&config)?;
let (environment_id, execution_id) = self let (environment_id, execution_id) = self
.execution_scope .execution_scope
.as_ref() .as_ref()
@@ -1027,6 +1049,15 @@ impl NetworkProxy {
); );
} }
/// Restores known dummy credentials before a child intentionally leaves managed networking.
pub fn restore_brokered_credentials(
&self,
env: &mut HashMap<String, String>,
command: &mut [String],
) {
self.state.restore_child_credentials(env, command);
}
pub fn apply_to_env_for_environment( pub fn apply_to_env_for_environment(
&self, &self,
env: &mut HashMap<String, String>, env: &mut HashMap<String, String>,
@@ -1969,7 +2000,12 @@ mod tests {
async fn remote_launch_config_carries_execution_scope() -> Result<()> { async fn remote_launch_config_carries_execution_scope() -> Result<()> {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let _permit = WINDOWS_INGRESS_TEST_LOCK.acquire().await.unwrap(); let _permit = WINDOWS_INGRESS_TEST_LOCK.acquire().await.unwrap();
let state = Arc::new(network_proxy_state_for_policy(NetworkProxyConfig::default())); let mut config = NetworkProxyConfig {
dangerously_allow_plaintext_credential_injection: true,
..NetworkProxyConfig::default()
};
config.set_credential_broker_enabled(/*enabled*/ true);
let state = Arc::new(network_proxy_state_for_policy(config));
let proxy = match NetworkProxy::builder().state(state).build().await { let proxy = match NetworkProxy::builder().state(state).build().await {
Ok(proxy) => proxy, Ok(proxy) => proxy,
Err(err) => { Err(err) => {
@@ -1995,6 +2031,39 @@ mod tests {
assert_eq!(launch.environment_id.as_deref(), Some("remote-env")); assert_eq!(launch.environment_id.as_deref(), Some("remote-env"));
assert_eq!(launch.execution_id.as_deref(), Some("execution-1")); assert_eq!(launch.execution_id.as_deref(), Some("execution-1"));
assert!(!launch.proxy.enabled);
for (enabled, mode, allowed_domain, proxy_url) in [
(false, config::NetworkMode::Full, Some("*"), None),
(false, config::NetworkMode::Full, Some("example.com"), None),
(
false,
config::NetworkMode::Full,
None,
Some("http://127.0.0.1:8123"),
),
(true, config::NetworkMode::Full, None, None),
(true, config::NetworkMode::Limited, None, None),
] {
let mut config = NetworkProxyConfig {
enabled,
mode,
..NetworkProxyConfig::default()
};
if let Some(domain) = allowed_domain {
config.set_allowed_domains(vec![domain.to_string()]);
}
if let Some(proxy_url) = proxy_url {
config.proxy_url = proxy_url.to_string();
}
config.set_credential_broker_enabled(/*enabled*/ true);
let proxy = NetworkProxy::builder()
.state(Arc::new(network_proxy_state_for_policy(config)))
.build()
.await?;
let launch = proxy.remote_launch_config().await?;
assert!(launch.proxy.enabled);
assert_eq!(launch.proxy.mode, mode);
}
assert_eq!( assert_eq!(
prepared prepared
.env .env
+92 -35
View File
@@ -167,6 +167,7 @@ fn blocked_request_violation_log_line(entry: &BlockedRequest) -> String {
#[derive(Clone)] #[derive(Clone)]
pub struct ConfigState { pub struct ConfigState {
pub config: NetworkProxyConfig, pub config: NetworkProxyConfig,
pub(crate) brokerage_created_default_allowlist: bool,
pub allow_set: GlobSet, pub allow_set: GlobSet,
pub deny_set: GlobSet, pub deny_set: GlobSet,
pub mitm: Option<Arc<MitmState>>, pub mitm: Option<Arc<MitmState>>,
@@ -343,8 +344,10 @@ impl NetworkProxyState {
audit_metadata: NetworkProxyAuditMetadata, audit_metadata: NetworkProxyAuditMetadata,
blocked_request_observer: Option<Arc<dyn BlockedRequestObserver>>, blocked_request_observer: Option<Arc<dyn BlockedRequestObserver>>,
) -> Self { ) -> Self {
let credential_broker = CredentialBroker::new(state.config.credential_broker);
credential_broker.configure(&state.config);
Self { Self {
credential_broker: CredentialBroker::new(state.config.credential_broker), credential_broker,
state: Arc::new(RwLock::new(state)), state: Arc::new(RwLock::new(state)),
reloader, reloader,
blocked_request_observer: Arc::new(RwLock::new(blocked_request_observer)), blocked_request_observer: Arc::new(RwLock::new(blocked_request_observer)),
@@ -418,6 +421,14 @@ impl NetworkProxyState {
self.credential_broker.virtualize_child_env(env); self.credential_broker.virtualize_child_env(env);
} }
pub(crate) fn restore_child_credentials(
&self,
env: &mut HashMap<String, String>,
command: &mut [String],
) {
self.credential_broker.restore_child_env(env, command);
}
pub fn inject_request_credentials(&self, host: &str, headers: &mut rama_http::HeaderMap) { pub fn inject_request_credentials(&self, host: &str, headers: &mut rama_http::HeaderMap) {
self.credential_broker.inject_request_headers(host, headers); self.credential_broker.inject_request_headers(host, headers);
} }
@@ -431,11 +442,22 @@ impl NetworkProxyState {
} }
pub async fn current_cfg(&self) -> Result<NetworkProxyConfig> { pub async fn current_cfg(&self) -> Result<NetworkProxyConfig> {
self.current_cfg_with_brokerage_provenance()
.await
.map(|(config, _)| config)
}
pub(crate) async fn current_cfg_with_brokerage_provenance(
&self,
) -> Result<(NetworkProxyConfig, bool)> {
// Callers treat `NetworkProxyState` as a live view of policy. We reload-on-demand so edits to // Callers treat `NetworkProxyState` as a live view of policy. We reload-on-demand so edits to
// `config.toml` (including Codex-managed writes) take effect without a restart. // `config.toml` (including Codex-managed writes) take effect without a restart.
self.reload_if_needed().await?; self.reload_if_needed().await?;
let guard = self.state.read().await; let guard = self.state.read().await;
Ok(guard.config.clone()) Ok((
guard.config.clone(),
guard.brokerage_created_default_allowlist,
))
} }
pub async fn current_patterns(&self) -> Result<(Vec<String>, Vec<String>)> { pub async fn current_patterns(&self) -> Result<(Vec<String>, Vec<String>)> {
@@ -461,7 +483,7 @@ impl NetworkProxyState {
match self.reloader.reload_now().await { match self.reloader.reload_now().await {
Ok(mut new_state) => { Ok(mut new_state) => {
self.ensure_credential_broker_enablement_unchanged(&new_state)?; self.credential_broker.configure(&new_state.config);
// Policy changes are operationally sensitive; logging diffs makes changes traceable // Policy changes are operationally sensitive; logging diffs makes changes traceable
// without needing to dump full config blobs (which can include unrelated settings). // without needing to dump full config blobs (which can include unrelated settings).
log_policy_changes(&previous_cfg, &new_state.config); log_policy_changes(&previous_cfg, &new_state.config);
@@ -484,7 +506,7 @@ impl NetworkProxyState {
pub async fn replace_config_state(&self, mut new_state: ConfigState) -> Result<()> { pub async fn replace_config_state(&self, mut new_state: ConfigState) -> Result<()> {
self.reload_if_needed().await?; self.reload_if_needed().await?;
self.ensure_credential_broker_enablement_unchanged(&new_state)?; self.credential_broker.configure(&new_state.config);
let mut guard = self.state.write().await; let mut guard = self.state.write().await;
log_policy_changes(&guard.config, &new_state.config); log_policy_changes(&guard.config, &new_state.config);
new_state.blocked = guard.blocked.clone(); new_state.blocked = guard.blocked.clone();
@@ -829,7 +851,7 @@ impl NetworkProxyState {
match self.reloader.maybe_reload().await? { match self.reloader.maybe_reload().await? {
None => Ok(()), None => Ok(()),
Some(mut new_state) => { Some(mut new_state) => {
self.ensure_credential_broker_enablement_unchanged(&new_state)?; self.credential_broker.configure(&new_state.config);
let (previous_cfg, blocked, blocked_total) = { let (previous_cfg, blocked, blocked_total) = {
let guard = self.state.read().await; let guard = self.state.read().await;
( (
@@ -851,14 +873,6 @@ impl NetworkProxyState {
} }
} }
} }
fn ensure_credential_broker_enablement_unchanged(&self, new_state: &ConfigState) -> Result<()> {
anyhow::ensure!(
self.credential_broker.enabled() == new_state.config.credential_broker,
"network.credential_broker cannot change while the proxy is running"
);
Ok(())
}
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -1025,10 +1039,14 @@ fn unix_timestamp() -> i64 {
#[cfg(test)] #[cfg(test)]
pub(crate) fn network_proxy_state_for_policy( pub(crate) fn network_proxy_state_for_policy(
mut network: crate::config::NetworkProxyConfig, mut config: crate::config::NetworkProxyConfig,
) -> NetworkProxyState { ) -> NetworkProxyState {
network.enabled = true; let brokerage_created_default_allowlist =
let config = network; config.credential_broker && !config.enabled && config.allowed_domains().is_none();
config.enabled = true;
if brokerage_created_default_allowlist {
config.set_allowed_domains(vec!["*".to_string()]);
}
let state = ConfigState { let state = ConfigState {
allow_set: crate::policy::compile_allowlist_globset( allow_set: crate::policy::compile_allowlist_globset(
&config.allowed_domains().unwrap_or_default(), &config.allowed_domains().unwrap_or_default(),
@@ -1036,7 +1054,7 @@ pub(crate) fn network_proxy_state_for_policy(
.unwrap(), .unwrap(),
blocked: VecDeque::new(), blocked: VecDeque::new(),
blocked_total: 0, blocked_total: 0,
config: config.clone(), brokerage_created_default_allowlist,
constraints: NetworkProxyConstraints::default(), constraints: NetworkProxyConstraints::default(),
deny_set: crate::policy::compile_denylist_globset( deny_set: crate::policy::compile_denylist_globset(
&config.denied_domains().unwrap_or_default(), &config.denied_domains().unwrap_or_default(),
@@ -1044,6 +1062,7 @@ pub(crate) fn network_proxy_state_for_policy(
.unwrap(), .unwrap(),
mitm: None, mitm: None,
mitm_hooks: crate::mitm_hook::compile_mitm_hooks(&config).unwrap(), mitm_hooks: crate::mitm_hook::compile_mitm_hooks(&config).unwrap(),
config,
}; };
NetworkProxyState::with_reloader(state, Arc::new(NoopReloader)) NetworkProxyState::with_reloader(state, Arc::new(NoopReloader))
@@ -1128,16 +1147,17 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn reload_rejects_credential_broker_enablement_changes() { async fn reload_applies_credential_broker_enablement_changes() {
let initial_state = build_config_state( let config = NetworkProxyConfig {
NetworkProxyConfig::default(), enabled: true,
NetworkProxyConstraints::default(), ..NetworkProxyConfig::default()
) };
.unwrap(); let initial_state =
let mut reloaded_state = initial_state.clone(); build_config_state(config.clone(), NetworkProxyConstraints::default()).unwrap();
reloaded_state let mut reloaded_config = config;
.config reloaded_config.set_credential_broker_enabled(/*enabled*/ true);
.set_credential_broker_enabled(/*enabled*/ true); let reloaded_state =
build_config_state(reloaded_config, NetworkProxyConstraints::default()).unwrap();
let state = NetworkProxyState::with_reloader( let state = NetworkProxyState::with_reloader(
initial_state, initial_state,
Arc::new(StaticReloader { Arc::new(StaticReloader {
@@ -1145,20 +1165,33 @@ mod tests {
}), }),
); );
let err = state state
.force_reload() .force_reload()
.await .await
.expect_err("credential broker enablement should require a proxy restart"); .expect("enable credential broker");
let mut env = HashMap::from([("OPENAI_API_KEY".to_string(), "sk-real".to_string())]); let mut env = HashMap::from([("OPENAI_API_KEY".to_string(), "sk-real".to_string())]);
state.virtualize_child_credentials(&mut env);
assert_ne!(env["OPENAI_API_KEY"], "sk-real");
}
#[test]
fn managed_disabled_proxy_does_not_virtualize_credentials() {
let mut config = NetworkProxyConfig::default();
config.set_credential_broker_enabled(/*enabled*/ true);
let config_state = build_config_state(
config,
NetworkProxyConstraints {
enabled: Some(false),
..NetworkProxyConstraints::default()
},
)
.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())]);
state.virtualize_child_credentials(&mut env); state.virtualize_child_credentials(&mut env);
assert!(
format!("{err:#}")
.contains("network.credential_broker cannot change while the proxy is running"),
"unexpected error: {err:#}"
);
assert_eq!(env["OPENAI_API_KEY"], "sk-real"); assert_eq!(env["OPENAI_API_KEY"], "sk-real");
assert!(!state.credential_broker.enabled());
} }
#[tokio::test] #[tokio::test]
@@ -1192,6 +1225,30 @@ mod tests {
state.host_blocked("8.8.8.8", /*port*/ 80).await.unwrap(), state.host_blocked("8.8.8.8", /*port*/ 80).await.unwrap(),
HostBlockDecision::Blocked(HostBlockReason::NotAllowed) HostBlockDecision::Blocked(HostBlockReason::NotAllowed)
); );
for enabled in [false, true] {
let mut config = NetworkProxyConfig {
enabled,
..NetworkProxyConfig::default()
};
config.set_credential_broker_enabled(/*enabled*/ true);
let config_state = build_config_state(config, NetworkProxyConstraints::default())
.expect("valid credential-broker configuration");
assert_eq!(config_state.brokerage_created_default_allowlist, !enabled);
let state = NetworkProxyState::with_reloader(config_state, Arc::new(NoopReloader));
assert_eq!(
state.host_blocked("8.8.8.8", /*port*/ 80).await.unwrap(),
if enabled {
HostBlockDecision::Blocked(HostBlockReason::NotAllowed)
} else {
HostBlockDecision::Allowed
}
);
assert_eq!(
state.host_blocked("127.0.0.1", /*port*/ 80).await.unwrap(),
HostBlockDecision::Blocked(HostBlockReason::NotAllowedLocal)
);
}
} }
#[tokio::test] #[tokio::test]
+15 -1
View File
@@ -58,9 +58,22 @@ pub struct PartialNetworkProxyConfig {
} }
pub fn build_config_state( pub fn build_config_state(
config: NetworkProxyConfig, mut config: NetworkProxyConfig,
constraints: NetworkProxyConstraints, constraints: NetworkProxyConstraints,
) -> anyhow::Result<ConfigState> { ) -> anyhow::Result<ConfigState> {
if constraints.enabled == Some(false) {
config.credential_broker = false;
}
let brokerage_created_proxy = config.credential_broker && !config.enabled;
let brokerage_created_default_allowlist = brokerage_created_proxy
&& config.allowed_domains().is_none()
&& constraints.allowed_domains.is_none();
if brokerage_created_proxy {
config.enabled = true;
}
if brokerage_created_default_allowlist {
config.set_allowed_domains(vec!["*".to_string()]);
}
crate::config::validate_unix_socket_allowlist_paths(&config)?; crate::config::validate_unix_socket_allowlist_paths(&config)?;
anyhow::ensure!( anyhow::ensure!(
!config.credential_broker || config.mitm, !config.credential_broker || config.mitm,
@@ -82,6 +95,7 @@ pub fn build_config_state(
}; };
Ok(ConfigState { Ok(ConfigState {
config, config,
brokerage_created_default_allowlist,
allow_set, allow_set,
deny_set, deny_set,
mitm, mitm,