Base: codex-main originale (prima del fork aKode)
This commit is contained in:
145
codex-rs/network-proxy/src/attribution.rs
Normal file
145
codex-rs/network-proxy/src/attribution.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use crate::state::NetworkProxyState;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_tcp::TcpStream;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
/// Internal handoff from the trusted Linux proxy bridge.
|
||||
#[doc(hidden)]
|
||||
pub const PROXY_ATTRIBUTION_TOKEN_ENV_KEY: &str = "CODEX_NETWORK_PROXY_ATTRIBUTION";
|
||||
|
||||
const ATTRIBUTION_FRAME_MAGIC: &[u8; 8] = b"\0CDXPXY1";
|
||||
const MAX_ATTRIBUTION_TOKEN_LEN: usize = 128;
|
||||
const ATTRIBUTION_FRAME_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
pub(crate) struct BindConnectionAttribution<S> {
|
||||
inner: S,
|
||||
state: Arc<NetworkProxyState>,
|
||||
environment_id: Option<String>,
|
||||
}
|
||||
|
||||
impl<S> BindConnectionAttribution<S> {
|
||||
pub(crate) fn new(
|
||||
inner: S,
|
||||
state: Arc<NetworkProxyState>,
|
||||
environment_id: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
state,
|
||||
environment_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Service<TcpStream> for BindConnectionAttribution<S>
|
||||
where
|
||||
S: Service<TcpStream>,
|
||||
S::Error: Into<BoxError>,
|
||||
{
|
||||
type Output = S::Output;
|
||||
type Error = BoxError;
|
||||
|
||||
async fn serve(&self, mut stream: TcpStream) -> Result<Self::Output, Self::Error> {
|
||||
let state = match read_attribution_token(&mut stream).await? {
|
||||
Some(token) => self.state.for_execution_token(&token).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"unknown network proxy attribution token",
|
||||
)
|
||||
})?,
|
||||
None => self
|
||||
.state
|
||||
.for_environment_id(self.environment_id.as_deref()),
|
||||
};
|
||||
if let Some(expected_environment_id) = self.environment_id.as_deref()
|
||||
&& state
|
||||
.environment_id()
|
||||
.is_some_and(|actual| actual != expected_environment_id)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"network proxy attribution environment mismatch",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
stream.extensions_mut().insert(Arc::new(state));
|
||||
self.inner.serve(stream).await.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_attribution_token(stream: &mut TcpStream) -> Result<Option<String>, BoxError> {
|
||||
let mut marker = [0_u8; 1];
|
||||
let read = stream.stream.peek(&mut marker).await?;
|
||||
if read == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "empty proxy connection").into());
|
||||
}
|
||||
if marker[0] != ATTRIBUTION_FRAME_MAGIC[0] {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let token = tokio::time::timeout(ATTRIBUTION_FRAME_TIMEOUT, async {
|
||||
let mut magic = [0_u8; ATTRIBUTION_FRAME_MAGIC.len()];
|
||||
stream.read_exact(&mut magic).await?;
|
||||
if &magic != ATTRIBUTION_FRAME_MAGIC {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid network proxy attribution frame",
|
||||
));
|
||||
}
|
||||
|
||||
let token_len = stream.read_u16().await? as usize;
|
||||
if token_len == 0 || token_len > MAX_ATTRIBUTION_TOKEN_LEN {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid network proxy attribution token length",
|
||||
));
|
||||
}
|
||||
let mut token = vec![0_u8; token_len];
|
||||
stream.read_exact(&mut token).await?;
|
||||
String::from_utf8(token).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"network proxy attribution token is not UTF-8",
|
||||
)
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"network proxy attribution frame timed out",
|
||||
)
|
||||
})??;
|
||||
|
||||
Ok(Some(token))
|
||||
}
|
||||
|
||||
/// Writes the trusted bridge preface consumed by the shared proxy ingress.
|
||||
#[doc(hidden)]
|
||||
pub fn write_attribution_frame(writer: &mut impl Write, token: &str) -> io::Result<()> {
|
||||
if token.is_empty() || token.len() > MAX_ATTRIBUTION_TOKEN_LEN {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid network proxy attribution token length",
|
||||
));
|
||||
}
|
||||
let token_len = u16::try_from(token.len()).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"network proxy attribution token is too long",
|
||||
)
|
||||
})?;
|
||||
writer.write_all(ATTRIBUTION_FRAME_MAGIC)?;
|
||||
writer.write_all(&token_len.to_be_bytes())?;
|
||||
writer.write_all(token.as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "attribution_tests.rs"]
|
||||
mod tests;
|
||||
61
codex-rs/network-proxy/src/attribution_tests.rs
Normal file
61
codex-rs/network-proxy/src/attribution_tests.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use super::BindConnectionAttribution;
|
||||
use super::write_attribution_frame;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::runtime::network_proxy_state_for_policy;
|
||||
use crate::state::NetworkProxyState;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_core::service::service_fn;
|
||||
use rama_tcp::TcpStream as RamaTcpStream;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
#[test]
|
||||
fn attribution_frame_has_bounded_binary_prefix() -> io::Result<()> {
|
||||
let mut frame = Vec::new();
|
||||
write_attribution_frame(&mut frame, "token-1")?;
|
||||
|
||||
assert_eq!(&frame[..8], b"\0CDXPXY1");
|
||||
assert_eq!(u16::from_be_bytes([frame[8], frame[9]]), 7);
|
||||
assert_eq!(&frame[10..], b"token-1");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn framed_connection_receives_registered_execution_state() -> Result<(), BoxError> {
|
||||
let state = Arc::new(network_proxy_state_for_policy(NetworkProxyConfig::default()));
|
||||
state.register_execution("token-1", "local", "execution-1");
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let addr = listener.local_addr()?;
|
||||
let client = tokio::spawn(async move {
|
||||
let mut stream = TcpStream::connect(addr).await?;
|
||||
let mut frame = Vec::new();
|
||||
write_attribution_frame(&mut frame, "token-1")?;
|
||||
stream.write_all(&frame).await
|
||||
});
|
||||
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let service = BindConnectionAttribution::new(
|
||||
service_fn(|stream: RamaTcpStream| async move {
|
||||
let state = stream.extensions().get::<Arc<NetworkProxyState>>().cloned();
|
||||
Ok::<_, io::Error>(state)
|
||||
}),
|
||||
state,
|
||||
Some("local".to_string()),
|
||||
);
|
||||
let actual = service
|
||||
.serve(RamaTcpStream::new(stream))
|
||||
.await?
|
||||
.expect("connection state");
|
||||
client.await??;
|
||||
|
||||
assert_eq!(actual.environment_id(), Some("local"));
|
||||
assert_eq!(actual.execution_id().as_deref(), Some("execution-1"));
|
||||
Ok(())
|
||||
}
|
||||
64
codex-rs/network-proxy/src/authorization_path.rs
Normal file
64
codex-rs/network-proxy/src/authorization_path.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
/// Returns whether `path` has an unambiguous interpretation for authorization.
|
||||
///
|
||||
/// MITM hooks authorize the request before the upstream server parses it. Reject
|
||||
/// path forms that common upstreams may decode or normalize into a different
|
||||
/// resource after a hook has matched.
|
||||
pub(crate) fn is_safe_for_authorization(path: &str) -> bool {
|
||||
path.split('/').all(is_safe_segment_for_authorization)
|
||||
}
|
||||
|
||||
fn is_safe_segment_for_authorization(segment: &str) -> bool {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut index = 0;
|
||||
let mut decoded_dots = 0;
|
||||
let mut has_non_dot = false;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'.' => {
|
||||
decoded_dots += 1;
|
||||
index += 1;
|
||||
}
|
||||
b'\\' | b';' => return false,
|
||||
b'%' => {
|
||||
let Some(high) = bytes
|
||||
.get(index + 1)
|
||||
.and_then(|byte| decode_hex_digit(*byte))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(low) = bytes
|
||||
.get(index + 2)
|
||||
.and_then(|byte| decode_hex_digit(*byte))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let decoded = high << 4 | low;
|
||||
match decoded {
|
||||
b'%' | b'/' | b'\\' | b';' => return false,
|
||||
b'.' => decoded_dots += 1,
|
||||
_ => has_non_dot = true,
|
||||
}
|
||||
index += 3;
|
||||
}
|
||||
_ => {
|
||||
has_non_dot = true;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
has_non_dot || !matches!(decoded_dots, 1 | 2)
|
||||
}
|
||||
|
||||
fn decode_hex_digit(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "authorization_path_tests.rs"]
|
||||
mod tests;
|
||||
50
codex-rs/network-proxy/src/authorization_path_tests.rs
Normal file
50
codex-rs/network-proxy/src/authorization_path_tests.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use super::is_safe_for_authorization;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn accepts_unambiguous_paths() {
|
||||
let paths = [
|
||||
"/openai/openai",
|
||||
"/openai/openai/issues/123",
|
||||
"/openai/openai/a..b",
|
||||
"/openai/openai/%20space",
|
||||
"/openai/openai/%E2%9C%93",
|
||||
"/openai/openai/contents/%2Egitignore",
|
||||
"/openai/openai/contents/.%2Egithub",
|
||||
"/openai/openai/%2e%2efoo",
|
||||
"/openai/openai/%2e%2e%2e",
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
paths.map(is_safe_for_authorization),
|
||||
[true, true, true, true, true, true, true, true, true]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_paths_with_ambiguous_segments_or_encodings() {
|
||||
let paths = [
|
||||
"/openai/openai/../codex",
|
||||
"/openai/openai/./issues",
|
||||
"/openai/openai\\..\\codex",
|
||||
"/openai/openai/%2e%2e/codex",
|
||||
"/openai/openai/%2E%2E/codex",
|
||||
"/openai/openai/%2f..%2fcodex",
|
||||
"/openai/openai/%5c..%5ccodex",
|
||||
"/openai/openai/%252e%252e/codex",
|
||||
"/openai/openai/%",
|
||||
"/openai/openai/%2",
|
||||
"/openai/openai/%zz",
|
||||
"/openai/openai/file;parameter",
|
||||
"/openai/openai/file%3bparameter",
|
||||
"/openai/openai/file%3Bparameter",
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
paths.map(is_safe_for_authorization),
|
||||
[
|
||||
false, false, false, false, false, false, false, false, false, false, false, false,
|
||||
false, false
|
||||
]
|
||||
);
|
||||
}
|
||||
656
codex-rs/network-proxy/src/aws_sigv4.rs
Normal file
656
codex-rs/network-proxy/src/aws_sigv4.rs
Normal file
@@ -0,0 +1,656 @@
|
||||
//! Trusted, destination-scoped AWS signing after network and HTTP hook authorization.
|
||||
//! Credentials never enter the workload; unsupported streaming signatures fail closed.
|
||||
|
||||
use crate::credential_broker::env_value;
|
||||
use crate::credential_broker::remove_env_value;
|
||||
use crate::credential_broker::set_env_value;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::ensure;
|
||||
use aws_credential_types::Credentials;
|
||||
use aws_sigv4::http_request::PayloadChecksumKind;
|
||||
use aws_sigv4::http_request::PercentEncodingMode;
|
||||
use aws_sigv4::http_request::SignableBody;
|
||||
use aws_sigv4::http_request::SignableRequest;
|
||||
use aws_sigv4::http_request::SigningSettings;
|
||||
use aws_sigv4::http_request::UriPathNormalizationMode;
|
||||
use aws_sigv4::http_request::sign;
|
||||
use aws_sigv4::sign::v4;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use rama_core::bytes::Bytes;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_http::Body;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::Request;
|
||||
use rama_http::body::StreamingBody as _;
|
||||
use rama_http::header::HeaderName;
|
||||
use rama_http::headers::Connection;
|
||||
use rama_http::headers::HeaderMapExt as _;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest as _;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// A credential source in the trusted proxy process, never in the executor environment.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProxySecretSource {
|
||||
EnvVar(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
impl ProxySecretSource {
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
match self {
|
||||
Self::EnvVar(name) if !name.is_empty() && !name.contains(['=', '\0']) => Ok(()),
|
||||
Self::File(path) if std::path::Path::new(path).is_absolute() => Ok(()),
|
||||
Self::EnvVar(_) | Self::File(_) => Err(anyhow!("invalid proxy secret source")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(
|
||||
&self,
|
||||
env: &impl Fn(&str) -> Option<String>,
|
||||
file: &impl Fn(&AbsolutePathBuf) -> Result<String>,
|
||||
) -> Result<String> {
|
||||
self.validate()?;
|
||||
let value = match self {
|
||||
Self::EnvVar(name) => env(name).ok_or_else(|| anyhow!("missing proxy credential"))?,
|
||||
Self::File(path) => file(&AbsolutePathBuf::from_absolute_path(path)?)?,
|
||||
};
|
||||
if value.is_empty() || value.len() > 65_536 {
|
||||
return Err(anyhow!("proxy credential is empty or exceeds 64 KiB"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// AWS SigV4 action selected by an exact-host, method, and path MITM hook.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AwsSigV4Config {
|
||||
/// Nonsecret access key ID installed in the guest AWS profile.
|
||||
pub placeholder_access_key_id: String,
|
||||
pub region: String,
|
||||
pub service: String,
|
||||
pub access_key_id: ProxySecretSource,
|
||||
pub secret_access_key: ProxySecretSource,
|
||||
pub session_token: Option<ProxySecretSource>,
|
||||
#[serde(default = "https_port")]
|
||||
pub port: u16,
|
||||
#[serde(default = "default_max_body_bytes")]
|
||||
pub max_body_bytes: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn https_port() -> u16 {
|
||||
443
|
||||
}
|
||||
pub(crate) fn default_max_body_bytes() -> usize {
|
||||
8 * 1024 * 1024
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub(crate) struct AwsSigV4Signer {
|
||||
config: AwsSigV4Config,
|
||||
credentials: Credentials,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AwsSigV4Signer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AwsSigV4Signer")
|
||||
.field("config", &self.config)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsSigV4Config {
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
!self.placeholder_access_key_id.is_empty()
|
||||
&& self.placeholder_access_key_id.len() <= 128
|
||||
&& self
|
||||
.placeholder_access_key_id
|
||||
.bytes()
|
||||
.all(|byte| { byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-') }),
|
||||
"invalid AWS placeholder access key ID"
|
||||
);
|
||||
for value in [&self.region, &self.service] {
|
||||
if value.is_empty()
|
||||
|| !value
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'-')
|
||||
{
|
||||
return Err(anyhow!("invalid AWS signing region or service"));
|
||||
}
|
||||
}
|
||||
ensure!(self.port != 0, "invalid AWS signing port");
|
||||
ensure!(
|
||||
self.max_body_bytes <= 16 * 1024 * 1024,
|
||||
"AWS signing body limit exceeds 16 MiB"
|
||||
);
|
||||
self.access_key_id.validate()?;
|
||||
self.secret_access_key.validate()?;
|
||||
if let Some(token) = &self.session_token {
|
||||
token.validate()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn compile(
|
||||
&self,
|
||||
env: &impl Fn(&str) -> Option<String>,
|
||||
file: &impl Fn(&AbsolutePathBuf) -> Result<String>,
|
||||
) -> Result<AwsSigV4Signer> {
|
||||
self.validate()?;
|
||||
let credentials = Credentials::new(
|
||||
self.access_key_id.resolve(env, file)?,
|
||||
self.secret_access_key.resolve(env, file)?,
|
||||
self.session_token
|
||||
.as_ref()
|
||||
.map(|source| source.resolve(env, file))
|
||||
.transpose()?,
|
||||
/*expires_after*/ None,
|
||||
"network-proxy",
|
||||
);
|
||||
Ok(AwsSigV4Signer {
|
||||
config: self.clone(),
|
||||
credentials,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct UnsupportedSigningKeys(Vec<String>);
|
||||
|
||||
impl std::fmt::Debug for UnsupportedSigningKeys {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("UnsupportedSigningKeys")
|
||||
}
|
||||
}
|
||||
|
||||
// Keep only the guest key IDs needed to deny a selected request after hop-header removal.
|
||||
pub(crate) fn preserve_signing_headers(req: &mut Request) {
|
||||
let headers = req.headers();
|
||||
if headers.contains_key("authorization")
|
||||
&& (unsupported_signing_headers(headers)
|
||||
|| headers
|
||||
.typed_get::<Connection>()
|
||||
.is_some_and(|connection| connection.contains_header("authorization")))
|
||||
{
|
||||
let keys = headers
|
||||
.get_all("authorization")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(authorization_keys)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
req.extensions_mut().insert(UnsupportedSigningKeys(keys));
|
||||
}
|
||||
}
|
||||
|
||||
fn authorization_keys(auth: &str) -> impl Iterator<Item = &str> {
|
||||
let fields = match auth.split_once(' ') {
|
||||
Some(("AWS4-HMAC-SHA256" | "AWS4-ECDSA-P256-SHA256", fields)) => fields,
|
||||
_ => "",
|
||||
};
|
||||
fields
|
||||
.split(',')
|
||||
.filter_map(|field| field.trim().strip_prefix("Credential=")?.split('/').next())
|
||||
}
|
||||
|
||||
fn unsupported_signing_headers(headers: &HeaderMap) -> bool {
|
||||
!crate::body_budget::supported_transfer_framing(headers)
|
||||
|| crate::body_budget::is_amazon_event_stream(headers)
|
||||
|| headers.contains_key("trailer")
|
||||
|| headers.contains_key("x-amz-trailer")
|
||||
|| headers.contains_key("x-amz-decoded-content-length")
|
||||
|| headers.get_all("content-encoding").iter().any(|value| {
|
||||
value.to_str().map_or(true, |value| {
|
||||
value
|
||||
.split(',')
|
||||
.any(|coding| coding.trim().eq_ignore_ascii_case("aws-chunked"))
|
||||
})
|
||||
})
|
||||
|| headers
|
||||
.get_all("x-amz-content-sha256")
|
||||
.iter()
|
||||
.any(|value| value.as_bytes().starts_with(b"STREAMING-"))
|
||||
}
|
||||
|
||||
/// Client signing inputs captured before any hook changes the request headers.
|
||||
pub(crate) struct GuestSignature {
|
||||
time: SystemTime,
|
||||
signed_headers: Vec<HeaderName>,
|
||||
unsigned_payload: bool,
|
||||
}
|
||||
|
||||
const DUMMY_SECRET: &str = "codex-local-aws-secret";
|
||||
const DUMMY_TOKEN: &str = "codex-local-aws-token";
|
||||
pub(crate) const AWS_CA_BUNDLE: &str = "AWS_CA_BUNDLE";
|
||||
|
||||
/// Every value exposed to a child must be safe with respect to every configured pair.
|
||||
pub(crate) fn validate_guest_placeholders<'a>(
|
||||
signers: impl Iterator<Item = &'a AwsSigV4Signer> + Clone,
|
||||
) -> Result<()> {
|
||||
for signer in signers.clone() {
|
||||
let credentials = &signer.credentials;
|
||||
let mut placeholders = [DUMMY_SECRET, DUMMY_TOKEN].into_iter().chain(
|
||||
signers
|
||||
.clone()
|
||||
.map(|other| other.config.placeholder_access_key_id.as_str()),
|
||||
);
|
||||
ensure!(
|
||||
placeholders.all(|placeholder| {
|
||||
[
|
||||
Some(credentials.access_key_id()),
|
||||
Some(credentials.secret_access_key()),
|
||||
credentials.session_token(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|real| !placeholder.contains(real))
|
||||
}),
|
||||
"AWS guest placeholders overlap a real credential"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn snapshot_env_keys(env: &HashMap<String, String>) -> Option<[&'static str; 5]> {
|
||||
(env_value(env, "AWS_SECRET_ACCESS_KEY") == Some(DUMMY_SECRET)
|
||||
|| env_value(env, AWS_CA_BUNDLE)
|
||||
.is_some_and(crate::certs::is_managed_mitm_ca_trust_bundle_path))
|
||||
.then_some([
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_SECRET_ACCESS_KEY",
|
||||
"AWS_SESSION_TOKEN",
|
||||
"AWS_SECURITY_TOKEN",
|
||||
AWS_CA_BUNDLE,
|
||||
])
|
||||
}
|
||||
|
||||
/// Prepare the standard AWS environment for a local process before generic credential discovery.
|
||||
pub(crate) fn mask_local_aws_env(
|
||||
signers: &[Arc<AwsSigV4Signer>],
|
||||
env: &mut HashMap<String, String>,
|
||||
ca_path: Option<&Path>,
|
||||
) {
|
||||
if signers.is_empty() {
|
||||
return;
|
||||
}
|
||||
if env_value(env, AWS_CA_BUNDLE).is_none_or(str::is_empty)
|
||||
&& let Some(path) = ca_path
|
||||
{
|
||||
set_env_value(env, AWS_CA_BUNDLE, path.to_string_lossy().into_owned());
|
||||
}
|
||||
let access = env_value(env, "AWS_ACCESS_KEY_ID").filter(|id| !id.is_empty());
|
||||
let use_default = access.is_none()
|
||||
&& env_value(env, "AWS_PROFILE").is_none()
|
||||
&& env_value(env, "AWS_DEFAULT_PROFILE").is_none();
|
||||
let mut candidates = signers.iter().filter(|s| {
|
||||
use_default
|
||||
|| access.is_some_and(|id| {
|
||||
id == s.credentials.access_key_id() || id == s.config.placeholder_access_key_id
|
||||
})
|
||||
});
|
||||
let first = candidates.next();
|
||||
let selected = first.filter(|first| {
|
||||
candidates.all(|s| {
|
||||
s.config.placeholder_access_key_id == first.config.placeholder_access_key_id
|
||||
&& s.credentials.session_token().is_some()
|
||||
== first.credentials.session_token().is_some()
|
||||
})
|
||||
});
|
||||
let ambiguous_access = access.is_some() && first.is_some() && selected.is_none();
|
||||
// Mask aliases of every configured pair, including pairs the SDK didn't select.
|
||||
for value in env.values_mut() {
|
||||
mask_local_aws_text(signers, value);
|
||||
}
|
||||
if ambiguous_access {
|
||||
for key in [
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_SECRET_ACCESS_KEY",
|
||||
"AWS_SESSION_TOKEN",
|
||||
"AWS_SECURITY_TOKEN",
|
||||
] {
|
||||
remove_env_value(env, key);
|
||||
}
|
||||
} else if let Some(signer) = selected {
|
||||
set_env_value(
|
||||
env,
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
signer.config.placeholder_access_key_id.clone(),
|
||||
);
|
||||
set_env_value(env, "AWS_SECRET_ACCESS_KEY", DUMMY_SECRET.to_string());
|
||||
remove_env_value(env, "AWS_SECURITY_TOKEN");
|
||||
if signer.credentials.session_token().is_some() {
|
||||
set_env_value(env, "AWS_SESSION_TOKEN", DUMMY_TOKEN.to_string());
|
||||
} else {
|
||||
remove_env_value(env, "AWS_SESSION_TOKEN");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mask_local_aws_text(signers: &[Arc<AwsSigV4Signer>], text: &mut String) {
|
||||
for signer in signers {
|
||||
for (real, dummy) in [
|
||||
(
|
||||
Some(signer.credentials.access_key_id()),
|
||||
signer.config.placeholder_access_key_id.as_str(),
|
||||
),
|
||||
(Some(signer.credentials.secret_access_key()), DUMMY_SECRET),
|
||||
(signer.credentials.session_token(), DUMMY_TOKEN),
|
||||
] {
|
||||
if let Some(real) = real
|
||||
&& text.contains(real)
|
||||
{
|
||||
*text = text.replace(real, dummy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsSigV4Signer {
|
||||
pub(crate) fn plan(&self, req: &Request) -> Result<Option<GuestSignature>> {
|
||||
let placeholder = &self.config.placeholder_access_key_id;
|
||||
let selects_pair = |scope: &str| scope.split('/').next() == Some(placeholder.as_str());
|
||||
let mut query =
|
||||
url::form_urlencoded::parse(req.uri().query().unwrap_or_default().as_bytes());
|
||||
ensure!(
|
||||
!query.clone().any(|(key, value)| {
|
||||
key.eq_ignore_ascii_case("x-amz-credential") && selects_pair(&value)
|
||||
}),
|
||||
"cannot re-sign a presigned AWS URL"
|
||||
);
|
||||
ensure!(
|
||||
req.extensions()
|
||||
.get::<UnsupportedSigningKeys>()
|
||||
.is_none_or(|keys| !keys.0.contains(placeholder)),
|
||||
"unsupported AWS signing headers"
|
||||
);
|
||||
let auths = req.headers().get_all("authorization");
|
||||
let selected = auths
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.find(|auth| authorization_keys(auth).any(|key| key == placeholder));
|
||||
let Some(auth) = selected else {
|
||||
return Ok(None);
|
||||
};
|
||||
ensure!(
|
||||
auths.iter().count() == 1
|
||||
&& !query.any(|(key, _)| key.eq_ignore_ascii_case("x-amz-signature"))
|
||||
&& !unsupported_signing_headers(req.headers()),
|
||||
"ambiguous or unsupported AWS signing request"
|
||||
);
|
||||
let fields = auth
|
||||
.strip_prefix("AWS4-HMAC-SHA256 ")
|
||||
.ok_or_else(|| anyhow!("unsupported AWS signature algorithm"))?;
|
||||
let mut scope = None;
|
||||
let mut signed = None;
|
||||
let mut signature = None;
|
||||
for field in fields.split(',') {
|
||||
match field.trim().split_once('=') {
|
||||
Some(("Credential", value)) if scope.is_none() => scope = Some(value),
|
||||
Some(("SignedHeaders", value)) if signed.is_none() => signed = Some(value),
|
||||
Some(("Signature", value)) if signature.is_none() => signature = Some(value),
|
||||
_ => return Err(anyhow!("invalid AWS authorization field")),
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
signature.is_some_and(|v| v.len() == 64 && v.bytes().all(|b| b.is_ascii_hexdigit())),
|
||||
"invalid AWS signature"
|
||||
);
|
||||
let dates = req.headers().get_all("x-amz-date");
|
||||
let mut dates = dates.iter();
|
||||
let date = dates
|
||||
.next()
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or_else(|| anyhow!("missing AWS signing date"))?;
|
||||
let time = chrono::NaiveDateTime::parse_from_str(date, "%Y%m%dT%H%M%SZ")
|
||||
.map_err(|_| anyhow!("invalid AWS signing date"))?;
|
||||
ensure!(
|
||||
dates.next().is_none()
|
||||
&& date.len() == 16
|
||||
&& date.is_ascii()
|
||||
&& scope.is_some_and(|s| s.split('/').eq([
|
||||
placeholder.as_str(),
|
||||
&date[..8],
|
||||
&self.config.region,
|
||||
&self.config.service,
|
||||
"aws4_request",
|
||||
])),
|
||||
"AWS credential scope does not match the configured destination"
|
||||
);
|
||||
let signed_headers = signed
|
||||
.ok_or_else(|| anyhow!("missing AWS signed headers"))?
|
||||
.split(';')
|
||||
.map(|name| {
|
||||
HeaderName::from_lowercase(name.as_bytes())
|
||||
.map_err(|_| anyhow!("invalid AWS signed header"))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
ensure!(
|
||||
signed_headers
|
||||
.windows(2)
|
||||
.all(|w| w[0].as_str() < w[1].as_str())
|
||||
&& signed_headers.contains(&rama_http::header::HOST)
|
||||
&& signed_headers.iter().any(|name| name == "x-amz-date")
|
||||
&& signed_headers.iter().all(|name| {
|
||||
name != "authorization"
|
||||
&& (name == "host"
|
||||
|| (name == "x-amz-security-token"
|
||||
&& self.credentials.session_token().is_some())
|
||||
|| req.headers().contains_key(name))
|
||||
}),
|
||||
"invalid AWS signed header list"
|
||||
);
|
||||
let hashes = req.headers().get_all("x-amz-content-sha256");
|
||||
ensure!(hashes.iter().count() <= 1, "ambiguous AWS payload hash");
|
||||
let unsigned_payload = hashes.iter().any(|v| v == "UNSIGNED-PAYLOAD");
|
||||
ensure!(
|
||||
!unsigned_payload || self.config.service != "aoss",
|
||||
"OpenSearch Serverless requires a signed payload"
|
||||
);
|
||||
Ok(Some(GuestSignature {
|
||||
time: time.and_utc().into(),
|
||||
signed_headers,
|
||||
unsigned_payload,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn sign(&self, mut req: Request, guest: &GuestSignature) -> Result<Request> {
|
||||
ensure!(
|
||||
req.uri().scheme_str() == Some("https")
|
||||
&& req.uri().port_u16().unwrap_or(443) == self.config.port
|
||||
&& !unsupported_signing_headers(req.headers()),
|
||||
"AWS signing requires the configured HTTPS origin and supported framing"
|
||||
);
|
||||
let had_payload_hash = req.headers().contains_key("x-amz-content-sha256");
|
||||
let mut permit = None;
|
||||
let (mut parts, body, payload_hash) = if guest.unsigned_payload {
|
||||
let (parts, body) = req.into_parts();
|
||||
ensure!(
|
||||
!parts.headers.contains_key("content-length")
|
||||
|| body
|
||||
.size_hint()
|
||||
.exact()
|
||||
.and_then(|n| usize::try_from(n).ok())
|
||||
.is_some_and(|n| crate::body_budget::content_length_matches(
|
||||
&parts.headers,
|
||||
n
|
||||
)),
|
||||
"ambiguous AWS unsigned payload length"
|
||||
);
|
||||
(parts, body, "UNSIGNED-PAYLOAD".to_string())
|
||||
} else {
|
||||
let (bytes, trailers) = if req.body().is_end_stream() {
|
||||
(Bytes::new(), None)
|
||||
} else {
|
||||
permit = Some(crate::body_budget::reserve(&mut req).await?);
|
||||
let body = std::mem::take(req.body_mut());
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
crate::body_budget::collect_body(body, self.config.max_body_bytes),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("AWS signing body read timed out"))??
|
||||
};
|
||||
let (parts, _) = req.into_parts();
|
||||
ensure!(
|
||||
trailers.is_none()
|
||||
&& crate::body_budget::content_length_matches(&parts.headers, bytes.len()),
|
||||
"AWS signing requires unambiguous payload framing"
|
||||
);
|
||||
let digest = format!("{:x}", sha2::Sha256::digest(&bytes));
|
||||
(parts, Body::from(bytes), digest)
|
||||
};
|
||||
if ["connection", "proxy-connection", "upgrade", "te"]
|
||||
.iter()
|
||||
.any(|name| parts.headers.contains_key(*name))
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"AWS signing cannot forward connection-specific headers"
|
||||
));
|
||||
}
|
||||
// Rama removes these HTTP/1 fields when the upstream negotiates HTTP/2.
|
||||
// They have no meaning for an ordinary signed request.
|
||||
for name in ["keep-alive", "sec-websocket-key", "transfer-encoding"] {
|
||||
parts.headers.remove(name);
|
||||
}
|
||||
// Recreate signing headers from the selected pair and the captured guest signature.
|
||||
for name in [
|
||||
"authorization",
|
||||
"x-amz-date",
|
||||
"x-amz-security-token",
|
||||
"x-amz-content-sha256",
|
||||
] {
|
||||
parts.headers.remove(name);
|
||||
}
|
||||
// HTTP/2-to-HTTP/1.1 forwarding joins Cookie fields with "; ". Sign that
|
||||
// representation now so upstream protocol negotiation cannot change it.
|
||||
let cookies = parts
|
||||
.headers
|
||||
.get_all("cookie")
|
||||
.iter()
|
||||
.map(HeaderValue::to_str)
|
||||
.collect::<std::result::Result<Vec<_>, _>>()
|
||||
.map_err(|_| anyhow!("AWS signing requires textual headers"))?;
|
||||
if cookies.len() > 1 {
|
||||
let mut cookie = HeaderValue::from_str(&cookies.join("; "))
|
||||
.map_err(|_| anyhow!("invalid AWS signing cookie header"))?;
|
||||
cookie.set_sensitive(
|
||||
parts
|
||||
.headers
|
||||
.get_all("cookie")
|
||||
.iter()
|
||||
.any(HeaderValue::is_sensitive),
|
||||
);
|
||||
parts.headers.insert("cookie", cookie);
|
||||
}
|
||||
let mut settings = SigningSettings::default();
|
||||
settings.excluded_headers = None;
|
||||
if matches!(
|
||||
self.config.service.as_str(),
|
||||
"s3" | "s3-object-lambda" | "s3-outposts"
|
||||
) {
|
||||
settings.percent_encoding_mode = PercentEncodingMode::Single;
|
||||
settings.uri_path_normalization_mode = UriPathNormalizationMode::Disabled;
|
||||
}
|
||||
// S3 and AOSS need the hash on the wire even when the client did not sign that field.
|
||||
if had_payload_hash
|
||||
|| matches!(
|
||||
self.config.service.as_str(),
|
||||
"s3" | "s3-object-lambda" | "s3-outposts" | "aoss"
|
||||
)
|
||||
{
|
||||
parts.headers.insert(
|
||||
"x-amz-content-sha256",
|
||||
HeaderValue::from_str(&payload_hash)?,
|
||||
);
|
||||
}
|
||||
if guest
|
||||
.signed_headers
|
||||
.iter()
|
||||
.any(|h| h == "x-amz-content-sha256")
|
||||
{
|
||||
settings.payload_checksum_kind = PayloadChecksumKind::XAmzSha256;
|
||||
}
|
||||
// Error messages are deliberately static: SDK errors can include request or credential data.
|
||||
for name in &guest.signed_headers {
|
||||
match name.as_str() {
|
||||
"host" | "x-amz-date" | "x-amz-content-sha256" => {}
|
||||
"x-amz-security-token" if self.credentials.session_token().is_some() => {}
|
||||
_ => ensure!(
|
||||
parts.headers.contains_key(name),
|
||||
"AWS signed header was removed"
|
||||
),
|
||||
}
|
||||
}
|
||||
let headers = parts
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|(name, _)| guest.signed_headers.contains(name))
|
||||
.map(|(name, value)| {
|
||||
value
|
||||
.to_str()
|
||||
.map(|value| (name.as_str(), value))
|
||||
.map_err(|_| anyhow!("AWS signing requires textual headers"))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let uri = parts.uri.to_string();
|
||||
let request = SignableRequest::new(
|
||||
parts.method.as_str(),
|
||||
&uri,
|
||||
headers.into_iter(),
|
||||
if guest.unsigned_payload {
|
||||
SignableBody::UnsignedPayload
|
||||
} else {
|
||||
SignableBody::Precomputed(payload_hash)
|
||||
},
|
||||
)
|
||||
.map_err(|_| anyhow!("invalid AWS signing request"))?;
|
||||
let identity = self.credentials.clone().into();
|
||||
let params = v4::SigningParams::builder()
|
||||
.identity(&identity)
|
||||
.region(&self.config.region)
|
||||
.name(&self.config.service)
|
||||
.time(guest.time)
|
||||
.settings(settings)
|
||||
.build()
|
||||
.map_err(|_| anyhow!("invalid AWS signing parameters"))?;
|
||||
// The SDK's TRACE events include canonical headers (including session tokens).
|
||||
// Signing is synchronous: suppress only those SDK events, without changing proxy audit logs.
|
||||
let (instructions, _) =
|
||||
tracing::dispatcher::with_default(&tracing::Dispatch::none(), || {
|
||||
sign(request, ¶ms.into())
|
||||
})
|
||||
.map_err(|_| anyhow!("AWS signing failed"))?
|
||||
.into_parts();
|
||||
for header in instructions.into_parts().0 {
|
||||
let mut value = HeaderValue::from_str(header.value())
|
||||
.map_err(|_| anyhow!("invalid AWS signed header"))?;
|
||||
value.set_sensitive(
|
||||
header.sensitive()
|
||||
|| matches!(header.name(), "authorization" | "x-amz-security-token"),
|
||||
);
|
||||
parts.headers.insert(header.name(), value);
|
||||
}
|
||||
let req = Request::from_parts(parts, body);
|
||||
Ok(if permit.is_some() {
|
||||
crate::body_budget::retain(req)
|
||||
} else {
|
||||
req
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "aws_sigv4_tests.rs"]
|
||||
pub(crate) mod tests;
|
||||
370
codex-rs/network-proxy/src/aws_sigv4_tests.rs
Normal file
370
codex-rs/network-proxy/src/aws_sigv4_tests.rs
Normal file
@@ -0,0 +1,370 @@
|
||||
//! SigV4 interoperability vectors and rejection boundaries for the actual signing action.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_http::HeaderMap;
|
||||
|
||||
fn config(service: &str) -> AwsSigV4Config {
|
||||
AwsSigV4Config {
|
||||
placeholder_access_key_id: "MASKEDACCESSKEY".into(),
|
||||
region: "us-east-1".into(),
|
||||
service: service.into(),
|
||||
access_key_id: ProxySecretSource::EnvVar("ACCESS_KEY".into()),
|
||||
secret_access_key: ProxySecretSource::EnvVar("SECRET_KEY".into()),
|
||||
session_token: None,
|
||||
port: 443,
|
||||
max_body_bytes: 1024,
|
||||
}
|
||||
}
|
||||
|
||||
fn signer(config: AwsSigV4Config) -> AwsSigV4Signer {
|
||||
config
|
||||
.compile(
|
||||
&|name| {
|
||||
Some(
|
||||
match name {
|
||||
"ACCESS_KEY" => "AKIDEXAMPLE",
|
||||
"SECRET_KEY" => "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
||||
"SESSION_TOKEN" => "secret-session-token",
|
||||
_ => panic!("unexpected credential source"),
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
},
|
||||
&|_| panic!("unexpected file lookup"),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn time() -> SystemTime {
|
||||
chrono::DateTime::parse_from_rfc3339("2015-08-30T12:36:00Z")
|
||||
.unwrap()
|
||||
.into()
|
||||
}
|
||||
|
||||
pub(crate) fn guest_authorization(service: &str, signed_headers: &str) -> String {
|
||||
format!(
|
||||
"AWS4-HMAC-SHA256 Credential=MASKEDACCESSKEY/20150830/us-east-1/{service}/aws4_request, SignedHeaders={signed_headers}, Signature={:064x}",
|
||||
1
|
||||
)
|
||||
}
|
||||
|
||||
async fn resign(signer: &AwsSigV4Signer, mut req: Request, headers: &str) -> Result<Request> {
|
||||
let auth = guest_authorization(&signer.config.service, headers);
|
||||
req.headers_mut()
|
||||
.insert("authorization", HeaderValue::from_str(&auth)?);
|
||||
req.headers_mut()
|
||||
.insert("x-amz-date", HeaderValue::from_static("20150830T123600Z"));
|
||||
let guest = signer.plan(&req)?.expect("selected guest credential");
|
||||
signer.sign(req, &guest).await
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_aws_published_iam_signature_vector() {
|
||||
use rama_core::futures::FutureExt as _;
|
||||
|
||||
// AWS Signature Version 4 ListUsers example, 2015-08-30.
|
||||
let request = Request::builder()
|
||||
.method("GET")
|
||||
.uri("https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08")
|
||||
.header("host", "iam.amazonaws.com")
|
||||
.header(
|
||||
"content-type",
|
||||
"application/x-www-form-urlencoded; charset=utf-8",
|
||||
)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let signed = resign(
|
||||
&signer(config("iam")),
|
||||
request,
|
||||
"content-type;host;x-amz-date",
|
||||
)
|
||||
.now_or_never()
|
||||
.expect("an empty request must sign without waiting for buffer capacity")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
signed.headers()["authorization"],
|
||||
"AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn signs_actual_payload_and_replaces_untrusted_signing_headers() {
|
||||
let mut config = config("s3");
|
||||
config.session_token = Some(ProxySecretSource::EnvVar("SESSION_TOKEN".into()));
|
||||
let signer = Arc::new(signer(config));
|
||||
let mut env = HashMap::from([
|
||||
(
|
||||
"AWS_ACCESS_KEY_ID".to_string(),
|
||||
signer.credentials.access_key_id().to_string(),
|
||||
),
|
||||
(
|
||||
"SESSION_TOKEN".to_string(),
|
||||
"secret-session-token".to_string(),
|
||||
),
|
||||
]);
|
||||
mask_local_aws_env(
|
||||
std::slice::from_ref(&signer),
|
||||
&mut env,
|
||||
/*ca_path*/ None,
|
||||
);
|
||||
assert_eq!(env["AWS_ACCESS_KEY_ID"], "MASKEDACCESSKEY");
|
||||
assert_eq!(env["SESSION_TOKEN"], env["AWS_SESSION_TOKEN"]);
|
||||
assert_ne!(env["AWS_SESSION_TOKEN"], "secret-session-token");
|
||||
env.insert("AWS_ACCESS_KEY_ID".to_string(), "OTHERKEY".to_string());
|
||||
env.insert("AWS_SECRET_ACCESS_KEY".to_string(), "unrelated".to_string());
|
||||
mask_local_aws_env(
|
||||
std::slice::from_ref(&signer),
|
||||
&mut env,
|
||||
/*ca_path*/ None,
|
||||
);
|
||||
assert_eq!(env["AWS_SECRET_ACCESS_KEY"], "unrelated");
|
||||
let mut cookie = HeaderValue::from_static("b=2");
|
||||
cookie.set_sensitive(true);
|
||||
let request = Request::builder()
|
||||
.method("PUT")
|
||||
.version(rama_http::Version::HTTP_2)
|
||||
.uri("https://bucket.s3.amazonaws.com/a%20b?tag=b&tag=a&empty=")
|
||||
.header("host", "bucket.s3.amazonaws.com")
|
||||
.header("cookie", "a=1")
|
||||
.header("cookie", cookie)
|
||||
.header("authorization", "guest-signature")
|
||||
.header("x-amz-date", "19700101T000000Z")
|
||||
.header("x-amz-security-token", "guest-token")
|
||||
.header("x-amz-content-sha256", "untrusted-guest-hash")
|
||||
.body(Body::from("hello"))
|
||||
.unwrap();
|
||||
let signed = resign(
|
||||
&signer,
|
||||
request,
|
||||
"cookie;host;x-amz-content-sha256;x-amz-date",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
signed.headers()["x-amz-content-sha256"],
|
||||
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
|
||||
);
|
||||
assert_eq!(signed.headers()["x-amz-date"], "20150830T123600Z");
|
||||
assert_eq!(
|
||||
signed.headers()["x-amz-security-token"],
|
||||
"secret-session-token"
|
||||
);
|
||||
assert!(signed.headers()["x-amz-security-token"].is_sensitive());
|
||||
assert!(signed.headers()["authorization"].is_sensitive());
|
||||
assert_eq!(
|
||||
signed
|
||||
.headers()
|
||||
.get_all("cookie")
|
||||
.iter()
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&HeaderValue::from_static("a=1; b=2")]
|
||||
);
|
||||
assert!(signed.headers()["cookie"].is_sensitive());
|
||||
let forwarded = signed.into_body().collect().await.unwrap().to_bytes();
|
||||
assert_eq!(forwarded.as_ref(), b"hello");
|
||||
assert!(!format!("{signer:?}").contains("EXAMPLEKEY"));
|
||||
assert!(!format!("{signer:?}").contains("AKIDEXAMPLE"));
|
||||
|
||||
// An SDK's unsigned S3 upload streams through without consuming the literal-body budget.
|
||||
let upload = Request::builder()
|
||||
.uri("https://bucket.s3.amazonaws.com/upload")
|
||||
.header("x-amz-content-sha256", "UNSIGNED-PAYLOAD")
|
||||
.header("x-unsigned-metadata", "forward only")
|
||||
.body(Body::from(vec![b'x'; 1025]))
|
||||
.unwrap();
|
||||
let upload = resign(&signer, upload, "host;x-amz-date").await.unwrap();
|
||||
assert_eq!(upload.headers()["x-amz-content-sha256"], "UNSIGNED-PAYLOAD");
|
||||
let authorization = upload.headers()["authorization"].to_str().unwrap();
|
||||
assert!(authorization.contains("SignedHeaders=host;x-amz-date;x-amz-security-token,"));
|
||||
use rama_http::body::util::BodyExt as _;
|
||||
assert_eq!(
|
||||
upload.into_body().collect().await.unwrap().to_bytes().len(),
|
||||
1025
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canonicalizes_query_order_without_changing_encoded_s3_path() {
|
||||
use sha2::Digest;
|
||||
|
||||
for service in ["s3", "s3-object-lambda", "s3-outposts"] {
|
||||
let signer = signer(config(service));
|
||||
let payload_hash = format!("{:x}", sha2::Sha256::digest(b""));
|
||||
let signed_headers = "host;x-amz-content-sha256;x-amz-date";
|
||||
// Build the canonical request independently of SDK request canonicalization.
|
||||
// The encoded space and repeated slash must remain part of the object key.
|
||||
let canonical_request = format!(
|
||||
"GET\n/a%20b//key\na=one&a=two&space=a%20b&z=last\nhost:bucket.s3.amazonaws.com\nx-amz-content-sha256:{payload_hash}\nx-amz-date:20150830T123600Z\n\n{signed_headers}\n{payload_hash}"
|
||||
);
|
||||
let scope = format!("20150830/us-east-1/{service}/aws4_request");
|
||||
let string_to_sign = format!(
|
||||
"AWS4-HMAC-SHA256\n20150830T123600Z\n{scope}\n{:x}",
|
||||
sha2::Sha256::digest(canonical_request.as_bytes())
|
||||
);
|
||||
let key = aws_sigv4::sign::v4::generate_signing_key(
|
||||
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
||||
time(),
|
||||
"us-east-1",
|
||||
service,
|
||||
);
|
||||
let signature = aws_sigv4::sign::v4::calculate_signature(key, string_to_sign.as_bytes());
|
||||
let authorization = format!(
|
||||
"AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/{scope}, SignedHeaders={signed_headers}, Signature={signature}"
|
||||
);
|
||||
for query in [
|
||||
"z=last&a=two&a=one&space=a%20b",
|
||||
"a=one&space=a%20b&a=two&z=last",
|
||||
] {
|
||||
let uri = format!("https://bucket.s3.amazonaws.com/a%20b//key?{query}");
|
||||
let request = Request::builder()
|
||||
.uri(&uri)
|
||||
.header("x-amz-content-sha256", payload_hash.as_str())
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let signed = resign(&signer, request, signed_headers).await.unwrap();
|
||||
assert_eq!(signed.uri().to_string(), uri);
|
||||
assert_eq!(
|
||||
signed.headers()["authorization"],
|
||||
authorization,
|
||||
"{service}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_wrong_transport_port_streaming_presigning_and_body_overflow() {
|
||||
let signer = signer(config("s3"));
|
||||
let valid = "https://bucket.s3.amazonaws.com/key";
|
||||
for uri in [
|
||||
"http://bucket.s3.amazonaws.com/key",
|
||||
"https://bucket.s3.amazonaws.com:8443/key",
|
||||
"https://bucket.s3.amazonaws.com/key?X-Amz-Signature=guest",
|
||||
] {
|
||||
let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
|
||||
assert!(
|
||||
resign(&signer, req, "host;x-amz-date").await.is_err(),
|
||||
"{uri}"
|
||||
);
|
||||
}
|
||||
for (name, value) in [
|
||||
("content-encoding", "aws-chunked"),
|
||||
("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"),
|
||||
("content-length", "1"),
|
||||
] {
|
||||
let req = Request::builder()
|
||||
.uri(valid)
|
||||
.header(name, value)
|
||||
.body(Body::from("abc"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
resign(&signer, req, "host;x-amz-date").await.is_err(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
let auth = guest_authorization("s3", "host;x-amz-date");
|
||||
for value in [
|
||||
auth.replace("us-east-1", "eu-west-1"),
|
||||
auth.replace("/s3/", "/sts/"),
|
||||
auth.replace("20150830/", "20150831/"),
|
||||
auth.replace("AWS4-HMAC-SHA256", "AWS4-ECDSA-P256-SHA256"),
|
||||
auth.replace("x-amz-date,", "x-amz-date;x-missing,"),
|
||||
] {
|
||||
let req = Request::builder()
|
||||
.uri(valid)
|
||||
.header("authorization", value)
|
||||
.header("x-amz-date", "20150830T123600Z")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert!(signer.plan(&req).is_err());
|
||||
}
|
||||
let presigned = Request::builder()
|
||||
.uri("https://bucket.s3.amazonaws.com/key?X-Amz-Credential=MASKEDACCESSKEY%2F20150830&X-Amz-Signature=guest")
|
||||
.body(Body::empty()).unwrap();
|
||||
assert!(signer.plan(&presigned).is_err());
|
||||
for body in [
|
||||
Body::from(vec![b'x'; 1025]),
|
||||
Body::empty().with_trailer_headers(HeaderMap::new()),
|
||||
] {
|
||||
let req = Request::builder().uri(valid).body(body).unwrap();
|
||||
assert!(resign(&signer, req, "host;x-amz-date").await.is_err());
|
||||
}
|
||||
let stalled = rama_core::futures::stream::pending::<std::io::Result<rama_core::bytes::Bytes>>();
|
||||
let mut req = Request::builder()
|
||||
.uri(valid)
|
||||
.body(Body::from_stream(stalled))
|
||||
.unwrap();
|
||||
// Other tests use the process-wide pool on real clocks.
|
||||
let _permit = crate::body_budget::reserve(&mut req).await.unwrap();
|
||||
tokio::time::pause();
|
||||
let start = tokio::time::Instant::now();
|
||||
let signing = resign(&signer, req, "host;x-amz-date");
|
||||
let result = tokio::time::timeout(Duration::from_secs(31), signing)
|
||||
.await
|
||||
.expect("signer must enforce its own deadline");
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.to_string(), "AWS signing body read timed out");
|
||||
assert!(start.elapsed() >= Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_are_required_and_configured_limits_are_bounded() {
|
||||
assert!(
|
||||
config("s3")
|
||||
.compile(&|_| None, &|_| panic!("unexpected file"))
|
||||
.is_err()
|
||||
);
|
||||
let first = signer(config("s3"));
|
||||
let mut other = config("sts");
|
||||
other.placeholder_access_key_id = format!("GUEST{}", first.credentials.access_key_id());
|
||||
let other = other
|
||||
.compile(&|key| Some(format!("other-{key}")), &|_| {
|
||||
panic!("unexpected file")
|
||||
})
|
||||
.unwrap();
|
||||
assert!(validate_guest_placeholders([&first, &other].into_iter()).is_err());
|
||||
|
||||
let mut config = config("s3");
|
||||
config.max_body_bytes = 16 * 1024 * 1024 + 1;
|
||||
assert_eq!(
|
||||
config.validate().unwrap_err().to_string(),
|
||||
"AWS signing body limit exceeds 16 MiB"
|
||||
);
|
||||
config.port = 0;
|
||||
assert_eq!(
|
||||
config.validate().unwrap_err().to_string(),
|
||||
"invalid AWS signing port"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sdk_trace_does_not_log_canonical_secret_headers() {
|
||||
use tracing::instrument::WithSubscriber;
|
||||
let capture = tempfile::NamedTempFile::new().unwrap();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_max_level(tracing::Level::TRACE)
|
||||
.with_writer(std::sync::Arc::new(capture.reopen().unwrap()))
|
||||
.finish();
|
||||
let request = Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.header("x-api-key", "secret-header-value")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let mut config = config("execute-api");
|
||||
config.session_token = Some(ProxySecretSource::EnvVar("SESSION_TOKEN".into()));
|
||||
async {
|
||||
tracing::trace!("proxy audit remains enabled");
|
||||
resign(&signer(config), request, "host;x-amz-date;x-api-key")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
.with_subscriber(subscriber)
|
||||
.await;
|
||||
let logs = std::fs::read_to_string(capture.path()).unwrap();
|
||||
assert!(logs.contains("proxy audit remains enabled"));
|
||||
assert!(!logs.contains("secret-header-value"));
|
||||
assert!(!logs.contains("secret-session-token"));
|
||||
assert!(!logs.contains("EXAMPLEKEY"));
|
||||
}
|
||||
195
codex-rs/network-proxy/src/body_budget.rs
Normal file
195
codex-rs/network-proxy/src/body_budget.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
//! Shared leases bound buffers across quota checks, secret substitution, and signing.
|
||||
//! Eight requests each reserve space for a 16 MiB input and 16 MiB transformed output.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use rama_core::bytes::Bytes;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_http::Body;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::Request;
|
||||
use rama_http::body::Frame;
|
||||
use rama_http::body::SizeHint;
|
||||
use rama_http::body::StreamingBody;
|
||||
use rama_http::body::util::BodyExt;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Weak;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
const BUFFER_SLOT_COUNT: usize = 8;
|
||||
static BUFFER_SLOTS: LazyLock<Arc<Semaphore>> =
|
||||
LazyLock::new(|| Arc::new(Semaphore::new(BUFFER_SLOT_COUNT)));
|
||||
|
||||
// Rama clones request metadata through response headers. Keep ownership in the transform or body.
|
||||
#[derive(Debug, Clone)]
|
||||
struct BufferLease(Weak<OwnedSemaphorePermit>);
|
||||
|
||||
pub(crate) async fn reserve(req: &mut Request) -> Result<Arc<OwnedSemaphorePermit>> {
|
||||
reserve_in(req, &BUFFER_SLOTS).await
|
||||
}
|
||||
|
||||
async fn reserve_in(
|
||||
req: &mut Request,
|
||||
slots: &Arc<Semaphore>,
|
||||
) -> Result<Arc<OwnedSemaphorePermit>> {
|
||||
if let Some(permit) = req
|
||||
.extensions()
|
||||
.get::<BufferLease>()
|
||||
.and_then(|lease| lease.0.upgrade())
|
||||
{
|
||||
return Ok(permit);
|
||||
}
|
||||
let permit = tokio::time::timeout(Duration::from_secs(5), slots.clone().acquire_owned())
|
||||
.await
|
||||
.map_err(|_| anyhow!("request buffer capacity unavailable"))?
|
||||
.map_err(|_| anyhow!("request buffer budget closed"))?;
|
||||
let permit = Arc::new(permit);
|
||||
req.extensions_mut()
|
||||
.insert(BufferLease(Arc::downgrade(&permit)));
|
||||
Ok(permit)
|
||||
}
|
||||
|
||||
pub(crate) fn is_amazon_event_stream(headers: &HeaderMap) -> bool {
|
||||
headers.get_all("content-type").iter().any(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
value.split(';').next().is_some_and(|mime| {
|
||||
mime.trim()
|
||||
.eq_ignore_ascii_case("application/vnd.amazon.eventstream")
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn supported_transfer_framing(headers: &HeaderMap) -> bool {
|
||||
let codings = headers.get_all("transfer-encoding");
|
||||
let mut codings = codings.iter();
|
||||
match codings.next() {
|
||||
None => true,
|
||||
Some(coding) => {
|
||||
!headers.contains_key("content-length")
|
||||
&& codings.next().is_none()
|
||||
&& coding
|
||||
.to_str()
|
||||
.is_ok_and(|value| value.trim().eq_ignore_ascii_case("chunked"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn content_length_matches(headers: &HeaderMap, size: usize) -> bool {
|
||||
let lengths = headers.get_all("content-length");
|
||||
let mut lengths = lengths.iter();
|
||||
match lengths.next() {
|
||||
None => true,
|
||||
Some(length) => {
|
||||
lengths.next().is_none()
|
||||
&& length.to_str().is_ok_and(|value| {
|
||||
!value.is_empty()
|
||||
&& value.bytes().all(|byte| byte.is_ascii_digit())
|
||||
&& value.parse::<usize>() == Ok(size)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy frames as they arrive so fragmented bodies cannot retain per-frame allocations.
|
||||
pub(crate) async fn collect_body(
|
||||
mut body: Body,
|
||||
max_bytes: usize,
|
||||
) -> Result<(Bytes, Option<HeaderMap>)> {
|
||||
let mut bytes = Vec::new();
|
||||
let mut trailers: Option<HeaderMap> = None;
|
||||
while let Some(frame) = body.frame().await {
|
||||
let frame = frame.map_err(|_| anyhow!("cannot read request body"))?;
|
||||
if trailers.is_some() {
|
||||
return Err(anyhow!("unexpected request frame after trailers"));
|
||||
}
|
||||
match frame.into_data() {
|
||||
Ok(data) => {
|
||||
if data.len() > max_bytes - bytes.len() {
|
||||
return Err(anyhow!("request body exceeds configured limit"));
|
||||
}
|
||||
let len = bytes.len() + data.len();
|
||||
if len > bytes.capacity() {
|
||||
// Grow geometrically without reserving beyond the configured byte limit.
|
||||
let capacity = max_bytes.min(bytes.capacity().saturating_mul(2).max(len));
|
||||
bytes
|
||||
.try_reserve_exact(capacity - bytes.len())
|
||||
.map_err(|_| anyhow!("request body buffer allocation failed"))?;
|
||||
}
|
||||
bytes.extend_from_slice(&data);
|
||||
}
|
||||
Err(frame) => trailers = frame.into_trailers().ok(),
|
||||
}
|
||||
}
|
||||
Ok((Bytes::from(bytes), trailers))
|
||||
}
|
||||
|
||||
struct RetainedBody {
|
||||
body: Body,
|
||||
lease: Option<Arc<OwnedSemaphorePermit>>,
|
||||
}
|
||||
|
||||
struct LeasedBytes {
|
||||
bytes: Bytes,
|
||||
_lease: Arc<OwnedSemaphorePermit>,
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for LeasedBytes {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamingBody for RetainedBody {
|
||||
type Data = Bytes;
|
||||
type Error = <Body as StreamingBody>::Error;
|
||||
|
||||
fn poll_frame(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
||||
match Pin::new(&mut self.body).poll_frame(cx) {
|
||||
Poll::Ready(Some(Ok(frame))) => {
|
||||
let lease = self.lease.clone();
|
||||
Poll::Ready(Some(Ok(frame.map_data(|bytes| match lease {
|
||||
Some(lease) => Bytes::from_owner(LeasedBytes {
|
||||
bytes,
|
||||
_lease: lease,
|
||||
}),
|
||||
None => bytes,
|
||||
}))))
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_end_stream(&self) -> bool {
|
||||
self.body.is_end_stream()
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> SizeHint {
|
||||
self.body.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn retain(req: Request) -> Request {
|
||||
let (parts, body) = req.into_parts();
|
||||
let lease = parts
|
||||
.extensions
|
||||
.get::<BufferLease>()
|
||||
.and_then(|lease| lease.0.upgrade());
|
||||
// Keep exact sizing, and retain the lease in data frames queued after the body is dropped.
|
||||
let body = Body::new(RetainedBody { body, lease });
|
||||
Request::from_parts(parts, body)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "body_budget_tests.rs"]
|
||||
mod tests;
|
||||
94
codex-rs/network-proxy/src/body_budget_tests.rs
Normal file
94
codex-rs/network-proxy/src/body_budget_tests.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! Reservations survive request metadata disposal and are reused across transform stages.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::futures::stream;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fragmented_body_collection_releases_chunks_and_enforces_the_byte_limit() {
|
||||
struct Chunk {
|
||||
bytes: [u8; 1],
|
||||
live: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for Chunk {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Chunk {
|
||||
fn drop(&mut self) {
|
||||
self.live.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
for max_bytes in [1024, 1023] {
|
||||
let live = Arc::new(AtomicUsize::new(0));
|
||||
let chunks = (0..1024).map({
|
||||
let live = live.clone();
|
||||
move |_| {
|
||||
assert_eq!(
|
||||
live.fetch_add(1, Ordering::SeqCst),
|
||||
0,
|
||||
"the collector retained a previous chunk"
|
||||
);
|
||||
Ok::<_, std::io::Error>(Bytes::from_owner(Chunk {
|
||||
bytes: *b"x",
|
||||
live: live.clone(),
|
||||
}))
|
||||
}
|
||||
});
|
||||
let result = collect_body(Body::from_stream(stream::iter(chunks)), max_bytes).await;
|
||||
assert_eq!(live.load(Ordering::SeqCst), 0);
|
||||
if max_bytes == 1024 {
|
||||
assert_eq!(result.unwrap(), (Bytes::from(vec![b'x'; 1024]), None));
|
||||
} else {
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn body_keeps_buffer_lease_and_nested_stages_reuse_it() {
|
||||
let mut request = Request::new(Body::from("payload"));
|
||||
let slots = Arc::new(Semaphore::new(BUFFER_SLOT_COUNT));
|
||||
let permit = reserve_in(&mut request, &slots).await.unwrap();
|
||||
let lease = Arc::downgrade(&permit);
|
||||
let nested = reserve_in(&mut request, &slots).await.unwrap();
|
||||
assert!(Arc::ptr_eq(&permit, &nested));
|
||||
let request = retain(request);
|
||||
drop(nested);
|
||||
drop(permit);
|
||||
let metadata = request.extensions().clone();
|
||||
let (parts, mut body) = request.into_parts();
|
||||
assert_eq!(body.size_hint().exact(), Some(7));
|
||||
drop(parts);
|
||||
assert!(lease.upgrade().is_some());
|
||||
let frame = body.frame().await.expect("body frame").expect("body data");
|
||||
drop(body);
|
||||
assert!(lease.upgrade().is_some());
|
||||
let bytes = frame.into_data().expect("data frame");
|
||||
assert_eq!(bytes.as_ref(), b"payload");
|
||||
let queued = bytes.clone();
|
||||
drop(bytes);
|
||||
assert!(lease.upgrade().is_some());
|
||||
let mut held = Vec::new();
|
||||
for _ in 1..8 {
|
||||
let permit = slots
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.expect("eight buffer slots");
|
||||
held.push(permit);
|
||||
}
|
||||
let mut ninth = Request::new(Body::empty());
|
||||
let reservation = reserve_in(&mut ninth, &slots);
|
||||
tokio::pin!(reservation);
|
||||
assert!(rama_core::futures::poll!(&mut reservation).is_pending());
|
||||
drop(queued);
|
||||
assert!(lease.upgrade().is_none());
|
||||
let _permit = reservation.await.expect("released buffer slot");
|
||||
drop(metadata);
|
||||
}
|
||||
217
codex-rs/network-proxy/src/brokered_tunnel.rs
Normal file
217
codex-rs/network-proxy/src/brokered_tunnel.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! Detect configured tunnel protocols without consuming bytes needed for opaque forwarding.
|
||||
//! HTTP requests retain their authorized tunnel destination; upgraded streams stay opaque.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use rama_core::Service;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_core::stream::PeekStream;
|
||||
use rama_core::stream::Stream;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::Method;
|
||||
use rama_http::Request;
|
||||
use rama_http::Response;
|
||||
use rama_http::StatusCode;
|
||||
use rama_http::Uri;
|
||||
use rama_http::header::CONNECTION;
|
||||
use rama_http::header::PROXY_AUTHENTICATE;
|
||||
use rama_http::header::UPGRADE;
|
||||
use rama_http::io::upgrade::OnUpgrade;
|
||||
use std::io::Cursor;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct BrokeredProtocols {
|
||||
pub(crate) tls: bool,
|
||||
pub(crate) http: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum TunnelProtocol {
|
||||
Tls,
|
||||
Http,
|
||||
Opaque,
|
||||
}
|
||||
|
||||
const PREFIX_TIMEOUT: Duration = Duration::from_millis(250);
|
||||
const MAX_REQUEST_LINE: usize = 8192;
|
||||
|
||||
/// Detect only configured protocols, replaying every byte for opaque forwarding.
|
||||
pub(crate) async fn peek_protocol<S>(
|
||||
mut stream: S,
|
||||
protocols: BrokeredProtocols,
|
||||
) -> Result<(TunnelProtocol, PeekStream<Cursor<Vec<u8>>, S>)>
|
||||
where
|
||||
S: Stream + Unpin + ExtensionsMut,
|
||||
{
|
||||
let mut prefix = Vec::new();
|
||||
let mut buf = [0_u8; 5];
|
||||
if let Ok(result) = timeout(PREFIX_TIMEOUT, stream.read(&mut buf)).await {
|
||||
prefix.extend_from_slice(&buf[..result.context("read tunnel prefix")?])
|
||||
}
|
||||
let protocol = if prefix.first() == Some(&0x16) && protocols.tls {
|
||||
// Do not time out a fragmented TLS record once the client has started its handshake.
|
||||
while prefix.len() < 5
|
||||
&& matches!(
|
||||
prefix.as_slice(),
|
||||
[0x16] | [0x16, 0x03] | [0x16, 0x03, 0x00..=0x04, ..]
|
||||
)
|
||||
{
|
||||
let read = stream.read(&mut buf[..5 - prefix.len()]).await?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
prefix.extend_from_slice(&buf[..read]);
|
||||
}
|
||||
if matches!(prefix.as_slice(), [0x16, 0x03, 0x00..=0x04, _, _]) {
|
||||
TunnelProtocol::Tls
|
||||
} else {
|
||||
TunnelProtocol::Opaque
|
||||
}
|
||||
} else if protocols.http && !prefix.is_empty() {
|
||||
// A bounded probe avoids stalling client-first opaque protocols that wait for a reply.
|
||||
let probe = async {
|
||||
let mut buf = [0_u8; 1024];
|
||||
loop {
|
||||
if let Some(end) = prefix.iter().position(|byte| *byte == b'\n') {
|
||||
let line = std::str::from_utf8(&prefix[..=end]).ok()?;
|
||||
let mut parts = line.strip_suffix("\r\n")?.split(' ');
|
||||
let method = parts.next()?;
|
||||
let target = parts.next()?;
|
||||
let version = parts.next()?;
|
||||
return (parts.next().is_none()
|
||||
&& Method::from_bytes(method.as_bytes()).is_ok()
|
||||
&& target.parse::<Uri>().is_ok()
|
||||
&& (matches!(version, "HTTP/1.0" | "HTTP/1.1")
|
||||
|| (method == "PRI" && target == "*" && version == "HTTP/2.0")))
|
||||
.then_some(());
|
||||
}
|
||||
if prefix.len() >= MAX_REQUEST_LINE
|
||||
|| prefix
|
||||
.iter()
|
||||
.any(|byte| !matches!(byte, b'\r' | b'\t' | 0x20..=0x7e))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let remaining = buf.len().min(MAX_REQUEST_LINE - prefix.len());
|
||||
let read = stream.read(&mut buf[..remaining]).await.ok()?;
|
||||
if read == 0 {
|
||||
return None;
|
||||
}
|
||||
prefix.extend_from_slice(&buf[..read]);
|
||||
}
|
||||
};
|
||||
if matches!(timeout(PREFIX_TIMEOUT, probe).await, Ok(Some(()))) {
|
||||
TunnelProtocol::Http
|
||||
} else {
|
||||
TunnelProtocol::Opaque
|
||||
}
|
||||
} else {
|
||||
TunnelProtocol::Opaque
|
||||
};
|
||||
Ok((protocol, PeekStream::new(Cursor::new(prefix), stream)))
|
||||
}
|
||||
|
||||
/// Preserve HTTP/1 upgrades on an already-authorized tunnel without interpreting upgraded bytes.
|
||||
pub(crate) async fn forward_http_request(
|
||||
mut req: Request,
|
||||
upstream: &crate::upstream::UpstreamClient,
|
||||
) -> Result<Response> {
|
||||
let upgrade = req.headers().get(UPGRADE).cloned().filter(|_| {
|
||||
req.headers().get_all(CONNECTION).iter().any(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.any(|token| token.trim().eq_ignore_ascii_case("upgrade"))
|
||||
})
|
||||
})
|
||||
});
|
||||
let downstream_upgrade = req.extensions().get::<OnUpgrade>().cloned();
|
||||
let h2c_settings = if upgrade.as_ref().is_some_and(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.any(|protocol| protocol.trim().eq_ignore_ascii_case("h2c"))
|
||||
})
|
||||
}) {
|
||||
req.headers()
|
||||
.get_all("http2-settings")
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
crate::http_proxy::remove_hop_by_hop_request_headers(req.headers_mut());
|
||||
if let Some(upgrade) = &upgrade {
|
||||
req.headers_mut().insert(UPGRADE, upgrade.clone());
|
||||
// The upgraded stream is relayed unchanged, including the client's h2c negotiation.
|
||||
let connection = if h2c_settings.is_empty() {
|
||||
"upgrade"
|
||||
} else {
|
||||
"upgrade, http2-settings"
|
||||
};
|
||||
if !h2c_settings.is_empty() {
|
||||
req.headers_mut().remove("http2-settings");
|
||||
}
|
||||
for settings in h2c_settings {
|
||||
req.headers_mut().append("http2-settings", settings);
|
||||
}
|
||||
req.headers_mut()
|
||||
.insert(CONNECTION, HeaderValue::from_static(connection));
|
||||
}
|
||||
let mut response = upstream.serve(req).await?;
|
||||
let response_upgrade = if response.status() == StatusCode::SWITCHING_PROTOCOLS {
|
||||
let expected = upgrade
|
||||
.as_ref()
|
||||
.context("unsolicited HTTP tunnel upgrade")?
|
||||
.to_str()?;
|
||||
let selected = response
|
||||
.headers()
|
||||
.get(UPGRADE)
|
||||
.context("missing HTTP upgrade protocol")?
|
||||
.clone();
|
||||
anyhow::ensure!(
|
||||
expected.split(',').any(|protocol| protocol
|
||||
.trim()
|
||||
.eq_ignore_ascii_case(selected.to_str().unwrap_or_default())),
|
||||
"HTTP tunnel upgrade protocol mismatch"
|
||||
);
|
||||
let downstream = downstream_upgrade.context("missing downstream HTTP upgrade")?;
|
||||
let upstream = response
|
||||
.extensions()
|
||||
.get::<OnUpgrade>()
|
||||
.cloned()
|
||||
.context("missing upstream HTTP upgrade")?;
|
||||
tokio::spawn(async move {
|
||||
let result = async {
|
||||
let (mut downstream, mut upstream) = tokio::try_join!(downstream, upstream)?;
|
||||
tokio::io::copy_bidirectional(&mut downstream, &mut upstream).await?;
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("HTTP tunnel upgrade failed: {err}");
|
||||
}
|
||||
});
|
||||
Some(selected)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
crate::http_proxy::remove_hop_by_hop_request_headers(response.headers_mut());
|
||||
response.headers_mut().remove(PROXY_AUTHENTICATE);
|
||||
if let Some(upgrade) = response_upgrade {
|
||||
response.headers_mut().insert(UPGRADE, upgrade);
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CONNECTION, HeaderValue::from_static("upgrade"));
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "brokered_tunnel_tests.rs"]
|
||||
mod tests;
|
||||
549
codex-rs/network-proxy/src/brokered_tunnel_tests.rs
Normal file
549
codex-rs/network-proxy/src/brokered_tunnel_tests.rs
Normal file
@@ -0,0 +1,549 @@
|
||||
//! End-to-end checks for credential scope and protocol compatibility on CONNECT and SOCKS5.
|
||||
|
||||
use crate::CredentialProviderConfig;
|
||||
use crate::NetworkMode;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::NetworkProxyConstraints;
|
||||
use crate::NetworkProxyState;
|
||||
use crate::build_config_state;
|
||||
use crate::connection_lifecycle::ProxyListeners;
|
||||
use crate::runtime::ConfigReloader;
|
||||
use crate::runtime::ConfigReloaderFuture;
|
||||
use crate::runtime::ConfigState;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::extensions::Extensions;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::TcpListener as StdTcpListener;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::DuplexStream;
|
||||
use tokio::io::ReadBuf;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
struct TestStream {
|
||||
inner: DuplexStream,
|
||||
extensions: Extensions,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
fn new(inner: DuplexStream) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
extensions: Extensions::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for TestStream {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for TestStream {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<std::io::Result<usize>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtensionsRef for TestStream {
|
||||
fn extensions(&self) -> &Extensions {
|
||||
&self.extensions
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtensionsMut for TestStream {
|
||||
fn extensions_mut(&mut self) -> &mut Extensions {
|
||||
&mut self.extensions
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tls_prefix_detection_accumulates_fragmented_reads() {
|
||||
let tls_prefix = [0x16, 0x03, 0x03, 0x00, 0x80];
|
||||
let (mut writer, reader) = tokio::io::duplex(16);
|
||||
let writer_task = tokio::spawn(async move {
|
||||
writer.write_all(&tls_prefix[..1]).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
writer.write_all(&tls_prefix[1..]).await.unwrap();
|
||||
});
|
||||
|
||||
let (protocol, mut stream) = crate::brokered_tunnel::peek_protocol(
|
||||
TestStream::new(reader),
|
||||
crate::brokered_tunnel::BrokeredProtocols {
|
||||
tls: true,
|
||||
http: true,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut replayed = [0_u8; 5];
|
||||
stream.read_exact(&mut replayed).await.unwrap();
|
||||
|
||||
assert_eq!(protocol, crate::brokered_tunnel::TunnelProtocol::Tls);
|
||||
assert_eq!(replayed, tls_prefix);
|
||||
writer_task.await.unwrap();
|
||||
}
|
||||
|
||||
const TOKEN: &str = "local_abcdefghijklmnopqrstuvwxyzabcdef";
|
||||
|
||||
struct StaticReloader(ConfigState);
|
||||
|
||||
impl ConfigReloader for StaticReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"HTTP tunnel test".to_string()
|
||||
}
|
||||
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Transport {
|
||||
Connect,
|
||||
Socks5,
|
||||
}
|
||||
|
||||
struct TestProxy {
|
||||
addr: SocketAddr,
|
||||
listeners: ProxyListeners,
|
||||
dummy: String,
|
||||
transport: Transport,
|
||||
}
|
||||
|
||||
impl Drop for TestProxy {
|
||||
fn drop(&mut self) {
|
||||
self.listeners.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl TestProxy {
|
||||
fn start(target: SocketAddr, transport: Transport, mode: NetworkMode) -> Self {
|
||||
let mut config = NetworkProxyConfig {
|
||||
enabled: true,
|
||||
mode,
|
||||
mitm: true,
|
||||
credential_broker: true,
|
||||
allow_local_binding: Some(true),
|
||||
credential_providers: BTreeMap::from([(
|
||||
"local".to_string(),
|
||||
CredentialProviderConfig {
|
||||
env: vec!["LOCAL_TOKEN".to_string()],
|
||||
patterns: vec!["^local_[a-z]{32}$".to_string()],
|
||||
url_prefixes: vec![format!("http://{target}/v1")],
|
||||
..CredentialProviderConfig::default()
|
||||
},
|
||||
)]),
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
config.set_allowed_domains(vec!["127.0.0.1".to_string()]);
|
||||
let config_state = build_config_state(
|
||||
config,
|
||||
NetworkProxyConstraints::default(),
|
||||
crate::Platform::native(),
|
||||
)
|
||||
.unwrap();
|
||||
let state = Arc::new(NetworkProxyState::with_reloader(
|
||||
config_state.clone(),
|
||||
Arc::new(StaticReloader(config_state)),
|
||||
));
|
||||
let mut env = HashMap::from([("LOCAL_TOKEN".to_string(), TOKEN.to_string())]);
|
||||
state.virtualize_snapshot_credentials(&mut env, /*environment_id*/ None);
|
||||
let dummy = env.remove("LOCAL_TOKEN").unwrap();
|
||||
assert_ne!(dummy, TOKEN);
|
||||
let listener = StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let mut listeners = ProxyListeners::new();
|
||||
match transport {
|
||||
Transport::Connect => listeners.spawn(move |guard| {
|
||||
crate::http_proxy::run_http_proxy_with_std_listener(
|
||||
state, listener, /*policy_decider*/ None, /*environment_id*/ None,
|
||||
guard,
|
||||
)
|
||||
}),
|
||||
Transport::Socks5 => listeners.spawn(move |guard| {
|
||||
crate::socks5::run_socks5_with_std_listener(
|
||||
state, listener, /*policy_decider*/ None, /*environment_id*/ None,
|
||||
/*enable_socks5_udp*/ false, guard,
|
||||
)
|
||||
}),
|
||||
}
|
||||
Self {
|
||||
addr,
|
||||
listeners,
|
||||
dummy,
|
||||
transport,
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(&self, target: SocketAddr) -> TcpStream {
|
||||
let mut stream = TcpStream::connect(self.addr).await.unwrap();
|
||||
match self.transport {
|
||||
Transport::Connect => {
|
||||
stream
|
||||
.write_all(
|
||||
format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(read_headers(&mut stream).await.starts_with("HTTP/1.1 200"));
|
||||
}
|
||||
Transport::Socks5 => {
|
||||
stream.write_all(&[5, 1, 0]).await.unwrap();
|
||||
let mut greeting = [0; 2];
|
||||
stream.read_exact(&mut greeting).await.unwrap();
|
||||
assert_eq!(greeting, [5, 0]);
|
||||
let mut request = vec![5, 1, 0, 1, 127, 0, 0, 1];
|
||||
request.extend_from_slice(&target.port().to_be_bytes());
|
||||
stream.write_all(&request).await.unwrap();
|
||||
let mut response = [0; 10];
|
||||
stream.read_exact(&mut response).await.unwrap();
|
||||
assert_eq!(&response[..4], &[5, 0, 0, 1]);
|
||||
}
|
||||
}
|
||||
stream
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_headers(stream: &mut TcpStream) -> String {
|
||||
timeout(Duration::from_secs(3), async {
|
||||
let mut bytes = Vec::new();
|
||||
while !bytes.ends_with(b"\r\n\r\n") {
|
||||
assert!(bytes.len() < 16384);
|
||||
bytes.push(stream.read_u8().await.unwrap());
|
||||
}
|
||||
String::from_utf8(bytes).unwrap()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plaintext_tunnels_translate_only_the_configured_url_prefix() {
|
||||
for transport in [Transport::Connect, Transport::Socks5] {
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Full);
|
||||
let mut client = proxy.connect(addr).await;
|
||||
for (method, path, body, expected) in [
|
||||
("GET", "/v1/models", "", TOKEN),
|
||||
("OPTIONS", "*", "", proxy.dummy.as_str()),
|
||||
("POST", "/v1/responses", "request body", TOKEN),
|
||||
("GET", "/v10/models", "", proxy.dummy.as_str()),
|
||||
("GET", "/v1/%2e%2e/private", "", proxy.dummy.as_str()),
|
||||
] {
|
||||
client.write_all(format!("{method} {path} HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {}\r\nContent-Length: {}\r\n\r\n{body}", proxy.dummy, body.len()).as_bytes()).await.unwrap();
|
||||
let (mut upstream, _) = timeout(Duration::from_secs(3), target.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let request = read_headers(&mut upstream).await;
|
||||
assert!(request.starts_with(&format!("{method} {path} HTTP/1.1\r\n")));
|
||||
assert!(
|
||||
request
|
||||
.lines()
|
||||
.any(|line| line
|
||||
.eq_ignore_ascii_case(&format!("authorization: Bearer {expected}"))),
|
||||
"{transport:?}, {path}: {request:?}"
|
||||
);
|
||||
let mut received_body = vec![0; body.len()];
|
||||
timeout(
|
||||
Duration::from_secs(3),
|
||||
upstream.read_exact(&mut received_body),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(received_body, body.as_bytes());
|
||||
upstream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(read_headers(&mut client).await.starts_with("HTTP/1.1 200"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plaintext_tunnels_accept_http2_clients() {
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::service::service_fn;
|
||||
use rama_http::Body;
|
||||
use rama_http::Request;
|
||||
use rama_http::Version;
|
||||
use rama_http_backend::client::HttpConnector;
|
||||
use rama_net::client::EstablishedClientConnection;
|
||||
for transport in [Transport::Connect, Transport::Socks5] {
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Full);
|
||||
let stream = Arc::new(tokio::sync::Mutex::new(Some(rama_tcp::TcpStream::from(
|
||||
proxy.connect(addr).await,
|
||||
))));
|
||||
let (captured_tx, mut captured_rx) = tokio::sync::mpsc::channel(1);
|
||||
let target_task = tokio::spawn(async move {
|
||||
let (stream, _) = target.accept().await.unwrap();
|
||||
rama_http_backend::server::HttpServer::auto(rama_core::rt::Executor::default())
|
||||
.service(service_fn(move |request: Request| {
|
||||
let captured_tx = captured_tx.clone();
|
||||
async move {
|
||||
captured_tx
|
||||
.send(request.headers().get("authorization").cloned())
|
||||
.await
|
||||
.unwrap();
|
||||
Ok::<_, std::convert::Infallible>(rama_http::Response::new(Body::empty()))
|
||||
}
|
||||
}))
|
||||
.serve(rama_tcp::TcpStream::from(stream))
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
let connector = HttpConnector::<_, Body>::new(service_fn(move |req: Request| {
|
||||
let stream = stream.clone();
|
||||
async move {
|
||||
Ok::<_, BoxError>(EstablishedClientConnection {
|
||||
input: req,
|
||||
conn: stream.lock().await.take().unwrap(),
|
||||
})
|
||||
}
|
||||
}));
|
||||
let request = Request::builder()
|
||||
.version(Version::HTTP_2)
|
||||
.uri(format!("http://{addr}/v1/models"))
|
||||
.header("authorization", format!("Bearer {}", proxy.dummy))
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let EstablishedClientConnection { input, conn } = connector.serve(request).await.unwrap();
|
||||
let response = tokio::spawn(async move { conn.serve(input).await });
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(3), captured_rx.recv())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
Some(rama_http::HeaderValue::from_str(&format!("Bearer {TOKEN}")).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
timeout(Duration::from_secs(3), response)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.status(),
|
||||
rama_http::StatusCode::OK
|
||||
);
|
||||
target_task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plaintext_tunnels_reject_retargeting_and_nested_connect() {
|
||||
for transport in [Transport::Connect, Transport::Socks5] {
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Full);
|
||||
for (method, uri, host, status) in [
|
||||
("GET", "/v1".to_string(), "127.0.0.1:1".to_string(), 400),
|
||||
(
|
||||
"GET",
|
||||
"http://127.0.0.1:1/v1".to_string(),
|
||||
addr.to_string(),
|
||||
400,
|
||||
),
|
||||
("GET", format!("https://{addr}/v1"), addr.to_string(), 400),
|
||||
("CONNECT", addr.to_string(), addr.to_string(), 405),
|
||||
] {
|
||||
let mut client = proxy.connect(addr).await;
|
||||
client.write_all(format!("{method} {uri} HTTP/1.1\r\nHost: {host}\r\nAuthorization: Bearer {}\r\nConnection: close\r\n\r\n", proxy.dummy).as_bytes()).await.unwrap();
|
||||
let response = read_headers(&mut client).await;
|
||||
assert!(
|
||||
response.starts_with(&format!("HTTP/1.1 {status}")),
|
||||
"{transport:?}: {response:?}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
timeout(Duration::from_millis(50), target.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plaintext_tunnels_preserve_server_first_and_client_first_opaque_bytes() {
|
||||
for transport in [Transport::Connect, Transport::Socks5] {
|
||||
for server_first in [true, false] {
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Full);
|
||||
let mut client = proxy.connect(addr).await;
|
||||
if !server_first {
|
||||
client.write_all(b"PING").await.unwrap();
|
||||
}
|
||||
let (mut upstream, _) = timeout(Duration::from_secs(3), target.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
upstream.write_all(b"SSH-2.0-server\r\n").await.unwrap();
|
||||
let mut banner = [0; 16];
|
||||
timeout(Duration::from_secs(3), client.read_exact(&mut banner))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&banner, b"SSH-2.0-server\r\n");
|
||||
if server_first {
|
||||
client.write_all(b"PING").await.unwrap();
|
||||
}
|
||||
let mut request = [0; 4];
|
||||
timeout(Duration::from_secs(3), upstream.read_exact(&mut request))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&request, b"PING");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn plaintext_tunnels_preserve_http_upgrades() {
|
||||
for (transport, protocol) in [Transport::Connect, Transport::Socks5]
|
||||
.into_iter()
|
||||
.flat_map(|transport| ["test-echo", "h2c"].map(move |protocol| (transport, protocol)))
|
||||
{
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Full);
|
||||
let mut client = proxy.connect(addr).await;
|
||||
client.write_all(format!("GET /v1 HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {}\r\nConnection: upgrade, HTTP2-Settings, X-Remove\r\nUpgrade: {protocol}\r\nHTTP2-Settings: AAMAAABk\r\nX-Remove: hop-local\r\n\r\n", proxy.dummy).as_bytes()).await.unwrap();
|
||||
let (mut upstream, _) = timeout(Duration::from_secs(3), target.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let request = read_headers(&mut upstream).await;
|
||||
assert!(
|
||||
request
|
||||
.lines()
|
||||
.any(|line| line.eq_ignore_ascii_case(&format!("Authorization: Bearer {TOKEN}")))
|
||||
);
|
||||
assert!(
|
||||
request
|
||||
.lines()
|
||||
.any(|line| line.eq_ignore_ascii_case(&format!("Upgrade: {protocol}")))
|
||||
);
|
||||
assert_eq!(
|
||||
request
|
||||
.lines()
|
||||
.any(|line| line.eq_ignore_ascii_case("HTTP2-Settings: AAMAAABk")),
|
||||
protocol == "h2c"
|
||||
);
|
||||
let connection = if protocol == "h2c" {
|
||||
"upgrade, http2-settings"
|
||||
} else {
|
||||
"upgrade"
|
||||
};
|
||||
assert!(
|
||||
request
|
||||
.lines()
|
||||
.any(|line| line.eq_ignore_ascii_case(&format!("Connection: {connection}")))
|
||||
);
|
||||
assert!(!request.to_ascii_lowercase().contains("x-remove"));
|
||||
upstream.write_all(format!("HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: {protocol}\r\n\r\nbanner").as_bytes()).await.unwrap();
|
||||
assert!(read_headers(&mut client).await.starts_with("HTTP/1.1 101"));
|
||||
let mut banner = [0; 6];
|
||||
timeout(Duration::from_secs(3), client.read_exact(&mut banner))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&banner, b"banner");
|
||||
client.write_all(b"PING").await.unwrap();
|
||||
let mut payload = [0; 4];
|
||||
timeout(Duration::from_secs(3), upstream.read_exact(&mut payload))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&payload, b"PING");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn limited_plaintext_tunnels_allow_reads_but_reject_writes_and_opaque_traffic() {
|
||||
for transport in [Transport::Connect, Transport::Socks5] {
|
||||
let target = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let addr = target.local_addr().unwrap();
|
||||
let proxy = TestProxy::start(addr, transport, NetworkMode::Limited);
|
||||
for method in ["GET", "HEAD", "OPTIONS"] {
|
||||
let mut client = proxy.connect(addr).await;
|
||||
client.write_all(format!("{method} /v1 HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {}\r\nConnection: close\r\n\r\n", proxy.dummy).as_bytes()).await.unwrap();
|
||||
let (mut upstream, _) = timeout(Duration::from_secs(3), target.accept())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let request = read_headers(&mut upstream).await;
|
||||
assert!(
|
||||
request.lines().any(
|
||||
|line| line.eq_ignore_ascii_case(&format!("Authorization: Bearer {TOKEN}"))
|
||||
)
|
||||
);
|
||||
upstream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(read_headers(&mut client).await.starts_with("HTTP/1.1 200"));
|
||||
}
|
||||
for (method, extra_headers) in [
|
||||
("POST", ""),
|
||||
("GET", "Upgrade: test-echo\r\nConnection: upgrade\r\n"),
|
||||
] {
|
||||
let mut client = proxy.connect(addr).await;
|
||||
client.write_all(format!("{method} /v1 HTTP/1.1\r\nHost: {addr}\r\nAuthorization: Bearer {}\r\nContent-Length: 0\r\n{extra_headers}\r\n", proxy.dummy).as_bytes()).await.unwrap();
|
||||
assert!(read_headers(&mut client).await.starts_with("HTTP/1.1 403"));
|
||||
}
|
||||
let mut client = proxy.connect(addr).await;
|
||||
client.write_all(b"PING").await.unwrap();
|
||||
let mut byte = [0];
|
||||
let result = timeout(Duration::from_secs(3), client.read(&mut byte))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(result, Ok(0) | Err(_)));
|
||||
assert!(
|
||||
timeout(Duration::from_millis(50), target.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
1297
codex-rs/network-proxy/src/certs.rs
Normal file
1297
codex-rs/network-proxy/src/certs.rs
Normal file
File diff suppressed because it is too large
Load Diff
1267
codex-rs/network-proxy/src/config.rs
Normal file
1267
codex-rs/network-proxy/src/config.rs
Normal file
File diff suppressed because it is too large
Load Diff
246
codex-rs/network-proxy/src/config/standalone.rs
Normal file
246
codex-rs/network-proxy/src/config/standalone.rs
Normal file
@@ -0,0 +1,246 @@
|
||||
use super::NetworkMode;
|
||||
use super::NetworkProxyConfig;
|
||||
use crate::ConfigState;
|
||||
use crate::NetworkProxyConstraints;
|
||||
use crate::Platform;
|
||||
use crate::build_config_state;
|
||||
use crate::validate_policy_against_constraints;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
|
||||
/// A resolved policy, including the ceilings applied by managed requirements.
|
||||
///
|
||||
/// Keep this document outside the workload's writable filesystem. It is not an
|
||||
/// attestation of enforcement: the host must separately ensure that all workload
|
||||
/// egress traverses the proxy and bind readiness to the current environment.
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
|
||||
pub struct StaticNetworkProxyConfig {
|
||||
pub network: NetworkProxyConfig,
|
||||
/// Standalone configurations may omit constraints. Managed callers must export
|
||||
/// the resolved requirements and use `from_slice_strict` to require this field.
|
||||
pub constraints: NetworkProxyConstraints,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for StaticNetworkProxyConfig {
|
||||
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
struct Document {
|
||||
network: NetworkProxyConfig,
|
||||
#[serde(default)]
|
||||
constraints: NetworkProxyConstraints,
|
||||
}
|
||||
|
||||
let config: Document = deserialize_document(deserializer, /*allow_metadata*/ true)?;
|
||||
Ok(Self {
|
||||
network: config.network,
|
||||
constraints: config.constraints,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Only the top-level metadata object is extensible. Ignoring a matcher key can widen access.
|
||||
fn deserialize_document<'de, D, T>(
|
||||
deserializer: D,
|
||||
allow_metadata: bool,
|
||||
) -> std::result::Result<T, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
T: Deserialize<'de>,
|
||||
{
|
||||
let mut unknown = None;
|
||||
let config = serde_ignored::deserialize(deserializer, |path| {
|
||||
let path = path.to_string();
|
||||
if unknown.is_none() && !(allow_metadata && path == "metadata") {
|
||||
unknown = Some(path);
|
||||
}
|
||||
})?;
|
||||
if let Some(path) = unknown {
|
||||
return Err(serde::de::Error::custom(format!("unknown field: {path}")));
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
impl StaticNetworkProxyConfig {
|
||||
/// Parse standalone policy, allowing optional constraints and top-level metadata.
|
||||
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
|
||||
Ok(serde_json::from_slice::<Self>(bytes)?.normalize())
|
||||
}
|
||||
|
||||
/// Require explicit constraints and reject unknown fields at every typed level.
|
||||
pub fn from_slice_strict(bytes: &[u8]) -> Result<Self> {
|
||||
#[derive(Deserialize)]
|
||||
struct RequiredConstraints {
|
||||
network: NetworkProxyConfig,
|
||||
constraints: NetworkProxyConstraints,
|
||||
}
|
||||
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(bytes);
|
||||
let config: RequiredConstraints =
|
||||
deserialize_document(&mut deserializer, /*allow_metadata*/ false)?;
|
||||
deserializer.end()?;
|
||||
Ok(Self {
|
||||
network: config.network,
|
||||
constraints: config.constraints,
|
||||
}
|
||||
.normalize())
|
||||
}
|
||||
|
||||
fn normalize(mut self) -> Self {
|
||||
self.network.mitm |=
|
||||
self.network.mode == NetworkMode::Limited || !self.network.mitm_hooks.is_empty();
|
||||
self
|
||||
}
|
||||
|
||||
/// Validate before creating listeners or loading credential/CA material.
|
||||
pub fn build_state(self, platform: Platform) -> Result<ConfigState> {
|
||||
let config = self.normalize();
|
||||
ensure!(
|
||||
config.network.enabled,
|
||||
"standalone network proxy requires network.enabled = true"
|
||||
);
|
||||
validate_policy_against_constraints(&config.network, &config.constraints)?;
|
||||
build_config_state(config.network, config.constraints, platform)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn static_config_preserves_constraints_and_rejects_weakened_policy() {
|
||||
let bytes = serde_json::to_vec(&json!({
|
||||
"network": {
|
||||
"enabled": true,
|
||||
"mode": "limited",
|
||||
"allow_upstream_proxy": false,
|
||||
"domains": {"*.example.com": "allow", "blocked.example.com": "deny"}
|
||||
},
|
||||
"constraints": {
|
||||
"enabled": true,
|
||||
"allow_upstream_proxy": false,
|
||||
"allowed_domains": ["*.example.com"],
|
||||
"allowlist_expansion_enabled": false,
|
||||
"denied_domains": ["blocked.example.com"],
|
||||
"denylist_expansion_enabled": true
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let config = StaticNetworkProxyConfig::from_slice(&bytes).unwrap();
|
||||
let round_trip =
|
||||
StaticNetworkProxyConfig::from_slice(&serde_json::to_vec(&config).unwrap()).unwrap();
|
||||
assert_eq!(round_trip, config);
|
||||
let direct: StaticNetworkProxyConfig = serde_json::from_slice(&bytes).unwrap();
|
||||
assert!(!direct.network.mitm);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ca = crate::certs::ManagedMitmCa::for_test(dir.path()).unwrap();
|
||||
let state = crate::certs::TEST_MITM_CA
|
||||
.sync_scope(ca, || direct.build_state(Platform::Linux))
|
||||
.unwrap();
|
||||
assert!(state.mitm.is_some());
|
||||
assert_eq!(state.config, config.network);
|
||||
assert_eq!(state.constraints, config.constraints);
|
||||
|
||||
let mut weakened = config;
|
||||
weakened.network.allow_upstream_proxy = true;
|
||||
assert!(weakened.build_state(Platform::Linux).is_err());
|
||||
|
||||
for bytes in [
|
||||
br#"{"network":{"enabled":true},"constraints":{"enabled":false}}"#.as_slice(),
|
||||
br#"{"network":{"enabled":false},"constraints":{}}"#.as_slice(),
|
||||
] {
|
||||
assert!(
|
||||
StaticNetworkProxyConfig::from_slice(bytes)
|
||||
.unwrap()
|
||||
.build_state(Platform::Linux)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_socket_paths_match_exactly() {
|
||||
let mut policy = StaticNetworkProxyConfig::from_slice_strict(
|
||||
br#"{"network":{"enabled":true,"unix_sockets":{"/run/Secret.sock":"allow"}},
|
||||
"constraints":{"allow_unix_sockets":["/run/Secret.sock"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(validate_policy_against_constraints(&policy.network, &policy.constraints).is_ok());
|
||||
policy
|
||||
.network
|
||||
.set_allow_unix_sockets(vec!["/run/secret.sock".to_string()]);
|
||||
assert!(validate_policy_against_constraints(&policy.network, &policy.constraints).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_modes_handle_constraints_and_unknown_fields() {
|
||||
let without_constraints = br#"{"network":{"enabled":true}}"#;
|
||||
assert!(StaticNetworkProxyConfig::from_slice(without_constraints).is_ok());
|
||||
assert!(StaticNetworkProxyConfig::from_slice_strict(without_constraints).is_err());
|
||||
|
||||
let baseline = json!({
|
||||
"network": {
|
||||
"enabled": true,
|
||||
"mitm_hooks": [{
|
||||
"host": "example.com",
|
||||
"match": {"methods": ["POST"]},
|
||||
"actions": {"strip_request_headers": ["x-debug"]}
|
||||
}]
|
||||
},
|
||||
"constraints": {"allow_upstream_proxy": false}
|
||||
});
|
||||
let expected =
|
||||
StaticNetworkProxyConfig::from_slice_strict(&serde_json::to_vec(&baseline).unwrap())
|
||||
.unwrap();
|
||||
let mut annotated = baseline.clone();
|
||||
annotated["metadata"] = json!({"producer_version": 2});
|
||||
let bytes = serde_json::to_vec(&annotated).unwrap();
|
||||
assert_eq!(
|
||||
StaticNetworkProxyConfig::from_slice(&bytes).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert!(StaticNetworkProxyConfig::from_slice_strict(&bytes).is_err());
|
||||
|
||||
for pointer in [
|
||||
"",
|
||||
"/network",
|
||||
"/constraints",
|
||||
"/network/mitm_hooks/0/match",
|
||||
"/network/mitm_hooks/0/actions",
|
||||
] {
|
||||
let mut config = baseline.clone();
|
||||
config.pointer_mut(pointer).unwrap()["future_setting"] = json!(true);
|
||||
let bytes = serde_json::to_vec(&config).unwrap();
|
||||
for parse in [
|
||||
StaticNetworkProxyConfig::from_slice,
|
||||
StaticNetworkProxyConfig::from_slice_strict,
|
||||
] {
|
||||
let error = parse(&bytes).unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("future_setting"),
|
||||
"{pointer}: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for bytes in [
|
||||
br#"{"constraints":{}}"#.as_slice(),
|
||||
br#"{"network":{"mitm_hooks":[{"host":"example.com","match":{"header":{}}}]},"constraints":{}}"#,
|
||||
br#"{"network":{},"constraint":{}}"#,
|
||||
br#"{"network":{"enabled":"true"},"constraints":{}}"#,
|
||||
br#"{"network":{},"constraints":null}"#,
|
||||
br#"{"network":{},"constraints":{}} {}"#,
|
||||
] {
|
||||
assert!(StaticNetworkProxyConfig::from_slice(bytes).is_err());
|
||||
assert!(StaticNetworkProxyConfig::from_slice_strict(bytes).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
260
codex-rs/network-proxy/src/connect_policy.rs
Normal file
260
codex-rs/network-proxy/src/connect_policy.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
use crate::policy::is_non_public_ip;
|
||||
use crate::runtime::HostAuthorization;
|
||||
use crate::runtime::HostBlockDecision;
|
||||
use crate::state::NetworkProxyState;
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::system_dns::SystemDnsResolver;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::error::ErrorExt as _;
|
||||
use rama_core::error::OpaqueError;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_net::address::Host;
|
||||
use rama_net::address::HostWithPort;
|
||||
use rama_net::address::ProxyAddress;
|
||||
use rama_net::client::EstablishedClientConnection;
|
||||
use rama_net::transport::TryRefIntoTransportContext;
|
||||
use rama_tcp::TcpStream;
|
||||
use rama_tcp::client::TcpStreamConnector;
|
||||
use rama_tcp::client::service::TcpConnector;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Connects traffic whose host policy has already allowed the request.
|
||||
/// Resolved non-public targets still undergo explicit-deny and local-address checks.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TargetCheckedTcpConnector {
|
||||
state: Arc<NetworkProxyState>,
|
||||
}
|
||||
|
||||
impl TargetCheckedTcpConnector {
|
||||
pub(crate) fn new(state: Arc<NetworkProxyState>) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input> Service<Input> for TargetCheckedTcpConnector
|
||||
where
|
||||
Input: TryRefIntoTransportContext + Send + ExtensionsMut + 'static,
|
||||
Input::Error: Into<BoxError> + Send + Sync + 'static,
|
||||
{
|
||||
type Output = EstablishedClientConnection<TcpStream, Input>;
|
||||
type Error = BoxError;
|
||||
|
||||
async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
|
||||
let connector = TcpConnector::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
let connector = connector.with_dns(SystemDnsResolver);
|
||||
|
||||
if input.extensions().get::<ProxyAddress>().is_some() {
|
||||
return connector.serve(input).await;
|
||||
}
|
||||
|
||||
let target = input
|
||||
.try_ref_into_transport_ctx()
|
||||
.map_err(|err| OpaqueError::from_boxed(err.into()).context("read network target"))?
|
||||
.host_with_port()
|
||||
.ok_or_else(|| OpaqueError::from_display("network target is missing a port"))?;
|
||||
|
||||
connector
|
||||
.with_connector(TargetCheckedStreamConnector {
|
||||
state: self.state.clone(),
|
||||
target,
|
||||
})
|
||||
.serve(input)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TargetCheckedStreamConnector {
|
||||
state: Arc<NetworkProxyState>,
|
||||
target: HostWithPort,
|
||||
}
|
||||
|
||||
impl TcpStreamConnector for TargetCheckedStreamConnector {
|
||||
type Error = BoxError;
|
||||
|
||||
async fn connect(&self, addr: SocketAddr) -> Result<TcpStream, Self::Error> {
|
||||
if is_non_public_ip(addr.ip()) && !self.allows_non_public_target(addr).await? {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"network target rejected by policy",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
tokio::net::TcpStream::connect(addr)
|
||||
.await
|
||||
.map(TcpStream::from)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl TargetCheckedStreamConnector {
|
||||
async fn allows_non_public_target(&self, addr: SocketAddr) -> Result<bool, BoxError> {
|
||||
if self.state.allow_local_binding().await.map_err(|err| {
|
||||
let err: BoxError = err.into();
|
||||
OpaqueError::from_boxed(err)
|
||||
.context("read network proxy config")
|
||||
.into_boxed()
|
||||
})? {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if !target_matches_non_public_addr(&self.target.host, addr.ip()) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
self.state
|
||||
.host_blocked_with_local_binding(
|
||||
&self.target.host.to_string(),
|
||||
self.target.port,
|
||||
/*allow_local_binding*/ None,
|
||||
HostAuthorization::Approved,
|
||||
)
|
||||
.await
|
||||
.map(|decision| decision == HostBlockDecision::Allowed)
|
||||
.map_err(|err| {
|
||||
let err: BoxError = err.into();
|
||||
OpaqueError::from_boxed(err)
|
||||
.context("evaluate network proxy target")
|
||||
.into_boxed()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_non_public_target(host: &Host) -> bool {
|
||||
match host {
|
||||
Host::Address(ip) => is_non_public_ip(*ip),
|
||||
Host::Name(name) => name
|
||||
.as_str()
|
||||
.trim_end_matches('.')
|
||||
.eq_ignore_ascii_case("localhost"),
|
||||
}
|
||||
}
|
||||
|
||||
fn target_matches_non_public_addr(host: &Host, addr: std::net::IpAddr) -> bool {
|
||||
match host {
|
||||
Host::Address(ip) => *ip == addr,
|
||||
Host::Name(name) => {
|
||||
name.as_str()
|
||||
.trim_end_matches('.')
|
||||
.eq_ignore_ascii_case("localhost")
|
||||
&& addr.is_loopback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::state::network_proxy_state_for_policy;
|
||||
use rama_net::address::HostWithPort;
|
||||
use std::net::Ipv4Addr;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn direct_connector_rejects_non_public_target_when_local_binding_disabled() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind local listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxyConfig::default(),
|
||||
)));
|
||||
|
||||
let request: rama_tcp::client::Request =
|
||||
rama_tcp::client::Request::new(HostWithPort::from(target));
|
||||
let err = Service::serve(&connector, request)
|
||||
.await
|
||||
.expect_err("local target should be rejected");
|
||||
|
||||
assert!(
|
||||
format!("{err:?}").contains("network target rejected by policy"),
|
||||
"unexpected error: {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn direct_connector_allows_non_public_target_when_local_binding_enabled() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind local listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxyConfig {
|
||||
allow_local_binding: Some(true),
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
)));
|
||||
|
||||
let request: rama_tcp::client::Request =
|
||||
rama_tcp::client::Request::new(HostWithPort::from(target));
|
||||
let result = Service::serve(&connector, request).await;
|
||||
|
||||
assert!(result.is_ok(), "local target should be allowed: {result:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn direct_connector_allows_explicitly_allowlisted_non_public_target() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind local listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let mut config = NetworkProxyConfig::default();
|
||||
config.set_allowed_domains(vec![target.ip().to_string()]);
|
||||
config.review_domains = vec![target.ip().to_string()];
|
||||
let state = Arc::new(network_proxy_state_for_policy(config));
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::clone(&state));
|
||||
|
||||
let request: rama_tcp::client::Request =
|
||||
rama_tcp::client::Request::new(HostWithPort::from(target));
|
||||
let result = Service::serve(&connector, request).await;
|
||||
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"explicitly allowlisted local target should be allowed: {result:?}"
|
||||
);
|
||||
state
|
||||
.add_denied_domain(&target.ip().to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
let request = rama_tcp::client::Request::new(HostWithPort::from(target));
|
||||
assert!(Service::serve(&connector, request).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn direct_connector_allows_explicitly_allowlisted_localhost_target() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind local listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let mut config = NetworkProxyConfig::default();
|
||||
config.set_allowed_domains(vec!["localhost".to_string()]);
|
||||
config.review_domains = vec!["localhost".to_string()];
|
||||
let connector =
|
||||
TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(config)));
|
||||
|
||||
let request: rama_tcp::client::Request =
|
||||
rama_tcp::client::Request::new(HostWithPort::new(Host::LOCALHOST_NAME, target.port()));
|
||||
let result = Service::serve(&connector, request).await;
|
||||
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"explicitly allowlisted localhost target should be allowed: {result:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_private_address_does_not_match_allowlisted_hostname() {
|
||||
let host = Host::Name("example.com".parse().expect("valid domain"));
|
||||
|
||||
assert!(!target_matches_non_public_addr(
|
||||
&host,
|
||||
Ipv4Addr::LOCALHOST.into()
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Exercises proxy teardown through live TCP connections, including half-closed tunnels.
|
||||
|
||||
use crate::NetworkProxy;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::state::network_proxy_state_for_policy;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::future::poll_fn;
|
||||
use std::io::ErrorKind;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ConnectionKind {
|
||||
HttpConnect(TunnelState),
|
||||
Socks5(TunnelState),
|
||||
HttpKeepAlive,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum TunnelState {
|
||||
Open,
|
||||
ClientWriteClosed,
|
||||
UpstreamWriteClosed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum PeerSide {
|
||||
Client,
|
||||
Upstream,
|
||||
}
|
||||
|
||||
struct Connection {
|
||||
client: TcpStream,
|
||||
upstream: TcpStream,
|
||||
eof_received_by: Option<PeerSide>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum StopProxy {
|
||||
Shutdown,
|
||||
Drop,
|
||||
CancelWait,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_closes_proxy_connections() -> Result<()> {
|
||||
assert_stop_closes_connections(StopProxy::Shutdown).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_handle_closes_proxy_connections() -> Result<()> {
|
||||
assert_stop_closes_connections(StopProxy::Drop).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceling_wait_closes_proxy_connections() -> Result<()> {
|
||||
assert_stop_closes_connections(StopProxy::CancelWait).await
|
||||
}
|
||||
|
||||
async fn assert_stop_closes_connections(stop: StopProxy) -> Result<()> {
|
||||
let mut config = NetworkProxyConfig {
|
||||
allow_local_binding: Some(true),
|
||||
allow_upstream_proxy: false,
|
||||
enable_socks5_udp: false,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
config.set_allowed_domains(vec![Ipv4Addr::LOCALHOST.to_string()]);
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(Arc::new(network_proxy_state_for_policy(config)))
|
||||
.managed_by_codex(!cfg!(target_os = "windows"))
|
||||
.http_addr(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.socks_addr(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.build()
|
||||
.await?;
|
||||
let handle = proxy.run().await?;
|
||||
// Environment listeners reserve ephemeral ports on every platform. Managed main
|
||||
// listeners do so off Windows, whose shared ingress has separate route tests.
|
||||
let prepared = proxy.prepare_for_remote_environment(HashMap::new(), "lifecycle-test")?;
|
||||
let scopes = [
|
||||
("environment", prepared.env),
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
(
|
||||
"main",
|
||||
proxy
|
||||
.prepare_for_optional_environment(HashMap::new(), /*environment_id*/ None)?
|
||||
.env,
|
||||
),
|
||||
];
|
||||
let mut connections = Vec::new();
|
||||
for (scope, env) in scopes {
|
||||
for kind in [
|
||||
ConnectionKind::HttpConnect(TunnelState::Open),
|
||||
ConnectionKind::HttpConnect(TunnelState::ClientWriteClosed),
|
||||
ConnectionKind::HttpConnect(TunnelState::UpstreamWriteClosed),
|
||||
ConnectionKind::Socks5(TunnelState::Open),
|
||||
ConnectionKind::Socks5(TunnelState::ClientWriteClosed),
|
||||
ConnectionKind::Socks5(TunnelState::UpstreamWriteClosed),
|
||||
ConnectionKind::HttpKeepAlive,
|
||||
] {
|
||||
let (key, prefix) = match kind {
|
||||
ConnectionKind::HttpConnect(_) | ConnectionKind::HttpKeepAlive => {
|
||||
("HTTP_PROXY", "http://")
|
||||
}
|
||||
ConnectionKind::Socks5(_) => ("ALL_PROXY", "socks5h://"),
|
||||
};
|
||||
let addr = env[key]
|
||||
.strip_prefix(prefix)
|
||||
.context("proxy URL scheme")?
|
||||
.parse()?;
|
||||
let connection = timeout(Duration::from_secs(5), open_connection(kind, addr))
|
||||
.await
|
||||
.with_context(|| format!("{scope} {kind:?} connection did not become ready"))??;
|
||||
connections.push((scope, kind, connection));
|
||||
}
|
||||
}
|
||||
|
||||
match stop {
|
||||
StopProxy::Shutdown => timeout(Duration::from_secs(2), handle.shutdown())
|
||||
.await
|
||||
.context("proxy shutdown did not finish with active connections")??,
|
||||
StopProxy::Drop => drop(handle),
|
||||
StopProxy::CancelWait => {
|
||||
let mut wait = Box::pin(handle.wait());
|
||||
let state = poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx))).await;
|
||||
assert!(
|
||||
state.is_pending(),
|
||||
"running proxy unexpectedly stopped: {state:?}"
|
||||
);
|
||||
drop(wait);
|
||||
}
|
||||
}
|
||||
|
||||
// Retain every endpoint until all checks finish: dropping a test peer could
|
||||
// otherwise cause the EOF that a later assertion attributes to proxy teardown.
|
||||
for (scope, kind, connection) in &mut connections {
|
||||
for (side, stream) in [
|
||||
(PeerSide::Client, &mut connection.client),
|
||||
(PeerSide::Upstream, &mut connection.upstream),
|
||||
] {
|
||||
if connection.eof_received_by == Some(side) {
|
||||
continue;
|
||||
}
|
||||
let mut byte = [0_u8; 1];
|
||||
let result = timeout(Duration::from_secs(2), stream.read(&mut byte))
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("{scope} {kind:?} {side:?} connection remained open after {stop:?}")
|
||||
})?;
|
||||
match result {
|
||||
Ok(0) => {}
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.kind(),
|
||||
ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted
|
||||
) => {}
|
||||
result => anyhow::bail!(
|
||||
"{scope} {kind:?} {side:?} did not close after {stop:?}: {result:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn open_connection(kind: ConnectionKind, proxy_addr: SocketAddr) -> Result<Connection> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?;
|
||||
let target = listener.local_addr()?;
|
||||
let mut client = TcpStream::connect(proxy_addr).await?;
|
||||
let request = match kind {
|
||||
ConnectionKind::HttpConnect(_) => {
|
||||
format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").into_bytes()
|
||||
}
|
||||
ConnectionKind::HttpKeepAlive => {
|
||||
format!("GET http://{target}/ HTTP/1.1\r\nHost: {target}\r\n\r\n").into_bytes()
|
||||
}
|
||||
ConnectionKind::Socks5(_) => {
|
||||
client.write_all(&[5, 1, 0]).await?;
|
||||
let mut greeting = [0_u8; 2];
|
||||
client.read_exact(&mut greeting).await?;
|
||||
assert_eq!(greeting, [5, 0]);
|
||||
let [port_high, port_low] = target.port().to_be_bytes();
|
||||
vec![5, 1, 0, 1, 127, 0, 0, 1, port_high, port_low]
|
||||
}
|
||||
};
|
||||
client.write_all(&request).await?;
|
||||
let (upstream, _) = listener.accept().await?;
|
||||
let mut connection = Connection {
|
||||
client,
|
||||
upstream,
|
||||
eof_received_by: None,
|
||||
};
|
||||
let tunnel_state = match kind {
|
||||
ConnectionKind::HttpConnect(state) => {
|
||||
let response = read_http_headers(&mut connection.client).await?;
|
||||
assert!(response.starts_with("HTTP/1.1 200 "), "{response:?}");
|
||||
state
|
||||
}
|
||||
ConnectionKind::Socks5(state) => {
|
||||
let mut response = [0_u8; 10];
|
||||
connection.client.read_exact(&mut response).await?;
|
||||
assert_eq!(&response[..4], &[5, 0, 0, 1]);
|
||||
state
|
||||
}
|
||||
ConnectionKind::HttpKeepAlive => {
|
||||
read_http_headers(&mut connection.upstream).await?;
|
||||
connection
|
||||
.upstream
|
||||
.write_all(b"HTTP/1.1 204 No Content\r\n\r\n")
|
||||
.await?;
|
||||
let response = read_http_headers(&mut connection.client).await?;
|
||||
assert!(response.starts_with("HTTP/1.1 204 "), "{response:?}");
|
||||
return Ok(connection);
|
||||
}
|
||||
};
|
||||
|
||||
let (sender, receiver, receiver_side) = match tunnel_state {
|
||||
TunnelState::Open | TunnelState::ClientWriteClosed => (
|
||||
&mut connection.client,
|
||||
&mut connection.upstream,
|
||||
PeerSide::Upstream,
|
||||
),
|
||||
TunnelState::UpstreamWriteClosed => (
|
||||
&mut connection.upstream,
|
||||
&mut connection.client,
|
||||
PeerSide::Client,
|
||||
),
|
||||
};
|
||||
sender.write_all(b"request").await?;
|
||||
let mut request = [0_u8; 7];
|
||||
receiver.read_exact(&mut request).await?;
|
||||
assert_eq!(&request, b"request");
|
||||
match tunnel_state {
|
||||
TunnelState::Open => {}
|
||||
TunnelState::ClientWriteClosed | TunnelState::UpstreamWriteClosed => {
|
||||
sender.shutdown().await?;
|
||||
assert_eq!(receiver.read(&mut [0_u8; 1]).await?, 0);
|
||||
connection.eof_received_by = Some(receiver_side);
|
||||
}
|
||||
}
|
||||
// Traffic in the opposite direction remains valid after a write half closes.
|
||||
receiver.write_all(b"response").await?;
|
||||
let mut response = [0_u8; 8];
|
||||
sender.read_exact(&mut response).await?;
|
||||
assert_eq!(&response, b"response");
|
||||
Ok(connection)
|
||||
}
|
||||
|
||||
async fn read_http_headers(stream: &mut TcpStream) -> Result<String> {
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(stream.read_u8().await?);
|
||||
}
|
||||
Ok(String::from_utf8(headers)?)
|
||||
}
|
||||
47
codex-rs/network-proxy/src/connection_lifecycle/listeners.rs
Normal file
47
codex-rs/network-proxy/src/connection_lifecycle/listeners.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
//! Keeps listener tasks and their connection scope alive under the same runtime owner.
|
||||
|
||||
use super::scope::ConnectionLifecycle;
|
||||
use anyhow::Result;
|
||||
use rama_core::graceful::ShutdownGuard;
|
||||
use std::future::Future;
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
pub(crate) struct ProxyListeners {
|
||||
connections: ConnectionLifecycle,
|
||||
listeners: JoinSet<Result<()>>,
|
||||
}
|
||||
|
||||
impl ProxyListeners {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
connections: ConnectionLifecycle::new(),
|
||||
listeners: JoinSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn<F, Fut>(&mut self, listener: F)
|
||||
where
|
||||
F: FnOnce(ShutdownGuard) -> Fut,
|
||||
Fut: Future<Output = Result<()>> + Send + 'static,
|
||||
{
|
||||
self.listeners.spawn(listener(self.connections.guard()));
|
||||
}
|
||||
|
||||
pub(crate) fn cancel(&mut self) {
|
||||
self.connections.cancel();
|
||||
self.listeners.abort_all();
|
||||
}
|
||||
|
||||
pub(crate) async fn wait(&mut self) -> Result<()> {
|
||||
while let Some(result) = self.listeners.join_next().await {
|
||||
result??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(mut self) {
|
||||
self.cancel();
|
||||
self.listeners.shutdown().await;
|
||||
self.connections.shutdown().await;
|
||||
}
|
||||
}
|
||||
12
codex-rs/network-proxy/src/connection_lifecycle/mod.rs
Normal file
12
codex-rs/network-proxy/src/connection_lifecycle/mod.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
mod listeners;
|
||||
mod scope;
|
||||
mod service;
|
||||
|
||||
pub(crate) use listeners::ProxyListeners;
|
||||
#[cfg(test)]
|
||||
pub(crate) use scope::ConnectionLifecycle;
|
||||
pub(crate) use service::CancelOnShutdown;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lifecycle_tests.rs"]
|
||||
mod tests;
|
||||
35
codex-rs/network-proxy/src/connection_lifecycle/scope.rs
Normal file
35
codex-rs/network-proxy/src/connection_lifecycle/scope.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Owns cancellation and completion of a proxy's accepted connections and descendant tasks.
|
||||
|
||||
use rama_core::graceful::Shutdown;
|
||||
use rama_core::graceful::ShutdownGuard;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
pub(crate) struct ConnectionLifecycle {
|
||||
// Only the runtime owner holds the sender. Dropping it also signals shutdown when an
|
||||
// enclosing wait/shutdown future is cancelled, without spawning another cleanup task.
|
||||
cancel: Option<oneshot::Sender<()>>,
|
||||
shutdown: Shutdown,
|
||||
}
|
||||
|
||||
impl ConnectionLifecycle {
|
||||
pub(crate) fn new() -> Self {
|
||||
let (cancel, signal) = oneshot::channel();
|
||||
Self {
|
||||
cancel: Some(cancel),
|
||||
shutdown: Shutdown::new(signal),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn guard(&self) -> ShutdownGuard {
|
||||
self.shutdown.guard()
|
||||
}
|
||||
|
||||
pub(crate) fn cancel(&mut self) {
|
||||
self.cancel.take();
|
||||
}
|
||||
|
||||
pub(crate) async fn shutdown(mut self) {
|
||||
self.cancel();
|
||||
self.shutdown.shutdown().await;
|
||||
}
|
||||
}
|
||||
43
codex-rs/network-proxy/src/connection_lifecycle/service.rs
Normal file
43
codex-rs/network-proxy/src/connection_lifecycle/service.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Cancels connection work when its executor's proxy scope ends, including HTTP upgrades.
|
||||
|
||||
use rama_core::Service;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_core::rt::Executor;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CancelOnShutdown<S> {
|
||||
inner: S,
|
||||
}
|
||||
|
||||
impl<S> CancelOnShutdown<S> {
|
||||
pub(crate) fn new(inner: S) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, Request> Service<Request> for CancelOnShutdown<S>
|
||||
where
|
||||
S: Service<Request, Output = ()>,
|
||||
Request: ExtensionsRef + Send + 'static,
|
||||
{
|
||||
type Output = ();
|
||||
type Error = S::Error;
|
||||
|
||||
async fn serve(&self, request: Request) -> Result<(), Self::Error> {
|
||||
let guard = request
|
||||
.extensions()
|
||||
.get::<Executor>()
|
||||
.and_then(Executor::guard)
|
||||
.cloned();
|
||||
match guard {
|
||||
Some(guard) => {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = guard.cancelled() => Ok(()),
|
||||
result = self.inner.serve(request) => result,
|
||||
}
|
||||
}
|
||||
None => self.inner.serve(request).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
1812
codex-rs/network-proxy/src/credential_broker.rs
Normal file
1812
codex-rs/network-proxy/src/credential_broker.rs
Normal file
File diff suppressed because it is too large
Load Diff
578
codex-rs/network-proxy/src/credential_broker/configured.rs
Normal file
578
codex-rs/network-proxy/src/credential_broker/configured.rs
Normal file
@@ -0,0 +1,578 @@
|
||||
use super::CredentialAuthMethod;
|
||||
use super::CredentialProviderConfig;
|
||||
use super::destination::CredentialDestination;
|
||||
use super::env_value;
|
||||
use super::providers;
|
||||
use super::providers::CredentialHostBinding;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use base64::Engine as _;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderName;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::header::AUTHORIZATION;
|
||||
use rand::Rng as _;
|
||||
use regex::Regex;
|
||||
use regex::RegexBuilder;
|
||||
use regex_automata::Anchored;
|
||||
use regex_automata::Input;
|
||||
use regex_automata::MatchKind;
|
||||
use regex_automata::nfa::thompson;
|
||||
use regex_automata::nfa::thompson::pikevm::PikeVM;
|
||||
use regex_syntax::hir::Class;
|
||||
use regex_syntax::hir::ClassBytes;
|
||||
use regex_syntax::hir::ClassBytesRange;
|
||||
use regex_syntax::hir::ClassUnicode;
|
||||
use regex_syntax::hir::ClassUnicodeRange;
|
||||
use regex_syntax::hir::Hir;
|
||||
use regex_syntax::hir::HirKind;
|
||||
use regex_syntax::hir::Look;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const MAX_REGEX_BYTES: usize = 2048;
|
||||
const MAX_REGEX_REPEAT: u32 = 64;
|
||||
const MAX_DUMMY_ATTEMPTS: usize = 64;
|
||||
const MIN_DISTINCTIVE_CREDENTIAL_PREFIX_LENGTH: usize = 4;
|
||||
const MAX_DUMMY_VALUE_BYTES: usize = 2048;
|
||||
|
||||
pub(super) struct ConfiguredCredentialProvider {
|
||||
pub(super) id: String,
|
||||
pub(super) config: CredentialProviderConfig,
|
||||
patterns: Vec<ConfiguredCredentialPattern>,
|
||||
header: Option<HeaderName>,
|
||||
}
|
||||
|
||||
struct ConfiguredCredentialPattern {
|
||||
matcher: Regex,
|
||||
longest_matcher: PikeVM,
|
||||
known_value_matcher: Regex,
|
||||
full_matcher: Regex,
|
||||
ascii_generator: Option<rand_regex::Regex>,
|
||||
generator: rand_regex::Regex,
|
||||
has_distinctive_prefix: bool,
|
||||
}
|
||||
|
||||
pub(super) struct DiscoveredCredential {
|
||||
pub(super) range: std::ops::Range<usize>,
|
||||
pub(super) has_distinctive_prefix: bool,
|
||||
}
|
||||
|
||||
impl ConfiguredCredentialPattern {
|
||||
fn candidates(&self) -> impl Iterator<Item = String> + '_ {
|
||||
self.ascii_generator
|
||||
.iter()
|
||||
.chain(std::iter::once(&self.generator))
|
||||
.flat_map(|generator| {
|
||||
(0..MAX_DUMMY_ATTEMPTS).map(move |_| rand::rng().sample::<String, _>(generator))
|
||||
})
|
||||
.filter(move |candidate| {
|
||||
candidate.len() <= MAX_DUMMY_VALUE_BYTES
|
||||
&& !candidate.contains('\0')
|
||||
&& self.full_matcher.is_match(candidate)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PatternPurpose {
|
||||
Discovery,
|
||||
AsciiDummy,
|
||||
UnicodeDummy,
|
||||
}
|
||||
|
||||
impl ConfiguredCredentialProvider {
|
||||
pub(super) fn compile(id: &str, config: &CredentialProviderConfig) -> Result<Self> {
|
||||
ensure!(!id.is_empty(), "credential provider name must not be empty");
|
||||
ensure!(
|
||||
!config.env.is_empty(),
|
||||
"credential provider `{id}` has no environment keys"
|
||||
);
|
||||
ensure!(
|
||||
!config.patterns.is_empty(),
|
||||
"credential provider `{id}` has no credential patterns"
|
||||
);
|
||||
ensure!(
|
||||
!config.url_prefixes.is_empty() || config.url_prefix_from_env.is_some(),
|
||||
"credential provider `{id}` has no destination URL prefixes"
|
||||
);
|
||||
ensure!(
|
||||
config.env.iter().all(|key| valid_environment_key(key)),
|
||||
"credential provider `{id}` has an invalid environment key"
|
||||
);
|
||||
ensure!(
|
||||
!config
|
||||
.env
|
||||
.iter()
|
||||
.any(|key| super::is_credential_broker_provider_env_key(key)),
|
||||
"credential provider `{id}` overlaps a built-in credential source"
|
||||
);
|
||||
if let Some(key) = config.url_prefix_from_env.as_deref() {
|
||||
ensure!(
|
||||
valid_environment_key(key)
|
||||
&& !config.env.iter().any(|source| {
|
||||
source.as_str() == key || cfg!(windows) && source.eq_ignore_ascii_case(key)
|
||||
}),
|
||||
"credential provider `{id}` has an invalid host environment key"
|
||||
);
|
||||
}
|
||||
for destination in &config.url_prefixes {
|
||||
CredentialDestination::parse(destination)
|
||||
.with_context(|| format!("invalid destination for credential provider `{id}`"))?;
|
||||
}
|
||||
let methods = auth_methods(config);
|
||||
let header = config
|
||||
.header
|
||||
.as_deref()
|
||||
.map(|header| HeaderName::from_bytes(header.as_bytes()))
|
||||
.transpose()
|
||||
.with_context(|| format!("invalid header for credential provider `{id}`"))?;
|
||||
ensure!(
|
||||
methods.contains(&CredentialAuthMethod::Header) == header.is_some(),
|
||||
"credential provider `{id}` requires a header name exactly when using header authentication"
|
||||
);
|
||||
ensure!(
|
||||
config.prefix.is_none() || header.is_some(),
|
||||
"credential provider `{id}` requires header authentication to use a header prefix"
|
||||
);
|
||||
let patterns = config
|
||||
.patterns
|
||||
.iter()
|
||||
.map(|pattern| {
|
||||
ensure!(
|
||||
pattern.len() <= MAX_REGEX_BYTES,
|
||||
"credential pattern exceeds {MAX_REGEX_BYTES} bytes"
|
||||
);
|
||||
let parsed = regex_syntax::parse(pattern)?;
|
||||
let searchable =
|
||||
prepare_credential_pattern(parsed.clone(), PatternPurpose::Discovery);
|
||||
let has_distinctive_prefix = regex_syntax::hir::literal::Extractor::new()
|
||||
.extract(&searchable)
|
||||
.literals()
|
||||
.is_some_and(|prefixes| {
|
||||
!prefixes.is_empty()
|
||||
&& prefixes.iter().all(|prefix| {
|
||||
prefix.len() >= MIN_DISTINCTIVE_CREDENTIAL_PREFIX_LENGTH
|
||||
})
|
||||
});
|
||||
let searchable_pattern = searchable.to_string();
|
||||
let matcher = RegexBuilder::new(&searchable_pattern)
|
||||
.size_limit(1 << 20)
|
||||
.dfa_size_limit(1 << 20)
|
||||
.build()?;
|
||||
let longest_matcher = PikeVM::builder()
|
||||
.configure(PikeVM::config().match_kind(MatchKind::All))
|
||||
.thompson(thompson::Config::new().nfa_size_limit(Some(1 << 20)))
|
||||
.build(&searchable_pattern)?;
|
||||
let known_value_matcher =
|
||||
RegexBuilder::new(&format!(r"\A(?s:.)(?:{searchable_pattern})(?s:.)\z"))
|
||||
.size_limit(1 << 20)
|
||||
.dfa_size_limit(1 << 20)
|
||||
.build()?;
|
||||
let ascii_generator = rand_regex::Regex::with_hir(
|
||||
prepare_credential_pattern(parsed.clone(), PatternPurpose::AsciiDummy),
|
||||
MAX_REGEX_REPEAT,
|
||||
)
|
||||
.ok();
|
||||
let generator = rand_regex::Regex::with_hir(
|
||||
prepare_credential_pattern(parsed.clone(), PatternPurpose::UnicodeDummy),
|
||||
MAX_REGEX_REPEAT,
|
||||
)?;
|
||||
let full_pattern =
|
||||
Hir::concat(vec![Hir::look(Look::Start), parsed, Hir::look(Look::End)])
|
||||
.to_string();
|
||||
let full_matcher = RegexBuilder::new(&full_pattern)
|
||||
.size_limit(1 << 20)
|
||||
.dfa_size_limit(1 << 20)
|
||||
.build()?;
|
||||
ensure!(
|
||||
searchable
|
||||
.properties()
|
||||
.minimum_len()
|
||||
.is_some_and(|length| length > 0),
|
||||
"credential pattern must not match an empty value"
|
||||
);
|
||||
ensure!(
|
||||
generator.is_utf8() && generator.capacity() <= MAX_REGEX_BYTES,
|
||||
"credential pattern must generate bounded UTF-8 values"
|
||||
);
|
||||
let compiled = ConfiguredCredentialPattern {
|
||||
matcher,
|
||||
longest_matcher,
|
||||
known_value_matcher,
|
||||
full_matcher,
|
||||
ascii_generator,
|
||||
generator,
|
||||
has_distinctive_prefix,
|
||||
};
|
||||
ensure!(
|
||||
compiled.candidates().next().is_some(),
|
||||
"credential pattern could not independently generate a matching dummy"
|
||||
);
|
||||
Ok(compiled)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.with_context(|| format!("invalid credential pattern for provider `{id}`"))?;
|
||||
|
||||
Ok(Self {
|
||||
id: id.to_string(),
|
||||
config: config.clone(),
|
||||
patterns,
|
||||
header,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn matches_value(&self, value: &str) -> bool {
|
||||
self.patterns
|
||||
.iter()
|
||||
.any(|pattern| pattern.full_matcher.is_match(value))
|
||||
}
|
||||
|
||||
pub(super) fn find_credential_matches<'a>(
|
||||
&'a self,
|
||||
value: &'a str,
|
||||
) -> impl Iterator<Item = std::ops::Range<usize>> + 'a {
|
||||
self.credential_matches(value).map(|matched| matched.range)
|
||||
}
|
||||
|
||||
fn credential_matches<'a>(
|
||||
&'a self,
|
||||
value: &'a str,
|
||||
) -> impl Iterator<Item = DiscoveredCredential> + 'a {
|
||||
self.patterns.iter().flat_map(move |pattern| {
|
||||
let mut offset = 0;
|
||||
let mut cache = pattern.longest_matcher.create_cache();
|
||||
std::iter::from_fn(move || {
|
||||
let start = pattern.matcher.find_at(value, offset)?.start();
|
||||
// Anchor at the first match, then explore every alternative to its longest end.
|
||||
// Keep the full input so word-boundary assertions retain their context.
|
||||
let input = Input::new(value).range(start..).anchored(Anchored::Yes);
|
||||
let matched = pattern.longest_matcher.find(&mut cache, input)?;
|
||||
offset = matched.end();
|
||||
Some(matched.range())
|
||||
})
|
||||
.filter(move |matched| {
|
||||
matched.len() >= super::MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| pattern.has_distinctive_prefix
|
||||
})
|
||||
.map(|range| DiscoveredCredential {
|
||||
range,
|
||||
has_distinctive_prefix: pattern.has_distinctive_prefix,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn find_discoverable_credentials<'a>(
|
||||
&'a self,
|
||||
value: &'a str,
|
||||
) -> impl Iterator<Item = DiscoveredCredential> + 'a {
|
||||
// Registration needs a complete token; redaction must still catch embedded matches.
|
||||
self.credential_matches(value).filter(move |matched| {
|
||||
value
|
||||
.as_bytes()
|
||||
.get(matched.range.end)
|
||||
.is_none_or(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-'))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn credential_value_match_ranges(
|
||||
&self,
|
||||
text: &str,
|
||||
credential: &str,
|
||||
) -> Vec<std::ops::Range<usize>> {
|
||||
let Some(first) = credential.chars().next() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut offset = 0;
|
||||
let mut ranges = Vec::new();
|
||||
while let Some(relative) = text[offset..].find(credential) {
|
||||
let start = offset + relative;
|
||||
let end = start + credential.len();
|
||||
// Force the full known span to match while retaining adjacent word boundaries.
|
||||
let before = text[..start].chars().next_back().unwrap_or('\0');
|
||||
let after = text[end..].chars().next().unwrap_or('\0');
|
||||
let context = format!("{before}{credential}{after}");
|
||||
offset = if self
|
||||
.patterns
|
||||
.iter()
|
||||
.any(|pattern| pattern.known_value_matcher.is_match(&context))
|
||||
{
|
||||
ranges.push(start..end);
|
||||
end
|
||||
} else {
|
||||
start + first.len_utf8()
|
||||
};
|
||||
}
|
||||
ranges
|
||||
}
|
||||
|
||||
pub(super) fn contains_strictly_embedded_pattern_match(&self, value: &str) -> bool {
|
||||
self.patterns.iter().any(|pattern| {
|
||||
pattern
|
||||
.matcher
|
||||
.find_iter(value)
|
||||
.any(|matched| matched.start() > 0 || matched.end() < value.len())
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn find_credentials<'a>(&'a self, value: &'a str) -> impl Iterator<Item = &'a str> {
|
||||
self.find_credential_matches(value)
|
||||
.map(|matched| &value[matched])
|
||||
}
|
||||
|
||||
pub(super) fn host_binding(
|
||||
&self,
|
||||
env: &HashMap<String, String>,
|
||||
) -> Option<CredentialHostBinding> {
|
||||
let mut destinations = self
|
||||
.config
|
||||
.url_prefixes
|
||||
.iter()
|
||||
.filter_map(|destination| CredentialDestination::parse(destination).ok())
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(destination) = self.dynamic_destination(env)
|
||||
&& !destinations.contains(&destination)
|
||||
{
|
||||
destinations.push(destination);
|
||||
}
|
||||
(!destinations.is_empty()).then_some(CredentialHostBinding::ConfiguredHosts(destinations))
|
||||
}
|
||||
|
||||
pub(super) fn dynamic_destination(
|
||||
&self,
|
||||
env: &HashMap<String, String>,
|
||||
) -> Option<CredentialDestination> {
|
||||
let key = self.config.url_prefix_from_env.as_deref()?;
|
||||
CredentialDestination::parse(env_value(env, key)?)
|
||||
.ok()
|
||||
.filter(|destination| !destination.is_wildcard())
|
||||
}
|
||||
|
||||
pub(super) fn dummy_value(&self, real_value: &str) -> Option<String> {
|
||||
let pattern = self
|
||||
.patterns
|
||||
.iter()
|
||||
.find(|pattern| pattern.full_matcher.is_match(real_value))?;
|
||||
pattern.candidates().find(|candidate| {
|
||||
candidate != real_value && self.preserves_usable_auth_methods(real_value, candidate)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn request_header_value(&self, value: &str) -> Option<HeaderValue> {
|
||||
auth_methods(&self.config)
|
||||
.iter()
|
||||
.find_map(|method| self.request_header_value_for_method(*method, value))
|
||||
}
|
||||
|
||||
fn preserves_usable_auth_methods(&self, real_value: &str, dummy_value: &str) -> bool {
|
||||
auth_methods(&self.config).iter().all(|method| {
|
||||
// Preserve whether clients serialize a whole Basic pair or one component.
|
||||
if *method == CredentialAuthMethod::Basic
|
||||
&& real_value.contains(':') != dummy_value.contains(':')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some(real_header) = self.request_header_value_for_method(*method, real_value)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let Some(dummy_header) = self.request_header_value_for_method(*method, dummy_value)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if dummy_header.as_bytes().trim_ascii() != dummy_header.as_bytes() {
|
||||
return false;
|
||||
}
|
||||
let header = match method {
|
||||
CredentialAuthMethod::Bearer
|
||||
| CredentialAuthMethod::Token
|
||||
| CredentialAuthMethod::Basic => AUTHORIZATION,
|
||||
CredentialAuthMethod::Header => {
|
||||
let Some(header) = self.header.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
header.clone()
|
||||
}
|
||||
};
|
||||
self.translate_request_headers(
|
||||
&HeaderMap::from_iter([(header.clone(), dummy_header)]),
|
||||
dummy_value,
|
||||
real_value,
|
||||
)
|
||||
.contains(&(header, real_header))
|
||||
})
|
||||
}
|
||||
|
||||
fn request_header_value_for_method(
|
||||
&self,
|
||||
method: CredentialAuthMethod,
|
||||
value: &str,
|
||||
) -> Option<HeaderValue> {
|
||||
let value = match method {
|
||||
CredentialAuthMethod::Bearer => format!("Bearer {value}"),
|
||||
CredentialAuthMethod::Token => format!("token {value}"),
|
||||
CredentialAuthMethod::Basic => format!(
|
||||
"Basic {}",
|
||||
base64::engine::general_purpose::STANDARD.encode(value)
|
||||
),
|
||||
CredentialAuthMethod::Header => {
|
||||
format!(
|
||||
"{}{value}",
|
||||
self.config.prefix.as_deref().unwrap_or_default()
|
||||
)
|
||||
}
|
||||
};
|
||||
HeaderValue::from_str(&value)
|
||||
.ok()
|
||||
.filter(|header| header.to_str().is_ok())
|
||||
}
|
||||
|
||||
pub(super) fn translate_request_headers(
|
||||
&self,
|
||||
headers: &HeaderMap,
|
||||
expected_value: &str,
|
||||
replacement_value: &str,
|
||||
) -> Vec<(HeaderName, HeaderValue)> {
|
||||
let mut translated = Vec::new();
|
||||
for method in auth_methods(&self.config) {
|
||||
match method {
|
||||
CredentialAuthMethod::Bearer
|
||||
| CredentialAuthMethod::Token
|
||||
| CredentialAuthMethod::Basic => {
|
||||
let Some(header) = headers
|
||||
.get(AUTHORIZATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some((scheme, _)) = header.split_once(' ') else {
|
||||
continue;
|
||||
};
|
||||
let expected_scheme = match method {
|
||||
CredentialAuthMethod::Bearer => "bearer",
|
||||
CredentialAuthMethod::Token => "token",
|
||||
CredentialAuthMethod::Basic => "basic",
|
||||
CredentialAuthMethod::Header => continue,
|
||||
};
|
||||
if !scheme.eq_ignore_ascii_case(expected_scheme) {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = providers::translate_standard_request_header(
|
||||
headers,
|
||||
expected_value,
|
||||
replacement_value,
|
||||
) && !translated.iter().any(|(header, _)| header == AUTHORIZATION)
|
||||
{
|
||||
translated.push((AUTHORIZATION, value));
|
||||
}
|
||||
}
|
||||
CredentialAuthMethod::Header => {
|
||||
let Some(header) = self.header.as_ref() else {
|
||||
continue;
|
||||
};
|
||||
let Some(value) = headers.get(header).and_then(|value| value.to_str().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let prefix = self.config.prefix.as_deref().unwrap_or_default();
|
||||
if value == format!("{prefix}{expected_value}")
|
||||
&& !translated.iter().any(|(name, _)| name == header)
|
||||
&& let Ok(value) =
|
||||
HeaderValue::from_str(&format!("{prefix}{replacement_value}"))
|
||||
{
|
||||
translated.push((header.clone(), value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
translated
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_credential_pattern(hir: Hir, purpose: PatternPurpose) -> Hir {
|
||||
match hir.into_kind() {
|
||||
HirKind::Empty => Hir::empty(),
|
||||
HirKind::Literal(literal) => {
|
||||
if matches!(purpose, PatternPurpose::AsciiDummy) && !literal.0.is_ascii() {
|
||||
Hir::fail()
|
||||
} else {
|
||||
Hir::literal(literal.0)
|
||||
}
|
||||
}
|
||||
HirKind::Class(mut class) => {
|
||||
if matches!(purpose, PatternPurpose::AsciiDummy) {
|
||||
match &mut class {
|
||||
Class::Unicode(class) => {
|
||||
class.intersect(&ClassUnicode::new([ClassUnicodeRange::new(' ', '~')]))
|
||||
}
|
||||
Class::Bytes(class) => {
|
||||
class.intersect(&ClassBytes::new([ClassBytesRange::new(b' ', b'~')]))
|
||||
}
|
||||
}
|
||||
}
|
||||
Hir::class(class)
|
||||
}
|
||||
HirKind::Look(look) => {
|
||||
if matches!(purpose, PatternPurpose::Discovery)
|
||||
&& !matches!(
|
||||
look,
|
||||
Look::Start
|
||||
| Look::End
|
||||
| Look::StartLF
|
||||
| Look::EndLF
|
||||
| Look::StartCRLF
|
||||
| Look::EndCRLF
|
||||
)
|
||||
{
|
||||
Hir::look(look)
|
||||
} else {
|
||||
Hir::empty()
|
||||
}
|
||||
}
|
||||
HirKind::Repetition(mut repetition) => {
|
||||
if matches!(purpose, PatternPurpose::Discovery) {
|
||||
// Discovery needs the whole credential, not a lazy prefix of it.
|
||||
repetition.greedy = true;
|
||||
}
|
||||
repetition.sub = Box::new(prepare_credential_pattern(*repetition.sub, purpose));
|
||||
Hir::repetition(repetition)
|
||||
}
|
||||
HirKind::Capture(mut capture) => {
|
||||
capture.sub = Box::new(prepare_credential_pattern(*capture.sub, purpose));
|
||||
Hir::capture(capture)
|
||||
}
|
||||
HirKind::Concat(expressions) => Hir::concat(
|
||||
expressions
|
||||
.into_iter()
|
||||
.map(|expression| prepare_credential_pattern(expression, purpose))
|
||||
.collect(),
|
||||
),
|
||||
HirKind::Alternation(expressions) => {
|
||||
let mut expressions = expressions
|
||||
.into_iter()
|
||||
.map(|expression| prepare_credential_pattern(expression, purpose))
|
||||
.filter(|expression| expression.properties().minimum_len().is_some())
|
||||
.collect::<Vec<_>>();
|
||||
expressions.sort_by_key(|expression| {
|
||||
std::cmp::Reverse(expression.properties().maximum_len().unwrap_or(usize::MAX))
|
||||
});
|
||||
Hir::alternation(expressions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_methods(config: &CredentialProviderConfig) -> &[CredentialAuthMethod] {
|
||||
if config.auth.is_empty() {
|
||||
&[CredentialAuthMethod::Bearer]
|
||||
} else {
|
||||
&config.auth
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn valid_environment_key(key: &str) -> bool {
|
||||
let mut chars = key.chars();
|
||||
chars
|
||||
.next()
|
||||
.is_some_and(|character| character == '_' || character.is_ascii_alphabetic())
|
||||
&& chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
|
||||
}
|
||||
3187
codex-rs/network-proxy/src/credential_broker/configured_tests.rs
Normal file
3187
codex-rs/network-proxy/src/credential_broker/configured_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
163
codex-rs/network-proxy/src/credential_broker/destination.rs
Normal file
163
codex-rs/network-proxy/src/credential_broker/destination.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
use crate::authorization_path::is_safe_for_authorization;
|
||||
use crate::policy::Host;
|
||||
use crate::policy::is_loopback_host;
|
||||
use crate::policy::normalize_host;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use anyhow::ensure;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub(super) struct CredentialDestination {
|
||||
scheme: CredentialDestinationScheme,
|
||||
host: String,
|
||||
wildcard: bool,
|
||||
port: u16,
|
||||
path_prefix: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum CredentialDestinationScheme {
|
||||
Http,
|
||||
Https,
|
||||
}
|
||||
|
||||
impl CredentialDestinationScheme {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Http => "http",
|
||||
Self::Https => "https",
|
||||
}
|
||||
}
|
||||
|
||||
fn default_port(self) -> u16 {
|
||||
match self {
|
||||
Self::Http => 80,
|
||||
Self::Https => 443,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialDestination {
|
||||
pub(super) fn parse(value: &str) -> Result<Self> {
|
||||
let value = value.trim();
|
||||
let (explicit_scheme, authority) = value
|
||||
.split_once("://")
|
||||
.map_or((None, value), |(scheme, authority)| {
|
||||
(Some(scheme), authority)
|
||||
});
|
||||
let (wildcard, authority) = authority
|
||||
.strip_prefix("*.")
|
||||
.map_or((false, authority), |suffix| (true, suffix));
|
||||
let authority = if wildcard {
|
||||
format!("wildcard.{authority}")
|
||||
} else {
|
||||
authority.to_string()
|
||||
};
|
||||
let url = Url::parse(&format!("https://{authority}"))?;
|
||||
ensure!(
|
||||
url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.query().is_none()
|
||||
&& url.fragment().is_none(),
|
||||
"credential destination cannot include user information, a query, or a fragment"
|
||||
);
|
||||
let host = url
|
||||
.host_str()
|
||||
.context("credential destination has no hostname")?;
|
||||
let host = if wildcard {
|
||||
host.strip_prefix("wildcard.")
|
||||
.context("credential destination has an invalid wildcard")?
|
||||
} else {
|
||||
host
|
||||
};
|
||||
let host = normalize_host(host);
|
||||
ensure!(
|
||||
!host.is_empty() && !host.contains('*') && !host.contains('/'),
|
||||
"credential destination must have an exact hostname or scoped wildcard"
|
||||
);
|
||||
let loopback = !wildcard && is_loopback_host(&Host::parse(&host)?);
|
||||
let scheme = match explicit_scheme {
|
||||
None if loopback => CredentialDestinationScheme::Http,
|
||||
None => CredentialDestinationScheme::Https,
|
||||
Some(scheme) if scheme.eq_ignore_ascii_case("https") => {
|
||||
CredentialDestinationScheme::Https
|
||||
}
|
||||
Some(scheme) if scheme.eq_ignore_ascii_case("http") && loopback => {
|
||||
CredentialDestinationScheme::Http
|
||||
}
|
||||
Some(_) => {
|
||||
bail!("credential destination must use HTTPS unless it targets loopback over HTTP")
|
||||
}
|
||||
};
|
||||
// HTTPS parsing removes an explicit :443, which HTTP must retain.
|
||||
let url = match scheme {
|
||||
CredentialDestinationScheme::Http => Url::parse(&format!("http://{authority}"))?,
|
||||
CredentialDestinationScheme::Https => url,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
scheme,
|
||||
host,
|
||||
wildcard,
|
||||
port: url.port().unwrap_or_else(|| scheme.default_port()),
|
||||
path_prefix: url.path().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn is_wildcard(&self) -> bool {
|
||||
self.wildcard
|
||||
}
|
||||
|
||||
pub(super) fn bypasses_proxy_with_local_binding(&self) -> bool {
|
||||
(!self.wildcard || self.host.parse::<std::net::IpAddr>().is_err())
|
||||
&& crate::policy::is_default_proxy_bypass_host(&self.host)
|
||||
}
|
||||
|
||||
pub(super) fn matches_host(&self, host: &str, port: u16) -> bool {
|
||||
self.port == port && self.matches_hostname(host)
|
||||
}
|
||||
|
||||
pub(super) fn matches_hostname(&self, host: &str) -> bool {
|
||||
if self.wildcard {
|
||||
host.strip_suffix(&self.host)
|
||||
.is_some_and(|prefix| prefix.ends_with('.'))
|
||||
} else {
|
||||
host == self.host
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn requires_mitm(&self, host: &str, port: u16) -> bool {
|
||||
self.scheme == CredentialDestinationScheme::Https && self.matches_host(host, port)
|
||||
}
|
||||
|
||||
pub(super) fn requires_http_interception(&self, host: &str, port: u16) -> bool {
|
||||
self.scheme == CredentialDestinationScheme::Http && self.matches_host(host, port)
|
||||
}
|
||||
|
||||
pub(super) fn matches_request(&self, host: &str, request: Option<&Url>) -> bool {
|
||||
let Some(request) = request else {
|
||||
return false;
|
||||
};
|
||||
if request.scheme() != self.scheme.as_str()
|
||||
|| !self.matches_host(
|
||||
host,
|
||||
request
|
||||
.port_or_known_default()
|
||||
.unwrap_or_else(|| self.scheme.default_port()),
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let path = request.path();
|
||||
if !is_safe_for_authorization(path) {
|
||||
return false;
|
||||
}
|
||||
self.path_prefix == "/"
|
||||
|| path == self.path_prefix
|
||||
|| path
|
||||
.strip_prefix(&self.path_prefix)
|
||||
.is_some_and(|suffix| self.path_prefix.ends_with('/') || suffix.starts_with('/'))
|
||||
}
|
||||
}
|
||||
473
codex-rs/network-proxy/src/credential_broker/environment.rs
Normal file
473
codex-rs/network-proxy/src/credential_broker/environment.rs
Normal file
@@ -0,0 +1,473 @@
|
||||
use super::BROKERED_CREDENTIAL_ALIAS_MARKER_PREFIX;
|
||||
use super::BROKERED_CREDENTIALS_ENV_KEY;
|
||||
use super::CREDENTIAL_BROKER_ACTIVE_ENV_KEY;
|
||||
use super::CredentialBrokerState;
|
||||
use super::MIN_EMBEDDED_CREDENTIAL_LENGTH;
|
||||
use super::configured::valid_environment_key;
|
||||
use super::env_entry;
|
||||
use super::env_key_matches;
|
||||
use super::env_value;
|
||||
use super::matching;
|
||||
use super::providers;
|
||||
use super::registry::BrokeredCredentialProvider;
|
||||
use super::remove_env_value;
|
||||
use super::set_env_value;
|
||||
use crate::NetworkProxy;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::PreparedManagedNetwork;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Local destination hints retained by the broker, not added to child environments.
|
||||
#[derive(Clone, Default, Eq, PartialEq)]
|
||||
pub struct CredentialBrokerContext(HashMap<String, String>);
|
||||
|
||||
impl From<HashMap<String, String>> for CredentialBrokerContext {
|
||||
fn from(env: HashMap<String, String>) -> Self {
|
||||
Self(env)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CredentialBrokerContext {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("CredentialBrokerContext(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialBrokerContext {
|
||||
/// Uses private destination hints during brokerage and returns an environment ready to spawn.
|
||||
/// Context values override routing inputs, but never change the child's visible values.
|
||||
pub fn prepare_child_environment(
|
||||
self,
|
||||
proxy: &NetworkProxy,
|
||||
mut env: HashMap<String, String>,
|
||||
environment_id: Option<&str>,
|
||||
) -> anyhow::Result<PreparedManagedNetwork> {
|
||||
let previous = self
|
||||
.0
|
||||
.into_iter()
|
||||
.map(|(key, value)| {
|
||||
let previous =
|
||||
env_entry(&env, &key).map(|(key, value)| (key.to_string(), value.to_string()));
|
||||
set_env_value(&mut env, &key, value);
|
||||
(key, previous)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut prepared = proxy.prepare_for_optional_environment(env, environment_id)?;
|
||||
for (key, previous) in previous {
|
||||
remove_env_value(&mut prepared.env, &key);
|
||||
if let Some((key, value)) = previous {
|
||||
prepared.env.insert(key, value);
|
||||
}
|
||||
}
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
pub(crate) fn capture(
|
||||
config: &NetworkProxyConfig,
|
||||
overrides: &HashMap<String, String>,
|
||||
) -> Self {
|
||||
Self(
|
||||
credential_broker_provider_context_env_keys()
|
||||
.map(str::to_string)
|
||||
.chain(
|
||||
config
|
||||
.credential_providers
|
||||
.values()
|
||||
.filter_map(|provider| provider.url_prefix_from_env.clone()),
|
||||
)
|
||||
.filter_map(|key| {
|
||||
env_value(overrides, &key)
|
||||
.map(str::to_string)
|
||||
.or_else(|| std::env::var(&key).ok())
|
||||
.map(|value| (key, value))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves destination hints without applying or changing child environment policy.
|
||||
pub fn with_fallbacks<'a>(
|
||||
&self,
|
||||
env: &'a HashMap<String, String>,
|
||||
) -> Cow<'a, HashMap<String, String>> {
|
||||
let mut context = Cow::Borrowed(env);
|
||||
for (key, value) in &self.0 {
|
||||
// A present value, including an empty one, overrides the trusted fallback.
|
||||
if env_value(&context, key).is_none() {
|
||||
set_env_value(context.to_mut(), key, value.clone());
|
||||
}
|
||||
}
|
||||
context
|
||||
}
|
||||
}
|
||||
|
||||
/// Trusted provider metadata and active credential bindings for one child environment.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct CredentialBrokerEnvironment {
|
||||
pub credential_keys: Vec<String>,
|
||||
pub binding_keys: Vec<String>,
|
||||
pub context_keys: Vec<String>,
|
||||
pub provider_keys: Vec<String>,
|
||||
pub provider_context_keys: Vec<String>,
|
||||
pub configured_provider_context_keys: Vec<String>,
|
||||
}
|
||||
|
||||
impl CredentialBrokerState {
|
||||
pub(super) fn environment(&self, env: &HashMap<String, String>) -> CredentialBrokerEnvironment {
|
||||
let mut metadata = CredentialBrokerEnvironment::default();
|
||||
for key in
|
||||
providers::credential_env_keys().chain(credential_broker_provider_context_env_keys())
|
||||
{
|
||||
push_unique_key(&mut metadata.provider_keys, key);
|
||||
}
|
||||
for key in credential_broker_provider_context_env_keys() {
|
||||
push_unique_key(&mut metadata.provider_context_keys, key);
|
||||
}
|
||||
for provider in &self.configured_providers {
|
||||
for key in &provider.config.env {
|
||||
push_unique_key(&mut metadata.provider_keys, key);
|
||||
}
|
||||
if let Some(key) = provider.config.url_prefix_from_env.as_deref() {
|
||||
push_unique_key(&mut metadata.provider_keys, key);
|
||||
push_unique_key(&mut metadata.provider_context_keys, key);
|
||||
push_unique_key(&mut metadata.configured_provider_context_keys, key);
|
||||
}
|
||||
}
|
||||
|
||||
if !self.enabled {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
metadata.credential_keys = brokered_credential_dummy_env_keys(env);
|
||||
let marked_credentials = env_value(env, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
.and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok())
|
||||
.unwrap_or_default();
|
||||
for credential in &self.credentials {
|
||||
if matches!(
|
||||
credential.provider,
|
||||
BrokeredCredentialProvider::Configured(_)
|
||||
) && env_value(env, &credential.env_var) == Some(credential.dummy_value.as_str())
|
||||
&& marked_credentials.iter().any(|(key, value)| {
|
||||
env_key_matches(key, &credential.env_var) && value == &credential.dummy_value
|
||||
})
|
||||
{
|
||||
push_unique_key(&mut metadata.credential_keys, &credential.env_var);
|
||||
}
|
||||
}
|
||||
|
||||
for key in providers::credential_context_env_keys(&metadata.credential_keys) {
|
||||
if env_value(env, key).is_some() {
|
||||
push_unique_key(&mut metadata.context_keys, key);
|
||||
}
|
||||
}
|
||||
for key in providers::credential_binding_env_keys(&metadata.credential_keys) {
|
||||
if env_value(env, key).is_some() {
|
||||
push_unique_key(&mut metadata.binding_keys, key);
|
||||
}
|
||||
}
|
||||
for provider in &self.configured_providers {
|
||||
if provider.config.env.iter().any(|provider_key| {
|
||||
metadata
|
||||
.credential_keys
|
||||
.iter()
|
||||
.any(|credential_key| env_key_matches(provider_key, credential_key))
|
||||
}) && let Some(key) = provider.config.url_prefix_from_env.as_deref()
|
||||
&& env_value(env, key).is_some()
|
||||
{
|
||||
push_unique_key(&mut metadata.context_keys, key);
|
||||
push_unique_key(&mut metadata.binding_keys, key);
|
||||
}
|
||||
}
|
||||
|
||||
metadata
|
||||
}
|
||||
}
|
||||
|
||||
fn push_unique_key(keys: &mut Vec<String>, key: &str) {
|
||||
if !keys.iter().any(|candidate| env_key_matches(candidate, key)) {
|
||||
keys.push(key.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update_brokered_credentials_marker(
|
||||
state: &CredentialBrokerState,
|
||||
env: &mut HashMap<String, String>,
|
||||
) {
|
||||
let credentials = state
|
||||
.credentials
|
||||
.iter()
|
||||
.filter(|credential| {
|
||||
env.iter().any(|(key, value)| {
|
||||
!env_key_matches(key, CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
&& !env_key_matches(key, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
&& (value == &credential.dummy_value
|
||||
|| credential.contains_embedded_value(value, &credential.dummy_value))
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut brokered = credentials
|
||||
.iter()
|
||||
.map(|credential| (credential.env_var.clone(), credential.dummy_value.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
brokered.extend(state.credential_aliases.iter().flat_map(|alias| {
|
||||
credentials
|
||||
.iter()
|
||||
.filter(|credential| {
|
||||
alias.dummy_value == credential.dummy_value
|
||||
|| credential
|
||||
.contains_embedded_value(&alias.dummy_value, &credential.dummy_value)
|
||||
})
|
||||
.map(|credential| {
|
||||
(
|
||||
format!("{BROKERED_CREDENTIAL_ALIAS_MARKER_PREFIX}{}", alias.env_var),
|
||||
credential.dummy_value.clone(),
|
||||
)
|
||||
})
|
||||
}));
|
||||
brokered.sort_unstable();
|
||||
brokered.dedup();
|
||||
match serde_json::to_string(&brokered) {
|
||||
Ok(marker) => {
|
||||
set_env_value(env, BROKERED_CREDENTIALS_ENV_KEY, marker);
|
||||
}
|
||||
Err(_) => {
|
||||
remove_env_value(env, BROKERED_CREDENTIALS_ENV_KEY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns supported environment keys whose current values still match the child-scoped dummy
|
||||
/// values recorded by the credential broker.
|
||||
///
|
||||
/// The broker marker is treated as untrusted: malformed metadata, unsupported keys, and values
|
||||
/// replaced by the user are ignored. The environment is not mutated; callers own the decision to
|
||||
/// remove the returned keys.
|
||||
pub fn brokered_credential_dummy_env_keys(env: &HashMap<String, String>) -> Vec<String> {
|
||||
let mut keys = marked_credential_dummy_env_keys(env)
|
||||
.into_iter()
|
||||
.filter(|key| {
|
||||
providers::credential_env_keys().any(|candidate| env_key_matches(key, candidate))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let context_bound = |key: &str| {
|
||||
providers::credential_providers().any(|provider| {
|
||||
provider.sources().iter().any(|source| {
|
||||
source
|
||||
.env_vars
|
||||
.iter()
|
||||
.any(|candidate| env_key_matches(key, candidate))
|
||||
&& source
|
||||
.binding_env_vars
|
||||
.iter()
|
||||
.any(|context| env_value(env, context).is_some())
|
||||
})
|
||||
})
|
||||
};
|
||||
keys.sort_unstable_by(|left, right| {
|
||||
context_bound(right)
|
||||
.cmp(&context_bound(left))
|
||||
.then_with(|| left.cmp(right))
|
||||
});
|
||||
keys
|
||||
}
|
||||
|
||||
pub(crate) fn marked_credential_dummy_env_keys(env: &HashMap<String, String>) -> Vec<String> {
|
||||
env_value(env, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
.and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|(key, dummy_value)| {
|
||||
let (actual_key, actual_value) = env_entry(env, &key)?;
|
||||
(actual_value == dummy_value.as_str()).then(|| actual_key.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns canonical credential and known alias keys recorded for an active brokered child,
|
||||
/// including configured provider keys and keys that are currently absent.
|
||||
pub fn brokered_credential_marker_env_keys(env: &HashMap<String, String>) -> Vec<String> {
|
||||
if env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY) != Some("1") {
|
||||
return Vec::new();
|
||||
}
|
||||
let entries = env_value(env, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
.and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok())
|
||||
.unwrap_or_default();
|
||||
let dummy_values = entries
|
||||
.iter()
|
||||
.filter(|(key, value)| valid_environment_key(key) && !value.is_empty())
|
||||
.map(|(_, dummy_value)| dummy_value.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let mut keys = entries
|
||||
.into_iter()
|
||||
.filter_map(|(key, value)| {
|
||||
if valid_environment_key(&key) {
|
||||
return (!value.is_empty()).then_some(key);
|
||||
}
|
||||
let alias_key = key.strip_prefix(BROKERED_CREDENTIAL_ALIAS_MARKER_PREFIX)?;
|
||||
let known_alias = dummy_values
|
||||
.iter()
|
||||
.any(|dummy_value| value.contains(dummy_value));
|
||||
(known_alias && valid_environment_key(alias_key)).then(|| alias_key.to_string())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
keys
|
||||
}
|
||||
|
||||
/// Returns environment keys whose current values are brokered dummies or aliases containing them,
|
||||
/// including aliases retained after their canonical source variable was removed.
|
||||
pub fn brokered_credential_value_env_keys(env: &HashMap<String, String>) -> Vec<String> {
|
||||
if env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY) != Some("1") {
|
||||
return Vec::new();
|
||||
}
|
||||
let marked_values = env_value(env, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
.and_then(|marker| serde_json::from_str::<Vec<(String, String)>>(marker).ok())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(key, dummy_value)| {
|
||||
!dummy_value.is_empty()
|
||||
&& (valid_environment_key(key)
|
||||
|| key
|
||||
.strip_prefix(BROKERED_CREDENTIAL_ALIAS_MARKER_PREFIX)
|
||||
.is_some_and(valid_environment_key))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut keys = env
|
||||
.iter()
|
||||
.filter(|(key, _)| {
|
||||
!env_key_matches(key, CREDENTIAL_BROKER_ACTIVE_ENV_KEY)
|
||||
&& !env_key_matches(key, BROKERED_CREDENTIALS_ENV_KEY)
|
||||
})
|
||||
.filter(|(key, value)| {
|
||||
marked_values.iter().any(|(marked_key, dummy)| {
|
||||
value.as_str() == dummy.as_str()
|
||||
|| (dummy.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| marked_key
|
||||
.strip_prefix(BROKERED_CREDENTIAL_ALIAS_MARKER_PREFIX)
|
||||
.is_some_and(|alias_key| env_key_matches(key, alias_key)))
|
||||
&& value.contains(dummy.as_str())
|
||||
})
|
||||
})
|
||||
.map(|(key, _)| key.clone())
|
||||
.collect::<Vec<_>>();
|
||||
keys.sort_unstable();
|
||||
keys
|
||||
}
|
||||
|
||||
/// Returns environment keys used to bind currently brokered credentials to hosts.
|
||||
pub fn brokered_credential_binding_env_keys(
|
||||
env: &HashMap<String, String>,
|
||||
) -> impl Iterator<Item = &'static str> {
|
||||
let brokered_keys = brokered_credential_dummy_env_keys(env);
|
||||
providers::credential_binding_env_keys(&brokered_keys)
|
||||
.filter(|key| env_value(env, key).is_some())
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()
|
||||
}
|
||||
|
||||
/// Returns environment keys used to bind registered credential providers to their destinations.
|
||||
pub fn credential_broker_provider_context_env_keys() -> impl Iterator<Item = &'static str> {
|
||||
providers::credential_providers().flat_map(|provider| provider.context_env_vars.iter().copied())
|
||||
}
|
||||
|
||||
/// Checks whether each credential in a value has an allowed source environment key.
|
||||
pub fn credential_broker_provider_sources_allowed(
|
||||
value: &str,
|
||||
virtualized: &str,
|
||||
source_env: &HashMap<String, String>,
|
||||
is_allowed: impl Fn(&str) -> bool,
|
||||
) -> bool {
|
||||
let mut recognized = false;
|
||||
let allowed = providers::credential_providers()
|
||||
.filter(move |provider| {
|
||||
provider.credential_prefixes.iter().any(|prefix| {
|
||||
value.match_indices(*prefix).any(|(start, _)| {
|
||||
matching::recognized_credential_match(provider, value, virtualized, start)
|
||||
.is_some()
|
||||
})
|
||||
})
|
||||
})
|
||||
.all(|provider| {
|
||||
recognized = true;
|
||||
let actual_sources = provider
|
||||
.sources()
|
||||
.iter()
|
||||
.flat_map(|source| source.env_vars.iter().copied())
|
||||
.filter(|source| {
|
||||
env_value(source_env, source).is_some_and(|source_value| {
|
||||
source_value.len() >= provider.minimum_credential_len
|
||||
&& value.contains(source_value)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let unattributed = provider.credential_prefixes.iter().any(|prefix| {
|
||||
value.match_indices(*prefix).any(|(start, _)| {
|
||||
matching::recognized_credential_match(provider, value, virtualized, start)
|
||||
.is_some_and(|credential| {
|
||||
!actual_sources.iter().any(|source| {
|
||||
env_value(source_env, source).is_some_and(|source_value| {
|
||||
credential == source_value
|
||||
|| credential
|
||||
.strip_prefix(source_value)
|
||||
.is_some_and(|suffix| suffix.starts_with(['_', '-']))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
if actual_sources.is_empty() || unattributed {
|
||||
provider
|
||||
.sources()
|
||||
.iter()
|
||||
.flat_map(|source| source.env_vars.iter().copied())
|
||||
.all(&is_allowed)
|
||||
} else {
|
||||
actual_sources.iter().all(|source| {
|
||||
actual_sources.iter().any(|equivalent| {
|
||||
env_value(source_env, source) == env_value(source_env, equivalent)
|
||||
&& is_allowed(equivalent)
|
||||
})
|
||||
})
|
||||
}
|
||||
});
|
||||
allowed && recognized
|
||||
}
|
||||
|
||||
/// Returns whether an environment key belongs to a supported credential provider.
|
||||
pub fn is_credential_broker_provider_env_key(key: &str) -> bool {
|
||||
providers::credential_providers().any(|provider| {
|
||||
provider
|
||||
.sources()
|
||||
.iter()
|
||||
.flat_map(|source| source.env_vars.iter().copied())
|
||||
.chain(provider.context_env_vars.iter().copied())
|
||||
.any(|candidate| env_key_matches(key, candidate))
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns credential keys plus provider context keys already present in an environment with an
|
||||
/// active broker.
|
||||
pub fn brokered_credential_env_keys(
|
||||
env: &HashMap<String, String>,
|
||||
) -> impl Iterator<Item = &'static str> {
|
||||
let active = env_value(env, CREDENTIAL_BROKER_ACTIVE_ENV_KEY).is_some_and(|value| value == "1");
|
||||
let mut keys = Vec::new();
|
||||
if active {
|
||||
if let Some(aws_keys) = crate::aws_sigv4::snapshot_env_keys(env) {
|
||||
keys.extend(aws_keys);
|
||||
}
|
||||
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()
|
||||
}
|
||||
541
codex-rs/network-proxy/src/credential_broker/matching.rs
Normal file
541
codex-rs/network-proxy/src/credential_broker/matching.rs
Normal file
@@ -0,0 +1,541 @@
|
||||
use super::CredentialBrokerState;
|
||||
use super::MIN_EMBEDDED_CREDENTIAL_LENGTH;
|
||||
use super::env_key_matches;
|
||||
use super::env_value;
|
||||
use super::prioritized_credentials;
|
||||
use super::providers;
|
||||
use super::registry::BrokeredCredentialProvider;
|
||||
use super::registry::is_builtin_shaped_credential;
|
||||
use super::replacement::Replacements;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use url::Position;
|
||||
use url::Url;
|
||||
|
||||
pub(super) struct KnownCredentialMatch<'a> {
|
||||
pub(super) range: std::ops::Range<usize>,
|
||||
pub(super) env_var: &'a str,
|
||||
pub(super) provider: BrokeredCredentialProvider,
|
||||
pub(super) real_value: &'a str,
|
||||
pub(super) value: &'a str,
|
||||
}
|
||||
|
||||
pub(super) fn known_credential_matches<'a>(
|
||||
state: &'a CredentialBrokerState,
|
||||
text: &str,
|
||||
source_env: &'a HashMap<String, String>,
|
||||
) -> Vec<KnownCredentialMatch<'a>> {
|
||||
let mut matches = Vec::new();
|
||||
let mut add = |env_var: &'a str,
|
||||
provider: &BrokeredCredentialProvider,
|
||||
real_value: &'a str,
|
||||
value: &'a str| {
|
||||
if value.is_empty() {
|
||||
return;
|
||||
}
|
||||
let ranges = if text == value {
|
||||
std::iter::once(0..value.len()).collect()
|
||||
} else if value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
&& (is_builtin_shaped_credential(real_value)
|
||||
|| matches!(provider, BrokeredCredentialProvider::Builtin(_)))
|
||||
{
|
||||
text.match_indices(value)
|
||||
.map(|(start, _)| start..start + value.len())
|
||||
.collect()
|
||||
} else if let BrokeredCredentialProvider::Configured(provider) = provider {
|
||||
// Configured short values retain their pattern boundaries and path exclusions.
|
||||
provider
|
||||
.credential_value_match_ranges(text, value)
|
||||
.into_iter()
|
||||
.filter(|range| {
|
||||
value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| !is_operational_path_match(text, range.start, range.end)
|
||||
// A complete longer configured token still needs its own source permission.
|
||||
&& !provider.find_discoverable_credentials(text).any(|candidate| {
|
||||
candidate.range.start <= range.start && candidate.range.end > range.end
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
matches.extend(ranges.into_iter().map(|range| KnownCredentialMatch {
|
||||
range,
|
||||
env_var,
|
||||
provider: provider.clone(),
|
||||
real_value,
|
||||
value,
|
||||
}));
|
||||
};
|
||||
for credential in &state.credentials {
|
||||
for value in [&credential.real_value, &credential.dummy_value] {
|
||||
add(
|
||||
&credential.env_var,
|
||||
&credential.provider,
|
||||
&credential.real_value,
|
||||
value,
|
||||
);
|
||||
}
|
||||
}
|
||||
for provider in super::credential_provider_definitions(state) {
|
||||
let owns_key = |key: &str| match &provider {
|
||||
BrokeredCredentialProvider::Builtin(provider) => {
|
||||
provider.sources().iter().any(|source| {
|
||||
source
|
||||
.env_vars
|
||||
.iter()
|
||||
.any(|source| env_key_matches(source, key))
|
||||
})
|
||||
}
|
||||
BrokeredCredentialProvider::Configured(provider) => provider
|
||||
.config
|
||||
.env
|
||||
.iter()
|
||||
.any(|source| env_key_matches(source, key)),
|
||||
};
|
||||
for owner in &state.credential_owners {
|
||||
if owns_key(&owner.env_var) {
|
||||
add(
|
||||
&owner.env_var,
|
||||
&provider,
|
||||
&owner.real_value,
|
||||
&owner.real_value,
|
||||
);
|
||||
}
|
||||
}
|
||||
for key in source_env.keys() {
|
||||
if owns_key(key)
|
||||
&& let Some(real) =
|
||||
super::brokerable_credential_value(source_env, state, key, &provider)
|
||||
{
|
||||
add(key, &provider, real, real);
|
||||
}
|
||||
}
|
||||
}
|
||||
for credential in &state.credentials {
|
||||
matches.extend(
|
||||
credential
|
||||
.generated_dummy_ranges(text)
|
||||
.into_iter()
|
||||
.map(|range| KnownCredentialMatch {
|
||||
range,
|
||||
env_var: &credential.env_var,
|
||||
provider: credential.provider.clone(),
|
||||
real_value: &credential.real_value,
|
||||
value: &credential.dummy_value,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Longest exact identities win over overlapping shorter identities, as in replacement.
|
||||
matches.sort_unstable_by_key(|matched| {
|
||||
(std::cmp::Reverse(matched.range.len()), matched.range.start)
|
||||
});
|
||||
let mut selected = Vec::<KnownCredentialMatch<'_>>::new();
|
||||
for matched in matches {
|
||||
if selected.iter().any(|known| {
|
||||
known.range.start < matched.range.end
|
||||
&& matched.range.start < known.range.end
|
||||
&& (known.range != matched.range
|
||||
|| known.provider.same_provider(&matched.provider)
|
||||
&& env_key_matches(known.env_var, matched.env_var)
|
||||
&& known.real_value == matched.real_value)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
selected.push(matched);
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
pub(super) fn mask_known_credentials(text: &str, matches: &[KnownCredentialMatch<'_>]) -> String {
|
||||
let mut uncovered = text.to_string();
|
||||
for matched in matches {
|
||||
uncovered.replace_range(matched.range.clone(), &"\0".repeat(matched.range.len()));
|
||||
}
|
||||
uncovered
|
||||
}
|
||||
|
||||
pub(super) fn virtualize_text(
|
||||
state: &CredentialBrokerState,
|
||||
output: &mut String,
|
||||
env: &HashMap<String, String>,
|
||||
) -> bool {
|
||||
if !state.enabled {
|
||||
return true;
|
||||
}
|
||||
|
||||
let allowed_keys = state.environment(env).credential_keys;
|
||||
let credentials = prioritized_credentials(state, env);
|
||||
let text = output.as_str();
|
||||
let source_env = HashMap::new();
|
||||
let known = known_credential_matches(state, text, &source_env);
|
||||
let mut replacements = Replacements::default();
|
||||
let binding_env = state.context.with_fallbacks(env);
|
||||
let mut allowed = true;
|
||||
for credential in &credentials {
|
||||
let ranges = known
|
||||
.iter()
|
||||
.filter(|matched| {
|
||||
matched.provider.same_provider(&credential.provider)
|
||||
&& env_key_matches(matched.env_var, &credential.env_var)
|
||||
&& matched.real_value == credential.real_value
|
||||
&& (matched.value == credential.real_value
|
||||
|| matched.value == credential.dummy_value)
|
||||
})
|
||||
.map(|matched| matched.range.clone())
|
||||
.collect::<Vec<_>>();
|
||||
if ranges.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let replacement = credentials.iter().copied().find(|candidate| {
|
||||
candidate.provider.same_provider(&credential.provider)
|
||||
&& candidate.real_value == credential.real_value
|
||||
&& (allowed_keys.iter().any(|key| {
|
||||
env_key_matches(key, &candidate.env_var)
|
||||
&& env_value(env, key) == Some(candidate.dummy_value.as_str())
|
||||
}) || state.credential_aliases.iter().any(|alias| {
|
||||
env_value(env, &alias.env_var) == Some(alias.dummy_value.as_str())
|
||||
&& (alias.dummy_value == candidate.dummy_value
|
||||
|| candidate.contains_embedded_value(
|
||||
&alias.dummy_value,
|
||||
&candidate.dummy_value,
|
||||
))
|
||||
&& !state.credentials.iter().any(|other| {
|
||||
other.dummy_value != candidate.dummy_value
|
||||
&& (alias.dummy_value == other.dummy_value
|
||||
|| other.contains_embedded_value(
|
||||
&alias.dummy_value,
|
||||
&other.dummy_value,
|
||||
))
|
||||
})
|
||||
}))
|
||||
});
|
||||
if replacement.is_none() {
|
||||
allowed = false;
|
||||
}
|
||||
replacements.add(
|
||||
ranges,
|
||||
replacement.map_or("", |candidate| candidate.dummy_value.as_str()),
|
||||
replacement,
|
||||
);
|
||||
}
|
||||
|
||||
let original = text;
|
||||
let mut uncovered = replacements.masked(original);
|
||||
let text = &mut uncovered;
|
||||
// Startup can copy a supported credential before unsetting its source variable.
|
||||
for provider in providers::credential_providers() {
|
||||
for prefix in provider.credential_prefixes {
|
||||
let mut offset = 0;
|
||||
while let Some(position) = text[offset..].find(prefix) {
|
||||
let start = offset + position;
|
||||
if let Some(length) = state
|
||||
.credentials
|
||||
.iter()
|
||||
.flat_map(|credential| {
|
||||
[&credential.real_value, &credential.dummy_value]
|
||||
.map(|value| (credential, value))
|
||||
})
|
||||
.filter(|(_, value)| text[start..].starts_with(value.as_str()))
|
||||
.filter(|(credential, value)| {
|
||||
value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| matches!(&credential.provider, BrokeredCredentialProvider::Configured(provider)
|
||||
if provider.credential_value_match_ranges(text, value)
|
||||
.iter().any(|range| range.start == start
|
||||
&& !is_operational_path_match(text, range.start, range.end)))
|
||||
})
|
||||
.map(|(_, value)| value.len())
|
||||
.max()
|
||||
{
|
||||
offset = start + length;
|
||||
continue;
|
||||
}
|
||||
let candidate = builtin_credential_candidate(provider, text, start);
|
||||
let length = candidate.len();
|
||||
if provider
|
||||
.ignored_credential_prefixes
|
||||
.iter()
|
||||
.any(|prefix| candidate.starts_with(prefix))
|
||||
&& provider
|
||||
.credential_watermark
|
||||
.is_none_or(|watermark| !candidate.contains(watermark))
|
||||
{
|
||||
let known_length = env
|
||||
.values()
|
||||
.filter(|known| {
|
||||
known.len() >= provider.minimum_credential_len
|
||||
&& candidate
|
||||
.strip_prefix(known.as_str())
|
||||
.is_some_and(|suffix| {
|
||||
provider.credential_prefixes.iter().any(|prefix| {
|
||||
suffix.match_indices(prefix).any(|(offset, _)| {
|
||||
suffix.len() - offset
|
||||
>= provider.minimum_credential_len
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(String::len)
|
||||
.min();
|
||||
let embedded_supported = provider
|
||||
.credential_prefixes
|
||||
.iter()
|
||||
.flat_map(|prefix| candidate.match_indices(prefix))
|
||||
.filter_map(|(offset, _)| {
|
||||
(offset > 0
|
||||
&& candidate.len() - offset >= provider.minimum_credential_len
|
||||
&& !provider
|
||||
.ignored_credential_prefixes
|
||||
.iter()
|
||||
.any(|ignored| candidate[offset..].starts_with(ignored)))
|
||||
.then_some(offset)
|
||||
})
|
||||
.min();
|
||||
offset = start
|
||||
+ known_length
|
||||
.into_iter()
|
||||
.chain(embedded_supported)
|
||||
.min()
|
||||
.unwrap_or(length);
|
||||
continue;
|
||||
}
|
||||
let end = start + length;
|
||||
let credential = &text[start..end];
|
||||
let ignored_credential_match =
|
||||
ignored_credential_match(provider, text, start, credential);
|
||||
if length >= provider.minimum_credential_len && !ignored_credential_match {
|
||||
replacements.add(std::iter::once(start..end), "", /*dummy*/ None);
|
||||
text.replace_range(start..end, &"\0".repeat(length));
|
||||
offset = end;
|
||||
allowed = false;
|
||||
} else {
|
||||
offset = start
|
||||
+ if ignored_credential_match {
|
||||
prefix.len()
|
||||
} else {
|
||||
length
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for provider in &state.configured_providers {
|
||||
if provider.host_binding(&binding_env).is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut matches = provider
|
||||
.find_credential_matches(text)
|
||||
.map(|matched| (matched.start, matched.end))
|
||||
.collect::<Vec<_>>();
|
||||
matches.sort_unstable_by_key(|(start, end)| (std::cmp::Reverse(end - start), *start));
|
||||
matches.dedup();
|
||||
let mut removed_ranges = Vec::<(usize, usize)>::new();
|
||||
for (start, end) in matches {
|
||||
let credential = &text[start..end];
|
||||
if credential.contains('\0')
|
||||
|| !provider
|
||||
.credential_value_match_ranges(original, credential)
|
||||
.contains(&(start..end))
|
||||
|| is_operational_path_match(original, start, end)
|
||||
|| state
|
||||
.credentials
|
||||
.iter()
|
||||
.flat_map(|known| [&known.real_value, &known.dummy_value])
|
||||
.flat_map(|known| {
|
||||
text.match_indices(known)
|
||||
.map(move |(index, _)| (index, known))
|
||||
})
|
||||
.any(|(index, known)| index <= start && end <= index + known.len())
|
||||
|| provider
|
||||
.config
|
||||
.env
|
||||
.iter()
|
||||
.any(|key| env_value(env, key).is_some_and(|value| value == credential))
|
||||
|| removed_ranges.iter().any(|(removed_start, removed_end)| {
|
||||
start < *removed_end && *removed_start < end
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
removed_ranges.push((start, end));
|
||||
allowed = false;
|
||||
}
|
||||
removed_ranges.sort_unstable_by_key(|(start, _)| std::cmp::Reverse(*start));
|
||||
for (start, end) in removed_ranges {
|
||||
replacements.add(std::iter::once(start..end), "", /*dummy*/ None);
|
||||
text.replace_range(start..end, &"\0".repeat(end - start));
|
||||
}
|
||||
}
|
||||
|
||||
replacements.render(output);
|
||||
allowed
|
||||
}
|
||||
|
||||
pub(super) fn is_operational_path_match(text: &str, start: usize, end: usize) -> bool {
|
||||
let is_value_boundary = |character: char| {
|
||||
character.is_ascii_whitespace() || matches!(character, '"' | '\'' | '=' | '`')
|
||||
};
|
||||
let value_start = text[..start]
|
||||
.rfind(is_value_boundary)
|
||||
.map_or(0, |index| index + 1);
|
||||
let value_end = text[end..]
|
||||
.find(is_value_boundary)
|
||||
.map_or(text.len(), |index| end + index);
|
||||
let value = &text[value_start..value_end];
|
||||
if let Ok(url) = Url::parse(value)
|
||||
&& url.has_host()
|
||||
{
|
||||
let relative_start = start - value_start;
|
||||
let relative_end = end - value_start;
|
||||
return relative_start >= url[..Position::BeforeHost].len()
|
||||
&& relative_end <= url[..Position::AfterPort].len();
|
||||
}
|
||||
|
||||
let relative_start = start - value_start;
|
||||
let relative_end = end - value_start;
|
||||
if !value[..relative_start].contains(['/', '\\'])
|
||||
&& !value[relative_end..].contains(['/', '\\'])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let path = Path::new(value);
|
||||
path.has_root() || path.components().count() > 1 || value.contains('\\')
|
||||
}
|
||||
|
||||
fn ignored_credential_match(
|
||||
provider: &providers::CredentialProvider,
|
||||
text: &str,
|
||||
start: usize,
|
||||
credential: &str,
|
||||
) -> bool {
|
||||
provider
|
||||
.ignored_credential_prefixes
|
||||
.iter()
|
||||
.any(|prefix| credential.starts_with(prefix))
|
||||
&& provider
|
||||
.credential_watermark
|
||||
.is_none_or(|watermark| !credential.contains(watermark))
|
||||
|| credential.starts_with("sk-")
|
||||
&& provider
|
||||
.credential_watermark
|
||||
.is_none_or(|watermark| !credential.contains(watermark))
|
||||
&& credential[3..].split(['-', '_']).any(|segment| {
|
||||
segment.len() == 64
|
||||
&& segment.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
&& credential
|
||||
.find(segment)
|
||||
.is_some_and(|offset| offset < provider.minimum_credential_len)
|
||||
})
|
||||
&& text[..start]
|
||||
.rsplit(|character: char| {
|
||||
character.is_ascii() && !character.is_ascii_alphanumeric()
|
||||
})
|
||||
.next()
|
||||
.is_some_and(|word| {
|
||||
((1..=3).contains(&word.len())
|
||||
|| word
|
||||
.get(word.len().saturating_sub(2)..)
|
||||
.is_some_and(|suffix| {
|
||||
suffix.eq_ignore_ascii_case("di")
|
||||
|| suffix.eq_ignore_ascii_case("ta")
|
||||
&& !word.eq_ignore_ascii_case("data")
|
||||
})
|
||||
|| credential.strip_prefix("sk-").is_some_and(|hash| {
|
||||
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}))
|
||||
&& word.bytes().all(|byte| byte.is_ascii_alphabetic())
|
||||
&& text[..start]
|
||||
.rsplit_once(['/', '\\'])
|
||||
.is_some_and(|(_, component)| {
|
||||
component.chars().all(|character| {
|
||||
!character.is_ascii()
|
||||
|| character.is_ascii_alphanumeric()
|
||||
|| matches!(character, '_' | '-')
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn recognized_credential_match<'a>(
|
||||
provider: &providers::CredentialProvider,
|
||||
value: &'a str,
|
||||
virtualized: &str,
|
||||
start: usize,
|
||||
) -> Option<&'a str> {
|
||||
let credential = builtin_credential_candidate(provider, value, start);
|
||||
let length = credential.len();
|
||||
let enclosing_start = value.as_bytes()[..start]
|
||||
.iter()
|
||||
.rposition(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-'))
|
||||
.map_or(0, |offset| offset + 1);
|
||||
let enclosing = &value[enclosing_start..start + length];
|
||||
(length >= provider.minimum_credential_len || !virtualized.contains(credential))
|
||||
.then_some(credential)
|
||||
.filter(|credential| !ignored_credential_match(provider, value, start, credential))
|
||||
.filter(|_| {
|
||||
!provider.ignored_credential_prefixes.iter().any(|prefix| {
|
||||
enclosing.match_indices(prefix).any(|(offset, _)| {
|
||||
let ignored = &enclosing[offset..];
|
||||
offset <= start - enclosing_start
|
||||
&& ignored_credential_match(
|
||||
provider,
|
||||
value,
|
||||
enclosing_start + offset,
|
||||
ignored,
|
||||
)
|
||||
&& virtualized.contains(ignored)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn builtin_credential_candidate<'a>(
|
||||
provider: &providers::CredentialProvider,
|
||||
value: &'a str,
|
||||
start: usize,
|
||||
) -> &'a str {
|
||||
let mut length = value.as_bytes()[start..]
|
||||
.iter()
|
||||
.take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
|
||||
.count();
|
||||
let candidate = &value[start..start + length];
|
||||
let current_prefix_len = provider
|
||||
.credential_prefixes
|
||||
.iter()
|
||||
.filter(|prefix| candidate.starts_with(**prefix))
|
||||
.map(|prefix| prefix.len())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if let Some(separator) = providers::credential_providers()
|
||||
.flat_map(|candidate_provider| {
|
||||
candidate_provider
|
||||
.credential_prefixes
|
||||
.iter()
|
||||
.map(move |prefix| (prefix, candidate_provider.minimum_credential_len))
|
||||
})
|
||||
.filter_map(|(candidate_prefix, minimum_length)| {
|
||||
candidate[current_prefix_len..]
|
||||
.match_indices(*candidate_prefix)
|
||||
.find_map(|(offset, _)| {
|
||||
let offset = current_prefix_len + offset;
|
||||
(matches!(candidate.as_bytes()[offset - 1], b'_' | b'-')
|
||||
&& offset > provider.minimum_credential_len
|
||||
&& candidate.len() - offset >= minimum_length)
|
||||
.then_some(offset - 1)
|
||||
})
|
||||
})
|
||||
.min()
|
||||
{
|
||||
length = separator;
|
||||
}
|
||||
let candidate = &value[start..start + length];
|
||||
if value.as_bytes().get(start + length) == Some(&b'\0') {
|
||||
// A masked known span may follow an alias separator, not part of this builtin token.
|
||||
candidate.trim_end_matches(['_', '-'])
|
||||
} else {
|
||||
candidate
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// Declarative description of an environment-backed credential family.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct CredentialProviderConfig {
|
||||
pub env: Vec<String>,
|
||||
pub patterns: Vec<String>,
|
||||
/// URL prefixes authorized for injection. Bare loopback hosts imply HTTP; other bare hosts
|
||||
/// imply HTTPS.
|
||||
pub url_prefixes: Vec<String>,
|
||||
/// Environment variable containing an additional URL prefix or hostname.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url_prefix_from_env: Option<String>,
|
||||
pub auth: Vec<CredentialAuthMethod>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub header: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub prefix: Option<String>,
|
||||
}
|
||||
|
||||
impl CredentialProviderConfig {
|
||||
/// Validate a complete provider definition using the broker's compilation rules.
|
||||
pub fn validate(&self, id: &str) -> anyhow::Result<()> {
|
||||
super::configured::ConfiguredCredentialProvider::compile(id, self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Authentication formats supported by declarative credential providers.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CredentialAuthMethod {
|
||||
Bearer,
|
||||
Token,
|
||||
Basic,
|
||||
Header,
|
||||
}
|
||||
215
codex-rs/network-proxy/src/credential_broker/providers.rs
Normal file
215
codex-rs/network-proxy/src/credential_broker/providers.rs
Normal file
@@ -0,0 +1,215 @@
|
||||
mod github;
|
||||
mod openai;
|
||||
|
||||
use super::destination::CredentialDestination;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rand::Rng as _;
|
||||
use std::collections::HashMap;
|
||||
use url::Url;
|
||||
|
||||
const DUMMY_ALPHANUMERIC: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
type TranslateRequestHeader = fn(&HeaderMap, &str, &str) -> Option<HeaderValue>;
|
||||
|
||||
/// Describes how one credential family is recognized and injected.
|
||||
///
|
||||
/// Providers must be declared as `static` values because the broker uses their addresses as stable
|
||||
/// identities when deduplicating credential records.
|
||||
pub(super) struct CredentialProvider {
|
||||
pub(super) context_env_vars: &'static [&'static str],
|
||||
pub(super) credential_prefixes: &'static [&'static str],
|
||||
pub(super) ignored_credential_prefixes: &'static [&'static str],
|
||||
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>,
|
||||
insert_request_header: fn(&mut HeaderMap, HeaderValue),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub(super) enum CredentialHostBinding {
|
||||
ExactHost(String),
|
||||
ExactHosts(Vec<String>),
|
||||
HostPattern {
|
||||
exact_hosts: &'static [&'static str],
|
||||
suffixes: &'static [&'static str],
|
||||
},
|
||||
ConfiguredHosts(Vec<CredentialDestination>),
|
||||
}
|
||||
|
||||
pub(super) struct CredentialSource {
|
||||
pub(super) env_vars: &'static [&'static str],
|
||||
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>,
|
||||
}
|
||||
|
||||
const CREDENTIAL_PROVIDERS: &[&CredentialProvider] = &[&github::PROVIDER, &openai::PROVIDER];
|
||||
|
||||
impl CredentialProvider {
|
||||
pub(super) fn sources(&self) -> &[CredentialSource] {
|
||||
self.sources
|
||||
}
|
||||
|
||||
pub(super) fn dummy_value(&self, real_value: &str) -> String {
|
||||
(self.dummy_value)(real_value)
|
||||
}
|
||||
|
||||
pub(super) fn translate_request_header(
|
||||
&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> {
|
||||
(self.request_header_value)(value)
|
||||
}
|
||||
|
||||
pub(super) fn insert_request_header(&self, headers: &mut HeaderMap, value: HeaderValue) {
|
||||
(self.insert_request_header)(headers, value);
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialHostBinding {
|
||||
pub(super) fn bypasses_proxy_with_local_binding(&self) -> bool {
|
||||
use crate::policy::is_default_proxy_bypass_host;
|
||||
|
||||
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)),
|
||||
Self::ConfiguredHosts(destinations) => destinations
|
||||
.iter()
|
||||
.any(CredentialDestination::bypasses_proxy_with_local_binding),
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
} => {
|
||||
exact_hosts.contains(&host) || suffixes.iter().any(|suffix| host.ends_with(suffix))
|
||||
}
|
||||
Self::ConfiguredHosts(destinations) => destinations
|
||||
.iter()
|
||||
.any(|destination| destination.matches_host(host, port)),
|
||||
}
|
||||
}
|
||||
|
||||
// Hooks apply to the host regardless of each credential destination's port or path.
|
||||
pub(super) fn matches_hostname(&self, host: &str) -> bool {
|
||||
match self {
|
||||
Self::ConfiguredHosts(destinations) => destinations
|
||||
.iter()
|
||||
.any(|destination| destination.matches_hostname(host)),
|
||||
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
|
||||
self.matches_host(host, /*port*/ 443)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn requires_mitm(&self, host: &str, port: u16) -> bool {
|
||||
match self {
|
||||
Self::ConfiguredHosts(destinations) => destinations
|
||||
.iter()
|
||||
.any(|destination| destination.requires_mitm(host, port)),
|
||||
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
|
||||
self.matches_host(host, port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn matches_request(&self, host: &str, request: Option<&Url>) -> bool {
|
||||
match self {
|
||||
Self::ConfiguredHosts(destinations) => destinations
|
||||
.iter()
|
||||
.any(|destination| destination.matches_request(host, request)),
|
||||
Self::ExactHost(_) | Self::ExactHosts(_) | Self::HostPattern { .. } => {
|
||||
request.is_none_or(|request| request.scheme() == "https")
|
||||
&& self.matches_host(
|
||||
host,
|
||||
request.and_then(Url::port_or_known_default).unwrap_or(443),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn credential_context_env_keys(
|
||||
brokered_keys: &[String],
|
||||
) -> impl Iterator<Item = &'static str> + '_ {
|
||||
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())
|
||||
}
|
||||
|
||||
pub(super) fn credential_binding_env_keys(
|
||||
brokered_keys: &[String],
|
||||
) -> impl Iterator<Item = &'static str> + '_ {
|
||||
credential_providers()
|
||||
.flat_map(CredentialProvider::sources)
|
||||
.filter(move |source| {
|
||||
source.env_vars.iter().any(|key| {
|
||||
brokered_keys
|
||||
.iter()
|
||||
.any(|brokered_key| super::env_key_matches(brokered_key, key))
|
||||
})
|
||||
})
|
||||
.flat_map(|source| source.binding_env_vars.iter().copied())
|
||||
}
|
||||
|
||||
pub(super) fn credential_env_keys() -> impl Iterator<Item = &'static str> {
|
||||
credential_providers()
|
||||
.flat_map(CredentialProvider::sources)
|
||||
.flat_map(|source| source.env_vars.iter().copied())
|
||||
}
|
||||
|
||||
pub(super) fn credential_providers() -> impl Iterator<Item = &'static CredentialProvider> {
|
||||
CREDENTIAL_PROVIDERS.iter().copied()
|
||||
}
|
||||
|
||||
pub(super) fn translate_standard_request_header(
|
||||
headers: &HeaderMap,
|
||||
expected_value: &str,
|
||||
replacement_value: &str,
|
||||
) -> Option<HeaderValue> {
|
||||
github::translate_request_header(headers, expected_value, replacement_value)
|
||||
}
|
||||
|
||||
fn shaped_dummy_value(real_value: &str, prefix: &str, minimum_len: usize) -> String {
|
||||
let mut dummy = format!("{prefix}masked");
|
||||
// Keep over 128 bits of randomness after the visible marker.
|
||||
let target_len = real_value.len().max(minimum_len).max(dummy.len() + 22);
|
||||
dummy.reserve(target_len - dummy.len());
|
||||
let mut rng = rand::rng();
|
||||
for _ in dummy.len()..target_len {
|
||||
let character = DUMMY_ALPHANUMERIC[rng.random_range(0..DUMMY_ALPHANUMERIC.len())];
|
||||
dummy.push(char::from(character));
|
||||
}
|
||||
dummy
|
||||
}
|
||||
171
codex-rs/network-proxy/src/credential_broker/providers/github.rs
Normal file
171
codex-rs/network-proxy/src/credential_broker/providers/github.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
use super::super::env_value;
|
||||
use super::CredentialHostBinding;
|
||||
use super::CredentialProvider;
|
||||
use super::CredentialSource;
|
||||
use super::shaped_dummy_value;
|
||||
use crate::policy::normalize_host;
|
||||
use base64::Engine as _;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::header::AUTHORIZATION;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const GH_HOST_ENV_VAR: &str = "GH_HOST";
|
||||
const GITHUB_TOKEN_PREFIXES: &[&str] = &["github_pat_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_"];
|
||||
const GITHUB_TOKEN_MIN_LEN: usize = 40;
|
||||
const GITHUB_CLOUD_TOKEN_ENV_VARS: &[&str] = &["GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GITHUB_ENTERPRISE_TOKEN_ENV_VARS: &[&str] =
|
||||
&["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
|
||||
const GITHUB_CLOUD_HOSTS: &[&str] = &["api.github.com", "github.com", "uploads.github.com"];
|
||||
const GITHUB_CLOUD_HOST_SUFFIXES: &[&str] = &[".ghe.com"];
|
||||
|
||||
pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
|
||||
context_env_vars: &[GH_HOST_ENV_VAR],
|
||||
credential_prefixes: GITHUB_TOKEN_PREFIXES,
|
||||
ignored_credential_prefixes: &[],
|
||||
credential_watermark: None,
|
||||
minimum_credential_len: GITHUB_TOKEN_MIN_LEN,
|
||||
sources: &[
|
||||
CredentialSource {
|
||||
env_vars: GITHUB_CLOUD_TOKEN_ENV_VARS,
|
||||
binding_env_vars: &[],
|
||||
invalidates_host_binding: |_| false,
|
||||
host_binding: github_cloud_binding,
|
||||
},
|
||||
CredentialSource {
|
||||
env_vars: GITHUB_ENTERPRISE_TOKEN_ENV_VARS,
|
||||
binding_env_vars: &[GH_HOST_ENV_VAR],
|
||||
invalidates_host_binding: |env| {
|
||||
env_value(env, GH_HOST_ENV_VAR).is_some()
|
||||
&& github_host_hint(env).is_none_or(|host| github_cloud_host(&host))
|
||||
},
|
||||
host_binding: github_enterprise_binding,
|
||||
},
|
||||
],
|
||||
reset_on_configuration_change: false,
|
||||
dummy_value,
|
||||
translate_request_header,
|
||||
request_header_value,
|
||||
insert_request_header,
|
||||
};
|
||||
|
||||
fn dummy_value(real_value: &str) -> String {
|
||||
shaped_dummy_value(
|
||||
real_value,
|
||||
github_token_prefix(real_value),
|
||||
GITHUB_TOKEN_MIN_LEN,
|
||||
)
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
pub(super) 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 mut translated = Vec::with_capacity(decoded.len() + replacement_value.len());
|
||||
if decoded == expected_value.as_bytes() {
|
||||
translated.extend_from_slice(replacement_value.as_bytes());
|
||||
} else {
|
||||
let separator = decoded.iter().position(|byte| *byte == b':')?;
|
||||
let username = &decoded[..separator];
|
||||
let password = &decoded[separator + 1..];
|
||||
if username != expected_value.as_bytes() && password != expected_value.as_bytes() {
|
||||
return None;
|
||||
}
|
||||
translated.extend_from_slice(if username == expected_value.as_bytes() {
|
||||
replacement_value.as_bytes()
|
||||
} else {
|
||||
username
|
||||
});
|
||||
translated.push(b':');
|
||||
translated.extend_from_slice(if password == expected_value.as_bytes() {
|
||||
replacement_value.as_bytes()
|
||||
} else {
|
||||
password
|
||||
});
|
||||
}
|
||||
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 {
|
||||
exact_hosts: GITHUB_CLOUD_HOSTS,
|
||||
suffixes: GITHUB_CLOUD_HOST_SUFFIXES,
|
||||
})
|
||||
}
|
||||
|
||||
fn github_enterprise_binding(
|
||||
env: &HashMap<String, String>,
|
||||
_: Option<&str>,
|
||||
) -> Option<CredentialHostBinding> {
|
||||
github_host_hint(env)
|
||||
.filter(|host| !github_cloud_host(host))
|
||||
.map(CredentialHostBinding::ExactHost)
|
||||
}
|
||||
|
||||
fn github_cloud_host(host: &str) -> bool {
|
||||
GITHUB_CLOUD_HOSTS.contains(&host)
|
||||
|| GITHUB_CLOUD_HOST_SUFFIXES
|
||||
.iter()
|
||||
.any(|suffix| host.ends_with(suffix))
|
||||
}
|
||||
|
||||
fn github_token_prefix(value: &str) -> &str {
|
||||
GITHUB_TOKEN_PREFIXES
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|prefix| value.starts_with(prefix))
|
||||
.unwrap_or("ghp_")
|
||||
}
|
||||
|
||||
fn github_host_hint(env: &HashMap<String, String>) -> Option<String> {
|
||||
let value = env_value(env, GH_HOST_ENV_VAR)?.trim();
|
||||
if value.is_empty() || value.contains(['/', '\\', '@', '?', '#', '*']) {
|
||||
return None;
|
||||
}
|
||||
let authority = if value.parse::<std::net::IpAddr>().is_ok()
|
||||
|| crate::policy::unscoped_ip_literal(value).is_some()
|
||||
{
|
||||
format!("[{value}]")
|
||||
} else {
|
||||
value.to_string()
|
||||
};
|
||||
let parsed = authority.parse::<rama_http::uri::Authority>().ok()?;
|
||||
let suffix = authority.strip_prefix(parsed.host())?;
|
||||
if !suffix.is_empty() {
|
||||
suffix.strip_prefix(':')?.parse::<u16>().ok()?;
|
||||
}
|
||||
let host = normalize_host(parsed.host());
|
||||
let ip_literal = host.parse::<std::net::IpAddr>().is_ok()
|
||||
|| crate::policy::unscoped_ip_literal(&host).is_some();
|
||||
if !ip_literal && (parsed.host().starts_with('[') || url::Host::parse(&host).is_err()) {
|
||||
return None;
|
||||
}
|
||||
Some(host)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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-")
|
||||
}
|
||||
473
codex-rs/network-proxy/src/credential_broker/registry.rs
Normal file
473
codex-rs/network-proxy/src/credential_broker/registry.rs
Normal file
@@ -0,0 +1,473 @@
|
||||
use super::CredentialBrokerState;
|
||||
use super::CredentialRecord;
|
||||
use super::MIN_EMBEDDED_CREDENTIAL_LENGTH;
|
||||
use super::configured::ConfiguredCredentialProvider;
|
||||
use super::env_entry;
|
||||
use super::env_key_matches;
|
||||
use super::env_value;
|
||||
use super::matching;
|
||||
use super::matching::is_operational_path_match;
|
||||
use super::providers;
|
||||
use super::source_accepts_credential;
|
||||
use super::source_tracks_credential;
|
||||
use crate::policy::normalize_host;
|
||||
use base64::Engine;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderName;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::header::AUTHORIZATION;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) enum BrokeredCredentialProvider {
|
||||
Builtin(&'static providers::CredentialProvider),
|
||||
Configured(Arc<ConfiguredCredentialProvider>),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ActiveCredentialSource {
|
||||
pub(super) provider: BrokeredCredentialProvider,
|
||||
pub(super) host_binding: providers::CredentialHostBinding,
|
||||
pub(super) env_vars: Vec<String>,
|
||||
}
|
||||
|
||||
impl BrokeredCredentialProvider {
|
||||
pub(super) fn same_provider(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Builtin(left), Self::Builtin(right)) => std::ptr::eq(*left, *right),
|
||||
(Self::Configured(left), Self::Configured(right)) => Arc::ptr_eq(left, right),
|
||||
(Self::Builtin(_), Self::Configured(_)) | (Self::Configured(_), Self::Builtin(_)) => {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn dummy_value(&self, real_value: &str) -> Option<String> {
|
||||
match self {
|
||||
Self::Builtin(provider) => Some(provider.dummy_value(real_value)),
|
||||
Self::Configured(provider) => provider.dummy_value(real_value),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn recognizes_credential_in(&self, value: &str) -> bool {
|
||||
match self {
|
||||
Self::Builtin(provider) => provider.credential_prefixes.iter().any(|prefix| {
|
||||
value.match_indices(*prefix).any(|(start, _)| {
|
||||
matching::recognized_credential_match(provider, value, "", start).is_some()
|
||||
})
|
||||
}),
|
||||
Self::Configured(provider) => provider.find_credential_matches(value).next().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn recognizes_strictly_embedded_dummy_collision_in(&self, value: &str) -> bool {
|
||||
match self {
|
||||
Self::Builtin(provider) => provider.credential_prefixes.iter().any(|prefix| {
|
||||
value.match_indices(*prefix).any(|(start, _)| {
|
||||
matching::recognized_credential_match(provider, value, "", start)
|
||||
.is_some_and(|credential| start > 0 || credential.len() < value.len())
|
||||
})
|
||||
}),
|
||||
Self::Configured(provider) => provider.contains_strictly_embedded_pattern_match(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn contains_embedded_value(&self, text: &str, value: &str) -> bool {
|
||||
match self {
|
||||
Self::Builtin(_) => {
|
||||
value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH && text.contains(value)
|
||||
}
|
||||
Self::Configured(provider) => provider
|
||||
.credential_value_match_ranges(text, value)
|
||||
.into_iter()
|
||||
.any(|range| {
|
||||
value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| !is_operational_path_match(text, range.start, range.end)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_header_value(&self, value: &str) -> Option<HeaderValue> {
|
||||
match self {
|
||||
Self::Builtin(provider) => provider.request_header_value(value),
|
||||
Self::Configured(provider) => provider
|
||||
.matches_value(value)
|
||||
.then(|| provider.request_header_value(value))
|
||||
.flatten(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn translate_request_headers(
|
||||
&self,
|
||||
headers: &HeaderMap,
|
||||
expected_value: &str,
|
||||
replacement_value: &str,
|
||||
) -> Vec<(HeaderName, HeaderValue)> {
|
||||
match self {
|
||||
Self::Builtin(provider) => provider
|
||||
.translate_request_header(headers, expected_value, replacement_value)
|
||||
.map(|value| (AUTHORIZATION, value)),
|
||||
Self::Configured(provider) => {
|
||||
return provider.translate_request_headers(
|
||||
headers,
|
||||
expected_value,
|
||||
replacement_value,
|
||||
);
|
||||
}
|
||||
}
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn insert_request_header(
|
||||
&self,
|
||||
headers: &mut HeaderMap,
|
||||
name: HeaderName,
|
||||
value: HeaderValue,
|
||||
) {
|
||||
match self {
|
||||
Self::Builtin(provider) => provider.insert_request_header(headers, value),
|
||||
Self::Configured(_) => {
|
||||
headers.insert(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CredentialRecord {
|
||||
pub(super) fn contains_embedded_value(&self, text: &str, value: &str) -> bool {
|
||||
!self.value_match_ranges(text, value).is_empty()
|
||||
}
|
||||
|
||||
pub(super) fn value_match_ranges(
|
||||
&self,
|
||||
text: &str,
|
||||
value: &str,
|
||||
) -> Vec<std::ops::Range<usize>> {
|
||||
let mut ranges = if text == value {
|
||||
std::iter::once(0..text.len()).collect()
|
||||
} else if is_builtin_shaped_credential(&self.real_value)
|
||||
|| matches!(self.provider, BrokeredCredentialProvider::Builtin(_))
|
||||
&& value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
{
|
||||
text.match_indices(value)
|
||||
.map(|(start, _)| start..start + value.len())
|
||||
.collect()
|
||||
} else if let BrokeredCredentialProvider::Configured(provider) = &self.provider {
|
||||
provider
|
||||
.credential_value_match_ranges(text, value)
|
||||
.into_iter()
|
||||
.filter(|range| {
|
||||
value.len() >= MIN_EMBEDDED_CREDENTIAL_LENGTH
|
||||
|| !is_operational_path_match(text, range.start, range.end)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if value == self.dummy_value {
|
||||
ranges.extend(self.generated_dummy_ranges(text));
|
||||
ranges.sort_by_key(|range| range.start);
|
||||
ranges.dedup();
|
||||
}
|
||||
ranges
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn is_builtin_shaped_credential(value: &str) -> bool {
|
||||
providers::credential_providers().any(|provider| {
|
||||
value.len() >= provider.minimum_credential_len
|
||||
&& provider
|
||||
.credential_prefixes
|
||||
.iter()
|
||||
.any(|prefix| value.starts_with(prefix))
|
||||
&& matching::recognized_credential_match(provider, value, "", /*start*/ 0)
|
||||
.is_some_and(|credential| credential == value)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn select_credentials<'a>(
|
||||
headers: &HeaderMap,
|
||||
destination: &str,
|
||||
credentials: &'a [CredentialRecord],
|
||||
environment_id: Option<&str>,
|
||||
) -> Vec<(&'a CredentialRecord, HeaderName, HeaderValue)> {
|
||||
let request = if destination.contains("://") {
|
||||
let Ok(request) = Url::parse(destination) else {
|
||||
return Vec::new();
|
||||
};
|
||||
Some(request)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let host = normalize_host(
|
||||
request
|
||||
.as_ref()
|
||||
.and_then(Url::host_str)
|
||||
.unwrap_or(destination),
|
||||
);
|
||||
let mut translated_matches = Vec::<(&CredentialRecord, HeaderName, HeaderValue)>::new();
|
||||
for credential in credentials.iter().filter(|credential| {
|
||||
credential.belongs_to_environment(environment_id)
|
||||
&& credential
|
||||
.host_bindings()
|
||||
.any(|binding| binding.matches_request(&host, request.as_ref()))
|
||||
}) {
|
||||
for candidate in credentials.iter().filter(|candidate| {
|
||||
candidate.belongs_to_environment(environment_id)
|
||||
&& candidate.provider.same_provider(&credential.provider)
|
||||
&& candidate.real_value == credential.real_value
|
||||
&& candidate
|
||||
.host_bindings()
|
||||
.any(|binding| binding.matches_request(&host, request.as_ref()))
|
||||
}) {
|
||||
for (name, value) in credential.provider.translate_request_headers(
|
||||
headers,
|
||||
&candidate.dummy_value,
|
||||
&credential.real_value,
|
||||
) {
|
||||
if !translated_matches
|
||||
.iter()
|
||||
.any(|(existing, header, translated)| {
|
||||
existing.provider.same_provider(&credential.provider)
|
||||
&& existing.real_value == credential.real_value
|
||||
&& *header == name
|
||||
&& *translated == value
|
||||
})
|
||||
{
|
||||
translated_matches.push((credential, name, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut selected = Vec::<(&CredentialRecord, HeaderName, HeaderValue)>::new();
|
||||
let mut ambiguous_headers = Vec::<HeaderName>::new();
|
||||
for (credential, header_name, header_value) in translated_matches {
|
||||
if ambiguous_headers.contains(&header_name) {
|
||||
continue;
|
||||
}
|
||||
let Some(existing) = selected
|
||||
.iter()
|
||||
.position(|(_, selected_header, _)| selected_header == header_name)
|
||||
else {
|
||||
selected.push((credential, header_name, header_value));
|
||||
continue;
|
||||
};
|
||||
if !credential
|
||||
.provider
|
||||
.same_provider(&selected[existing].0.provider)
|
||||
|| credential.real_value != selected[existing].0.real_value
|
||||
|| header_value != selected[existing].2
|
||||
{
|
||||
if header_name == AUTHORIZATION
|
||||
&& let Some(merged) = headers.get(AUTHORIZATION).and_then(|original| {
|
||||
merge_basic_auth_fields(original, &selected[existing].2, &header_value)
|
||||
})
|
||||
{
|
||||
// Keep configured-provider raw-path validation for either field.
|
||||
if matches!(
|
||||
credential.provider,
|
||||
BrokeredCredentialProvider::Configured(_)
|
||||
) {
|
||||
selected[existing].0 = credential;
|
||||
}
|
||||
selected[existing].2 = merged;
|
||||
continue;
|
||||
}
|
||||
selected.swap_remove(existing);
|
||||
ambiguous_headers.push(header_name);
|
||||
}
|
||||
}
|
||||
if selected.iter().any(|(credential, _, _)| {
|
||||
matches!(
|
||||
&credential.provider,
|
||||
BrokeredCredentialProvider::Configured(_)
|
||||
)
|
||||
}) && let Some(request) = request.as_ref()
|
||||
{
|
||||
let Ok(raw_request) = destination.parse::<rama_http::Uri>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let raw_path = raw_request.path();
|
||||
if raw_path != request.path()
|
||||
|| !crate::authorization_path::is_safe_for_authorization(raw_path)
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
fn merge_basic_auth_fields(
|
||||
original: &HeaderValue,
|
||||
left: &HeaderValue,
|
||||
right: &HeaderValue,
|
||||
) -> Option<HeaderValue> {
|
||||
let decode = |header: &HeaderValue| {
|
||||
let (scheme, value) = header.to_str().ok()?.split_once(' ')?;
|
||||
scheme.eq_ignore_ascii_case("basic").then_some(())?;
|
||||
let decoded = base64::engine::general_purpose::STANDARD
|
||||
.decode(value.trim())
|
||||
.ok()?;
|
||||
let separator = decoded.iter().position(|byte| *byte == b':')?;
|
||||
Some((
|
||||
decoded[..separator].to_vec(),
|
||||
decoded[separator + 1..].to_vec(),
|
||||
))
|
||||
};
|
||||
let (original_user, original_password) = decode(original)?;
|
||||
let (left_user, left_password) = decode(left)?;
|
||||
let (right_user, right_password) = decode(right)?;
|
||||
// Only combine independent fields. Overlapping translations remain ambiguous.
|
||||
let (user, password) = if left_user != original_user
|
||||
&& left_password == original_password
|
||||
&& right_user == original_user
|
||||
&& right_password != original_password
|
||||
{
|
||||
(left_user, right_password)
|
||||
} else if right_user != original_user
|
||||
&& right_password == original_password
|
||||
&& left_user == original_user
|
||||
&& left_password != original_password
|
||||
{
|
||||
(right_user, left_password)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let encoded =
|
||||
base64::engine::general_purpose::STANDARD.encode([user, vec![b':'], password].concat());
|
||||
HeaderValue::from_str(&format!("Basic {encoded}")).ok()
|
||||
}
|
||||
|
||||
pub(super) fn active_credential_sources(
|
||||
state: &CredentialBrokerState,
|
||||
env: &HashMap<String, String>,
|
||||
) -> Vec<ActiveCredentialSource> {
|
||||
let binding_env = state.context.with_fallbacks(env);
|
||||
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())
|
||||
{
|
||||
sources.push(ActiveCredentialSource {
|
||||
provider: BrokeredCredentialProvider::Builtin(provider),
|
||||
host_binding,
|
||||
env_vars: source
|
||||
.env_vars
|
||||
.iter()
|
||||
.map(|key| (*key).to_string())
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for provider in &state.configured_providers {
|
||||
if let Some(host_binding) = provider.host_binding(&binding_env) {
|
||||
sources.push(ActiveCredentialSource {
|
||||
provider: BrokeredCredentialProvider::Configured(provider.clone()),
|
||||
host_binding,
|
||||
env_vars: provider.config.env.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
pub(super) fn registered_credential_source(
|
||||
credential: &CredentialRecord,
|
||||
sources: &[ActiveCredentialSource],
|
||||
env: &HashMap<String, String>,
|
||||
) -> Option<ActiveCredentialSource> {
|
||||
let retained_env_vars = match &credential.provider {
|
||||
BrokeredCredentialProvider::Builtin(provider) => provider
|
||||
.sources()
|
||||
.iter()
|
||||
.find(|source| {
|
||||
source
|
||||
.env_vars
|
||||
.iter()
|
||||
.any(|key| env_key_matches(key, &credential.env_var))
|
||||
&& !source.binding_env_vars.is_empty()
|
||||
&& source
|
||||
.binding_env_vars
|
||||
.iter()
|
||||
.all(|key| env_value(env, key).is_none())
|
||||
})
|
||||
.map(|source| {
|
||||
source
|
||||
.env_vars
|
||||
.iter()
|
||||
.map(|key| (*key).to_string())
|
||||
.collect()
|
||||
}),
|
||||
BrokeredCredentialProvider::Configured(provider) => provider
|
||||
.config
|
||||
.url_prefix_from_env
|
||||
.as_deref()
|
||||
.filter(|key| env_value(env, key).is_none())
|
||||
.map(|_| provider.config.env.clone()),
|
||||
};
|
||||
// Filtering a destination hint out of the child must not undo an existing
|
||||
// registration or rebind it to the broker's ambient fallback.
|
||||
if let Some(env_vars) = retained_env_vars {
|
||||
Some(ActiveCredentialSource {
|
||||
provider: credential.provider.clone(),
|
||||
host_binding: credential.host_binding.clone(),
|
||||
env_vars,
|
||||
})
|
||||
} else {
|
||||
sources
|
||||
.iter()
|
||||
.find(|source| source_accepts_credential(source, credential))
|
||||
.cloned()
|
||||
.map(|mut source| {
|
||||
// A new canonical token does not authorize an older alias at its destination.
|
||||
if !credential.invalidates_host_binding(env)
|
||||
&& !source_tracks_credential(&source, credential, env)
|
||||
{
|
||||
source.host_binding = credential.host_binding.clone();
|
||||
}
|
||||
source
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prioritized_credentials<'a>(
|
||||
state: &'a CredentialBrokerState,
|
||||
env: &HashMap<String, String>,
|
||||
) -> Vec<&'a CredentialRecord> {
|
||||
let binding_env = state.context.with_fallbacks(env);
|
||||
let mut credentials = state.credentials.iter().collect::<Vec<_>>();
|
||||
credentials.sort_unstable_by_key(|credential| {
|
||||
let active = env_entry(env, &credential.env_var)
|
||||
.is_some_and(|(_, value)| value == credential.dummy_value);
|
||||
let has_matching_host_binding = match &credential.provider {
|
||||
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())
|
||||
.is_some_and(|binding| binding == credential.host_binding)
|
||||
})
|
||||
}
|
||||
BrokeredCredentialProvider::Configured(provider) => provider
|
||||
.config
|
||||
.url_prefix_from_env
|
||||
.as_deref()
|
||||
.is_some_and(|key| {
|
||||
env_value(&binding_env, key).is_some()
|
||||
&& provider
|
||||
.host_binding(&binding_env)
|
||||
.is_some_and(|binding| binding == credential.host_binding)
|
||||
}),
|
||||
};
|
||||
(
|
||||
std::cmp::Reverse(credential.real_value.len()),
|
||||
std::cmp::Reverse(active),
|
||||
std::cmp::Reverse(has_matching_host_binding),
|
||||
)
|
||||
});
|
||||
credentials
|
||||
}
|
||||
155
codex-rs/network-proxy/src/credential_broker/replacement.rs
Normal file
155
codex-rs/network-proxy/src/credential_broker/replacement.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
use super::CredentialBrokerState;
|
||||
use super::CredentialRecord;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
|
||||
impl CredentialBrokerState {
|
||||
pub(super) fn replace_child_env_dummies(
|
||||
&self,
|
||||
env: &mut HashMap<String, String>,
|
||||
replacements: &[(String, String)],
|
||||
) {
|
||||
if replacements.is_empty() {
|
||||
return;
|
||||
}
|
||||
let credentials = self
|
||||
.credentials
|
||||
.iter()
|
||||
.map(|credential| {
|
||||
let replacement = replacements
|
||||
.iter()
|
||||
.find(|(dummy, _)| *dummy == credential.dummy_value)
|
||||
.map_or(credential.dummy_value.as_str(), |(_, replacement)| {
|
||||
replacement
|
||||
});
|
||||
let target = self
|
||||
.credentials
|
||||
.iter()
|
||||
.find(|candidate| candidate.dummy_value == replacement);
|
||||
(credential, replacement, target)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for value in env.values_mut() {
|
||||
let mut spans = Replacements::default();
|
||||
for (credential, replacement, target) in &credentials {
|
||||
spans.add(
|
||||
credential.value_match_ranges(value, &credential.dummy_value),
|
||||
replacement,
|
||||
*target,
|
||||
);
|
||||
}
|
||||
spans.render(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Retain emitted context without keeping another copy of any real credentials in it.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub(super) struct GeneratedAlias {
|
||||
digest: [u8; 32],
|
||||
len: usize,
|
||||
range: Range<usize>,
|
||||
}
|
||||
|
||||
impl CredentialRecord {
|
||||
pub(super) fn generated_dummy_ranges(&self, text: &str) -> Vec<Range<usize>> {
|
||||
let aliases = self
|
||||
.generated_aliases
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
text.char_indices()
|
||||
.filter(|(start, _)| text[*start..].starts_with(&self.dummy_value))
|
||||
.filter_map(|(start, _)| {
|
||||
aliases
|
||||
.iter()
|
||||
.any(|alias| {
|
||||
start.checked_sub(alias.range.start).is_some_and(|offset| {
|
||||
text.get(offset..offset + alias.len).is_some_and(|context| {
|
||||
<[u8; 32]>::from(Sha256::digest(context)) == alias.digest
|
||||
})
|
||||
})
|
||||
})
|
||||
.then_some(start..start + self.dummy_value.len())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Replacements<'a> {
|
||||
spans: Vec<(Range<usize>, &'a str, Option<&'a CredentialRecord>)>,
|
||||
}
|
||||
|
||||
impl<'a> Replacements<'a> {
|
||||
pub(super) fn add(
|
||||
&mut self,
|
||||
ranges: impl IntoIterator<Item = Range<usize>>,
|
||||
value: &'a str,
|
||||
dummy: Option<&'a CredentialRecord>,
|
||||
) {
|
||||
self.spans
|
||||
.extend(ranges.into_iter().map(|range| (range, value, dummy)));
|
||||
}
|
||||
|
||||
pub(super) fn masked(&self, text: &str) -> String {
|
||||
let mut masked = text.to_string();
|
||||
for (range, _, _) in &self.spans {
|
||||
masked.replace_range(range.clone(), &"\0".repeat(range.len()));
|
||||
}
|
||||
masked
|
||||
}
|
||||
|
||||
pub(super) fn render(mut self, text: &mut String) -> bool {
|
||||
if self.spans.is_empty() {
|
||||
return false;
|
||||
}
|
||||
self.spans
|
||||
.sort_by_key(|(range, _, _)| std::cmp::Reverse(range.len()));
|
||||
let mut selected = Vec::<(Range<usize>, &str, Option<&CredentialRecord>)>::new();
|
||||
for span in self.spans {
|
||||
if !selected
|
||||
.iter()
|
||||
.any(|(range, _, _)| range.start < span.0.end && span.0.start < range.end)
|
||||
{
|
||||
selected.push(span);
|
||||
}
|
||||
}
|
||||
selected.sort_by_key(|(range, _, _)| range.start);
|
||||
let mut output = String::with_capacity(text.len());
|
||||
let mut previous = 0;
|
||||
let mut dummies = Vec::new();
|
||||
for (range, value, dummy) in selected {
|
||||
output.push_str(&text[previous..range.start]);
|
||||
let start = output.len();
|
||||
output.push_str(value);
|
||||
if let Some(dummy) = dummy {
|
||||
dummies.push((dummy, start..output.len()));
|
||||
}
|
||||
previous = range.end;
|
||||
}
|
||||
output.push_str(&text[previous..]);
|
||||
for (dummy, range) in dummies {
|
||||
if !dummy
|
||||
.value_match_ranges(&output, &dummy.dummy_value)
|
||||
.contains(&range)
|
||||
{
|
||||
let alias = GeneratedAlias {
|
||||
digest: Sha256::digest(&output).into(),
|
||||
len: output.len(),
|
||||
range,
|
||||
};
|
||||
let mut aliases = dummy
|
||||
.generated_aliases
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if !aliases.contains(&alias) {
|
||||
aliases.push(alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
*text = output;
|
||||
true
|
||||
}
|
||||
}
|
||||
1763
codex-rs/network-proxy/src/credential_broker_tests.rs
Normal file
1763
codex-rs/network-proxy/src/credential_broker_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
218
codex-rs/network-proxy/src/domain_matcher.rs
Normal file
218
codex-rs/network-proxy/src/domain_matcher.rs
Normal file
@@ -0,0 +1,218 @@
|
||||
//! Network-domain wildcards over UTF-8 bytes, independent of filesystem semantics.
|
||||
//! Construction validates and normalizes patterns and expands domain prefixes.
|
||||
//! Callers normalize candidate hosts before matching. No IDNA conversion is performed.
|
||||
//! Byte matching preserves the historical globset wildcard semantics.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use anyhow::ensure;
|
||||
use std::collections::HashSet;
|
||||
use std::net::IpAddr;
|
||||
use std::net::Ipv6Addr;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum GlobalWildcard {
|
||||
Allow,
|
||||
Reject,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DomainPatternSet {
|
||||
patterns: Arc<[Vec<u8>]>,
|
||||
}
|
||||
|
||||
impl DomainPatternSet {
|
||||
pub(crate) fn new(patterns: &[String], global_wildcard: GlobalWildcard) -> Result<Self> {
|
||||
let mut compiled = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
for pattern in patterns {
|
||||
if global_wildcard == GlobalWildcard::Reject
|
||||
&& is_global_wildcard_domain_pattern(pattern)
|
||||
{
|
||||
bail!(
|
||||
"unsupported global wildcard domain pattern \"*\"; use exact hosts or scoped wildcards like *.example.com or **.example.com"
|
||||
);
|
||||
}
|
||||
let raw = pattern.trim();
|
||||
ensure!(
|
||||
!raw.contains(['{', '}', '\\', '/']) && !raw.chars().any(char::is_whitespace),
|
||||
"unsupported domain pattern syntax: {pattern}"
|
||||
);
|
||||
let host = raw
|
||||
.strip_prefix("**.")
|
||||
.or_else(|| raw.strip_prefix("*."))
|
||||
.unwrap_or(raw);
|
||||
ensure!(
|
||||
!host.contains("**"),
|
||||
"unsupported repeated wildcard: {pattern}"
|
||||
);
|
||||
if host.contains(['[', ']']) {
|
||||
let literal = host.strip_prefix('[').and_then(|s| s.split_once(']'));
|
||||
ensure!(
|
||||
literal.is_some_and(|(ip, suffix)| {
|
||||
let normalized = normalize_dns_host_or_ip_literal(ip);
|
||||
let unscoped = normalized.split('%').next().unwrap_or_default();
|
||||
!ip.contains(['[', ']'])
|
||||
&& (normalized == "*" || unscoped.parse::<Ipv6Addr>().is_ok())
|
||||
&& !suffix.contains(['[', ']'])
|
||||
&& (suffix.chars().all(|c| c == '.') || suffix.starts_with(':'))
|
||||
}),
|
||||
"brackets are only supported for IPv6 literals or [*]: {pattern}"
|
||||
);
|
||||
}
|
||||
let pattern = normalize_pattern(pattern);
|
||||
// Supported domain patterns:
|
||||
// - "example.com": match the exact host
|
||||
// - "*.example.com": match any subdomain (not the apex)
|
||||
// - "**.example.com": match the apex and any subdomain
|
||||
// - "api?.example.com": match exactly one byte after "api"
|
||||
// - "*": match every host when explicitly enabled for allowlist compilation
|
||||
for candidate in expand_domain_pattern(&pattern) {
|
||||
if !seen.insert(candidate.clone()) {
|
||||
continue;
|
||||
}
|
||||
ensure!(!candidate.is_empty(), "domain pattern is empty");
|
||||
compiled.push(candidate.into_bytes());
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
patterns: compiled.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_match(&self, host: impl AsRef<str>) -> bool {
|
||||
let host = host.as_ref().as_bytes();
|
||||
self.patterns.iter().any(|pattern| matches(pattern, host))
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize host fragments for policy matching (trim whitespace, strip ports/brackets, lowercase).
|
||||
pub fn normalize_host(host: &str) -> String {
|
||||
let host = host.trim();
|
||||
if host.starts_with('[')
|
||||
&& let Some(end) = host.find(']')
|
||||
{
|
||||
return normalize_dns_host_or_ip_literal(&host[1..end]);
|
||||
}
|
||||
|
||||
// The proxy stack should typically hand us a host without a port, but be
|
||||
// defensive and strip `:port` when there is exactly one `:`.
|
||||
if host.bytes().filter(|b| *b == b':').count() == 1 {
|
||||
let host = host.split(':').next().unwrap_or_default();
|
||||
return normalize_dns_host_or_ip_literal(host);
|
||||
}
|
||||
|
||||
// Avoid mangling unbracketed IPv6 literals, but strip trailing dots so fully qualified domain
|
||||
// names are treated the same as their dotless variants.
|
||||
normalize_dns_host_or_ip_literal(host)
|
||||
}
|
||||
|
||||
fn normalize_dns_host_or_ip_literal(host: &str) -> String {
|
||||
let host = host.to_ascii_lowercase();
|
||||
let host = host.trim_end_matches('.');
|
||||
if let Some(ip) = normalize_ip_literal(host) {
|
||||
return ip;
|
||||
}
|
||||
host.to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn unscoped_ip_literal(host: &str) -> Option<&str> {
|
||||
let (ip, _) = host.split_once('%')?;
|
||||
ip.parse::<IpAddr>().ok()?;
|
||||
Some(ip)
|
||||
}
|
||||
|
||||
fn normalize_ip_literal(host: &str) -> Option<String> {
|
||||
if host.parse::<IpAddr>().is_ok() {
|
||||
return Some(host.to_string());
|
||||
}
|
||||
for delimiter in ["%25", "%"] {
|
||||
if let Some((ip, scope)) = host.split_once(delimiter)
|
||||
&& ip.parse::<IpAddr>().is_ok()
|
||||
{
|
||||
return Some(format!("{ip}%{scope}"));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn normalize_pattern(pattern: &str) -> String {
|
||||
let pattern = pattern.trim();
|
||||
if pattern == "*" {
|
||||
return "*".to_string();
|
||||
}
|
||||
|
||||
let (prefix, remainder) = if let Some(domain) = pattern.strip_prefix("**.") {
|
||||
("**.", domain)
|
||||
} else if let Some(domain) = pattern.strip_prefix("*.") {
|
||||
("*.", domain)
|
||||
} else {
|
||||
("", pattern)
|
||||
};
|
||||
|
||||
let remainder = normalize_host(remainder);
|
||||
if prefix.is_empty() {
|
||||
remainder
|
||||
} else {
|
||||
format!("{prefix}{remainder}")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_global_wildcard_domain_pattern(pattern: &str) -> bool {
|
||||
let normalized = normalize_pattern(pattern);
|
||||
expand_domain_pattern(&normalized)
|
||||
.iter()
|
||||
.any(|candidate| candidate == "*")
|
||||
}
|
||||
|
||||
fn expand_domain_pattern(pattern: &str) -> Vec<String> {
|
||||
let pattern = pattern.trim();
|
||||
let Some(domain) = pattern
|
||||
.strip_prefix("**.")
|
||||
.or_else(|| pattern.strip_prefix("*."))
|
||||
else {
|
||||
return vec![pattern.to_string()];
|
||||
};
|
||||
let domain = domain.trim();
|
||||
if domain.is_empty() {
|
||||
return vec![String::new()];
|
||||
}
|
||||
if pattern.starts_with("**.") {
|
||||
vec![domain.to_string(), format!("?*.{domain}")]
|
||||
} else {
|
||||
vec![format!("?*.{domain}")]
|
||||
}
|
||||
}
|
||||
|
||||
// Only the latest star needs retrying: it can absorb any extension that an earlier star could.
|
||||
// Its retry position advances monotonically, bounding work by O(pattern length * host length).
|
||||
fn matches(pattern: &[u8], host: &[u8]) -> bool {
|
||||
let (mut p, mut h) = (0, 0);
|
||||
let mut star = None;
|
||||
while h < host.len() {
|
||||
match pattern.get(p) {
|
||||
Some(b'*') => {
|
||||
star = Some((p + 1, h));
|
||||
p += 1;
|
||||
}
|
||||
Some(c) if *c == b'?' || c.eq_ignore_ascii_case(&host[h]) => {
|
||||
p += 1;
|
||||
h += 1;
|
||||
}
|
||||
_ => match &mut star {
|
||||
Some((resume, consumed)) => {
|
||||
*consumed += 1;
|
||||
p = *resume;
|
||||
h = *consumed;
|
||||
}
|
||||
None => return false,
|
||||
},
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|c| *c == b'*')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "domain_matcher_tests.rs"]
|
||||
mod tests;
|
||||
238
codex-rs/network-proxy/src/domain_matcher_tests.rs
Normal file
238
codex-rs/network-proxy/src/domain_matcher_tests.rs
Normal file
@@ -0,0 +1,238 @@
|
||||
use super::*;
|
||||
use crate::policy::compile_allowlist;
|
||||
use crate::policy::compile_denylist;
|
||||
use crate::policy::normalize_host;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn unicode_wildcards_preserve_utf8_byte_matching() {
|
||||
for (pattern, host, expected) in [
|
||||
("api?.com", "api1.com", true),
|
||||
("api??.com", "apié.com", true),
|
||||
("api????.com", "api😀.com", true),
|
||||
("api???.com", "apie\u{301}.com", true),
|
||||
("api?*.com", "apié.com", true),
|
||||
("*.例???.com", "a.例子.com", true),
|
||||
("*.例???.com", "例子.com", false),
|
||||
("**.例???.com", "例子.com", true),
|
||||
("büch?.de", "büch1.de", true),
|
||||
("bücher.de", "bücher.de", true),
|
||||
("bücher.de", "xn--bcher-kva.de", false),
|
||||
("xn--*.de", "xn--bcher-kva.de", true),
|
||||
("É.com", "é.com", false),
|
||||
("É.COM", "É.com", true),
|
||||
] {
|
||||
let mut legacy = globset::GlobSetBuilder::new();
|
||||
for expanded in expand_domain_pattern(&normalize_pattern(pattern)) {
|
||||
legacy.add(
|
||||
globset::GlobBuilder::new(&expanded)
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
legacy.build().unwrap().is_match(normalize_host(host)),
|
||||
expected
|
||||
);
|
||||
for compile in [compile_allowlist, compile_denylist] {
|
||||
assert_eq!(
|
||||
compile(&[pattern.to_string()])
|
||||
.unwrap()
|
||||
.is_match(normalize_host(host)),
|
||||
expected,
|
||||
"{pattern} / {host}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compilation_rejects_unsupported_syntax_instead_of_dropping_rules() {
|
||||
for pattern in [
|
||||
"",
|
||||
" ",
|
||||
"*.",
|
||||
"**.",
|
||||
"**",
|
||||
"a**b.com",
|
||||
"[ab].com",
|
||||
"a[bc].com",
|
||||
"{a,b}.com",
|
||||
r"a\*.com",
|
||||
"a/b.com",
|
||||
"a b.com",
|
||||
"[::1]suffix",
|
||||
"[fe80::1%abc[def]",
|
||||
"[::1]:443[ab]",
|
||||
"example.com:{a,b}",
|
||||
] {
|
||||
for compile in [compile_allowlist, compile_denylist] {
|
||||
assert!(
|
||||
compile(&["valid.com".to_string(), pattern.to_string()]).is_err(),
|
||||
"{pattern}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for pattern in [
|
||||
"[::1]",
|
||||
"[::1]:443",
|
||||
"[fe80::1%25en0]:443",
|
||||
"region*.com",
|
||||
"**.api?.com",
|
||||
] {
|
||||
assert!(
|
||||
compile_allowlist(&[pattern.to_string()]).is_ok(),
|
||||
"{pattern}"
|
||||
);
|
||||
}
|
||||
for pattern in ["*", "**.*", "[*]", "**.[*]"] {
|
||||
assert!(
|
||||
compile_denylist(&[pattern.to_string()]).is_err(),
|
||||
"{pattern}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_patterns_preserve_port_and_trailing_dot_normalization() {
|
||||
for (bracketed, plain) in [
|
||||
("[*]", "*"),
|
||||
("[*]:443", "*"),
|
||||
("[*.]", "*"),
|
||||
("[*].", "*"),
|
||||
("[::1]:443", "::1"),
|
||||
("[::1.]", "::1"),
|
||||
("[::1].", "::1"),
|
||||
("[fe80::1%25en0]:443", "fe80::1%en0"),
|
||||
] {
|
||||
for prefix in ["", "*.", "**."] {
|
||||
for compile in [compile_allowlist, compile_denylist] {
|
||||
let compiled_bracketed = compile(&[format!(" {prefix}{bracketed} ")]);
|
||||
let compiled_plain = compile(&[format!("{prefix}{plain}")]);
|
||||
match (compiled_bracketed, compiled_plain) {
|
||||
(Ok(bracketed), Ok(plain)) => assert_eq!(bracketed.patterns, plain.patterns),
|
||||
(Err(_), Err(_)) => {}
|
||||
_ => panic!("different compilation outcomes for {prefix}{bracketed:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matcher_agrees_with_independent_dynamic_program_for_short_inputs() {
|
||||
fn words(alphabet: &[u8], max_len: usize) -> Vec<Vec<u8>> {
|
||||
let mut all = vec![vec![]];
|
||||
let mut level = vec![vec![]];
|
||||
for _ in 0..max_len {
|
||||
level = level
|
||||
.iter()
|
||||
.flat_map(|word| {
|
||||
alphabet.iter().map(move |c| {
|
||||
let mut next = word.clone();
|
||||
next.push(*c);
|
||||
next
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
all.extend(level.iter().cloned());
|
||||
}
|
||||
all
|
||||
}
|
||||
fn reference(pattern: &[u8], host: &[u8]) -> bool {
|
||||
let mut rows = vec![vec![false; host.len() + 1]; pattern.len() + 1];
|
||||
rows[0][0] = true;
|
||||
for (p, c) in pattern.iter().enumerate() {
|
||||
rows[p + 1][0] = *c == b'*' && rows[p][0];
|
||||
for (h, candidate) in host.iter().enumerate() {
|
||||
rows[p + 1][h + 1] = if *c == b'*' {
|
||||
rows[p][h + 1] || rows[p + 1][h]
|
||||
} else {
|
||||
rows[p][h] && (*c == b'?' || c.eq_ignore_ascii_case(candidate))
|
||||
};
|
||||
}
|
||||
}
|
||||
rows[pattern.len()][host.len()]
|
||||
}
|
||||
for pattern in words(&[b'a', 0xc3, 0xa9, b'?', b'*'], /*max_len*/ 4) {
|
||||
for host in words(&[b'a', 0xc3, 0xa9], /*max_len*/ 5) {
|
||||
assert_eq!(
|
||||
matches(&pattern, &host),
|
||||
reference(&pattern, &host),
|
||||
"{pattern:?} / {host:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adversarial_retries_and_empty_boundaries() {
|
||||
let pattern = format!("*{}b", "a".repeat(1024)).into_bytes();
|
||||
let host = vec![b'a'; 4096];
|
||||
assert!(!matches(&pattern, &host));
|
||||
let pattern = format!("{}b", "*a".repeat(1024)).into_bytes();
|
||||
assert!(!matches(&pattern, &host));
|
||||
assert_eq!(
|
||||
(matches(&[], &[]), matches(b"*", &[]), matches(b"?", &[])),
|
||||
(true, true, false)
|
||||
);
|
||||
assert!(!compile_allowlist(&[]).unwrap().is_match("host"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_loading_rejects_an_invalid_entry_in_either_list() {
|
||||
for denied in [false, true] {
|
||||
let mut config = crate::config::NetworkProxyConfig::default();
|
||||
config.set_allowed_domains(vec!["example.com".to_string()]);
|
||||
let invalid = vec!["valid.com".to_string(), "api[12].com".to_string()];
|
||||
if denied {
|
||||
config.set_denied_domains(invalid);
|
||||
} else {
|
||||
config.set_allowed_domains(invalid);
|
||||
}
|
||||
assert!(
|
||||
crate::state::build_config_state(config, Default::default(), crate::Platform::native())
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_lowercases_and_trims() {
|
||||
assert_eq!(normalize_host(" ExAmPlE.CoM "), "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_strips_port_for_host_port() {
|
||||
assert_eq!(normalize_host("example.com:1234"), "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_preserves_unbracketed_ipv6() {
|
||||
assert_eq!(normalize_host("2001:db8::1"), "2001:db8::1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_strips_trailing_dot() {
|
||||
assert_eq!(normalize_host("example.com."), "example.com");
|
||||
assert_eq!(normalize_host("ExAmPlE.CoM."), "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_strips_trailing_dot_with_port() {
|
||||
assert_eq!(normalize_host("example.com.:443"), "example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_strips_brackets_for_ipv6() {
|
||||
assert_eq!(normalize_host("[::1]"), "::1");
|
||||
assert_eq!(normalize_host("[::1]:443"), "::1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_host_preserves_ipv6_scope_ids() {
|
||||
assert_eq!(normalize_host("fe80::1%lo0"), "fe80::1%lo0");
|
||||
assert_eq!(normalize_host("[fe80::1%lo0]"), "fe80::1%lo0");
|
||||
assert_eq!(normalize_host("[fe80::1%25lo0]"), "fe80::1%lo0");
|
||||
}
|
||||
116
codex-rs/network-proxy/src/environment_policy.rs
Normal file
116
codex-rs/network-proxy/src/environment_policy.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use crate::NetworkDomainPermissions;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::NetworkUnixSocketPermission;
|
||||
use crate::NetworkUnixSocketPermissions;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// Managed proxy requirements supplied by the owner of one execution environment.
|
||||
///
|
||||
/// The owner can require proxy routing without granting direct network access.
|
||||
/// Listeners, network mode, MITM, and credentials remain controller-owned.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EnvironmentNetworkPolicy {
|
||||
/// Requires managed proxy routing even when direct network access is restricted.
|
||||
/// False or omission leaves activation to the controller and command permissions.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub requires_proxy: bool,
|
||||
pub domains: Option<NetworkDomainPermissions>,
|
||||
/// Managed host selectors inherited by every execution in this environment.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub review_domains: Vec<String>,
|
||||
pub unix_sockets: Option<NetworkUnixSocketPermissions>,
|
||||
pub allow_upstream_proxy: bool,
|
||||
pub dangerously_allow_all_unix_sockets: bool,
|
||||
/// Omission inherits local-binding policy; an explicit false remains a restriction.
|
||||
pub allow_local_binding: Option<bool>,
|
||||
pub managed_allowed_domains_only: bool,
|
||||
}
|
||||
|
||||
impl EnvironmentNetworkPolicy {
|
||||
/// Captures proxy activation and traffic restrictions without controller runtime settings.
|
||||
pub fn from_config(config: &NetworkProxyConfig, managed_allowed_domains_only: bool) -> Self {
|
||||
Self {
|
||||
requires_proxy: config.enabled,
|
||||
domains: config.domains.clone(),
|
||||
review_domains: config.review_domains.clone(),
|
||||
unix_sockets: config.unix_sockets.clone(),
|
||||
allow_upstream_proxy: config.allow_upstream_proxy,
|
||||
dangerously_allow_all_unix_sockets: config
|
||||
.dangerously_allow_all_unix_sockets
|
||||
.unwrap_or(false),
|
||||
allow_local_binding: config.allow_local_binding,
|
||||
managed_allowed_domains_only,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies attachment-owned traffic settings while preserving inherited denials and proxy setup.
|
||||
pub fn apply_to(&self, config: &mut NetworkProxyConfig) {
|
||||
// Neither owner nor controller may remove the other's review selectors.
|
||||
for pattern in &self.review_domains {
|
||||
if !config
|
||||
.review_domains
|
||||
.iter()
|
||||
.any(|existing| existing.eq_ignore_ascii_case(pattern))
|
||||
{
|
||||
config.review_domains.push(pattern.clone());
|
||||
}
|
||||
}
|
||||
// Use the owner's domain rules without dropping controller denials.
|
||||
let inherited_denials = config.denied_domains().unwrap_or_default();
|
||||
config.domains.clone_from(&self.domains);
|
||||
for domain in inherited_denials {
|
||||
config.upsert_domain_permission(
|
||||
domain,
|
||||
crate::NetworkDomainPermission::Deny,
|
||||
crate::normalize_host,
|
||||
);
|
||||
}
|
||||
// An omitted controller policy leaves socket permissions to the attachment;
|
||||
// an explicitly empty socket map still supplies a restrictive ceiling.
|
||||
let inherited_allow_all = config
|
||||
.dangerously_allow_all_unix_sockets
|
||||
.unwrap_or(config.unix_sockets.is_none());
|
||||
let inherited_sockets = config.unix_sockets.take().unwrap_or_default();
|
||||
let mut effective_sockets = self.unix_sockets.clone().unwrap_or_default();
|
||||
|
||||
// "Allow all" cannot override a socket denied by either policy.
|
||||
let inherited_permits_all = inherited_allow_all
|
||||
&& !inherited_sockets
|
||||
.entries
|
||||
.values()
|
||||
.any(|permission| matches!(permission, NetworkUnixSocketPermission::Deny));
|
||||
let owner_permits_all = self.dangerously_allow_all_unix_sockets
|
||||
&& !effective_sockets
|
||||
.entries
|
||||
.values()
|
||||
.any(|permission| matches!(permission, NetworkUnixSocketPermission::Deny));
|
||||
|
||||
// Keep shared socket grants; controller denials always take priority.
|
||||
effective_sockets.entries.retain(|path, permission| {
|
||||
matches!(permission, NetworkUnixSocketPermission::Deny)
|
||||
|| inherited_permits_all
|
||||
|| matches!(
|
||||
inherited_sockets.entries.get(path),
|
||||
Some(NetworkUnixSocketPermission::Allow)
|
||||
)
|
||||
});
|
||||
for (path, permission) in inherited_sockets.entries {
|
||||
if owner_permits_all || matches!(permission, NetworkUnixSocketPermission::Deny) {
|
||||
effective_sockets.entries.insert(path, permission);
|
||||
}
|
||||
}
|
||||
|
||||
// Socket and upstream-proxy permissions require both controller and owner grants.
|
||||
config.unix_sockets = (!effective_sockets.entries.is_empty()).then_some(effective_sockets);
|
||||
config.dangerously_allow_all_unix_sockets =
|
||||
Some(inherited_permits_all && owner_permits_all);
|
||||
config.allow_upstream_proxy &= self.allow_upstream_proxy;
|
||||
// Either explicit denial wins; defer unresolved defaults to the executor.
|
||||
config.allow_local_binding = match (config.allow_local_binding, self.allow_local_binding) {
|
||||
(Some(controller), Some(owner)) => Some(controller && owner),
|
||||
(controller, owner) => controller.or(owner),
|
||||
};
|
||||
}
|
||||
}
|
||||
153
codex-rs/network-proxy/src/host_policy_tests.rs
Normal file
153
codex-rs/network-proxy/src/host_policy_tests.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
//! Verify DNS authorization ordering and mandatory checks after approval.
|
||||
|
||||
use super::*;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::runtime::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
|
||||
#[tokio::test]
|
||||
async fn unapproved_hosts_do_not_trigger_dns() {
|
||||
for allowed in [vec![], vec!["allowed.example".to_string()]] {
|
||||
let mut config = NetworkProxyConfig::default();
|
||||
config.set_allowed_domains(allowed);
|
||||
let state = network_proxy_state_for_policy(config);
|
||||
let lookups = Cell::new(0);
|
||||
let decision = state
|
||||
.host_blocked_with_lookup(
|
||||
"payload.unapproved.example",
|
||||
/*port*/ 443,
|
||||
/*allow_local_binding*/ None,
|
||||
HostAuthorization::RequireAllowlist,
|
||||
|_host, _port| {
|
||||
lookups.set(lookups.get() + 1);
|
||||
async { Ok(vec!["93.184.215.14:443".parse().unwrap()]) }
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(decision, lookups.get()),
|
||||
(HostBlockDecision::Blocked(HostBlockReason::NotAllowed), 0),
|
||||
"rejecting an unapproved hostname must not disclose it to DNS",
|
||||
);
|
||||
}
|
||||
// Approval permits DNS, but must still reject private resolution.
|
||||
let state = network_proxy_state_for_policy(NetworkProxyConfig::default());
|
||||
let decision = state
|
||||
.host_blocked_with_lookup(
|
||||
"approved.example",
|
||||
/*port*/ 443,
|
||||
/*allow_local_binding*/ None,
|
||||
HostAuthorization::Approved,
|
||||
|_host, _port| async { Ok(vec!["10.0.0.1:443".parse().unwrap()]) },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
decision,
|
||||
HostBlockDecision::Blocked(HostBlockReason::NotAllowedLocal)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_and_remote_approvals_preserve_review_precedence_and_recheck_dns() -> Result<()> {
|
||||
use crate::NetworkDecision;
|
||||
use crate::NetworkDecisionSource;
|
||||
use crate::NetworkPolicyDecider;
|
||||
use crate::NetworkPolicyRequest;
|
||||
use crate::NetworkPolicyRequestArgs;
|
||||
use crate::NetworkProtocol;
|
||||
use crate::NetworkProxy;
|
||||
use crate::network_policy::evaluate_host_policy;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
for remote in [false, true] {
|
||||
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||
let decider_calls = Arc::clone(&calls);
|
||||
let decider: Arc<dyn NetworkPolicyDecider> =
|
||||
Arc::new(move |request: NetworkPolicyRequest| {
|
||||
decider_calls.lock().unwrap().push(request.host);
|
||||
async { NetworkDecision::Allow }
|
||||
});
|
||||
// Explicit controller false must survive an executor allowing local binding.
|
||||
let mut config = NetworkProxyConfig {
|
||||
allow_local_binding: Some(false),
|
||||
review_domains: vec![
|
||||
"8.8.8.8".to_string(),
|
||||
"9.9.9.9".to_string(),
|
||||
"host.review.invalid".to_string(),
|
||||
],
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
config.set_allowed_domains(vec![
|
||||
"8.8.8.8".to_string(),
|
||||
"1.1.1.1".to_string(),
|
||||
"9.9.9.9".to_string(),
|
||||
"**.review.invalid".to_string(),
|
||||
]);
|
||||
config.set_denied_domains(vec!["9.9.9.9".to_string()]);
|
||||
let state = Arc::new(network_proxy_state_for_policy(config));
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(Arc::clone(&state))
|
||||
.managed_by_codex(/*managed_by_codex*/ false)
|
||||
.policy_decider_arc(Arc::clone(&decider))
|
||||
.build()
|
||||
.await?;
|
||||
let scoped = proxy.for_execution(
|
||||
"remote",
|
||||
"execution",
|
||||
"token".to_string(),
|
||||
/*environment_policy*/ None,
|
||||
/*fallback_policy_decider*/ None,
|
||||
)?;
|
||||
let remote_decider = scoped
|
||||
.remote_policy_decider(/*allow_local_binding*/ true)
|
||||
.unwrap();
|
||||
for host in [
|
||||
"does-not-resolve.invalid",
|
||||
"8.8.8.8",
|
||||
"host.review.invalid",
|
||||
"ordinary.review.invalid",
|
||||
"1.1.1.1",
|
||||
"9.9.9.9",
|
||||
] {
|
||||
let request = NetworkPolicyRequest::new(NetworkPolicyRequestArgs {
|
||||
protocol: NetworkProtocol::HttpsConnect,
|
||||
host: host.to_string(),
|
||||
port: 443,
|
||||
environment_id: None,
|
||||
client_addr: None,
|
||||
method: None,
|
||||
command: None,
|
||||
exec_policy_hint: None,
|
||||
});
|
||||
let decision = if remote {
|
||||
remote_decider.decide(request).await
|
||||
} else {
|
||||
evaluate_host_policy(&state, Some(&decider), &request).await?
|
||||
};
|
||||
let expected = if host.ends_with(".invalid") {
|
||||
NetworkDecision::deny_with_source(
|
||||
HostBlockReason::NotAllowedLocal.as_str(),
|
||||
NetworkDecisionSource::BaselinePolicy,
|
||||
)
|
||||
} else if host == "9.9.9.9" {
|
||||
NetworkDecision::deny_with_source(
|
||||
HostBlockReason::Denied.as_str(),
|
||||
NetworkDecisionSource::BaselinePolicy,
|
||||
)
|
||||
} else {
|
||||
NetworkDecision::Allow
|
||||
};
|
||||
assert_eq!(decision, expected);
|
||||
}
|
||||
assert_eq!(
|
||||
*calls.lock().unwrap(),
|
||||
vec!["does-not-resolve.invalid", "8.8.8.8", "host.review.invalid"],
|
||||
"review selectors precede exact and wildcard allows; ordinary allows and denies skip the decider"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
2109
codex-rs/network-proxy/src/http_proxy.rs
Normal file
2109
codex-rs/network-proxy/src/http_proxy.rs
Normal file
File diff suppressed because it is too large
Load Diff
168
codex-rs/network-proxy/src/http_proxy/host_header_tests.rs
Normal file
168
codex-rs/network-proxy/src/http_proxy/host_header_tests.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Checks Host field cardinality before policy evaluation and upstream forwarding.
|
||||
|
||||
use super::http_plain_proxy;
|
||||
use crate::NetworkProxy;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::runtime::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_http::Body;
|
||||
use rama_http::Request;
|
||||
use rama_http::StatusCode;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum RequestTarget {
|
||||
Origin,
|
||||
Absolute,
|
||||
Connect,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum HostFields {
|
||||
Single,
|
||||
Identical,
|
||||
Conflicting,
|
||||
}
|
||||
|
||||
async fn exchange(target: RequestTarget, hosts: HostFields) -> (String, Option<String>) {
|
||||
let origin = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
|
||||
let origin_addr = origin.local_addr().unwrap();
|
||||
let (stop_origin, stop_requested) = oneshot::channel::<()>();
|
||||
let origin_task = tokio::spawn(async move {
|
||||
let (mut stream, _) = tokio::select! {
|
||||
biased;
|
||||
accepted = origin.accept() => accepted.unwrap(),
|
||||
_ = stop_requested => return None,
|
||||
};
|
||||
if matches!(target, RequestTarget::Connect) {
|
||||
stream.write_all(b"fixture tunnel\r\n").await.unwrap();
|
||||
return Some("CONNECT tunnel established".to_string());
|
||||
}
|
||||
let mut headers = Vec::new();
|
||||
loop {
|
||||
let byte = stream.read_u8().await.unwrap();
|
||||
headers.push(byte);
|
||||
assert!(headers.len() < 8192);
|
||||
if headers.ends_with(b"\r\n\r\n") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK")
|
||||
.await
|
||||
.unwrap();
|
||||
Some(String::from_utf8(headers).unwrap())
|
||||
});
|
||||
|
||||
let mut network = NetworkProxyConfig {
|
||||
allow_local_binding: Some(true),
|
||||
allow_upstream_proxy: false,
|
||||
enable_socks5: false,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.set_allowed_domains(vec!["127.0.0.1".to_string()]);
|
||||
network.set_denied_domains(vec!["localhost".to_string()]);
|
||||
let state = Arc::new(network_proxy_state_for_policy(network));
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(state)
|
||||
.managed_proxy_routing(crate::ManagedProxyRouting::DedicatedListeners)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
let handle = proxy.run().await.unwrap();
|
||||
let mut client = TcpStream::connect(proxy.http_addr()).await.unwrap();
|
||||
let first_host = format!("Host: {origin_addr}\r\n");
|
||||
let second_host = match hosts {
|
||||
HostFields::Single => String::new(),
|
||||
HostFields::Identical => format!("hOsT: {origin_addr}\r\n"),
|
||||
HostFields::Conflicting => format!("hOsT: localhost:{}\r\n", origin_addr.port()),
|
||||
};
|
||||
let request_line = match target {
|
||||
RequestTarget::Origin => "GET / HTTP/1.1".to_string(),
|
||||
RequestTarget::Absolute => format!("GET http://{origin_addr}/ HTTP/1.1"),
|
||||
RequestTarget::Connect => format!("CONNECT {origin_addr} HTTP/1.1"),
|
||||
};
|
||||
let request = format!("{request_line}\r\n{first_host}{second_host}Connection: close\r\n\r\n");
|
||||
client.write_all(request.as_bytes()).await.unwrap();
|
||||
let mut response = Vec::new();
|
||||
timeout(Duration::from_secs(5), client.read_to_end(&mut response))
|
||||
.await
|
||||
.expect("proxy should complete the response")
|
||||
.unwrap();
|
||||
drop(client);
|
||||
let _ = stop_origin.send(());
|
||||
let origin_request = timeout(Duration::from_secs(5), origin_task)
|
||||
.await
|
||||
.expect("origin should stop")
|
||||
.unwrap();
|
||||
timeout(Duration::from_secs(5), handle.shutdown())
|
||||
.await
|
||||
.expect("proxy should shut down")
|
||||
.unwrap();
|
||||
(String::from_utf8(response).unwrap(), origin_request)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_duplicate_host_fields_before_upstream() {
|
||||
let mut observed = Vec::new();
|
||||
for target in [
|
||||
RequestTarget::Origin,
|
||||
RequestTarget::Absolute,
|
||||
RequestTarget::Connect,
|
||||
] {
|
||||
for hosts in [HostFields::Identical, HostFields::Conflicting] {
|
||||
let (response, origin_request) = exchange(target, hosts).await;
|
||||
observed.push((
|
||||
response.lines().next().unwrap().to_string(),
|
||||
origin_request.is_some(),
|
||||
));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
observed,
|
||||
vec![("HTTP/1.1 400 Bad Request".to_string(), false); 6]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_single_host_forwarding() {
|
||||
for target in [RequestTarget::Origin, RequestTarget::Absolute] {
|
||||
let (response, origin_request) = exchange(target, HostFields::Single).await;
|
||||
assert!(response.starts_with("HTTP/1.1 200 OK\r\n"));
|
||||
let host_count = origin_request
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter(|line| line.to_ascii_lowercase().starts_with("host:"))
|
||||
.count();
|
||||
assert_eq!(host_count, 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_duplicate_hosts_before_unix_socket_routing() {
|
||||
let state = Arc::new(network_proxy_state_for_policy(NetworkProxyConfig::default()));
|
||||
let mut request = Request::builder()
|
||||
.uri("/")
|
||||
.header("host", "allowed.test")
|
||||
.header("host", "denied.test")
|
||||
.header("x-unix-socket", "/not-an-allowed-socket")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
request.extensions_mut().insert(state);
|
||||
let response = http_plain_proxy(
|
||||
/*policy_decider*/ None, /*environment_id*/ None, request,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
138
codex-rs/network-proxy/src/lib.rs
Normal file
138
codex-rs/network-proxy/src/lib.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
#![deny(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
mod attribution;
|
||||
mod authorization_path;
|
||||
mod aws_sigv4;
|
||||
mod body_budget;
|
||||
mod brokered_tunnel;
|
||||
mod certs;
|
||||
mod config;
|
||||
mod connect_policy;
|
||||
mod connection_lifecycle;
|
||||
mod credential_broker;
|
||||
mod domain_matcher;
|
||||
mod environment_policy;
|
||||
mod http_proxy;
|
||||
mod mitm;
|
||||
mod mitm_hook;
|
||||
mod native_certs;
|
||||
mod network_policy;
|
||||
mod policy;
|
||||
mod process_log_metadata;
|
||||
mod proxy;
|
||||
mod reasons;
|
||||
mod remote_config;
|
||||
mod request_cancellation;
|
||||
mod request_disconnect;
|
||||
mod responses;
|
||||
mod runtime;
|
||||
mod secret_substitution;
|
||||
mod socket_path;
|
||||
mod socks5;
|
||||
mod state;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod system_dns;
|
||||
mod upstream;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_proxy_ingress;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_tcp_attribution;
|
||||
|
||||
pub use attribution::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
pub use attribution::write_attribution_frame;
|
||||
pub use aws_sigv4::AwsSigV4Config;
|
||||
pub use aws_sigv4::ProxySecretSource;
|
||||
pub use certs::CUSTOM_CA_ENV_KEYS;
|
||||
pub use certs::is_managed_mitm_ca_trust_bundle_path;
|
||||
pub use codex_utils_path_uri::Platform;
|
||||
pub use config::NetworkDomainPermission;
|
||||
pub use config::NetworkDomainPermissionEntry;
|
||||
pub use config::NetworkDomainPermissions;
|
||||
pub use config::NetworkMitmCaConfig;
|
||||
pub use config::NetworkMode;
|
||||
pub use config::NetworkProxyConfig;
|
||||
pub use config::NetworkUnixSocketPermission;
|
||||
pub use config::NetworkUnixSocketPermissions;
|
||||
pub use config::StaticNetworkProxyConfig;
|
||||
pub use config::host_and_port_from_network_addr;
|
||||
pub use config::managed_proxy_ports;
|
||||
pub use credential_broker::CREDENTIAL_BROKER_ACTIVE_ENV_KEY;
|
||||
pub use credential_broker::CredentialAuthMethod;
|
||||
pub use credential_broker::CredentialBrokerContext;
|
||||
pub use credential_broker::CredentialBrokerEnvironment;
|
||||
pub use credential_broker::CredentialMaskingFailureMode;
|
||||
pub use credential_broker::CredentialProviderConfig;
|
||||
pub use credential_broker::brokered_credential_binding_env_keys;
|
||||
pub use credential_broker::brokered_credential_dummy_env_keys;
|
||||
pub use credential_broker::brokered_credential_env_keys;
|
||||
pub use credential_broker::brokered_credential_marker_env_keys;
|
||||
pub use credential_broker::brokered_credential_value_env_keys;
|
||||
pub use credential_broker::credential_broker_provider_context_env_keys;
|
||||
pub use credential_broker::credential_broker_provider_sources_allowed;
|
||||
pub use credential_broker::is_credential_broker_provider_env_key;
|
||||
pub use environment_policy::EnvironmentNetworkPolicy;
|
||||
pub use mitm_hook::InjectedHeaderConfig;
|
||||
pub use mitm_hook::MitmHookActionsConfig;
|
||||
pub use mitm_hook::MitmHookBodyConfig;
|
||||
pub use mitm_hook::MitmHookConfig;
|
||||
pub use mitm_hook::MitmHookMatchConfig;
|
||||
pub use network_policy::NetworkDecision;
|
||||
pub use network_policy::NetworkDecisionSource;
|
||||
pub use network_policy::NetworkPolicyAuditEvent;
|
||||
pub use network_policy::NetworkPolicyAuditObserver;
|
||||
pub use network_policy::NetworkPolicyDecider;
|
||||
pub use network_policy::NetworkPolicyDeciderFuture;
|
||||
pub use network_policy::NetworkPolicyDecision;
|
||||
pub use network_policy::NetworkPolicyRequest;
|
||||
pub use network_policy::NetworkPolicyRequestArgs;
|
||||
pub use network_policy::NetworkProtocol;
|
||||
pub use policy::is_non_public_ip;
|
||||
pub use policy::normalize_host;
|
||||
pub use process_log_metadata::ExecutorLogIdentity;
|
||||
pub use process_log_metadata::NetworkProxyProcessLogMetadata;
|
||||
pub use proxy::ALL_PROXY_ENV_KEYS;
|
||||
pub use proxy::ALLOW_LOCAL_BINDING_ENV_KEY;
|
||||
pub use proxy::Args;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use proxy::CODEX_PROXY_GIT_SSH_COMMAND_MARKER;
|
||||
pub use proxy::DEFAULT_NO_PROXY_VALUE;
|
||||
pub use proxy::ManagedNetworkSandboxContext;
|
||||
pub use proxy::ManagedProxyRouting;
|
||||
pub use proxy::NO_PROXY_ENV_KEYS;
|
||||
pub use proxy::NetworkProxy;
|
||||
pub use proxy::NetworkProxyBuilder;
|
||||
pub use proxy::NetworkProxyHandle;
|
||||
pub use proxy::PROXY_ACTIVE_ENV_KEY;
|
||||
pub use proxy::PROXY_ENV_KEYS;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use proxy::PROXY_GIT_SSH_COMMAND_ENV_KEY;
|
||||
pub use proxy::PROXY_URL_ENV_KEYS;
|
||||
pub use proxy::PreparedManagedNetwork;
|
||||
pub use proxy::has_proxy_url_env_vars;
|
||||
pub use proxy::is_managed_proxy_env_var;
|
||||
pub use proxy::proxy_url_env_value;
|
||||
pub use proxy::strip_managed_proxy_env;
|
||||
pub use remote_config::RemoteCredentialBrokerCache;
|
||||
pub use remote_config::RemoteCredentialMasking;
|
||||
pub use remote_config::RemoteNetworkProxyConfig;
|
||||
pub use remote_config::RemoteNetworkProxyLaunchConfig;
|
||||
pub use request_cancellation::NetworkRequestCancellation;
|
||||
pub use request_cancellation::NetworkRequestCancellationReason;
|
||||
pub use request_disconnect::NetworkRequestDisconnect;
|
||||
pub use runtime::BlockedRequest;
|
||||
pub use runtime::BlockedRequestArgs;
|
||||
pub use runtime::BlockedRequestObserver;
|
||||
pub use runtime::BlockedRequestObserverFuture;
|
||||
pub use runtime::ConfigReloader;
|
||||
pub use runtime::ConfigReloaderFuture;
|
||||
pub use runtime::ConfigState;
|
||||
pub use runtime::LocalBindingPolicy;
|
||||
pub use runtime::NetworkProxyState;
|
||||
pub use secret_substitution::BodySecretReplacement;
|
||||
pub use secret_substitution::BodySecretSubstitutionConfig;
|
||||
pub use state::NetworkProxyAuditMetadata;
|
||||
pub use state::NetworkProxyConstraintError;
|
||||
pub use state::NetworkProxyConstraints;
|
||||
pub use state::PartialNetworkProxyConfig;
|
||||
pub use state::build_config_state;
|
||||
pub use state::validate_policy_against_constraints;
|
||||
103
codex-rs/network-proxy/src/main.rs
Normal file
103
codex-rs/network-proxy/src/main.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
#![deny(clippy::print_stdout, clippy::print_stderr)]
|
||||
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use clap::Parser;
|
||||
use codex_network_proxy::ConfigReloader;
|
||||
use codex_network_proxy::ConfigReloaderFuture;
|
||||
use codex_network_proxy::ConfigState;
|
||||
use codex_network_proxy::NetworkProxy;
|
||||
use codex_network_proxy::NetworkProxyState;
|
||||
use codex_network_proxy::Platform;
|
||||
use codex_network_proxy::StaticNetworkProxyConfig;
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const MAX_CONFIG_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(name = "codex-network-proxy", about = "Codex network policy proxy")]
|
||||
struct Args {
|
||||
/// Standalone JSON configuration containing a `network` object.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
config: PathBuf,
|
||||
/// Reject unknown config fields and require explicit managed constraints.
|
||||
#[arg(long)]
|
||||
strict: bool,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse_config(&self, bytes: &[u8]) -> Result<StaticNetworkProxyConfig> {
|
||||
if self.strict {
|
||||
StaticNetworkProxyConfig::from_slice_strict(bytes)
|
||||
} else {
|
||||
StaticNetworkProxyConfig::from_slice(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct StaticConfigReloader {
|
||||
state: ConfigState,
|
||||
}
|
||||
|
||||
impl ConfigReloader for StaticConfigReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"standalone network proxy config".to_string()
|
||||
}
|
||||
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(async { Ok(self.state.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
let args = Args::parse();
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(&args.config)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"failed to read network proxy config: {}",
|
||||
args.config.display()
|
||||
)
|
||||
})?
|
||||
.take((MAX_CONFIG_BYTES + 1) as u64)
|
||||
.read_to_end(&mut bytes)?;
|
||||
ensure!(
|
||||
bytes.len() <= MAX_CONFIG_BYTES,
|
||||
"network proxy config exceeds {MAX_CONFIG_BYTES} bytes"
|
||||
);
|
||||
let config = args
|
||||
.parse_config(&bytes)
|
||||
.with_context(|| format!("invalid network proxy config: {}", args.config.display()))?;
|
||||
let config_state = config
|
||||
.build_state(Platform::native())
|
||||
.context("failed to initialize network proxy policy")?;
|
||||
let reloader = Arc::new(StaticConfigReloader {
|
||||
state: config_state.clone(),
|
||||
});
|
||||
let state = Arc::new(NetworkProxyState::with_reloader(config_state, reloader));
|
||||
NetworkProxy::builder()
|
||||
.state(state)
|
||||
.managed_by_codex(/*managed_by_codex*/ false)
|
||||
.build()
|
||||
.await?
|
||||
.run()
|
||||
.await?
|
||||
.wait()
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
103
codex-rs/network-proxy/src/main_tests.rs
Normal file
103
codex-rs/network-proxy/src/main_tests.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use clap::Parser;
|
||||
use codex_network_proxy::NetworkMitmCaConfig;
|
||||
use codex_network_proxy::StaticNetworkProxyConfig;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn enables_mitm_for_limited_mode_and_hooks() {
|
||||
for (network, expected_mitm, expected_ca) in [
|
||||
(json!({"enabled": true, "mode": "full"}), false, None),
|
||||
(
|
||||
json!({"enabled": true, "mode": "full", "mitm": true}),
|
||||
true,
|
||||
None,
|
||||
),
|
||||
(json!({"enabled": true, "mode": "limited"}), true, None),
|
||||
(
|
||||
json!({
|
||||
"enabled": true,
|
||||
"mitm_hooks": [{"host": "api.example.com"}]
|
||||
}),
|
||||
true,
|
||||
None,
|
||||
),
|
||||
(
|
||||
json!({
|
||||
"enabled": true,
|
||||
"mode": "limited",
|
||||
"mitm_ca": {
|
||||
"certificate_file": "/run/proxy/ca.pem",
|
||||
"private_key_file": "/run/proxy/key.pem"
|
||||
}
|
||||
}),
|
||||
true,
|
||||
Some(NetworkMitmCaConfig {
|
||||
certificate_file: "/run/proxy/ca.pem".to_string(),
|
||||
private_key_file: "/run/proxy/key.pem".to_string(),
|
||||
}),
|
||||
),
|
||||
] {
|
||||
let bytes = serde_json::to_vec(&json!({"network": network, "constraints": {}})).unwrap();
|
||||
for parse in [
|
||||
StaticNetworkProxyConfig::from_slice,
|
||||
StaticNetworkProxyConfig::from_slice_strict,
|
||||
] {
|
||||
let config = parse(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(config.network.mitm, config.network.mitm_ca),
|
||||
(expected_mitm, expected_ca.clone())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_dynamic_domain_socket_and_hook_matcher_keys() {
|
||||
let bytes = serde_json::to_vec(&json!({
|
||||
"network": {
|
||||
"enabled": true,
|
||||
"domains": {"api.example.com": "allow"},
|
||||
"unix_sockets": {"/tmp/example.sock": "allow"},
|
||||
"mitm_hooks": [{
|
||||
"host": "api.example.com",
|
||||
"match": {
|
||||
"query": {"scope": ["read"]},
|
||||
"headers": {"authorization": ["Bearer token"]}
|
||||
}
|
||||
}]
|
||||
},
|
||||
"constraints": {}
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let config = StaticNetworkProxyConfig::from_slice_strict(&bytes).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
config.network.allowed_domains(),
|
||||
Some(vec!["api.example.com".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
config.network.allow_unix_sockets(),
|
||||
vec!["/tmp/example.sock".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_flag_controls_config_parsing() {
|
||||
let base = ["codex-network-proxy", "--config", "policy.json"];
|
||||
let lenient = super::Args::try_parse_from(base).unwrap();
|
||||
let strict = super::Args::try_parse_from(base.into_iter().chain(["--strict"])).unwrap();
|
||||
for bytes in [
|
||||
br#"{"network":{"enabled":true}}"#.as_slice(),
|
||||
br#"{"network":{"enabled":true},"metadata":{"future_setting":true},"constraints":{}}"#,
|
||||
] {
|
||||
assert!(lenient.parse_config(bytes).is_ok());
|
||||
assert!(strict.parse_config(bytes).is_err());
|
||||
}
|
||||
assert!(
|
||||
strict
|
||||
.parse_config(br#"{"network":{"enabled":true},"constraints":{}}"#)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
731
codex-rs/network-proxy/src/mitm.rs
Normal file
731
codex-rs/network-proxy/src/mitm.rs
Normal file
@@ -0,0 +1,731 @@
|
||||
use crate::certs::ManagedMitmCa;
|
||||
use crate::config::NetworkMitmCaConfig;
|
||||
use crate::config::NetworkMode;
|
||||
use crate::mitm_hook::HookEvaluation;
|
||||
use crate::mitm_hook::MitmHookActions;
|
||||
use crate::policy::normalize_host;
|
||||
use crate::reasons::REASON_METHOD_NOT_ALLOWED;
|
||||
use crate::reasons::REASON_MITM_HOOK_DENIED;
|
||||
use crate::responses::blocked_text_response;
|
||||
use crate::responses::text_response;
|
||||
use crate::runtime::HostAuthorization;
|
||||
use crate::runtime::HostBlockDecision;
|
||||
use crate::runtime::HostBlockReason;
|
||||
use crate::state::BlockedRequest;
|
||||
use crate::state::BlockedRequestArgs;
|
||||
use crate::state::NetworkProxyState;
|
||||
use crate::upstream::UpstreamClient;
|
||||
use anyhow::Context as _;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use rama_core::Layer;
|
||||
use rama_core::Service;
|
||||
use rama_core::bytes::Bytes;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_core::futures::stream::Stream as FuturesStream;
|
||||
use rama_core::rt::Executor;
|
||||
use rama_core::service::service_fn;
|
||||
use rama_core::stream::Stream;
|
||||
use rama_http::Body;
|
||||
use rama_http::BodyDataStream;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::Request;
|
||||
use rama_http::Response;
|
||||
use rama_http::StatusCode;
|
||||
use rama_http::Uri;
|
||||
use rama_http::header::HOST;
|
||||
use rama_http::layer::remove_header::RemoveRequestHeaderLayer;
|
||||
use rama_http::layer::remove_header::RemoveResponseHeaderLayer;
|
||||
use rama_http::uri::Scheme;
|
||||
use rama_http_backend::server::HttpServer;
|
||||
use rama_net::proxy::ProxyTarget;
|
||||
use rama_net::stream::SocketInfo;
|
||||
use rama_tls_rustls::dep::rustls;
|
||||
use rama_tls_rustls::server::TlsAcceptorData;
|
||||
use rama_tls_rustls::server::TlsAcceptorLayer;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::Context as TaskContext;
|
||||
use std::task::Poll;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
/// State needed to terminate a CONNECT tunnel and enforce policy on inner HTTPS requests.
|
||||
pub struct MitmState {
|
||||
ca: Arc<ManagedMitmCa>,
|
||||
allow_upstream_proxy: bool,
|
||||
upstream_tls_root_store: Arc<rustls::RootCertStore>,
|
||||
inspect: bool,
|
||||
max_body_bytes: usize,
|
||||
}
|
||||
|
||||
pub(crate) struct MitmUpstreamConfig {
|
||||
pub(crate) allow_upstream_proxy: bool,
|
||||
pub(crate) external_ca: Option<NetworkMitmCaConfig>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MitmPolicyContext {
|
||||
target_host: String,
|
||||
target_port: u16,
|
||||
scheme: Scheme,
|
||||
mode: NetworkMode,
|
||||
app_state: Arc<NetworkProxyState>,
|
||||
}
|
||||
|
||||
impl MitmPolicyContext {
|
||||
async fn deny_hook(&self, method: &str, client: Option<String>) -> Response {
|
||||
let _ = self
|
||||
.app_state
|
||||
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
|
||||
host: self.target_host.clone(),
|
||||
reason: REASON_MITM_HOOK_DENIED.to_string(),
|
||||
client,
|
||||
method: Some(method.to_string()),
|
||||
mode: Some(self.mode),
|
||||
protocol: self.scheme.to_string(),
|
||||
decision: None,
|
||||
source: None,
|
||||
port: Some(self.target_port),
|
||||
}))
|
||||
.await;
|
||||
warn!(
|
||||
"MITM blocked by hook policy (host={}, method={method}, mode={:?})",
|
||||
self.target_host, self.mode
|
||||
);
|
||||
blocked_text_response(REASON_MITM_HOOK_DENIED)
|
||||
}
|
||||
|
||||
fn placeholders_match(&self, req: &Request, actions: &MitmHookActions) -> bool {
|
||||
actions.inject_request_headers.iter().all(|header| {
|
||||
header.placeholder.as_ref().is_none_or(|placeholder| {
|
||||
self.scheme == Scheme::HTTPS
|
||||
&& self.target_port == 443
|
||||
&& req
|
||||
.headers()
|
||||
.get_all(&header.name)
|
||||
.iter()
|
||||
.eq(std::iter::once(placeholder))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn credential_destination(&self, req: &Request) -> String {
|
||||
let authority = authority_header_value(&self.target_host, self.target_port, &self.scheme);
|
||||
let path = path_and_query(req.uri());
|
||||
// Server-wide OPTIONS must not borrow authority from a narrower credential URL prefix.
|
||||
let credential_path = if path == "*" { "/" } else { &path };
|
||||
format!("{}://{authority}{credential_path}", self.scheme)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MitmRequestContext {
|
||||
policy: MitmPolicyContext,
|
||||
mitm: Arc<MitmState>,
|
||||
upstream: UpstreamClient,
|
||||
}
|
||||
|
||||
enum MitmPolicyDecision {
|
||||
Allow {
|
||||
hook_actions: Option<MitmHookActions>,
|
||||
},
|
||||
Block(Response),
|
||||
}
|
||||
|
||||
const MITM_INSPECT_BODIES: bool = false;
|
||||
const MITM_MAX_BODY_BYTES: usize = 4096;
|
||||
impl std::fmt::Debug for MitmState {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Avoid dumping internal state (CA material, connectors, etc.) to logs.
|
||||
f.debug_struct("MitmState")
|
||||
.field("inspect", &self.inspect)
|
||||
.field("max_body_bytes", &self.max_body_bytes)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl MitmState {
|
||||
pub(crate) fn new(config: MitmUpstreamConfig) -> Result<Self> {
|
||||
ensure_rustls_crypto_provider();
|
||||
|
||||
// MITM exists when HTTPS policy depends on the inner request: limited-mode method clamps
|
||||
// and host-specific hooks both need visibility after CONNECT is established. We
|
||||
// generate a process-local CA and issue per-host leaf certs so we can terminate TLS and
|
||||
// apply policy.
|
||||
let ca = match config.external_ca.as_ref() {
|
||||
Some(ca) => ManagedMitmCa::load_from_files(ca)?,
|
||||
None => ManagedMitmCa::load_or_create()?,
|
||||
};
|
||||
let upstream_tls_root_store = crate::certs::upstream_tls_root_store_for_cert_path(
|
||||
ca.certificate_path(),
|
||||
&crate::certs::ca_env_from_process(),
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
ca,
|
||||
allow_upstream_proxy: config.allow_upstream_proxy,
|
||||
upstream_tls_root_store,
|
||||
inspect: MITM_INSPECT_BODIES,
|
||||
max_body_bytes: MITM_MAX_BODY_BYTES,
|
||||
})
|
||||
}
|
||||
|
||||
fn tls_acceptor_data_for_host(&self, host: &str) -> Result<TlsAcceptorData> {
|
||||
self.ca.tls_acceptor_data_for_host(host)
|
||||
}
|
||||
|
||||
pub(crate) fn inspect_enabled(&self) -> bool {
|
||||
self.inspect
|
||||
}
|
||||
|
||||
pub(crate) fn max_body_bytes(&self) -> usize {
|
||||
self.max_body_bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Proxy inner HTTP traffic, terminating TLS with a generated leaf certificate for HTTPS.
|
||||
pub(crate) async fn mitm_stream<S>(stream: S, scheme: Scheme) -> Result<()>
|
||||
where
|
||||
S: Stream + Unpin + ExtensionsMut,
|
||||
{
|
||||
let mitm = stream
|
||||
.extensions()
|
||||
.get::<Arc<MitmState>>()
|
||||
.cloned()
|
||||
.context("missing MITM state")?;
|
||||
let app_state = stream
|
||||
.extensions()
|
||||
.get::<Arc<NetworkProxyState>>()
|
||||
.cloned()
|
||||
.context("missing app state")?;
|
||||
let target = stream
|
||||
.extensions()
|
||||
.get::<ProxyTarget>()
|
||||
.context("missing proxy target")?
|
||||
.0
|
||||
.clone();
|
||||
let target_host = normalize_host(&target.host.to_string());
|
||||
let target_port = target.port;
|
||||
let acceptor_data = if scheme == Scheme::HTTPS {
|
||||
Some(mitm.tls_acceptor_data_for_host(&target_host)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mode = stream
|
||||
.extensions()
|
||||
.get::<NetworkMode>()
|
||||
.copied()
|
||||
.unwrap_or(NetworkMode::Full);
|
||||
let upstream = if mitm.allow_upstream_proxy {
|
||||
UpstreamClient::from_env_proxy_with_tls_root_store(
|
||||
app_state.clone(),
|
||||
mitm.upstream_tls_root_store.clone(),
|
||||
)
|
||||
} else {
|
||||
UpstreamClient::direct_with_tls_root_store(
|
||||
app_state.clone(),
|
||||
mitm.upstream_tls_root_store.clone(),
|
||||
)
|
||||
};
|
||||
let request_ctx = Arc::new(MitmRequestContext {
|
||||
policy: MitmPolicyContext {
|
||||
target_host,
|
||||
target_port,
|
||||
scheme,
|
||||
mode,
|
||||
app_state,
|
||||
},
|
||||
mitm,
|
||||
upstream,
|
||||
});
|
||||
|
||||
let executor = stream
|
||||
.extensions()
|
||||
.get::<Executor>()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let http_service = HttpServer::auto(executor).service(
|
||||
(request_ctx.policy.scheme == Scheme::HTTPS)
|
||||
.then(RemoveResponseHeaderLayer::hop_by_hop)
|
||||
.into_layer(service_fn({
|
||||
let request_ctx = request_ctx.clone();
|
||||
move |req| {
|
||||
let request_ctx = request_ctx.clone();
|
||||
async move { handle_mitm_request(req, request_ctx).await }
|
||||
}
|
||||
})),
|
||||
);
|
||||
|
||||
match acceptor_data {
|
||||
Some(acceptor_data) => {
|
||||
TlsAcceptorLayer::new(acceptor_data)
|
||||
.with_store_client_hello(true)
|
||||
.into_layer(http_service)
|
||||
.serve(stream)
|
||||
.await
|
||||
}
|
||||
None => http_service.serve(stream).await,
|
||||
}
|
||||
.map_err(|err| anyhow!("MITM serve error: {err}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_mitm_request(
|
||||
mut req: Request,
|
||||
request_ctx: Arc<MitmRequestContext>,
|
||||
) -> Result<Response, std::convert::Infallible> {
|
||||
crate::aws_sigv4::preserve_signing_headers(&mut req);
|
||||
crate::secret_substitution::preserve_body_substitution_headers(&mut req);
|
||||
let response = match (request_ctx.policy.scheme == Scheme::HTTPS)
|
||||
.then(RemoveRequestHeaderLayer::hop_by_hop)
|
||||
.into_layer(service_fn(move |req| {
|
||||
let request_ctx = request_ctx.clone();
|
||||
async move { forward_request(req, &request_ctx).await }
|
||||
}))
|
||||
.serve(req)
|
||||
.await
|
||||
{
|
||||
Ok(resp) => resp,
|
||||
Err(err) => {
|
||||
warn!("MITM request handling failed: {err}");
|
||||
text_response(StatusCode::BAD_GATEWAY, "mitm upstream error")
|
||||
}
|
||||
};
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn forward_request(req: Request, request_ctx: &MitmRequestContext) -> Result<Response> {
|
||||
let credential_destination = request_ctx.policy.credential_destination(&req);
|
||||
let hook_actions = match evaluate_mitm_policy(&req, &request_ctx.policy).await? {
|
||||
MitmPolicyDecision::Allow { hook_actions } => hook_actions,
|
||||
MitmPolicyDecision::Block(response) => return Ok(response),
|
||||
};
|
||||
|
||||
// Select the credential from the guest's headers before injecting or stripping anything.
|
||||
let mut signing = None;
|
||||
let client = req
|
||||
.extensions()
|
||||
.get::<SocketInfo>()
|
||||
.map(|info| info.peer_addr().to_string());
|
||||
if let Some(signer) = hook_actions
|
||||
.as_ref()
|
||||
.and_then(|actions| actions.aws_sigv4.as_ref())
|
||||
{
|
||||
match signer.plan(&req) {
|
||||
Ok(Some(guest)) => signing = Some((signer, guest)),
|
||||
Ok(None) => {}
|
||||
Err(_) => {
|
||||
return Ok(request_ctx
|
||||
.policy
|
||||
.deny_hook(req.method().as_str(), client)
|
||||
.await);
|
||||
}
|
||||
}
|
||||
}
|
||||
let target_host = request_ctx.policy.target_host.clone();
|
||||
let target_port = request_ctx.policy.target_port;
|
||||
let mitm = request_ctx.mitm.clone();
|
||||
|
||||
let method = req.method().as_str().to_string();
|
||||
let path = path_and_query(req.uri());
|
||||
let log_path = path_for_log(req.uri());
|
||||
|
||||
let (mut parts, body) = req.into_parts();
|
||||
let authority = authority_header_value(&target_host, target_port, &request_ctx.policy.scheme);
|
||||
parts.uri = Uri::builder()
|
||||
.scheme(request_ctx.policy.scheme.clone())
|
||||
.authority(authority.as_str())
|
||||
.path_and_query(path.as_str())
|
||||
.build()?;
|
||||
apply_request_credentials(
|
||||
&mut parts.headers,
|
||||
hook_actions.as_ref(),
|
||||
request_ctx.policy.app_state.as_ref(),
|
||||
&credential_destination,
|
||||
);
|
||||
parts
|
||||
.headers
|
||||
.insert(HOST, HeaderValue::from_str(&authority)?);
|
||||
|
||||
let inspect = mitm.inspect_enabled();
|
||||
let max_body_bytes = mitm.max_body_bytes();
|
||||
let body = if inspect {
|
||||
inspect_body(
|
||||
body,
|
||||
max_body_bytes,
|
||||
RequestLogContext {
|
||||
host: authority.clone(),
|
||||
method: method.clone(),
|
||||
path: log_path.clone(),
|
||||
},
|
||||
)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
|
||||
let mut upstream_req = Request::from_parts(parts, body);
|
||||
if let Some(substitution) = hook_actions
|
||||
.as_ref()
|
||||
.and_then(|actions| actions.body_secret_substitution.as_ref())
|
||||
{
|
||||
let Ok(substituted) = substitution.apply(upstream_req).await else {
|
||||
return Ok(request_ctx.policy.deny_hook(&method, client).await);
|
||||
};
|
||||
upstream_req = substituted;
|
||||
}
|
||||
if let Some((signer, guest)) = signing {
|
||||
let Ok(signed) = signer.sign(upstream_req, &guest).await else {
|
||||
return Ok(request_ctx.policy.deny_hook(&method, client).await);
|
||||
};
|
||||
upstream_req = signed;
|
||||
}
|
||||
let upstream_resp = if request_ctx.policy.scheme == Scheme::HTTP {
|
||||
crate::brokered_tunnel::forward_http_request(upstream_req, &request_ctx.upstream).await?
|
||||
} else {
|
||||
request_ctx.upstream.serve(upstream_req).await?
|
||||
};
|
||||
respond_with_inspection(
|
||||
upstream_resp,
|
||||
inspect,
|
||||
max_body_bytes,
|
||||
&method,
|
||||
&log_path,
|
||||
&authority,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
async fn mitm_blocking_response(
|
||||
req: &Request,
|
||||
policy: &MitmPolicyContext,
|
||||
) -> Result<Option<Response>> {
|
||||
match evaluate_mitm_policy(req, policy).await? {
|
||||
MitmPolicyDecision::Allow { .. } => Ok(None),
|
||||
MitmPolicyDecision::Block(response) => Ok(Some(response)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn evaluate_mitm_policy(
|
||||
req: &Request,
|
||||
policy: &MitmPolicyContext,
|
||||
) -> Result<MitmPolicyDecision> {
|
||||
if policy.scheme == Scheme::HTTP {
|
||||
let matches_target = |authority: &rama_http::uri::Authority| {
|
||||
!authority.as_str().contains('@')
|
||||
&& normalize_host(authority.host()) == policy.target_host
|
||||
&& authority.port_u16().unwrap_or(80) == policy.target_port
|
||||
};
|
||||
let invalid_destination = req
|
||||
.uri()
|
||||
.scheme()
|
||||
.is_some_and(|scheme| scheme != &Scheme::HTTP)
|
||||
|| req
|
||||
.uri()
|
||||
.authority()
|
||||
.is_some_and(|authority| !matches_target(authority))
|
||||
|| req.headers().get_all(HOST).iter().any(|value| {
|
||||
value
|
||||
.to_str()
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<rama_http::uri::Authority>().ok())
|
||||
.is_none_or(|authority| !matches_target(&authority))
|
||||
});
|
||||
if invalid_destination {
|
||||
return Ok(MitmPolicyDecision::Block(text_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"tunnel destination mismatch",
|
||||
)));
|
||||
}
|
||||
}
|
||||
if req.method().as_str() == "CONNECT" {
|
||||
return Ok(MitmPolicyDecision::Block(text_response(
|
||||
StatusCode::METHOD_NOT_ALLOWED,
|
||||
"CONNECT not supported inside MITM",
|
||||
)));
|
||||
}
|
||||
|
||||
let method = req.method().as_str().to_string();
|
||||
let log_path = path_for_log(req.uri());
|
||||
let client = req
|
||||
.extensions()
|
||||
.get::<SocketInfo>()
|
||||
.map(|info| info.peer_addr().to_string());
|
||||
|
||||
if let Some(request_host) = extract_request_host(req) {
|
||||
let normalized = normalize_host(&request_host);
|
||||
if !normalized.is_empty() && normalized != policy.target_host {
|
||||
warn!(
|
||||
"MITM host mismatch (target={}, request_host={normalized})",
|
||||
policy.target_host
|
||||
);
|
||||
return Ok(MitmPolicyDecision::Block(text_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"host mismatch",
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
// CONNECT already handled allowlist/denylist + decider policy. Re-check local/private
|
||||
// resolution here to defend against DNS rebinding between CONNECT and inner HTTPS requests.
|
||||
if matches!(
|
||||
policy
|
||||
.app_state
|
||||
.host_blocked_with_local_binding(
|
||||
&policy.target_host,
|
||||
policy.target_port,
|
||||
/*allow_local_binding*/ None,
|
||||
HostAuthorization::Approved,
|
||||
)
|
||||
.await?,
|
||||
HostBlockDecision::Blocked(HostBlockReason::NotAllowedLocal)
|
||||
) {
|
||||
let reason = HostBlockReason::NotAllowedLocal.as_str();
|
||||
let _ = policy
|
||||
.app_state
|
||||
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
|
||||
host: policy.target_host.clone(),
|
||||
reason: reason.to_string(),
|
||||
client: client.clone(),
|
||||
method: Some(method.clone()),
|
||||
mode: Some(policy.mode),
|
||||
protocol: policy.scheme.to_string(),
|
||||
decision: None,
|
||||
source: None,
|
||||
port: Some(policy.target_port),
|
||||
}))
|
||||
.await;
|
||||
warn!(
|
||||
"MITM blocked local/private target after CONNECT (host={}, port={}, method={method}, path={log_path})",
|
||||
policy.target_host, policy.target_port
|
||||
);
|
||||
return Ok(MitmPolicyDecision::Block(blocked_text_response(reason)));
|
||||
}
|
||||
|
||||
let hook_actions = match policy
|
||||
.app_state
|
||||
.evaluate_mitm_hook_request(
|
||||
&policy.target_host,
|
||||
req,
|
||||
&crate::mitm_hook::MitmHookOrigin {
|
||||
scheme: policy.scheme.clone(),
|
||||
port: policy.target_port,
|
||||
},
|
||||
&[policy.credential_destination(req)],
|
||||
)
|
||||
.await?
|
||||
{
|
||||
HookEvaluation::Matched { actions } if policy.placeholders_match(req, &actions) => {
|
||||
Some(actions)
|
||||
}
|
||||
HookEvaluation::Matched { .. } | HookEvaluation::HookedHostNoMatch => {
|
||||
return Ok(MitmPolicyDecision::Block(
|
||||
policy.deny_hook(&method, client).await,
|
||||
));
|
||||
}
|
||||
HookEvaluation::NoHooksForHost => None,
|
||||
};
|
||||
|
||||
let opaque_http_upgrade = policy.scheme == Scheme::HTTP
|
||||
&& policy.mode == NetworkMode::Limited
|
||||
&& req.headers().contains_key(rama_http::header::UPGRADE);
|
||||
if !policy.mode.allows_method(&method) || opaque_http_upgrade {
|
||||
let _ = policy
|
||||
.app_state
|
||||
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
|
||||
host: policy.target_host.clone(),
|
||||
reason: REASON_METHOD_NOT_ALLOWED.to_string(),
|
||||
client: client.clone(),
|
||||
method: Some(method.clone()),
|
||||
mode: Some(policy.mode),
|
||||
protocol: policy.scheme.to_string(),
|
||||
decision: None,
|
||||
source: None,
|
||||
port: Some(policy.target_port),
|
||||
}))
|
||||
.await;
|
||||
warn!(
|
||||
"MITM blocked by method policy (host={}, method={method}, path={log_path}, mode={:?}, allowed_methods=GET, HEAD, OPTIONS)",
|
||||
policy.target_host, policy.mode
|
||||
);
|
||||
return Ok(MitmPolicyDecision::Block(blocked_text_response(
|
||||
REASON_METHOD_NOT_ALLOWED,
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(MitmPolicyDecision::Allow { hook_actions })
|
||||
}
|
||||
|
||||
fn apply_request_credentials(
|
||||
headers: &mut HeaderMap,
|
||||
actions: Option<&MitmHookActions>,
|
||||
app_state: &NetworkProxyState,
|
||||
credential_destination: &str,
|
||||
) {
|
||||
app_state.inject_request_credentials(credential_destination, headers);
|
||||
let Some(actions) = actions else {
|
||||
return;
|
||||
};
|
||||
for header_name in &actions.strip_request_headers {
|
||||
headers.remove(header_name);
|
||||
}
|
||||
for injected_header in &actions.inject_request_headers {
|
||||
headers.insert(injected_header.name.clone(), injected_header.value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn respond_with_inspection(
|
||||
resp: Response,
|
||||
inspect: bool,
|
||||
max_body_bytes: usize,
|
||||
method: &str,
|
||||
log_path: &str,
|
||||
authority: &str,
|
||||
) -> Result<Response> {
|
||||
if !inspect {
|
||||
return Ok(resp);
|
||||
}
|
||||
|
||||
let (parts, body) = resp.into_parts();
|
||||
let body = inspect_body(
|
||||
body,
|
||||
max_body_bytes,
|
||||
ResponseLogContext {
|
||||
host: authority.to_string(),
|
||||
method: method.to_string(),
|
||||
path: log_path.to_string(),
|
||||
status: parts.status,
|
||||
},
|
||||
);
|
||||
Ok(Response::from_parts(parts, body))
|
||||
}
|
||||
|
||||
fn inspect_body<T: BodyLoggable + Send + 'static>(
|
||||
body: Body,
|
||||
max_body_bytes: usize,
|
||||
ctx: T,
|
||||
) -> Body {
|
||||
Body::from_stream(InspectStream {
|
||||
inner: Box::pin(body.into_data_stream()),
|
||||
ctx: Some(Box::new(ctx)),
|
||||
len: 0,
|
||||
max_body_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
struct InspectStream<T> {
|
||||
inner: Pin<Box<BodyDataStream>>,
|
||||
ctx: Option<Box<T>>,
|
||||
len: usize,
|
||||
max_body_bytes: usize,
|
||||
}
|
||||
|
||||
impl<T: BodyLoggable> FuturesStream for InspectStream<T> {
|
||||
type Item = Result<Bytes, BoxError>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = self.get_mut();
|
||||
match this.inner.as_mut().poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(bytes))) => {
|
||||
this.len = this.len.saturating_add(bytes.len());
|
||||
Poll::Ready(Some(Ok(bytes)))
|
||||
}
|
||||
Poll::Ready(Some(Err(err))) => Poll::Ready(Some(Err(err))),
|
||||
Poll::Ready(None) => {
|
||||
if let Some(ctx) = this.ctx.take() {
|
||||
ctx.log(this.len, this.len > this.max_body_bytes);
|
||||
}
|
||||
Poll::Ready(None)
|
||||
}
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RequestLogContext {
|
||||
host: String,
|
||||
method: String,
|
||||
path: String,
|
||||
}
|
||||
|
||||
struct ResponseLogContext {
|
||||
host: String,
|
||||
method: String,
|
||||
path: String,
|
||||
status: StatusCode,
|
||||
}
|
||||
|
||||
trait BodyLoggable {
|
||||
fn log(self, len: usize, truncated: bool);
|
||||
}
|
||||
|
||||
impl BodyLoggable for RequestLogContext {
|
||||
fn log(self, len: usize, truncated: bool) {
|
||||
let host = self.host;
|
||||
let method = self.method;
|
||||
let path = self.path;
|
||||
info!(
|
||||
"MITM inspected request body (host={host}, method={method}, path={path}, body_len={len}, truncated={truncated})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl BodyLoggable for ResponseLogContext {
|
||||
fn log(self, len: usize, truncated: bool) {
|
||||
let host = self.host;
|
||||
let method = self.method;
|
||||
let path = self.path;
|
||||
let status = self.status;
|
||||
info!(
|
||||
"MITM inspected response body (host={host}, method={method}, path={path}, status={status}, body_len={len}, truncated={truncated})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_request_host(req: &Request) -> Option<String> {
|
||||
req.headers()
|
||||
.get(HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(ToString::to_string)
|
||||
.or_else(|| req.uri().authority().map(|a| a.as_str().to_string()))
|
||||
}
|
||||
|
||||
fn authority_header_value(host: &str, port: u16, scheme: &Scheme) -> String {
|
||||
// Host header / URI authority formatting.
|
||||
let default_port = if scheme == &Scheme::HTTP { 80 } else { 443 };
|
||||
if host.contains(':') {
|
||||
if port == default_port {
|
||||
format!("[{host}]")
|
||||
} else {
|
||||
format!("[{host}]:{port}")
|
||||
}
|
||||
} else if port == default_port {
|
||||
host.to_string()
|
||||
} else {
|
||||
format!("{host}:{port}")
|
||||
}
|
||||
}
|
||||
|
||||
fn path_and_query(uri: &Uri) -> String {
|
||||
uri.path_and_query()
|
||||
.map(rama_http::uri::PathAndQuery::as_str)
|
||||
.unwrap_or("/")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn path_for_log(uri: &Uri) -> String {
|
||||
uri.path().to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mitm_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mitm_forwarding_tests.rs"]
|
||||
mod forwarding_tests;
|
||||
593
codex-rs/network-proxy/src/mitm_forwarding_tests.rs
Normal file
593
codex-rs/network-proxy/src/mitm_forwarding_tests.rs
Normal file
@@ -0,0 +1,593 @@
|
||||
//! Exercise authorized MITM forwarding over TLS, including transport-owned request bodies.
|
||||
|
||||
use super::*;
|
||||
use crate::aws_sigv4::AwsSigV4Config;
|
||||
use crate::aws_sigv4::ProxySecretSource;
|
||||
use crate::aws_sigv4::tests::guest_authorization;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::mitm_hook::MitmHookActionsConfig;
|
||||
use crate::mitm_hook::MitmHookConfig;
|
||||
use crate::mitm_hook::MitmHookMatchConfig;
|
||||
use crate::runtime::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_tls_rustls::dep::pki_types::PrivateKeyDer;
|
||||
use rama_tls_rustls::dep::pki_types::pem::PemObject;
|
||||
use rama_tls_rustls::dep::rcgen::CertificateParams;
|
||||
use rama_tls_rustls::dep::rcgen::KeyPair;
|
||||
use rama_tls_rustls::dep::tokio_rustls::TlsAcceptor;
|
||||
use sha2::Digest as _;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use tempfile::tempdir;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const FORWARD_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const RESPONSE: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
|
||||
async fn tls_origin(
|
||||
dir: &Path,
|
||||
service: &str,
|
||||
alpn: &[u8],
|
||||
) -> (MitmRequestContext, TcpListener, TlsAcceptor) {
|
||||
tls_origin_with_hook(dir, service, alpn, |_, _| {}).await
|
||||
}
|
||||
|
||||
async fn tls_origin_with_hook(
|
||||
dir: &Path,
|
||||
service: &str,
|
||||
alpn: &[u8],
|
||||
configure: impl FnOnce(&mut MitmHookConfig, u16),
|
||||
) -> (MitmRequestContext, TcpListener, TlsAcceptor) {
|
||||
ensure_rustls_crypto_provider();
|
||||
let key = KeyPair::generate().expect("generate origin key");
|
||||
let cert = CertificateParams::new(vec!["localhost".to_string()])
|
||||
.expect("origin certificate parameters")
|
||||
.self_signed(&key)
|
||||
.expect("origin certificate");
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
roots
|
||||
.add(cert.der().clone())
|
||||
.expect("trust origin certificate");
|
||||
let key =
|
||||
PrivateKeyDer::from_pem_slice(key.serialize_pem().as_bytes()).expect("parse origin key");
|
||||
let mut server_config =
|
||||
rustls::ServerConfig::builder_with_protocol_versions(rustls::ALL_VERSIONS)
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert.der().clone()], key)
|
||||
.expect("origin TLS configuration");
|
||||
server_config.alpn_protocols = vec![alpn.to_vec()];
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind TLS origin");
|
||||
let port = listener.local_addr().expect("origin address").port();
|
||||
|
||||
let access_key = dir.join("access-key");
|
||||
let secret_key = dir.join("secret-key");
|
||||
std::fs::write(&access_key, "AKIDEXAMPLE").expect("write access key");
|
||||
std::fs::write(&secret_key, "test-secret-key").expect("write secret key");
|
||||
let mut config = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
mode: NetworkMode::Full,
|
||||
allow_local_binding: Some(true),
|
||||
mitm_hooks: vec![MitmHookConfig {
|
||||
host: "localhost".to_string(),
|
||||
matcher: MitmHookMatchConfig {
|
||||
schemes: vec!["https".to_string()],
|
||||
ports: vec![port],
|
||||
methods: vec!["GET".to_string(), "POST".to_string()],
|
||||
path_prefixes: vec!["/".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
actions: MitmHookActionsConfig {
|
||||
strip_request_headers: vec!["x-amz-trailer".to_string()],
|
||||
aws_sigv4: Some(AwsSigV4Config {
|
||||
placeholder_access_key_id: "MASKEDACCESSKEY".to_string(),
|
||||
region: "us-east-1".to_string(),
|
||||
service: service.to_string(),
|
||||
access_key_id: ProxySecretSource::File(access_key.display().to_string()),
|
||||
secret_access_key: ProxySecretSource::File(secret_key.display().to_string()),
|
||||
session_token: None,
|
||||
port,
|
||||
max_body_bytes: 1024,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
configure(&mut config.mitm_hooks[0], port);
|
||||
config.set_credential_broker_enabled(/*enabled*/ true);
|
||||
config.set_allowed_domains(vec!["localhost".to_string()]);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(config));
|
||||
let roots = Arc::new(roots);
|
||||
let upstream =
|
||||
UpstreamClient::direct_with_tls_root_store(Arc::clone(&app_state), Arc::clone(&roots));
|
||||
let mitm = Arc::new(MitmState {
|
||||
ca: ManagedMitmCa::for_test(dir).expect("create test MITM CA"),
|
||||
allow_upstream_proxy: false,
|
||||
upstream_tls_root_store: roots,
|
||||
inspect: false,
|
||||
max_body_bytes: MITM_MAX_BODY_BYTES,
|
||||
});
|
||||
let context = MitmRequestContext {
|
||||
policy: MitmPolicyContext {
|
||||
target_host: "localhost".to_string(),
|
||||
target_port: port,
|
||||
scheme: Scheme::HTTPS,
|
||||
mode: NetworkMode::Full,
|
||||
app_state,
|
||||
},
|
||||
mitm,
|
||||
upstream,
|
||||
};
|
||||
(
|
||||
context,
|
||||
listener,
|
||||
TlsAcceptor::from(Arc::new(server_config)),
|
||||
)
|
||||
}
|
||||
|
||||
struct ReceivedRequest {
|
||||
path: String,
|
||||
headers: HashMap<String, String>,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
async fn read_request(stream: &mut (impl AsyncRead + Unpin)) -> ReceivedRequest {
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
assert!(head.len() < 16 * 1024, "bounded origin request headers");
|
||||
head.push(stream.read_u8().await.expect("read request headers"));
|
||||
}
|
||||
let head = String::from_utf8(head).expect("ASCII request headers");
|
||||
let mut lines = head.split("\r\n");
|
||||
let path = lines
|
||||
.next()
|
||||
.expect("request line")
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.expect("request target")
|
||||
.to_string();
|
||||
let headers = lines
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| {
|
||||
let (name, value) = line.split_once(':').expect("header separator");
|
||||
(name.to_ascii_lowercase(), value.trim().to_string())
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
assert!(!headers.contains_key("transfer-encoding"));
|
||||
let length = headers
|
||||
.get("content-length")
|
||||
.map_or(0, |length| length.parse::<usize>().expect("content length"));
|
||||
assert!(length <= 1024, "bounded origin request body");
|
||||
let mut body = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut body)
|
||||
.await
|
||||
.expect("drain request body");
|
||||
ReceivedRequest {
|
||||
path,
|
||||
headers,
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
fn request(
|
||||
context: &MitmRequestContext,
|
||||
service: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: &[u8],
|
||||
) -> Request {
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header(HOST, format!("localhost:{}", context.policy.target_port))
|
||||
.header(
|
||||
"authorization",
|
||||
guest_authorization(service, "host;x-amz-content-sha256;x-amz-date"),
|
||||
)
|
||||
.header("x-amz-date", "20150830T123600Z")
|
||||
.header("x-amz-content-sha256", "guest-hash")
|
||||
.body(Body::from(body.to_vec()))
|
||||
.expect("inner MITM request")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_aoss_payload_hashes_and_signatures_over_tls() {
|
||||
let dir = tempdir().expect("TLS fixture directory");
|
||||
let (context, listener, acceptor) = tls_origin(dir.path(), "aoss", b"http/1.1").await;
|
||||
let builder = crate::NetworkProxy::builder()
|
||||
.state(Arc::clone(&context.policy.app_state))
|
||||
.managed_proxy_routing(crate::ManagedProxyRouting::DedicatedListeners);
|
||||
let proxy = crate::certs::TEST_MITM_CA
|
||||
.scope(Arc::clone(&context.mitm.ca), builder.build())
|
||||
.await
|
||||
.expect("local proxy");
|
||||
let mut env = HashMap::from([("ALIAS".to_string(), "prefix:test-secret-key".to_string())]);
|
||||
proxy.apply_to_env_for_snapshot(&mut env);
|
||||
assert_eq!(env["AWS_ACCESS_KEY_ID"], "MASKEDACCESSKEY");
|
||||
assert_eq!(env["AWS_CA_BUNDLE"], env["SSL_CERT_FILE"]);
|
||||
assert_eq!(Path::new(&env["AWS_CA_BUNDLE"]).parent(), Some(dir.path()));
|
||||
assert!(crate::brokered_credential_env_keys(&env).any(|key| key == "AWS_ACCESS_KEY_ID"));
|
||||
assert_eq!(
|
||||
env["ALIAS"],
|
||||
format!("prefix:{}", env["AWS_SECRET_ACCESS_KEY"])
|
||||
);
|
||||
let mut snapshot = "export COPY=test-secret-key".to_string();
|
||||
assert!(proxy.virtualize_brokered_text(&mut snapshot, &env));
|
||||
assert_eq!(
|
||||
snapshot,
|
||||
format!("export COPY={}", env["AWS_SECRET_ACCESS_KEY"])
|
||||
);
|
||||
let remote = proxy
|
||||
.prepare_for_remote_environment(HashMap::new(), "remote")
|
||||
.expect("remote environment");
|
||||
assert!(!remote.env.contains_key("AWS_ACCESS_KEY_ID"));
|
||||
assert!(!remote.env.contains_key("AWS_CA_BUNDLE"));
|
||||
let cases: [(&str, &[u8]); 4] = [
|
||||
("/unsigned", b""),
|
||||
("/other-key", b""),
|
||||
("/get", b""),
|
||||
("/post", b"{\"message\":\"hello\"}"),
|
||||
];
|
||||
let other_key =
|
||||
guest_authorization("aoss", "host;x-amz-date").replace("MASKEDACCESSKEY", "OTHERKEY");
|
||||
let expected_other = other_key.clone();
|
||||
let server = tokio::spawn(async move {
|
||||
for (path, body) in cases {
|
||||
let (stream, _) = listener.accept().await.expect("accept origin connection");
|
||||
let mut stream = acceptor.accept(stream).await.expect("origin TLS handshake");
|
||||
let received = read_request(&mut stream).await;
|
||||
assert_eq!(received.path, path);
|
||||
assert_eq!(received.body, body);
|
||||
match path {
|
||||
"/unsigned" => assert!(!received.headers.contains_key("authorization")),
|
||||
"/other-key" => assert_eq!(received.headers["authorization"], expected_other),
|
||||
_ => {
|
||||
assert_eq!(
|
||||
received.headers["x-amz-content-sha256"],
|
||||
format!("{:x}", sha2::Sha256::digest(body))
|
||||
);
|
||||
assert!(received.headers["authorization"].contains(
|
||||
"Credential=AKIDEXAMPLE/20150830/us-east-1/aoss/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date,"
|
||||
));
|
||||
}
|
||||
}
|
||||
stream.write_all(RESPONSE).await.expect("origin response");
|
||||
}
|
||||
});
|
||||
|
||||
for (path, body) in cases {
|
||||
let method = if body.is_empty() { "GET" } else { "POST" };
|
||||
let mut req = request(&context, "aoss", method, path, body);
|
||||
if path == "/unsigned" {
|
||||
req.headers_mut().remove("authorization");
|
||||
} else if path == "/other-key" {
|
||||
req.headers_mut()
|
||||
.insert("authorization", HeaderValue::from_str(&other_key).unwrap());
|
||||
}
|
||||
let response = timeout(FORWARD_TIMEOUT, forward_request(req, &context))
|
||||
.await
|
||||
.expect("MITM forwarding deadline")
|
||||
.expect("MITM forwarding");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
timeout(FORWARD_TIMEOUT, server)
|
||||
.await
|
||||
.expect("origin completion deadline")
|
||||
.expect("origin assertions");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn signs_only_supported_http1_requests_for_an_http2_origin() {
|
||||
use rama_core::ServiceInput;
|
||||
use rama_http::body::util::BodyExt;
|
||||
|
||||
let dir = tempdir().expect("TLS fixture directory");
|
||||
let (context, listener, acceptor) = tls_origin(dir.path(), "s3", b"h2").await;
|
||||
let context = Arc::new(context);
|
||||
let (observed, mut received) = mpsc::unbounded_channel();
|
||||
let origin = tokio::spawn(async move {
|
||||
loop {
|
||||
let (socket, _) = listener.accept().await.expect("accept origin");
|
||||
let stream = acceptor.accept(socket).await.expect("origin TLS");
|
||||
let observed = observed.clone();
|
||||
let service = service_fn(move |request: Request| {
|
||||
let observed = observed.clone();
|
||||
async move {
|
||||
let (parts, body) = request.into_parts();
|
||||
let body = body.collect().await.expect("origin body").to_bytes();
|
||||
observed.send((parts, body)).expect("report origin request");
|
||||
Ok::<_, std::convert::Infallible>(Response::new(Body::empty()))
|
||||
}
|
||||
});
|
||||
HttpServer::h2(Executor::default())
|
||||
.service(service)
|
||||
.serve(ServiceInput::new(stream))
|
||||
.await
|
||||
.expect("serve HTTP/2");
|
||||
}
|
||||
});
|
||||
|
||||
let auth = guest_authorization("s3", "host;x-amz-date");
|
||||
for (extra_headers, status) in [
|
||||
("Content-Length: 1\r\nTransfer-Encoding: chunked\r\n", 403),
|
||||
("Transfer-Encoding: gzip, chunked\r\n", 403),
|
||||
(
|
||||
"Transfer-Encoding: chunked\r\nConnection: Authorization\r\n",
|
||||
403,
|
||||
),
|
||||
(
|
||||
"Transfer-Encoding: chunked\r\nX-Amz-Trailer: checksum\r\n",
|
||||
403,
|
||||
),
|
||||
(
|
||||
"Transfer-Encoding: chunked\r\nContent-Encoding: aws-chunked\r\nConnection: content-encoding\r\n",
|
||||
403,
|
||||
),
|
||||
// Rama discards Content-Length when it appears after Transfer-Encoding.
|
||||
// Verify that the retained chunk framing and the signed payload agree.
|
||||
(
|
||||
"Transfer-Encoding: chunked\r\nContent-Length: 1\r\nKeep-Alive: timeout=5\r\nSec-WebSocket-Key: test\r\n",
|
||||
200,
|
||||
),
|
||||
] {
|
||||
let (mut guest, io) = tokio::io::duplex(4096);
|
||||
let handler = service_fn({
|
||||
let context = Arc::clone(&context);
|
||||
move |request| handle_mitm_request(request, Arc::clone(&context))
|
||||
});
|
||||
let guest_server = tokio::spawn(async move {
|
||||
HttpServer::http1()
|
||||
.service(handler)
|
||||
.serve(ServiceInput::new(io))
|
||||
.await
|
||||
.expect("serve guest");
|
||||
});
|
||||
let request = format!(
|
||||
"POST /key HTTP/1.1\r\nHost: localhost:{}\r\nAuthorization: {auth}\r\nX-Amz-Date: 20150830T123600Z\r\n{extra_headers}Connection: close\r\n\r\n3\r\nabc\r\n0\r\n\r\n",
|
||||
context.policy.target_port
|
||||
);
|
||||
guest
|
||||
.write_all(request.as_bytes())
|
||||
.await
|
||||
.expect("send guest request");
|
||||
let mut response = Vec::new();
|
||||
timeout(FORWARD_TIMEOUT, guest.read_to_end(&mut response))
|
||||
.await
|
||||
.expect("response deadline")
|
||||
.expect("read guest response");
|
||||
guest_server.await.expect("guest server");
|
||||
assert!(
|
||||
response.starts_with(format!("HTTP/1.1 {status} ").as_bytes()),
|
||||
"{extra_headers}: {}",
|
||||
String::from_utf8_lossy(&response)
|
||||
);
|
||||
}
|
||||
let (parts, body) = received.try_recv().expect("one allowed request");
|
||||
assert!(received.try_recv().is_err());
|
||||
assert_eq!(parts.version, rama_http::Version::HTTP_2);
|
||||
assert_eq!(body.as_ref(), b"abc");
|
||||
assert_eq!(
|
||||
parts.headers["x-amz-content-sha256"],
|
||||
format!("{:x}", sha2::Sha256::digest(&body))
|
||||
);
|
||||
let authorization = parts.headers["authorization"].to_str().expect("signature");
|
||||
let (fields, _) = authorization
|
||||
.split_once("SignedHeaders=")
|
||||
.expect("signed fields")
|
||||
.1
|
||||
.split_once(',')
|
||||
.expect("signature suffix");
|
||||
for name in fields.split(';') {
|
||||
// HTTP/2 transports Host in :authority.
|
||||
assert!(name == "host" || parts.headers.contains_key(name), "{name}");
|
||||
}
|
||||
origin.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drained_signed_bodies_release_capacity_before_response_headers() {
|
||||
let dir = tempdir().expect("TLS fixture directory");
|
||||
let (context, listener, acceptor) = tls_origin(dir.path(), "sqs", b"http/1.1").await;
|
||||
let (arrived, mut arrivals) = mpsc::channel(9);
|
||||
let (release, released) = watch::channel(false);
|
||||
let server = tokio::spawn(async move {
|
||||
let mut requests = JoinSet::new();
|
||||
for _ in 0..9 {
|
||||
let (stream, _) = listener.accept().await.expect("accept origin connection");
|
||||
let acceptor = acceptor.clone();
|
||||
let arrived = arrived.clone();
|
||||
let mut released = released.clone();
|
||||
requests.spawn(async move {
|
||||
let mut stream = acceptor.accept(stream).await.expect("origin TLS handshake");
|
||||
let received = read_request(&mut stream).await;
|
||||
let wait = received.path.starts_with("/wait/");
|
||||
let expected_body = if wait {
|
||||
b"Action=ReceiveMessage".as_slice()
|
||||
} else {
|
||||
b"Action=SendMessage&MessageBody=hello".as_slice()
|
||||
};
|
||||
assert_eq!(received.body, expected_body);
|
||||
assert!(received.headers["authorization"].contains("/sqs/aws4_request"));
|
||||
arrived
|
||||
.send(received.path)
|
||||
.await
|
||||
.expect("report drained body");
|
||||
if wait {
|
||||
released
|
||||
.wait_for(|released| *released)
|
||||
.await
|
||||
.expect("release delayed headers");
|
||||
}
|
||||
stream.write_all(RESPONSE).await.expect("origin response");
|
||||
});
|
||||
}
|
||||
while let Some(result) = requests.join_next().await {
|
||||
result.expect("origin request assertions");
|
||||
}
|
||||
});
|
||||
|
||||
let mut pending = JoinSet::new();
|
||||
for index in 0..8 {
|
||||
let context = context.clone();
|
||||
pending.spawn(async move {
|
||||
let req = request(
|
||||
&context,
|
||||
"sqs",
|
||||
"POST",
|
||||
&format!("/wait/{index}"),
|
||||
b"Action=ReceiveMessage",
|
||||
);
|
||||
forward_request(req, &context).await
|
||||
});
|
||||
}
|
||||
for _ in 0..8 {
|
||||
let path = timeout(FORWARD_TIMEOUT, arrivals.recv())
|
||||
.await
|
||||
.expect("eight request bodies must drain")
|
||||
.expect("origin remains connected");
|
||||
assert!(path.starts_with("/wait/"));
|
||||
}
|
||||
|
||||
// All eight responses still lack headers; only their request bodies have completed.
|
||||
let ninth = timeout(
|
||||
FORWARD_TIMEOUT,
|
||||
forward_request(
|
||||
request(
|
||||
&context,
|
||||
"sqs",
|
||||
"POST",
|
||||
"/send",
|
||||
b"Action=SendMessage&MessageBody=hello",
|
||||
),
|
||||
&context,
|
||||
),
|
||||
)
|
||||
.await;
|
||||
release.send(true).expect("release long polls");
|
||||
while let Some(result) = timeout(FORWARD_TIMEOUT, pending.join_next())
|
||||
.await
|
||||
.expect("long poll completion deadline")
|
||||
{
|
||||
let response = result.expect("forward task").expect("long poll response");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
// Aborting the origin also aborts its request tasks if the ninth request never arrived.
|
||||
server.abort();
|
||||
let response = ninth
|
||||
.expect("ninth forwarding deadline")
|
||||
.expect("drained bodies must release buffer slots before response headers");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_substituted_body_before_signing() {
|
||||
let marker = b"codex-secret-0123456789abcdef";
|
||||
let dir = tempdir().expect("TLS fixture directory");
|
||||
let secret = dir.path().join("body-secret");
|
||||
std::fs::write(&secret, "expanded-payload").unwrap();
|
||||
let configure = |hook: &mut MitmHookConfig, port| {
|
||||
hook.matcher.path_prefixes = vec!["/allowed/".into()];
|
||||
hook.actions.strip_request_headers.push("digest".into());
|
||||
hook.actions.body_secret_substitution = Some(crate::BodySecretSubstitutionConfig {
|
||||
replacements: vec![crate::BodySecretReplacement {
|
||||
placeholder: String::from_utf8(marker.to_vec()).unwrap(),
|
||||
secret: ProxySecretSource::File(secret.display().to_string()),
|
||||
}],
|
||||
port,
|
||||
max_body_bytes: 64,
|
||||
});
|
||||
};
|
||||
let (context, listener, acceptor) =
|
||||
tls_origin_with_hook(dir.path(), "s3", b"http/1.1", configure).await;
|
||||
let context = Arc::new(context);
|
||||
let signed_headers = "content-length;cookie;host;x-amz-date";
|
||||
let make_request = |path: &str| {
|
||||
let mut req = request(&context, "s3", "POST", path, marker);
|
||||
*req.version_mut() = rama_http::Version::HTTP_2;
|
||||
let headers = req.headers_mut();
|
||||
headers.remove("x-amz-content-sha256");
|
||||
headers.insert(
|
||||
"authorization",
|
||||
HeaderValue::from_str(&guest_authorization("s3", signed_headers)).unwrap(),
|
||||
);
|
||||
headers.insert("content-length", HeaderValue::from(marker.len()));
|
||||
headers.append("cookie", HeaderValue::from_static("a=1"));
|
||||
headers.append("cookie", HeaderValue::from_static("b=2"));
|
||||
req
|
||||
};
|
||||
let denied = handle_mitm_request(make_request("/denied"), context.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
|
||||
let mut invalid = make_request("/allowed/item");
|
||||
invalid
|
||||
.headers_mut()
|
||||
.insert("digest", HeaderValue::from_static("sha-256=guest"));
|
||||
let denied = handle_mitm_request(invalid, context.clone()).await.unwrap();
|
||||
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
|
||||
let origin = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut stream = acceptor.accept(socket).await.unwrap();
|
||||
let wire = read_request(&mut stream).await;
|
||||
stream.write_all(RESPONSE).await.unwrap();
|
||||
wire
|
||||
});
|
||||
let req = make_request("/allowed/item");
|
||||
let response = timeout(FORWARD_TIMEOUT, handle_mitm_request(req, context))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let wire = origin.await.unwrap();
|
||||
assert_eq!(wire.body.as_slice(), b"expanded-payload");
|
||||
assert_eq!(wire.path, "/allowed/item");
|
||||
let headers = wire.headers;
|
||||
assert_eq!(headers["cookie"], "a=1; b=2");
|
||||
let expected_hash = format!("{:x}", sha2::Sha256::digest(&wire.body));
|
||||
assert_eq!(headers["x-amz-content-sha256"], expected_hash);
|
||||
// Rebuild the canonical request from the received HTTP/1.1 headers, without
|
||||
// the signer's request preparation or the SDK's header canonicalization.
|
||||
let canonical_headers = signed_headers
|
||||
.split(';')
|
||||
.map(|name| format!("{name}:{}\n", headers[name]))
|
||||
.collect::<String>();
|
||||
let canonical_request =
|
||||
format!("POST\n/allowed/item\n\n{canonical_headers}\n{signed_headers}\n{expected_hash}");
|
||||
let timestamp = &headers["x-amz-date"];
|
||||
let signing_time = chrono::NaiveDateTime::parse_from_str(timestamp, "%Y%m%dT%H%M%SZ")
|
||||
.unwrap()
|
||||
.and_utc();
|
||||
let scope = format!(
|
||||
"{}/us-east-1/s3/aws4_request",
|
||||
signing_time.format("%Y%m%d")
|
||||
);
|
||||
let string_to_sign = format!(
|
||||
"AWS4-HMAC-SHA256\n{timestamp}\n{scope}\n{:x}",
|
||||
sha2::Sha256::digest(canonical_request.as_bytes())
|
||||
);
|
||||
let signing_key = aws_sigv4::sign::v4::generate_signing_key(
|
||||
"test-secret-key",
|
||||
signing_time.into(),
|
||||
"us-east-1",
|
||||
"s3",
|
||||
);
|
||||
let signature =
|
||||
aws_sigv4::sign::v4::calculate_signature(signing_key, string_to_sign.as_bytes());
|
||||
assert_eq!(
|
||||
headers["authorization"],
|
||||
format!(
|
||||
"AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/{scope}, SignedHeaders={signed_headers}, Signature={signature}"
|
||||
)
|
||||
);
|
||||
}
|
||||
1320
codex-rs/network-proxy/src/mitm_hook.rs
Normal file
1320
codex-rs/network-proxy/src/mitm_hook.rs
Normal file
File diff suppressed because it is too large
Load Diff
593
codex-rs/network-proxy/src/mitm_tests.rs
Normal file
593
codex-rs/network-proxy/src/mitm_tests.rs
Normal file
@@ -0,0 +1,593 @@
|
||||
use super::*;
|
||||
|
||||
use crate::CredentialProviderConfig;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::reasons::REASON_METHOD_NOT_ALLOWED;
|
||||
use crate::reasons::REASON_MITM_HOOK_DENIED;
|
||||
use crate::reasons::REASON_NOT_ALLOWED_LOCAL;
|
||||
use crate::runtime::network_proxy_state_for_policy;
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_http::Body;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::Method;
|
||||
use rama_http::Request;
|
||||
use rama_http::StatusCode;
|
||||
use rama_http::header::HeaderName;
|
||||
use std::collections::HashMap;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
fn github_write_hook() -> crate::mitm_hook::MitmHookConfig {
|
||||
crate::mitm_hook::MitmHookConfig {
|
||||
host: "api.github.com".to_string(),
|
||||
matcher: crate::mitm_hook::MitmHookMatchConfig {
|
||||
methods: vec!["POST".to_string(), "PUT".to_string()],
|
||||
path_prefixes: vec!["/repos/openai/".to_string()],
|
||||
..crate::mitm_hook::MitmHookMatchConfig::default()
|
||||
},
|
||||
actions: crate::mitm_hook::MitmHookActionsConfig {
|
||||
body_secret_substitution: None,
|
||||
aws_sigv4: None,
|
||||
strip_request_headers: vec!["authorization".to_string()],
|
||||
inject_request_headers: vec![crate::mitm_hook::InjectedHeaderConfig {
|
||||
placeholder: None,
|
||||
name: "authorization".to_string(),
|
||||
secret_env_var: Some("CODEX_GITHUB_TOKEN".to_string()),
|
||||
secret_file: None,
|
||||
prefix: Some("Bearer ".to_string()),
|
||||
}],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn policy_ctx(
|
||||
app_state: Arc<NetworkProxyState>,
|
||||
mode: NetworkMode,
|
||||
target_host: &str,
|
||||
target_port: u16,
|
||||
) -> MitmPolicyContext {
|
||||
MitmPolicyContext {
|
||||
target_host: target_host.to_string(),
|
||||
target_port,
|
||||
scheme: Scheme::HTTPS,
|
||||
mode,
|
||||
app_state,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_blocks_disallowed_method_and_records_telemetry() {
|
||||
let app_state = Arc::new(network_proxy_state_for_policy({
|
||||
let mut network = NetworkProxyConfig::default();
|
||||
network.set_allowed_domains(vec!["example.com".to_string()]);
|
||||
network
|
||||
}));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Limited,
|
||||
"example.com",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/v1/responses?api_key=secret")
|
||||
.header(HOST, "example.com")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let response = mitm_blocking_response(&req, &ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("POST should be blocked in limited mode");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(
|
||||
response.headers().get("x-proxy-error").unwrap(),
|
||||
"blocked-by-method-policy"
|
||||
);
|
||||
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(blocked.len(), 1);
|
||||
assert_eq!(blocked[0].reason, REASON_METHOD_NOT_ALLOWED);
|
||||
assert_eq!(blocked[0].method.as_deref(), Some("POST"));
|
||||
assert_eq!(blocked[0].host, "example.com");
|
||||
assert_eq!(blocked[0].port, Some(443));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_rejects_host_mismatch() {
|
||||
let app_state = Arc::new(network_proxy_state_for_policy({
|
||||
let mut network = NetworkProxyConfig::default();
|
||||
network.set_allowed_domains(vec!["example.com".to_string()]);
|
||||
network
|
||||
}));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Full,
|
||||
"example.com",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/")
|
||||
.header(HOST, "evil.example")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let response = mitm_blocking_response(&req, &ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("mismatched host should be rejected");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
assert_eq!(app_state.blocked_snapshot().await.unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_rechecks_local_private_target_after_connect() {
|
||||
let app_state = Arc::new(network_proxy_state_for_policy({
|
||||
let mut network = NetworkProxyConfig::default();
|
||||
network.set_allowed_domains(vec!["example.com".to_string()]);
|
||||
network.allow_local_binding = Some(false);
|
||||
network
|
||||
}));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Full,
|
||||
"10.0.0.1",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/health?token=secret")
|
||||
.header(HOST, "10.0.0.1")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let response = mitm_blocking_response(&req, &ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("local/private target should be blocked on inner request");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(blocked.len(), 1);
|
||||
assert_eq!(blocked[0].reason, REASON_NOT_ALLOWED_LOCAL);
|
||||
assert_eq!(blocked[0].host, "10.0.0.1");
|
||||
assert_eq!(blocked[0].port, Some(443));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_rechecks_dns_for_approved_unallowlisted_host() {
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(NetworkProxyConfig::default()));
|
||||
let host = "does-not-resolve.invalid";
|
||||
// The context represents an approved CONNECT, without a persisted allowlist entry.
|
||||
let ctx = policy_ctx(
|
||||
Arc::clone(&app_state),
|
||||
NetworkMode::Full,
|
||||
host,
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/")
|
||||
.header(HOST, host)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let response = mitm_blocking_response(&req, &ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("approved CONNECT must still validate DNS on inner requests");
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
response.status(),
|
||||
blocked
|
||||
.iter()
|
||||
.map(|request| (request.host.as_str(), request.reason.as_str(), request.port))
|
||||
.collect::<Vec<_>>()
|
||||
),
|
||||
(
|
||||
StatusCode::FORBIDDEN,
|
||||
vec![(host, REASON_NOT_ALLOWED_LOCAL, Some(443))]
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_allows_matching_hooked_write_in_full_mode() {
|
||||
let secret_file = NamedTempFile::new().unwrap();
|
||||
std::fs::write(secret_file.path(), "ghp-secret\n").unwrap();
|
||||
let mut hook = github_write_hook();
|
||||
hook.actions.inject_request_headers[0].placeholder = Some("guest".into());
|
||||
hook.actions.inject_request_headers[0].secret_env_var = None;
|
||||
hook.actions.inject_request_headers[0].secret_file =
|
||||
Some(secret_file.path().display().to_string());
|
||||
let mut network = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
mitm_hooks: vec![hook],
|
||||
mode: NetworkMode::Full,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.set_allowed_domains(vec!["api.github.com".to_string()]);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(network));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Full,
|
||||
"api.github.com",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/repos/openai/codex/issues")
|
||||
.header(HOST, "api.github.com")
|
||||
.header("authorization", "guest")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let response = mitm_blocking_response(&req, &ctx).await.unwrap();
|
||||
|
||||
assert!(
|
||||
response.is_none(),
|
||||
"matching hook should bypass method clamp"
|
||||
);
|
||||
assert_eq!(app_state.blocked_snapshot().await.unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_enforces_brokered_aliases_without_blocking_unrelated_credentials() {
|
||||
for hooked_hosts in [
|
||||
vec!["api.github.com"],
|
||||
vec!["api.github.com", "github.com"],
|
||||
vec![],
|
||||
] {
|
||||
let network = NetworkProxyConfig {
|
||||
credential_broker: true,
|
||||
mitm: true,
|
||||
allow_local_binding: Some(true),
|
||||
mitm_hooks: hooked_hosts
|
||||
.iter()
|
||||
.map(|host| {
|
||||
let mut hook = github_write_hook();
|
||||
hook.host = (*host).to_string();
|
||||
hook.matcher.methods = vec!["GET".to_string()];
|
||||
hook.actions.inject_request_headers.clear();
|
||||
hook
|
||||
})
|
||||
.collect(),
|
||||
..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()),
|
||||
("GH_HOST".to_string(), "enterprise.example".to_string()),
|
||||
(
|
||||
"GH_ENTERPRISE_TOKEN".to_string(),
|
||||
"ghp-enterprise-real".to_string(),
|
||||
),
|
||||
]);
|
||||
app_state.virtualize_child_credentials(&mut env);
|
||||
let github = format!("Bearer {}", env["GH_TOKEN"]);
|
||||
let token = format!("token {}", env["GH_TOKEN"]);
|
||||
let basic = format!(
|
||||
"Basic {}",
|
||||
STANDARD.encode(format!("x-access-token:{}", env["GH_TOKEN"]))
|
||||
);
|
||||
let openai = format!("Bearer {}", env["OPENAI_API_KEY"]);
|
||||
let enterprise = format!("Bearer {}", env["GH_ENTERPRISE_TOKEN"]);
|
||||
for (host, authorization, uses_cloud_credential) in [
|
||||
("github.com", Some(github.as_str()), true),
|
||||
("api.astemu.ghe.com", Some(github.as_str()), true),
|
||||
("github.com", Some(token.as_str()), true),
|
||||
("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),
|
||||
("enterprise.example", Some(enterprise.as_str()), false),
|
||||
] {
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Full,
|
||||
host,
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let mut req = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri("/repos/openai/codex/issues")
|
||||
.header(HOST, host)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
if let Some(value) = authorization {
|
||||
req.headers_mut()
|
||||
.insert("authorization", HeaderValue::from_str(value).unwrap());
|
||||
}
|
||||
let denied =
|
||||
uses_cloud_credential && !hooked_hosts.is_empty() && !hooked_hosts.contains(&host);
|
||||
let response = mitm_blocking_response(&req, &ctx).await.unwrap();
|
||||
assert_eq!(
|
||||
response.as_ref().map(Response::status),
|
||||
denied.then_some(StatusCode::FORBIDDEN),
|
||||
"host: {host}, hooks: {hooked_hosts:?}"
|
||||
);
|
||||
if let Some(response) = response {
|
||||
assert_eq!(response.headers()["x-proxy-error"], "blocked-by-mitm-hook");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_checks_configured_credential_aliases_at_the_request_destination() {
|
||||
let mut hook = github_write_hook();
|
||||
hook.host = "api.hooked.example".to_string();
|
||||
hook.actions.inject_request_headers.clear();
|
||||
let mut network = NetworkProxyConfig {
|
||||
credential_broker: true,
|
||||
mitm: true,
|
||||
allow_local_binding: Some(true),
|
||||
mitm_hooks: vec![hook],
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.credential_providers.insert(
|
||||
"custom".to_string(),
|
||||
CredentialProviderConfig {
|
||||
env: vec!["PROVIDER_TOKEN".to_string()],
|
||||
patterns: vec!["provider_[a-z]{24}".to_string()],
|
||||
// The hooked host need not use the alias's port or path prefix.
|
||||
url_prefixes: vec![
|
||||
"https://*.hooked.example/v1".to_string(),
|
||||
"https://alias.example:8443/v2".to_string(),
|
||||
],
|
||||
..CredentialProviderConfig::default()
|
||||
},
|
||||
);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(network));
|
||||
let mut env = HashMap::from([(
|
||||
"PROVIDER_TOKEN".to_string(),
|
||||
"provider_abcdefghijklmnopqrstuvwx".to_string(),
|
||||
)]);
|
||||
app_state.virtualize_child_credentials(&mut env);
|
||||
let ctx = policy_ctx(
|
||||
app_state,
|
||||
NetworkMode::Full,
|
||||
"alias.example",
|
||||
/*target_port*/ 8443,
|
||||
);
|
||||
for (path, denied) in [
|
||||
("/v2/models", true),
|
||||
("/v20/models", false),
|
||||
("/v2/../v2/models", false),
|
||||
] {
|
||||
let req = Request::builder()
|
||||
.uri(path)
|
||||
.header(HOST, "alias.example:8443")
|
||||
.header("authorization", format!("Bearer {}", env["PROVIDER_TOKEN"]))
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let response = mitm_blocking_response(&req, &ctx).await.unwrap();
|
||||
assert_eq!(
|
||||
response.as_ref().map(Response::status),
|
||||
denied.then_some(StatusCode::FORBIDDEN),
|
||||
"path: {path}"
|
||||
);
|
||||
if let Some(response) = response {
|
||||
assert_eq!(response.headers()["x-proxy-error"], "blocked-by-mitm-hook");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_blocks_encoded_path_traversal_for_repository_allowlist() {
|
||||
let mut hook = github_write_hook();
|
||||
hook.host = "github.com".to_string();
|
||||
hook.matcher.methods = vec!["GET".to_string()];
|
||||
hook.matcher.path_prefixes = vec!["pattern:/openai/openai/**".to_string()];
|
||||
hook.actions.inject_request_headers.clear();
|
||||
let mut network = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
mitm_hooks: vec![hook],
|
||||
mode: NetworkMode::Full,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.set_allowed_domains(vec!["github.com".to_string()]);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(network));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Full,
|
||||
"github.com",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let paths = [
|
||||
"/openai/openai/issues",
|
||||
"/openai/codex",
|
||||
"/openai/openai/%2e%2e/codex",
|
||||
"/openai/openai/%2e%2e/%2e%2e/microsoft/vscode",
|
||||
];
|
||||
let mut actual = Vec::with_capacity(paths.len());
|
||||
for path in paths {
|
||||
let req = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri(path)
|
||||
.header(HOST, "github.com")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let response = mitm_blocking_response(&req, &ctx).await.unwrap();
|
||||
actual.push(response.map(|response| {
|
||||
(
|
||||
response.status(),
|
||||
response.headers().get("x-proxy-error").cloned(),
|
||||
)
|
||||
}));
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
actual,
|
||||
vec![
|
||||
None,
|
||||
Some((
|
||||
StatusCode::FORBIDDEN,
|
||||
Some(HeaderValue::from_static("blocked-by-mitm-hook")),
|
||||
)),
|
||||
Some((
|
||||
StatusCode::FORBIDDEN,
|
||||
Some(HeaderValue::from_static("blocked-by-mitm-hook")),
|
||||
)),
|
||||
Some((
|
||||
StatusCode::FORBIDDEN,
|
||||
Some(HeaderValue::from_static("blocked-by-mitm-hook")),
|
||||
)),
|
||||
]
|
||||
);
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(blocked.len(), 3);
|
||||
assert!(
|
||||
blocked
|
||||
.iter()
|
||||
.all(|request| request.reason == REASON_MITM_HOOK_DENIED)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_blocks_matching_hooked_write_in_limited_mode() {
|
||||
let mut hook = github_write_hook();
|
||||
hook.actions.inject_request_headers.clear();
|
||||
let mut network = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
mitm_hooks: vec![hook],
|
||||
mode: NetworkMode::Limited,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.set_allowed_domains(vec!["api.github.com".to_string()]);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(network));
|
||||
let ctx = policy_ctx(
|
||||
app_state.clone(),
|
||||
NetworkMode::Limited,
|
||||
"api.github.com",
|
||||
/*target_port*/ 443,
|
||||
);
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri("/repos/openai/codex/issues")
|
||||
.header(HOST, "api.github.com")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let response = mitm_blocking_response(&req, &ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("matching POST hook should still be blocked in limited mode");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(
|
||||
response.headers().get("x-proxy-error").unwrap(),
|
||||
"blocked-by-method-policy"
|
||||
);
|
||||
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(blocked.len(), 1);
|
||||
assert_eq!(blocked[0].reason, REASON_METHOD_NOT_ALLOWED);
|
||||
assert_eq!(blocked[0].method.as_deref(), Some("POST"));
|
||||
assert_eq!(blocked[0].host, "api.github.com");
|
||||
assert_eq!(blocked[0].port, Some(443));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_policy_records_hook_denials_in_full_mode() {
|
||||
let secret_file = NamedTempFile::new().unwrap();
|
||||
std::fs::write(secret_file.path(), "ghp-secret\n").unwrap();
|
||||
let mut hook = github_write_hook();
|
||||
hook.actions.inject_request_headers[0].placeholder = Some("guest".into());
|
||||
hook.actions.inject_request_headers[0].secret_env_var = None;
|
||||
hook.actions.inject_request_headers[0].secret_file =
|
||||
Some(secret_file.path().display().to_string());
|
||||
let mut network = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
mitm_hooks: vec![hook],
|
||||
mode: NetworkMode::Full,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
network.set_allowed_domains(vec!["api.github.com".to_string()]);
|
||||
let app_state = Arc::new(network_proxy_state_for_policy(network));
|
||||
for (method, scheme, port, values) in [
|
||||
(Method::GET, Scheme::HTTPS, 443, &["guest"][..]),
|
||||
(Method::POST, Scheme::HTTPS, 443, &[]),
|
||||
(Method::POST, Scheme::HTTPS, 443, &["wrong"]),
|
||||
(Method::POST, Scheme::HTTPS, 443, &["guest", "guest"]),
|
||||
(Method::POST, Scheme::HTTP, 80, &["guest"]),
|
||||
(Method::POST, Scheme::HTTPS, 8443, &["guest"]),
|
||||
] {
|
||||
let mut ctx = policy_ctx(app_state.clone(), NetworkMode::Full, "api.github.com", port);
|
||||
ctx.scheme = scheme;
|
||||
let mut req = Request::builder()
|
||||
.method(method.as_str())
|
||||
.uri("/repos/openai/codex/issues?token=secret")
|
||||
.header(HOST, "api.github.com");
|
||||
for value in values {
|
||||
req = req.header("authorization", *value);
|
||||
}
|
||||
let req = req.body(Body::empty()).unwrap();
|
||||
let response = mitm_blocking_response(&req, &ctx).await.unwrap().unwrap();
|
||||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
assert_eq!(response.headers()["x-proxy-error"], "blocked-by-mitm-hook");
|
||||
|
||||
let blocked = app_state.drain_blocked().await.unwrap();
|
||||
assert_eq!(blocked.len(), 1);
|
||||
assert_eq!(blocked[0].reason, REASON_MITM_HOOK_DENIED);
|
||||
assert_eq!(blocked[0].method.as_deref(), Some(method.as_str()));
|
||||
assert_eq!(blocked[0].host, "api.github.com");
|
||||
assert_eq!(blocked[0].port, Some(port));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_credentials_apply_hook_after_brokerage() {
|
||||
let app_state = network_proxy_state_for_policy(NetworkProxyConfig {
|
||||
credential_broker: true,
|
||||
mitm: true,
|
||||
..NetworkProxyConfig::default()
|
||||
});
|
||||
let mut env = HashMap::from([("GH_TOKEN".to_string(), "ghp-real".to_string())]);
|
||||
app_state.virtualize_child_credentials(&mut env);
|
||||
assert_ne!(env["GH_TOKEN"], "ghp-real");
|
||||
let placeholder = HeaderValue::from_str(&format!("Bearer {}", env["GH_TOKEN"])).unwrap();
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("authorization", placeholder.clone());
|
||||
headers.insert("x-request-id", HeaderValue::from_static("req_123"));
|
||||
let destination = "https://api.github.com/";
|
||||
let mut expected = headers.clone();
|
||||
let mut brokered = headers.clone();
|
||||
apply_request_credentials(
|
||||
&mut brokered,
|
||||
/*actions*/ None,
|
||||
&app_state,
|
||||
destination,
|
||||
);
|
||||
expected.insert("authorization", HeaderValue::from_static("Bearer ghp-real"));
|
||||
assert_eq!(brokered, expected);
|
||||
|
||||
let mut secret = HeaderValue::from_static("Bearer secret-token");
|
||||
secret.set_sensitive(true);
|
||||
let actions = crate::mitm_hook::MitmHookActions {
|
||||
body_secret_substitution: None,
|
||||
aws_sigv4: None,
|
||||
strip_request_headers: vec![HeaderName::from_static("authorization")],
|
||||
inject_request_headers: vec![crate::mitm_hook::ResolvedInjectedHeader {
|
||||
placeholder: Some(placeholder),
|
||||
name: HeaderName::from_static("authorization"),
|
||||
value: secret.clone(),
|
||||
source: crate::mitm_hook::SecretSource::File(
|
||||
AbsolutePathBuf::try_from("/tmp/github-token").unwrap(),
|
||||
),
|
||||
}],
|
||||
};
|
||||
|
||||
expected.insert("authorization", secret);
|
||||
apply_request_credentials(&mut headers, Some(&actions), &app_state, destination);
|
||||
assert_eq!(headers, expected);
|
||||
assert!(headers["authorization"].is_sensitive());
|
||||
}
|
||||
260
codex-rs/network-proxy/src/native_certs.rs
Normal file
260
codex-rs/network-proxy/src/native_certs.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
use rama_tls_rustls::dep::pki_types::CertificateDer;
|
||||
use rustls_native_certs::CertificateResult;
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
use rustls_native_certs::Error;
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
use rustls_native_certs::ErrorKind;
|
||||
|
||||
// `rustls_native_certs::load_native_certs()` first consults SSL_CERT_FILE and
|
||||
// SSL_CERT_DIR. Load platform roots directly so a startup custom CA can be
|
||||
// layered onto the managed bundle without replacing the platform trust store.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub(crate) fn load_platform_native_certs() -> CertificateResult {
|
||||
let mut result =
|
||||
rustls_native_certs::load_certs_from_paths(platform_cert_file().as_deref(), None);
|
||||
for cert_dir in platform_cert_dirs() {
|
||||
extend_certificate_result(
|
||||
&mut result,
|
||||
rustls_native_certs::load_certs_from_paths(None, Some(&cert_dir)),
|
||||
);
|
||||
}
|
||||
dedupe_certs(&mut result);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn load_platform_native_certs() -> CertificateResult {
|
||||
use security_framework::trust_settings::Domain;
|
||||
use security_framework::trust_settings::TrustSettings;
|
||||
use security_framework::trust_settings::TrustSettingsForCertificate;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
let mut result = CertificateResult::default();
|
||||
let mut all_certs = BTreeMap::new();
|
||||
for domain in &[Domain::User, Domain::Admin, Domain::System] {
|
||||
let ts = TrustSettings::new(*domain);
|
||||
let iter = match ts.iter() {
|
||||
Ok(iter) => iter,
|
||||
Err(err) => {
|
||||
result.errors.push(Error {
|
||||
context: match domain {
|
||||
Domain::User => "failed to load user trust settings",
|
||||
Domain::Admin => "failed to load admin trust settings",
|
||||
Domain::System => "failed to load system trust settings",
|
||||
},
|
||||
kind: ErrorKind::Os(err.into()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
for cert in iter {
|
||||
let der = cert.to_der();
|
||||
let trusted = match ts.tls_trust_settings_for_certificate(&cert) {
|
||||
Ok(trusted) => trusted.unwrap_or(TrustSettingsForCertificate::TrustRoot),
|
||||
Err(err) => {
|
||||
result.errors.push(Error {
|
||||
context: "certificate not trusted",
|
||||
kind: ErrorKind::Os(err.into()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
all_certs.entry(der).or_insert(trusted);
|
||||
}
|
||||
}
|
||||
|
||||
for (der, trusted) in all_certs {
|
||||
use TrustSettingsForCertificate::*;
|
||||
|
||||
if let TrustRoot | TrustAsRoot = trusted {
|
||||
result.certs.push(CertificateDer::from(der));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn load_platform_native_certs() -> CertificateResult {
|
||||
use schannel::cert_store::CertStore;
|
||||
|
||||
let mut result = CertificateResult::default();
|
||||
let current_user_store = match CertStore::open_current_user("ROOT") {
|
||||
Ok(store) => store,
|
||||
Err(err) => {
|
||||
result.errors.push(Error {
|
||||
context: "failed to open current user certificate store",
|
||||
kind: ErrorKind::Os(err.into()),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
for cert in current_user_store.certs() {
|
||||
let valid_uses = match cert.valid_uses() {
|
||||
Ok(valid_uses) => valid_uses,
|
||||
Err(err) => {
|
||||
result.errors.push(Error {
|
||||
context: "failed to inspect certificate valid uses",
|
||||
kind: ErrorKind::Os(err.into()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let is_time_valid = match cert.is_time_valid() {
|
||||
Ok(is_time_valid) => is_time_valid,
|
||||
Err(err) => {
|
||||
result.errors.push(Error {
|
||||
context: "failed to inspect certificate time validity",
|
||||
kind: ErrorKind::Os(err.into()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if usable_for_rustls(valid_uses) && is_time_valid {
|
||||
result
|
||||
.certs
|
||||
.push(CertificateDer::from(cert.to_der().to_vec()));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(not(any(all(unix, not(target_os = "macos")), target_os = "macos", windows)))]
|
||||
pub(crate) fn load_platform_native_certs() -> CertificateResult {
|
||||
rustls_native_certs::load_native_certs()
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn extend_certificate_result(result: &mut CertificateResult, extra: CertificateResult) {
|
||||
result.certs.extend(extra.certs);
|
||||
result.errors.extend(extra.errors);
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn dedupe_certs(result: &mut CertificateResult) {
|
||||
result.certs.sort_unstable_by(|a, b| a.cmp(b));
|
||||
result.certs.dedup();
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn platform_cert_file() -> Option<std::path::PathBuf> {
|
||||
PLATFORM_CERTIFICATE_FILE_NAMES
|
||||
.iter()
|
||||
.map(std::path::Path::new)
|
||||
.find(|path| path.exists())
|
||||
.map(std::path::Path::to_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn platform_cert_dirs() -> impl Iterator<Item = std::path::PathBuf> {
|
||||
PLATFORM_CERTIFICATE_DIRS
|
||||
.iter()
|
||||
.map(std::path::Path::new)
|
||||
.filter(|path| path.exists())
|
||||
.map(std::path::Path::to_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "linux"))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &[
|
||||
"/etc/ssl/certs",
|
||||
"/etc/pki/tls/certs",
|
||||
"/etc/security/certificates",
|
||||
];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "freebsd"))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &["/etc/ssl/certs", "/usr/local/share/certs"];
|
||||
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(target_os = "macos"),
|
||||
any(target_os = "illumos", target_os = "solaris")
|
||||
))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &["/etc/certs/CA"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "netbsd"))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &["/etc/openssl/certs"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "aix"))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &["/var/ssl/certs"];
|
||||
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(target_os = "macos"),
|
||||
not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "illumos",
|
||||
target_os = "solaris",
|
||||
target_os = "netbsd",
|
||||
target_os = "aix"
|
||||
))
|
||||
))]
|
||||
const PLATFORM_CERTIFICATE_DIRS: &[&str] = &["/etc/ssl/certs"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "linux"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &[
|
||||
"/etc/ssl/certs/ca-certificates.crt",
|
||||
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
|
||||
"/etc/pki/tls/certs/ca-bundle.crt",
|
||||
"/etc/ssl/ca-bundle.pem",
|
||||
"/etc/pki/tls/cacert.pem",
|
||||
"/etc/ssl/cert.pem",
|
||||
"/opt/etc/ssl/certs/ca-certificates.crt",
|
||||
"/etc/ssl/certs/cacert.pem",
|
||||
];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "freebsd"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/usr/local/etc/ssl/cert.pem"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "dragonfly"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/usr/local/share/certs/ca-root-nss.crt"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "netbsd"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/etc/openssl/certs/ca-certificates.crt"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "openbsd"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/etc/ssl/cert.pem"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "solaris"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/etc/certs/ca-certificates.crt"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "illumos"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] =
|
||||
&["/etc/ssl/cacert.pem", "/etc/certs/ca-certificates.crt"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "android"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] =
|
||||
&["/data/data/com.termux/files/usr/etc/tls/cert.pem"];
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), target_os = "haiku"))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/boot/system/data/ssl/CARootCertificates.pem"];
|
||||
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(target_os = "macos"),
|
||||
not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "dragonfly",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "solaris",
|
||||
target_os = "illumos",
|
||||
target_os = "android",
|
||||
target_os = "haiku",
|
||||
))
|
||||
))]
|
||||
const PLATFORM_CERTIFICATE_FILE_NAMES: &[&str] = &["/etc/ssl/certs/ca-certificates.crt"];
|
||||
|
||||
#[cfg(windows)]
|
||||
fn usable_for_rustls(uses: schannel::cert_context::ValidUses) -> bool {
|
||||
match uses {
|
||||
schannel::cert_context::ValidUses::All => true,
|
||||
schannel::cert_context::ValidUses::Oids(strs) => strs.iter().any(|x| x == PKIX_SERVER_AUTH),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const PKIX_SERVER_AUTH: &str = "1.3.6.1.5.5.7.3.1";
|
||||
1142
codex-rs/network-proxy/src/network_policy.rs
Normal file
1142
codex-rs/network-proxy/src/network_policy.rs
Normal file
File diff suppressed because it is too large
Load Diff
370
codex-rs/network-proxy/src/policy.rs
Normal file
370
codex-rs/network-proxy/src/policy.rs
Normal file
@@ -0,0 +1,370 @@
|
||||
#[cfg(test)]
|
||||
use crate::config::NetworkMode;
|
||||
use crate::domain_matcher::DomainPatternSet;
|
||||
use crate::domain_matcher::GlobalWildcard;
|
||||
pub(crate) use crate::domain_matcher::is_global_wildcard_domain_pattern;
|
||||
pub use crate::domain_matcher::normalize_host;
|
||||
pub(crate) use crate::domain_matcher::unscoped_ip_literal;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use std::net::IpAddr;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::Ipv6Addr;
|
||||
use url::Host as UrlHost;
|
||||
|
||||
/// A normalized host string for policy evaluation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Host(String);
|
||||
|
||||
impl Host {
|
||||
pub fn parse(input: &str) -> Result<Self> {
|
||||
let normalized = normalize_host(input);
|
||||
ensure!(!normalized.is_empty(), "host is empty");
|
||||
Ok(Self(normalized))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the host is a loopback hostname or IP literal.
|
||||
pub fn is_loopback_host(host: &Host) -> bool {
|
||||
let host = host.as_str();
|
||||
let host = unscoped_ip_literal(host).unwrap_or(host);
|
||||
if host == "localhost" {
|
||||
return true;
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
return ip.is_loopback();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Matches the destinations in `DEFAULT_NO_PROXY_VALUE`, without resolving DNS.
|
||||
pub(crate) fn is_default_proxy_bypass_host(host: &str) -> bool {
|
||||
let host = normalize_host(host);
|
||||
match host.parse::<IpAddr>() {
|
||||
Ok(IpAddr::V4(ip)) => ip == Ipv4Addr::LOCALHOST || ip.is_private(),
|
||||
Ok(IpAddr::V6(ip)) => ip == Ipv6Addr::LOCALHOST,
|
||||
Err(_) => host == "localhost" || host.ends_with(".localhost"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies IP literals excluded from public network destinations; does not resolve DNS.
|
||||
pub fn is_non_public_ip(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(ip) => is_non_public_ipv4(ip),
|
||||
IpAddr::V6(ip) => is_non_public_ipv6(ip),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_non_public_ipv4(ip: Ipv4Addr) -> bool {
|
||||
// Use the standard library classification helpers where possible; they encode the intent more
|
||||
// clearly than hand-rolled range checks. Some non-public ranges (e.g., CGNAT and TEST-NET
|
||||
// blocks) are not covered by stable stdlib helpers yet, so we fall back to CIDR checks.
|
||||
ip.is_loopback()
|
||||
|| ip.is_private()
|
||||
|| ip.is_link_local()
|
||||
|| ip.is_unspecified()
|
||||
|| ip.is_multicast()
|
||||
|| ip.is_broadcast()
|
||||
|| ipv4_in_cidr(ip, [0, 0, 0, 0], /*prefix*/ 8) // "this network" (RFC 1122)
|
||||
|| ipv4_in_cidr(ip, [100, 64, 0, 0], /*prefix*/ 10) // CGNAT (RFC 6598)
|
||||
|| ipv4_in_cidr(ip, [192, 0, 0, 0], /*prefix*/ 24) // IETF Protocol Assignments (RFC 6890)
|
||||
|| ipv4_in_cidr(ip, [192, 0, 2, 0], /*prefix*/ 24) // TEST-NET-1 (RFC 5737)
|
||||
|| ipv4_in_cidr(ip, [198, 18, 0, 0], /*prefix*/ 15) // Benchmarking (RFC 2544)
|
||||
|| ipv4_in_cidr(ip, [198, 51, 100, 0], /*prefix*/ 24) // TEST-NET-2 (RFC 5737)
|
||||
|| ipv4_in_cidr(ip, [203, 0, 113, 0], /*prefix*/ 24) // TEST-NET-3 (RFC 5737)
|
||||
|| ipv4_in_cidr(ip, [240, 0, 0, 0], /*prefix*/ 4) // Reserved (RFC 6890)
|
||||
}
|
||||
|
||||
fn ipv4_in_cidr(ip: Ipv4Addr, base: [u8; 4], prefix: u8) -> bool {
|
||||
let ip = u32::from(ip);
|
||||
let base = u32::from(Ipv4Addr::from(base));
|
||||
let mask = if prefix == 0 {
|
||||
0
|
||||
} else {
|
||||
u32::MAX << (32 - prefix)
|
||||
};
|
||||
(ip & mask) == (base & mask)
|
||||
}
|
||||
|
||||
/// Private unicast ranges that may be reachable through an upstream VPN proxy.
|
||||
/// Loopback, link-local, and other special-use addresses retain their normal routing.
|
||||
pub(crate) fn is_private_network_ip(ip: IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(ip) => ip.is_private() || ipv4_in_cidr(ip, [100, 64, 0, 0], /*prefix*/ 10),
|
||||
IpAddr::V6(ip) => match ip.to_ipv4() {
|
||||
Some(ip) => is_private_network_ip(IpAddr::V4(ip)),
|
||||
None => ip.is_unique_local(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn is_non_public_ipv6(ip: Ipv6Addr) -> bool {
|
||||
if let Some(v4) = ip.to_ipv4() {
|
||||
return is_non_public_ipv4(v4) || ip.is_loopback();
|
||||
}
|
||||
// Treat anything that isn't globally routable as "local" for SSRF prevention. In particular:
|
||||
// - `::1` loopback
|
||||
// - `fc00::/7` unique-local (RFC 4193)
|
||||
// - `fe80::/10` link-local
|
||||
// - `::` unspecified
|
||||
// - multicast ranges
|
||||
ip.is_loopback()
|
||||
|| ip.is_unspecified()
|
||||
|| ip.is_multicast()
|
||||
|| ip.is_unique_local()
|
||||
|| ip.is_unicast_link_local()
|
||||
}
|
||||
|
||||
pub(crate) fn compile_allowlist(patterns: &[String]) -> Result<DomainPatternSet> {
|
||||
DomainPatternSet::new(patterns, GlobalWildcard::Allow)
|
||||
}
|
||||
|
||||
pub(crate) fn compile_denylist(patterns: &[String]) -> Result<DomainPatternSet> {
|
||||
DomainPatternSet::new(patterns, GlobalWildcard::Reject)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum DomainPattern {
|
||||
ApexAndSubdomains(String),
|
||||
SubdomainsOnly(String),
|
||||
Exact(String),
|
||||
}
|
||||
|
||||
impl DomainPattern {
|
||||
/// Parse a policy pattern for constraint comparisons, validating domain parts with `url`.
|
||||
pub(crate) fn parse_for_constraints(input: &str) -> Self {
|
||||
let input = input.trim();
|
||||
if input.is_empty() {
|
||||
return Self::Exact(String::new());
|
||||
}
|
||||
if let Some(domain) = input.strip_prefix("**.") {
|
||||
return Self::ApexAndSubdomains(parse_domain_for_constraints(domain));
|
||||
}
|
||||
if let Some(domain) = input.strip_prefix("*.") {
|
||||
return Self::SubdomainsOnly(parse_domain_for_constraints(domain));
|
||||
}
|
||||
Self::Exact(parse_domain_for_constraints(input))
|
||||
}
|
||||
|
||||
pub(crate) fn allows(&self, candidate: &DomainPattern) -> bool {
|
||||
match self {
|
||||
DomainPattern::Exact(domain) => match candidate {
|
||||
DomainPattern::Exact(candidate) => domain_eq(candidate, domain),
|
||||
_ => false,
|
||||
},
|
||||
DomainPattern::SubdomainsOnly(domain) => match candidate {
|
||||
DomainPattern::Exact(candidate) => is_strict_subdomain(candidate, domain),
|
||||
DomainPattern::SubdomainsOnly(candidate) => {
|
||||
is_subdomain_or_equal(candidate, domain)
|
||||
}
|
||||
DomainPattern::ApexAndSubdomains(candidate) => {
|
||||
is_strict_subdomain(candidate, domain)
|
||||
}
|
||||
},
|
||||
DomainPattern::ApexAndSubdomains(domain) => match candidate {
|
||||
DomainPattern::Exact(candidate) => is_subdomain_or_equal(candidate, domain),
|
||||
DomainPattern::SubdomainsOnly(candidate) => {
|
||||
is_subdomain_or_equal(candidate, domain)
|
||||
}
|
||||
DomainPattern::ApexAndSubdomains(candidate) => {
|
||||
is_subdomain_or_equal(candidate, domain)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_domain_for_constraints(domain: &str) -> String {
|
||||
let domain = domain.trim().trim_end_matches('.');
|
||||
if domain.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let host = if domain.starts_with('[') && domain.ends_with(']') {
|
||||
&domain[1..domain.len().saturating_sub(1)]
|
||||
} else {
|
||||
domain
|
||||
};
|
||||
if host.contains('*') || host.contains('?') || host.contains('%') {
|
||||
return domain.to_string();
|
||||
}
|
||||
match UrlHost::parse(host) {
|
||||
Ok(host) => host.to_string(),
|
||||
Err(_) => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_domain(domain: &str) -> String {
|
||||
domain.trim_end_matches('.').to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn domain_eq(left: &str, right: &str) -> bool {
|
||||
normalize_domain(left) == normalize_domain(right)
|
||||
}
|
||||
|
||||
fn is_subdomain_or_equal(child: &str, parent: &str) -> bool {
|
||||
let child = normalize_domain(child);
|
||||
let parent = normalize_domain(parent);
|
||||
if child == parent {
|
||||
return true;
|
||||
}
|
||||
child.ends_with(&format!(".{parent}"))
|
||||
}
|
||||
|
||||
fn is_strict_subdomain(child: &str, parent: &str) -> bool {
|
||||
let child = normalize_domain(child);
|
||||
let parent = normalize_domain(parent);
|
||||
child != parent && child.ends_with(&format!(".{parent}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn method_allowed_full_allows_everything() {
|
||||
assert!(NetworkMode::Full.allows_method("GET"));
|
||||
assert!(NetworkMode::Full.allows_method("POST"));
|
||||
assert!(NetworkMode::Full.allows_method("CONNECT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_allowed_limited_allows_only_safe_methods() {
|
||||
assert!(NetworkMode::Limited.allows_method("GET"));
|
||||
assert!(NetworkMode::Limited.allows_method("HEAD"));
|
||||
assert!(NetworkMode::Limited.allows_method("OPTIONS"));
|
||||
assert!(!NetworkMode::Limited.allows_method("POST"));
|
||||
assert!(!NetworkMode::Limited.allows_method("CONNECT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_normalizes_trailing_dots() {
|
||||
let set = compile_denylist(&["Example.COM.".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("example.com"));
|
||||
assert_eq!(false, set.is_match("api.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_normalizes_wildcards() {
|
||||
let set = compile_denylist(&["*.Example.COM.".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("api.example.com"));
|
||||
assert_eq!(false, set.is_match("example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_supports_mid_label_wildcards() {
|
||||
let set = compile_denylist(&["region*.v2.argotunnel.com".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("region1.v2.argotunnel.com"));
|
||||
assert_eq!(true, set.is_match("region.v2.argotunnel.com"));
|
||||
assert_eq!(false, set.is_match("xregion1.v2.argotunnel.com"));
|
||||
assert_eq!(false, set.is_match("foo.region1.v2.argotunnel.com"));
|
||||
}
|
||||
|
||||
// Keep this table one-for-one with the browser network-policy matchers'
|
||||
// question-mark contract cases so grammar changes are checked on both sides.
|
||||
#[test]
|
||||
fn compile_globset_supports_question_mark_wildcards() -> Result<()> {
|
||||
for (pattern, host, expected) in [
|
||||
("api?.example.com", "api1.example.com", true),
|
||||
("api?.example.com", "api.example.com", false),
|
||||
("api?.example.com", "api12.example.com", false),
|
||||
("api??.example.com", "api12.example.com", true),
|
||||
("api??.example.com", "api1.example.com", false),
|
||||
("api*?.example.com", "api.example.com", false),
|
||||
("api*?.example.com", "api1.example.com", true),
|
||||
("api*?.example.com", "api123.example.com", true),
|
||||
("api?example.com", "api.example.com", true),
|
||||
("*.api?.example.com", "api1.example.com", false),
|
||||
("*.api?.example.com", "www.api1.example.com", true),
|
||||
("*.api?.example.com", "nested.www.api1.example.com", true),
|
||||
("*.api?.example.com", "www.api12.example.com", false),
|
||||
("**.api?.example.com", "api1.example.com", true),
|
||||
("**.api?.example.com", "www.api1.example.com", true),
|
||||
("**.api?.example.com", "nested.www.api1.example.com", true),
|
||||
("**.api?.example.com", "api12.example.com", false),
|
||||
("**.api?.example.com", "www.api12.example.com", false),
|
||||
(" API?.EXAMPLE.COM. ", "API1.EXAMPLE.COM.", true),
|
||||
] {
|
||||
let patterns = [pattern.to_string()];
|
||||
for set in [compile_allowlist(&patterns)?, compile_denylist(&patterns)?] {
|
||||
assert_eq!(
|
||||
set.is_match(normalize_host(host)),
|
||||
expected,
|
||||
"pattern {pattern}, host {host}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_normalizes_apex_and_subdomains() {
|
||||
let set = compile_denylist(&["**.Example.COM.".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("example.com"));
|
||||
assert_eq!(true, set.is_match("api.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_normalizes_bracketed_ipv6_literals() {
|
||||
let set = compile_denylist(&["[::1]".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compile_globset_preserves_scoped_ipv6_literals() {
|
||||
let set = compile_denylist(&["[fe80::1%25lo0]".to_string()]).unwrap();
|
||||
|
||||
assert_eq!(true, set.is_match("fe80::1%lo0"));
|
||||
assert_eq!(false, set.is_match("fe80::1%lo1"));
|
||||
assert_eq!(false, set.is_match("fe80::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_loopback_host_handles_localhost_variants() {
|
||||
assert!(is_loopback_host(&Host::parse("localhost").unwrap()));
|
||||
assert!(is_loopback_host(&Host::parse("localhost.").unwrap()));
|
||||
assert!(is_loopback_host(&Host::parse("LOCALHOST").unwrap()));
|
||||
assert!(!is_loopback_host(&Host::parse("notlocalhost").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_loopback_host_handles_ip_literals() {
|
||||
assert!(is_loopback_host(&Host::parse("127.0.0.1").unwrap()));
|
||||
assert!(is_loopback_host(&Host::parse("::1").unwrap()));
|
||||
assert!(!is_loopback_host(&Host::parse("1.2.3.4").unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_non_public_ip_rejects_private_and_loopback_ranges() {
|
||||
assert!(is_non_public_ip("127.0.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("10.0.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("192.168.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("100.64.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("192.0.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("192.0.2.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("198.18.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("198.51.100.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("203.0.113.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("240.0.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("0.1.2.3".parse().unwrap()));
|
||||
assert!(!is_non_public_ip("8.8.8.8".parse().unwrap()));
|
||||
|
||||
assert!(is_non_public_ip("::ffff:127.0.0.1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("::ffff:10.0.0.1".parse().unwrap()));
|
||||
assert!(!is_non_public_ip("::ffff:8.8.8.8".parse().unwrap()));
|
||||
|
||||
assert!(is_non_public_ip("::1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("fe80::1".parse().unwrap()));
|
||||
assert!(is_non_public_ip("fc00::1".parse().unwrap()));
|
||||
}
|
||||
}
|
||||
17
codex-rs/network-proxy/src/process_log_metadata.rs
Normal file
17
codex-rs/network-proxy/src/process_log_metadata.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
//! Process attribution captured at launch for network policy logs.
|
||||
//! Executor registration identity comes from the executor, never the controller.
|
||||
|
||||
/// Registry-issued identity of the executor that launched a process.
|
||||
#[derive(Clone)]
|
||||
pub struct ExecutorLogIdentity {
|
||||
pub environment_id: String,
|
||||
pub registration_id: String,
|
||||
}
|
||||
|
||||
/// Correlation metadata only; these values do not authorize network requests.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct NetworkProxyProcessLogMetadata {
|
||||
pub thread_id: Option<String>,
|
||||
pub tool_call_id: Option<String>,
|
||||
pub executor_identity: Option<ExecutorLogIdentity>,
|
||||
}
|
||||
3250
codex-rs/network-proxy/src/proxy.rs
Normal file
3250
codex-rs/network-proxy/src/proxy.rs
Normal file
File diff suppressed because it is too large
Load Diff
64
codex-rs/network-proxy/src/proxy/execution_scope.rs
Normal file
64
codex-rs/network-proxy/src/proxy/execution_scope.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) struct ExecutionScope {
|
||||
pub(super) environment_id: String,
|
||||
pub(super) execution_id: String,
|
||||
pub(super) attribution_token: String,
|
||||
pub(super) environment_policy: Option<crate::EnvironmentNetworkPolicy>,
|
||||
// Dropping the execution scope closes this channel and cancels remote reviews.
|
||||
pub(super) lifetime_tx: tokio::sync::watch::Sender<()>,
|
||||
state: Arc<NetworkProxyState>,
|
||||
}
|
||||
|
||||
impl Drop for ExecutionScope {
|
||||
fn drop(&mut self) {
|
||||
self.state.unregister_execution(&self.attribution_token);
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkProxy {
|
||||
/// Waits until every remote decision callback and in-flight request for this
|
||||
/// execution has been dropped. Call after the executor has started, when no
|
||||
/// further callbacks will be installed for this scope. An unscoped proxy
|
||||
/// cannot establish this boundary, so its wait remains pending.
|
||||
pub async fn wait_for_remote_policy_deciders(&self) {
|
||||
match &self.execution_scope {
|
||||
Some(scope) => scope.lifetime_tx.closed().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a proxy with execution-specific attribution and attachment policy.
|
||||
pub fn for_execution(
|
||||
&self,
|
||||
environment_id: &str,
|
||||
execution_id: &str,
|
||||
attribution_token: String,
|
||||
environment_policy: Option<crate::EnvironmentNetworkPolicy>,
|
||||
fallback_policy_decider: Option<Arc<dyn NetworkPolicyDecider>>,
|
||||
) -> Result<Self> {
|
||||
anyhow::ensure!(
|
||||
self.execution_scope.is_none(),
|
||||
"cannot scope an execution-scoped network proxy"
|
||||
);
|
||||
self.state
|
||||
.register_execution(&attribution_token, environment_id, execution_id);
|
||||
|
||||
let (lifetime_tx, _) = tokio::sync::watch::channel(());
|
||||
let mut proxy = self.clone();
|
||||
proxy.policy_decider = proxy.policy_decider.or(fallback_policy_decider);
|
||||
// Strict attachment allowlists cannot be expanded through approval callbacks.
|
||||
if matches!(&environment_policy, Some(policy) if policy.managed_allowed_domains_only) {
|
||||
proxy.policy_decider = None;
|
||||
}
|
||||
proxy.execution_scope = Some(Arc::new(ExecutionScope {
|
||||
environment_id: environment_id.to_string(),
|
||||
execution_id: execution_id.to_string(),
|
||||
attribution_token,
|
||||
environment_policy,
|
||||
lifetime_tx,
|
||||
state: Arc::clone(&self.state),
|
||||
}));
|
||||
Ok(proxy)
|
||||
}
|
||||
}
|
||||
123
codex-rs/network-proxy/src/proxy/managed_routing_tests.rs
Normal file
123
codex-rs/network-proxy/src/proxy/managed_routing_tests.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
//! Dedicated managed proxy routing regression coverage.
|
||||
//! Each proxy must use distinct loopback listeners while preserving HTTP and SOCKS policy.
|
||||
|
||||
use super::*;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::state::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
#[tokio::test]
|
||||
async fn dedicated_listeners_preserve_http_and_socks_policy_without_restricted_tokens() -> Result<()>
|
||||
{
|
||||
let origin = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?;
|
||||
let origin_port = origin.local_addr()?.port();
|
||||
let origin_task = tokio::spawn(async move {
|
||||
while let Ok((mut stream, _)) = origin.accept().await {
|
||||
tokio::spawn(async move {
|
||||
let mut request = [0; 1024];
|
||||
let _ = stream.read(&mut request).await;
|
||||
let _ = stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut handles = Vec::new();
|
||||
let mut addresses = Vec::new();
|
||||
for allowed in [true, false] {
|
||||
let mut config = NetworkProxyConfig {
|
||||
enabled: true,
|
||||
mode: crate::NetworkMode::Full,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
config.set_allowed_domains(vec![if allowed {
|
||||
"127.0.0.1".to_string()
|
||||
} else {
|
||||
"unreachable.invalid".to_string()
|
||||
}]);
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(Arc::new(network_proxy_state_for_policy(config)))
|
||||
.managed_proxy_routing(ManagedProxyRouting::DedicatedListeners)
|
||||
.build()
|
||||
.await?;
|
||||
handles.push(proxy.run().await?);
|
||||
let proxy = proxy.for_execution(
|
||||
"environment",
|
||||
"execution",
|
||||
"token".to_string(),
|
||||
/*environment_policy*/ None,
|
||||
/*fallback_policy_decider*/ None,
|
||||
)?;
|
||||
let prepared =
|
||||
proxy.prepare_for_optional_environment(HashMap::new(), /*environment_id*/ None)?;
|
||||
let http = prepared.env["HTTP_PROXY"]
|
||||
.trim_start_matches("http://")
|
||||
.parse::<SocketAddr>()?;
|
||||
let socks = prepared.env["ALL_PROXY"]
|
||||
.trim_start_matches("socks5h://")
|
||||
.parse::<SocketAddr>()?;
|
||||
let mut ports = vec![http.port(), socks.port()];
|
||||
ports.sort_unstable();
|
||||
assert_eq!(
|
||||
prepared.sandbox_context,
|
||||
ManagedNetworkSandboxContext {
|
||||
loopback_ports: ports,
|
||||
allow_local_binding: false,
|
||||
..ManagedNetworkSandboxContext::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
(http.ip(), socks.ip()),
|
||||
(Ipv4Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into())
|
||||
);
|
||||
for addr in [http, socks] {
|
||||
assert!(!addresses.contains(&addr));
|
||||
addresses.push(addr);
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert_eq!(
|
||||
proxy.network_proxy_restricting_sid(/*environment_id*/ None),
|
||||
None
|
||||
);
|
||||
assert!(
|
||||
!prepared
|
||||
.env
|
||||
.contains_key(WINDOWS_SANDBOX_PROXY_PORTS_ENV_KEY)
|
||||
);
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let mut stream = TcpStream::connect(http).await?;
|
||||
stream.write_all(format!(
|
||||
"GET http://127.0.0.1:{origin_port}/ HTTP/1.1\r\nHost: 127.0.0.1:{origin_port}\r\nConnection: close\r\n\r\n"
|
||||
).as_bytes()).await?;
|
||||
let mut response = Vec::new();
|
||||
stream.read_to_end(&mut response).await?;
|
||||
let status = if allowed { "200" } else { "403" };
|
||||
assert_eq!(String::from_utf8(response)?.split_whitespace().nth(1), Some(status));
|
||||
|
||||
let mut stream = TcpStream::connect(socks).await?;
|
||||
stream.write_all(&[5, 1, 0]).await?;
|
||||
let mut greeting = [0; 2];
|
||||
stream.read_exact(&mut greeting).await?;
|
||||
assert_eq!(greeting, [5, 0]);
|
||||
let mut connect = vec![5, 1, 0, 1, 127, 0, 0, 1];
|
||||
connect.extend_from_slice(&origin_port.to_be_bytes());
|
||||
stream.write_all(&connect).await?;
|
||||
let mut reply = [0; 4];
|
||||
stream.read_exact(&mut reply).await?;
|
||||
assert_eq!(reply[1] == 0, allowed);
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}).await??;
|
||||
}
|
||||
for handle in handles {
|
||||
handle.shutdown().await?;
|
||||
}
|
||||
origin_task.abort();
|
||||
Ok(())
|
||||
}
|
||||
9
codex-rs/network-proxy/src/reasons.rs
Normal file
9
codex-rs/network-proxy/src/reasons.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub(crate) const REASON_DENIED: &str = "denied";
|
||||
pub(crate) const REASON_METHOD_NOT_ALLOWED: &str = "method_not_allowed";
|
||||
pub(crate) const REASON_MITM_HOOK_DENIED: &str = "mitm_hook_denied";
|
||||
pub(crate) const REASON_MITM_REQUIRED: &str = "mitm_required";
|
||||
pub(crate) const REASON_NOT_ALLOWED: &str = "not_allowed";
|
||||
pub(crate) const REASON_NOT_ALLOWED_LOCAL: &str = "not_allowed_local";
|
||||
pub(crate) const REASON_POLICY_DENIED: &str = "policy_denied";
|
||||
pub(crate) const REASON_PROXY_DISABLED: &str = "proxy_disabled";
|
||||
pub(crate) const REASON_UNIX_SOCKET_UNSUPPORTED: &str = "unix_socket_unsupported";
|
||||
262
codex-rs/network-proxy/src/remote_config.rs
Normal file
262
codex-rs/network-proxy/src/remote_config.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::CredentialProviderConfig;
|
||||
use crate::NetworkDomainPermissions;
|
||||
use crate::NetworkMode;
|
||||
use crate::NetworkProxyAuditMetadata;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::NetworkUnixSocketPermissions;
|
||||
use crate::credential_broker::CredentialBroker;
|
||||
|
||||
/// Credential mappings retained by one executor session across process launches.
|
||||
/// Only mappings are shared; proxy listeners, network policy, and approvals remain per command.
|
||||
#[derive(Default)]
|
||||
pub struct RemoteCredentialBrokerCache {
|
||||
brokers: Mutex<Vec<CachedCredentialBroker>>,
|
||||
}
|
||||
|
||||
struct CachedCredentialBroker {
|
||||
environment_id: Option<String>,
|
||||
conversation_id: Option<String>,
|
||||
config: NetworkProxyConfig,
|
||||
broker: CredentialBroker,
|
||||
}
|
||||
|
||||
impl RemoteCredentialBrokerCache {
|
||||
pub(crate) fn broker_if_enabled(
|
||||
&self,
|
||||
environment_id: Option<&str>,
|
||||
conversation_id: Option<&str>,
|
||||
config: &NetworkProxyConfig,
|
||||
) -> Option<CredentialBroker> {
|
||||
if !config.credential_broker {
|
||||
return None;
|
||||
}
|
||||
// Retain broker configuration and the command's destination context so ordinary
|
||||
// network-policy changes preserve placeholders, while destination changes cannot
|
||||
// invalidate another command's mappings.
|
||||
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()
|
||||
};
|
||||
let mut brokers = self
|
||||
.brokers
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(cached) = brokers.iter().find(|cached| {
|
||||
cached.environment_id.as_deref() == environment_id
|
||||
&& cached.conversation_id.as_deref() == conversation_id
|
||||
&& cached.config == config
|
||||
}) {
|
||||
return Some(cached.broker.clone());
|
||||
}
|
||||
let broker = CredentialBroker::new(config.credential_broker);
|
||||
broker.configure(&config);
|
||||
brokers.push(CachedCredentialBroker {
|
||||
environment_id: environment_id.map(str::to_owned),
|
||||
conversation_id: conversation_id.map(str::to_owned),
|
||||
config,
|
||||
broker: broker.clone(),
|
||||
});
|
||||
Some(broker)
|
||||
}
|
||||
}
|
||||
|
||||
/// Credential masking supported by an executor or requested for a remote launch.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub enum RemoteCredentialMasking {
|
||||
#[default]
|
||||
Disabled,
|
||||
/// Mask only when the configuration contains no custom providers.
|
||||
BuiltInOnly,
|
||||
WithConfiguredProviders,
|
||||
}
|
||||
|
||||
/// Masking fields shared with independently deployed executors.
|
||||
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(default)]
|
||||
struct CredentialMaskingConfig {
|
||||
#[serde(
|
||||
rename = "credentialMasking",
|
||||
skip_serializing_if = "std::ops::Not::not"
|
||||
)]
|
||||
enabled: bool,
|
||||
#[serde(
|
||||
rename = "credentialProviders",
|
||||
skip_serializing_if = "BTreeMap::is_empty"
|
||||
)]
|
||||
providers: BTreeMap<String, CredentialProviderConfig>,
|
||||
}
|
||||
|
||||
impl CredentialMaskingConfig {
|
||||
fn deserialize_normalized<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Self, D::Error> {
|
||||
let mut config = Self::deserialize(deserializer)?;
|
||||
// Discard provider rules sent with masking off, even if we forward this configuration.
|
||||
if !config.enabled {
|
||||
config.providers.clear();
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CredentialMaskingConfig {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CredentialMaskingConfig")
|
||||
.field("enabled", &self.enabled)
|
||||
.field("credential_provider_count", &self.providers.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Executor-local proxy launch inputs transported with one process start.
|
||||
///
|
||||
/// Unlike [`crate::ManagedNetworkSandboxContext`], this describes how the executor should create
|
||||
/// proxy listeners. The sandbox context is materialized only after those listeners are running.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct RemoteNetworkProxyLaunchConfig {
|
||||
pub proxy: RemoteNetworkProxyConfig,
|
||||
#[serde(default)]
|
||||
pub audit_metadata: NetworkProxyAuditMetadata,
|
||||
#[serde(default)]
|
||||
pub environment_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub execution_id: Option<String>,
|
||||
/// Controller-side policy decision budget. The executor adds transport overhead.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub policy_decision_timeout_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl RemoteNetworkProxyLaunchConfig {
|
||||
pub fn new(proxy: RemoteNetworkProxyConfig) -> Self {
|
||||
Self {
|
||||
proxy,
|
||||
audit_metadata: NetworkProxyAuditMetadata::default(),
|
||||
environment_id: None,
|
||||
execution_id: None,
|
||||
policy_decision_timeout_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_audit_metadata(mut self, audit_metadata: NetworkProxyAuditMetadata) -> Self {
|
||||
self.audit_metadata = audit_metadata;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn for_execution(mut self, environment_id: String, execution_id: String) -> Self {
|
||||
self.environment_id = Some(environment_id);
|
||||
self.execution_id = Some(execution_id);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective network proxy settings that are safe to send to a remote executor.
|
||||
///
|
||||
/// Listener addresses are deliberately omitted because the executor chooses its own loopback
|
||||
/// ports. Masking carries provider rules; credential values and destination context are resolved
|
||||
/// on the executor. CA configuration and MITM hooks stay on their execution host.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct RemoteNetworkProxyConfig {
|
||||
pub enabled: bool,
|
||||
#[serde(
|
||||
flatten,
|
||||
deserialize_with = "CredentialMaskingConfig::deserialize_normalized"
|
||||
)]
|
||||
credential_masking: CredentialMaskingConfig,
|
||||
pub enable_socks5: bool,
|
||||
pub enable_socks5_udp: bool,
|
||||
pub allow_upstream_proxy: bool,
|
||||
pub dangerously_allow_all_unix_sockets: bool,
|
||||
pub mode: NetworkMode,
|
||||
pub domains: Option<NetworkDomainPermissions>,
|
||||
/// Clients must require the `networkProxyReviewDomains` executor capability when nonempty.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub review_domains: Vec<String>,
|
||||
pub unix_sockets: Option<NetworkUnixSocketPermissions>,
|
||||
pub allow_local_binding: bool,
|
||||
}
|
||||
|
||||
impl RemoteNetworkProxyConfig {
|
||||
pub fn from_effective_config(config: &NetworkProxyConfig) -> Result<Self> {
|
||||
ensure!(
|
||||
config.mitm_ca.is_none()
|
||||
&& (!config.enabled
|
||||
|| (!config.mitm
|
||||
&& !config.credential_broker
|
||||
&& !config.dangerously_allow_plaintext_credential_injection
|
||||
&& config.mitm_hooks.is_empty())),
|
||||
"remote exec-server network proxy does not support MITM, external CAs, credential injection, or MITM hooks"
|
||||
);
|
||||
Ok(Self {
|
||||
enabled: config.enabled,
|
||||
credential_masking: CredentialMaskingConfig::default(),
|
||||
enable_socks5: config.enable_socks5,
|
||||
enable_socks5_udp: config.enable_socks5_udp,
|
||||
allow_upstream_proxy: config.allow_upstream_proxy,
|
||||
dangerously_allow_all_unix_sockets: config
|
||||
.dangerously_allow_all_unix_sockets
|
||||
.unwrap_or(false),
|
||||
mode: config.mode,
|
||||
domains: config.domains.clone(),
|
||||
review_domains: config.review_domains.clone(),
|
||||
unix_sockets: config.unix_sockets.clone(),
|
||||
allow_local_binding: config.allow_local_binding(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Enable masking with the given provider rules, or just the built-ins if empty.
|
||||
pub fn enable_credential_masking(
|
||||
&mut self,
|
||||
providers: BTreeMap<String, CredentialProviderConfig>,
|
||||
) {
|
||||
self.credential_masking = CredentialMaskingConfig {
|
||||
enabled: true,
|
||||
providers,
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether the executor should mask credentials for this launch.
|
||||
pub fn credential_masking_enabled(&self) -> bool {
|
||||
self.credential_masking.enabled
|
||||
}
|
||||
|
||||
pub(crate) fn into_network_proxy_config(self) -> NetworkProxyConfig {
|
||||
let mut config = NetworkProxyConfig {
|
||||
enabled: self.enabled,
|
||||
enable_socks5: self.enable_socks5,
|
||||
enable_socks5_udp: self.enable_socks5_udp,
|
||||
allow_upstream_proxy: self.allow_upstream_proxy,
|
||||
dangerously_allow_all_unix_sockets: Some(self.dangerously_allow_all_unix_sockets),
|
||||
mode: self.mode,
|
||||
domains: self.domains,
|
||||
review_domains: self.review_domains,
|
||||
unix_sockets: self.unix_sockets,
|
||||
allow_local_binding: Some(self.allow_local_binding),
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
if self.credential_masking.enabled {
|
||||
config.set_credential_broker_enabled(/*enabled*/ true);
|
||||
config.credential_providers = self.credential_masking.providers;
|
||||
}
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "remote_config_tests.rs"]
|
||||
mod tests;
|
||||
445
codex-rs/network-proxy/src/remote_config_tests.rs
Normal file
445
codex-rs/network-proxy/src/remote_config_tests.rs
Normal file
@@ -0,0 +1,445 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::RemoteNetworkProxyConfig;
|
||||
use super::RemoteNetworkProxyLaunchConfig;
|
||||
use crate::LocalBindingPolicy::DefaultFalse;
|
||||
use crate::LocalBindingPolicy::RequireTrue;
|
||||
use crate::MitmHookConfig;
|
||||
use crate::NetworkMitmCaConfig;
|
||||
use crate::NetworkMode;
|
||||
use crate::NetworkProxy;
|
||||
use crate::NetworkProxyAuditMetadata;
|
||||
use crate::NetworkProxyConfig;
|
||||
use crate::NetworkProxyState;
|
||||
use crate::Platform;
|
||||
use crate::RemoteCredentialMasking;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn optional_socket_policy_preserves_input_and_resolves_at_remote_boundary() {
|
||||
for allow_all in [None, Some(false), Some(true)] {
|
||||
let mut config = NetworkProxyConfig {
|
||||
dangerously_allow_all_unix_sockets: allow_all,
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
config.set_allow_unix_sockets(Vec::new());
|
||||
let serialized = serde_json::to_value(&config).expect("serialize config");
|
||||
assert_eq!(
|
||||
serialized.get("dangerously_allow_all_unix_sockets"),
|
||||
allow_all.map(serde_json::Value::Bool).as_ref()
|
||||
);
|
||||
assert_eq!(serialized["unix_sockets"], serde_json::json!({}));
|
||||
assert_eq!(
|
||||
serde_json::from_value::<NetworkProxyConfig>(serialized).expect("deserialize config"),
|
||||
config
|
||||
);
|
||||
|
||||
let remote = RemoteNetworkProxyConfig::from_effective_config(&config)
|
||||
.expect("supported remote config");
|
||||
assert_eq!(
|
||||
remote.dangerously_allow_all_unix_sockets,
|
||||
allow_all.unwrap_or(false)
|
||||
);
|
||||
config.dangerously_allow_all_unix_sockets = Some(allow_all.unwrap_or(false));
|
||||
config.allow_local_binding = Some(false);
|
||||
assert_eq!(remote.into_network_proxy_config(), config);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn round_trip_preserves_supported_effective_settings() {
|
||||
for (executor_os, socket, credential_masking, configured_provider) in [
|
||||
(Platform::Linux, "/var/run/example.sock", false, false),
|
||||
(Platform::Linux, "/var/run/example.sock", true, false),
|
||||
(Platform::Linux, "/var/run/example.sock", true, true),
|
||||
(Platform::Macos, "/var/run/example.sock", false, false),
|
||||
(Platform::Macos, "/var/run/example.sock", true, true),
|
||||
(Platform::Windows, r"C:\example.sock", false, false),
|
||||
(Platform::Unknown, r"C:\example.sock", false, false),
|
||||
] {
|
||||
let mut config = NetworkProxyConfig {
|
||||
enabled: true,
|
||||
enable_socks5: false,
|
||||
enable_socks5_udp: false,
|
||||
allow_upstream_proxy: false,
|
||||
dangerously_allow_all_unix_sockets: Some(true),
|
||||
mode: NetworkMode::Limited,
|
||||
allow_local_binding: Some(true),
|
||||
review_domains: vec!["review.example.com".to_string()],
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
// Domain permissions serialize as a sorted map.
|
||||
config.set_denied_domains(vec!["blocked.example.com".into()]);
|
||||
config.set_allowed_domains(vec!["example.com".into()]);
|
||||
config.set_allow_unix_sockets(vec![socket.into()]);
|
||||
|
||||
let mut remote = RemoteNetworkProxyConfig::from_effective_config(&config)
|
||||
.expect("supported remote config");
|
||||
config.set_credential_broker_enabled(credential_masking);
|
||||
if configured_provider {
|
||||
config.credential_providers.insert(
|
||||
"vendor".to_string(),
|
||||
crate::CredentialProviderConfig {
|
||||
env: vec!["VENDOR_TOKEN".to_string()],
|
||||
patterns: vec!["vendor_[a-z]{8}".to_string()],
|
||||
url_prefix_from_env: Some("VENDOR_BASE_URL".to_string()),
|
||||
auth: vec![crate::CredentialAuthMethod::Bearer],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
if credential_masking {
|
||||
remote.enable_credential_masking(config.credential_providers.clone());
|
||||
}
|
||||
let wire = serde_json::to_value(&remote).expect("serialize remote config");
|
||||
assert_eq!(
|
||||
wire.get("credentialMasking"),
|
||||
credential_masking.then_some(&serde_json::Value::Bool(true))
|
||||
);
|
||||
assert_eq!(
|
||||
wire.get("credentialProviders"),
|
||||
configured_provider
|
||||
.then(|| serde_json::to_value(&config.credential_providers).unwrap())
|
||||
.as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<RemoteNetworkProxyConfig>(wire.clone())
|
||||
.expect("deserialize remote config"),
|
||||
remote
|
||||
);
|
||||
let mut disabled_wire = wire;
|
||||
disabled_wire
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("credentialMasking");
|
||||
let mut expected_wire = disabled_wire.clone();
|
||||
expected_wire
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("credentialProviders");
|
||||
// Ignore provider rules when the peer omits or explicitly disables masking.
|
||||
let mut explicitly_disabled_wire = disabled_wire.clone();
|
||||
explicitly_disabled_wire["credentialMasking"] = false.into();
|
||||
for wire in [disabled_wire, explicitly_disabled_wire] {
|
||||
let disabled: RemoteNetworkProxyConfig =
|
||||
serde_json::from_value(wire).expect("disabled masking ignores provider rules");
|
||||
assert!(!disabled.credential_masking_enabled());
|
||||
assert_eq!(serde_json::to_value(disabled).unwrap(), expected_wire);
|
||||
}
|
||||
let diagnostic = format!("{remote:?}");
|
||||
assert!(!diagnostic.contains("vendor_[a-z]{8}"));
|
||||
assert!(!diagnostic.contains("VENDOR_BASE_URL"));
|
||||
let round_trip = remote.clone().into_network_proxy_config();
|
||||
|
||||
assert_eq!(round_trip, config);
|
||||
|
||||
let state = Arc::new(
|
||||
NetworkProxyState::from_remote_launch_config(
|
||||
RemoteNetworkProxyLaunchConfig::new(remote),
|
||||
executor_os,
|
||||
&crate::RemoteCredentialBrokerCache::default(),
|
||||
&std::collections::HashMap::new(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
// Policy edits and carrier construction must retain the executor's OS even
|
||||
// when the controller itself cannot interpret the socket as a native path.
|
||||
state.add_allowed_domain("added.example.com").await.unwrap();
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(state)
|
||||
.managed_by_codex(/*managed_by_codex*/ false)
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
config.upsert_domain_permission(
|
||||
"added.example.com".into(),
|
||||
crate::NetworkDomainPermission::Allow,
|
||||
crate::normalize_host,
|
||||
);
|
||||
assert_eq!(
|
||||
proxy
|
||||
.remote_launch_config(
|
||||
DefaultFalse,
|
||||
if credential_masking {
|
||||
RemoteCredentialMasking::WithConfiguredProviders
|
||||
} else {
|
||||
RemoteCredentialMasking::Disabled
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.proxy
|
||||
.into_network_proxy_config(),
|
||||
config
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsupported_configuration() {
|
||||
let cases = [
|
||||
(
|
||||
"MITM",
|
||||
NetworkProxyConfig {
|
||||
enabled: true,
|
||||
mitm: true,
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"credential broker",
|
||||
NetworkProxyConfig {
|
||||
enabled: true,
|
||||
credential_broker: true,
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"plaintext credential injection",
|
||||
NetworkProxyConfig {
|
||||
enabled: true,
|
||||
dangerously_allow_plaintext_credential_injection: true,
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"MITM hooks",
|
||||
NetworkProxyConfig {
|
||||
enabled: true,
|
||||
mitm_hooks: vec![MitmHookConfig::default()],
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
for (feature, config) in cases {
|
||||
assert!(
|
||||
RemoteNetworkProxyConfig::from_effective_config(&config).is_err(),
|
||||
"{feature} must not cross the remote executor boundary"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_unsupported_configuration_when_proxy_is_disabled() {
|
||||
let config = NetworkProxyConfig {
|
||||
mitm: true,
|
||||
credential_broker: true,
|
||||
dangerously_allow_plaintext_credential_injection: true,
|
||||
mitm_hooks: vec![MitmHookConfig::default()],
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
|
||||
let remote = RemoteNetworkProxyConfig::from_effective_config(&config)
|
||||
.expect("disabled proxy configuration does not cross the executor boundary");
|
||||
|
||||
assert!(!remote.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_external_ca_even_when_proxy_is_disabled() {
|
||||
for (enabled, mitm_enabled) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let config = NetworkProxyConfig {
|
||||
enabled,
|
||||
mitm: mitm_enabled,
|
||||
mitm_ca: Some(NetworkMitmCaConfig {
|
||||
certificate_file: "/run/proxy/ca.pem".to_string(),
|
||||
private_key_file: "/run/proxy/key.pem".to_string(),
|
||||
}),
|
||||
..NetworkProxyConfig::default()
|
||||
};
|
||||
|
||||
assert!(
|
||||
RemoteNetworkProxyConfig::from_effective_config(&config).is_err(),
|
||||
"external CA configuration must not cross the remote executor boundary (proxy enabled={enabled}, MITM enabled={mitm_enabled})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_config_materializes_audit_and_execution_attribution() {
|
||||
let proxy = RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig {
|
||||
enabled: true,
|
||||
..NetworkProxyConfig::default()
|
||||
})
|
||||
.expect("supported remote config");
|
||||
let audit_metadata = NetworkProxyAuditMetadata {
|
||||
conversation_id: Some("conversation-1".to_string()),
|
||||
user_account_id: Some("account-1".to_string()),
|
||||
originator: Some("codex_cli_rs".to_string()),
|
||||
model: Some("model-1".to_string()),
|
||||
..NetworkProxyAuditMetadata::default()
|
||||
};
|
||||
let state = NetworkProxyState::from_remote_launch_config(
|
||||
RemoteNetworkProxyLaunchConfig {
|
||||
proxy,
|
||||
audit_metadata: audit_metadata.clone(),
|
||||
environment_id: Some("remote".to_string()),
|
||||
execution_id: Some("execution-1".to_string()),
|
||||
policy_decision_timeout_ms: None,
|
||||
},
|
||||
Platform::native(),
|
||||
&crate::RemoteCredentialBrokerCache::default(),
|
||||
&std::collections::HashMap::new(),
|
||||
)
|
||||
.expect("remote launch state");
|
||||
|
||||
assert_eq!(state.audit_metadata(), &audit_metadata);
|
||||
assert_eq!(state.environment_id(), Some("remote"));
|
||||
assert_eq!(state.execution_id().as_deref(), Some("execution-1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_credential_mappings_follow_the_environment_and_broker_config() {
|
||||
const TOKEN: &str = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
let brokers = crate::RemoteCredentialBrokerCache::default();
|
||||
let launch = |environment_id: &str,
|
||||
conversation_id: &str,
|
||||
mode,
|
||||
allow_local_binding,
|
||||
env: &std::collections::HashMap<String, String>| {
|
||||
let mut proxy = RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig {
|
||||
enabled: true,
|
||||
allow_local_binding: Some(allow_local_binding),
|
||||
mode,
|
||||
..NetworkProxyConfig::default()
|
||||
})
|
||||
.unwrap();
|
||||
proxy.enable_credential_masking(Default::default());
|
||||
NetworkProxyState::from_remote_launch_config(
|
||||
RemoteNetworkProxyLaunchConfig::new(proxy)
|
||||
.for_execution(environment_id.to_string(), "execution".to_string())
|
||||
.with_audit_metadata(NetworkProxyAuditMetadata {
|
||||
conversation_id: Some(conversation_id.to_string()),
|
||||
..NetworkProxyAuditMetadata::default()
|
||||
}),
|
||||
Platform::Linux,
|
||||
&brokers,
|
||||
env,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let mut env = std::collections::HashMap::from([
|
||||
("GH_ENTERPRISE_TOKEN".to_string(), TOKEN.to_string()),
|
||||
(
|
||||
"GH_HOST".to_string(),
|
||||
"github.enterprise.example".to_string(),
|
||||
),
|
||||
]);
|
||||
let first = launch(
|
||||
"remote",
|
||||
"thread",
|
||||
NetworkMode::Full,
|
||||
/*allow_local_binding*/ false,
|
||||
&env,
|
||||
);
|
||||
first.virtualize_child_credentials(&mut env);
|
||||
let placeholder = env["GH_ENTERPRISE_TOKEN"].clone();
|
||||
assert_ne!(placeholder, TOKEN);
|
||||
|
||||
let mut next_env = std::collections::HashMap::from([
|
||||
("GH_ENTERPRISE_TOKEN".to_string(), TOKEN.to_string()),
|
||||
("GH_HOST".to_string(), String::new()),
|
||||
]);
|
||||
let next = launch(
|
||||
"remote",
|
||||
"thread",
|
||||
NetworkMode::Full,
|
||||
/*allow_local_binding*/ false,
|
||||
&env,
|
||||
);
|
||||
let listener = next.clone();
|
||||
next.bind_credential_broker_environment(&brokers, &next_env)
|
||||
.await
|
||||
.expect("bind startup credential context");
|
||||
next.virtualize_child_credentials(&mut next_env);
|
||||
let mut headers = rama_http::HeaderMap::from_iter([(
|
||||
rama_http::header::AUTHORIZATION,
|
||||
rama_http::HeaderValue::from_str(&format!("Bearer {placeholder}")).unwrap(),
|
||||
)]);
|
||||
let mut listener_headers = headers.clone();
|
||||
listener.inject_request_credentials("github.enterprise.example", &mut listener_headers);
|
||||
assert_eq!(listener_headers, headers);
|
||||
first.inject_request_credentials("github.enterprise.example", &mut headers);
|
||||
assert_eq!(
|
||||
headers[rama_http::header::AUTHORIZATION].to_str().unwrap(),
|
||||
format!("Bearer {TOKEN}")
|
||||
);
|
||||
drop(first);
|
||||
|
||||
for (environment_id, conversation_id, allow_local_binding, expected) in [
|
||||
("remote", "thread", false, TOKEN),
|
||||
("other", "thread", false, placeholder.as_str()),
|
||||
("remote", "other", false, placeholder.as_str()),
|
||||
("remote", "thread", true, placeholder.as_str()),
|
||||
] {
|
||||
// A different network mode must not discard mappings for the same scope.
|
||||
let state = launch(
|
||||
environment_id,
|
||||
conversation_id,
|
||||
NetworkMode::Limited,
|
||||
allow_local_binding,
|
||||
&env,
|
||||
);
|
||||
let mut headers = rama_http::HeaderMap::new();
|
||||
headers.insert(
|
||||
rama_http::header::AUTHORIZATION,
|
||||
rama_http::HeaderValue::from_str(&format!("Bearer {placeholder}")).unwrap(),
|
||||
);
|
||||
state.inject_request_credentials("github.enterprise.example", &mut headers);
|
||||
assert_eq!(
|
||||
headers[rama_http::header::AUTHORIZATION].to_str().unwrap(),
|
||||
format!("Bearer {expected}")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_decision_callback_timeout_round_trips() {
|
||||
let config = RemoteNetworkProxyConfig::from_effective_config(&NetworkProxyConfig::default())
|
||||
.expect("supported remote config");
|
||||
let mut launch = RemoteNetworkProxyLaunchConfig::new(config);
|
||||
let without_timeout = serde_json::to_value(&launch).expect("serialize launch config");
|
||||
assert_eq!(without_timeout.get("policyDecisionTimeoutMs"), None);
|
||||
launch.policy_decision_timeout_ms = Some(900_000);
|
||||
let with_timeout = serde_json::to_value(&launch).expect("serialize launch timeout");
|
||||
assert_eq!(with_timeout["policyDecisionTimeoutMs"], 900_000);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<RemoteNetworkProxyLaunchConfig>(with_timeout)
|
||||
.expect("deserialize launch timeout"),
|
||||
launch
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_binding_is_resolved_for_each_executor() -> anyhow::Result<()> {
|
||||
for (binding, policy, expected) in [
|
||||
(None, DefaultFalse, Some(false)),
|
||||
(None, RequireTrue, Some(true)),
|
||||
(Some(false), DefaultFalse, Some(false)),
|
||||
(Some(false), RequireTrue, None),
|
||||
(Some(true), DefaultFalse, Some(true)),
|
||||
] {
|
||||
let config = NetworkProxyConfig {
|
||||
enabled: true,
|
||||
allow_local_binding: binding,
|
||||
..Default::default()
|
||||
};
|
||||
let mut state = crate::runtime::network_proxy_state_for_policy(config);
|
||||
state.local_binding_policy = RequireTrue;
|
||||
let proxy = NetworkProxy::builder()
|
||||
.state(Arc::new(state))
|
||||
.managed_by_codex(false)
|
||||
.build()
|
||||
.await?;
|
||||
assert_eq!(
|
||||
proxy
|
||||
.remote_launch_config(policy, RemoteCredentialMasking::Disabled)
|
||||
.await
|
||||
.ok()
|
||||
.map(|launch| launch.proxy.allow_local_binding),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
32
codex-rs/network-proxy/src/request_cancellation.rs
Normal file
32
codex-rs/network-proxy/src/request_cancellation.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
//! Records why a policy request was withdrawn before its decision future is dropped.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The controller's first known reason for withdrawing a policy request.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum NetworkRequestCancellationReason {
|
||||
/// The process exited and its output streams closed normally.
|
||||
ProcessFinished,
|
||||
/// The process was explicitly terminated or its handle was abandoned.
|
||||
ProcessCancelled,
|
||||
/// The connection to the executor was lost.
|
||||
ConnectionClosed,
|
||||
/// The policy decision deadline expired.
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
/// Shared, in-process metadata; recording a reason does not authorize network access.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NetworkRequestCancellation(Arc<OnceLock<NetworkRequestCancellationReason>>);
|
||||
|
||||
impl NetworkRequestCancellation {
|
||||
pub fn reason(&self) -> Option<NetworkRequestCancellationReason> {
|
||||
self.0.get().copied()
|
||||
}
|
||||
|
||||
/// Publish before dropping the decision future. Cleanup cannot replace an earlier cause.
|
||||
pub fn record(&self, reason: NetworkRequestCancellationReason) {
|
||||
let _ = self.0.set(reason);
|
||||
}
|
||||
}
|
||||
45
codex-rs/network-proxy/src/request_disconnect.rs
Normal file
45
codex-rs/network-proxy/src/request_disconnect.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::future::Future;
|
||||
use std::pin::pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Transport metadata available while cleaning up an abandoned HTTP policy request.
|
||||
/// This does not cancel the approval reviewer or change its decision.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NetworkRequestDisconnect(Arc<OnceLock<Duration>>);
|
||||
|
||||
impl NetworkRequestDisconnect {
|
||||
pub fn elapsed(&self) -> Option<Duration> {
|
||||
self.0.get().copied()
|
||||
}
|
||||
|
||||
pub(crate) async fn track_http_request<F: Future>(
|
||||
&self,
|
||||
started_at: Instant,
|
||||
future: F,
|
||||
) -> F::Output {
|
||||
// Publish the cause before dropping the policy future: its cleanup may
|
||||
// immediately finish the owning tool call.
|
||||
let mut future = pin!(future);
|
||||
let mut guard = HttpRequestGuard(Some((self, started_at)));
|
||||
let result = future.as_mut().await;
|
||||
guard.0 = None;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
struct HttpRequestGuard<'a>(Option<(&'a NetworkRequestDisconnect, Instant)>);
|
||||
|
||||
impl Drop for HttpRequestGuard<'_> {
|
||||
fn drop(&mut self) {
|
||||
if let Some((disconnect, started_at)) = self.0 {
|
||||
let _ = disconnect.0.set(started_at.elapsed());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "request_disconnect_tests.rs"]
|
||||
mod tests;
|
||||
41
codex-rs/network-proxy/src/request_disconnect_tests.rs
Normal file
41
codex-rs/network-proxy/src/request_disconnect_tests.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use super::NetworkRequestDisconnect;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::future::pending;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnect_is_published_before_policy_cleanup() {
|
||||
struct ObserveOnDrop(NetworkRequestDisconnect);
|
||||
impl Drop for ObserveOnDrop {
|
||||
fn drop(&mut self) {
|
||||
assert!(self.0.elapsed().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
let disconnect = NetworkRequestDisconnect::default();
|
||||
let observer = ObserveOnDrop(disconnect.clone());
|
||||
let started_at = Instant::now();
|
||||
let decision = disconnect.track_http_request(started_at, async move {
|
||||
let _observer = observer;
|
||||
pending::<()>().await;
|
||||
});
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(1), decision)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(disconnect.elapsed().expect("disconnect time") <= started_at.elapsed());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_policy_request_is_not_a_disconnect() {
|
||||
let disconnect = NetworkRequestDisconnect::default();
|
||||
assert_eq!(
|
||||
disconnect
|
||||
.track_http_request(Instant::now(), async { 42 })
|
||||
.await,
|
||||
42
|
||||
);
|
||||
assert_eq!(disconnect.elapsed(), None);
|
||||
}
|
||||
121
codex-rs/network-proxy/src/responses.rs
Normal file
121
codex-rs/network-proxy/src/responses.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use crate::network_policy::NetworkDecisionSource;
|
||||
use crate::network_policy::NetworkPolicyDecision;
|
||||
use crate::network_policy::NetworkProtocol;
|
||||
use crate::reasons::REASON_DENIED;
|
||||
use crate::reasons::REASON_METHOD_NOT_ALLOWED;
|
||||
use crate::reasons::REASON_MITM_HOOK_DENIED;
|
||||
use crate::reasons::REASON_MITM_REQUIRED;
|
||||
use crate::reasons::REASON_NOT_ALLOWED;
|
||||
use crate::reasons::REASON_NOT_ALLOWED_LOCAL;
|
||||
use crate::reasons::REASON_PROXY_DISABLED;
|
||||
use rama_http::Body;
|
||||
use rama_http::Response;
|
||||
use rama_http::StatusCode;
|
||||
use serde::Serialize;
|
||||
use tracing::error;
|
||||
|
||||
pub struct PolicyDecisionDetails<'a> {
|
||||
pub decision: NetworkPolicyDecision,
|
||||
pub reason: &'a str,
|
||||
pub source: NetworkDecisionSource,
|
||||
pub protocol: NetworkProtocol,
|
||||
pub host: &'a str,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
pub fn text_response(status: StatusCode, body: &str) -> Response {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header("content-type", "text/plain")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap_or_else(|_| Response::new(Body::from(body.to_string())))
|
||||
}
|
||||
|
||||
pub fn json_response<T: Serialize>(value: &T) -> Response {
|
||||
let body = match serde_json::to_string(value) {
|
||||
Ok(body) => body,
|
||||
Err(err) => {
|
||||
error!("failed to serialize JSON response: {err}");
|
||||
"{}".to_string()
|
||||
}
|
||||
};
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body))
|
||||
.unwrap_or_else(|err| {
|
||||
error!("failed to build JSON response: {err}");
|
||||
Response::new(Body::from("{}"))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn blocked_header_value(reason: &str) -> &'static str {
|
||||
match reason {
|
||||
REASON_NOT_ALLOWED | REASON_NOT_ALLOWED_LOCAL => "blocked-by-allowlist",
|
||||
REASON_DENIED => "blocked-by-denylist",
|
||||
REASON_METHOD_NOT_ALLOWED => "blocked-by-method-policy",
|
||||
REASON_MITM_HOOK_DENIED => "blocked-by-mitm-hook",
|
||||
REASON_MITM_REQUIRED => "blocked-by-mitm-required",
|
||||
_ => "blocked-by-policy",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn blocked_message(reason: &str) -> &'static str {
|
||||
match reason {
|
||||
REASON_NOT_ALLOWED => "Domain not in allowlist.",
|
||||
REASON_NOT_ALLOWED_LOCAL => "Sandbox policy blocks local/private network addresses.",
|
||||
REASON_DENIED => "Domain denied by the sandbox policy.",
|
||||
REASON_METHOD_NOT_ALLOWED => "Method not allowed in limited mode.",
|
||||
REASON_MITM_HOOK_DENIED => "HTTPS request denied by MITM hook policy.",
|
||||
REASON_MITM_REQUIRED => "MITM required for limited HTTPS.",
|
||||
REASON_PROXY_DISABLED => "network proxy is disabled",
|
||||
_ => "Request blocked by network policy.",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn blocked_text_response(reason: &str) -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::FORBIDDEN)
|
||||
.header("content-type", "text/plain")
|
||||
.header("x-proxy-error", blocked_header_value(reason))
|
||||
.body(Body::from(blocked_message(reason)))
|
||||
.unwrap_or_else(|_| Response::new(Body::from("blocked")))
|
||||
}
|
||||
pub fn blocked_message_with_policy(reason: &str, details: &PolicyDecisionDetails<'_>) -> String {
|
||||
let _ = (details.reason, details.host);
|
||||
blocked_message(reason).to_string()
|
||||
}
|
||||
|
||||
pub fn blocked_text_response_with_policy(
|
||||
reason: &str,
|
||||
details: &PolicyDecisionDetails<'_>,
|
||||
) -> Response {
|
||||
Response::builder()
|
||||
.status(StatusCode::FORBIDDEN)
|
||||
.header("content-type", "text/plain")
|
||||
.header("x-proxy-error", blocked_header_value(reason))
|
||||
.body(Body::from(blocked_message_with_policy(reason, details)))
|
||||
.unwrap_or_else(|_| Response::new(Body::from("blocked")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::reasons::REASON_NOT_ALLOWED;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn blocked_message_with_policy_returns_human_message() {
|
||||
let details = PolicyDecisionDetails {
|
||||
decision: NetworkPolicyDecision::Ask,
|
||||
reason: REASON_NOT_ALLOWED,
|
||||
source: NetworkDecisionSource::Decider,
|
||||
protocol: NetworkProtocol::HttpsConnect,
|
||||
host: "api.example.com",
|
||||
port: 443,
|
||||
};
|
||||
|
||||
let message = blocked_message_with_policy(REASON_NOT_ALLOWED, &details);
|
||||
assert_eq!(message, "Domain not in allowlist.");
|
||||
}
|
||||
}
|
||||
2561
codex-rs/network-proxy/src/runtime.rs
Normal file
2561
codex-rs/network-proxy/src/runtime.rs
Normal file
File diff suppressed because it is too large
Load Diff
264
codex-rs/network-proxy/src/secret_substitution.rs
Normal file
264
codex-rs/network-proxy/src/secret_substitution.rs
Normal file
@@ -0,0 +1,264 @@
|
||||
//! Bounded byte-exact secret substitution after destination authorization, before signing.
|
||||
//! Placeholder bindings and resolved secret values are private to the trusted proxy.
|
||||
|
||||
use crate::aws_sigv4::ProxySecretSource;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_http::Body;
|
||||
use rama_http::HeaderMap;
|
||||
use rama_http::HeaderValue;
|
||||
use rama_http::Request;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::time::Duration;
|
||||
|
||||
// Bound the worst-case number of bytes compared by the placeholder window scans.
|
||||
const MAX_SUBSTITUTION_SEARCH_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct OriginalBodyHeadersSupported(bool);
|
||||
|
||||
pub(crate) fn preserve_body_substitution_headers(req: &mut Request) {
|
||||
if req
|
||||
.extensions()
|
||||
.get::<OriginalBodyHeadersSupported>()
|
||||
.is_none()
|
||||
{
|
||||
let supported = body_substitution_headers_supported(req.headers());
|
||||
req.extensions_mut()
|
||||
.insert(OriginalBodyHeadersSupported(supported));
|
||||
}
|
||||
}
|
||||
|
||||
fn body_substitution_headers_supported(headers: &HeaderMap) -> bool {
|
||||
let identity_encoding = headers.get_all("content-encoding").iter().all(|value| {
|
||||
value.to_str().is_ok_and(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.all(|coding| coding.trim().eq_ignore_ascii_case("identity"))
|
||||
})
|
||||
});
|
||||
identity_encoding
|
||||
&& crate::body_budget::supported_transfer_framing(headers)
|
||||
&& !crate::body_budget::is_amazon_event_stream(headers)
|
||||
&& !headers.contains_key("trailer")
|
||||
&& !headers.contains_key("x-amz-trailer")
|
||||
&& !headers.contains_key("x-amz-decoded-content-length")
|
||||
&& !headers.keys().any(|name| {
|
||||
matches!(
|
||||
name.as_str(),
|
||||
"content-md5"
|
||||
| "digest"
|
||||
| "content-digest"
|
||||
| "repr-digest"
|
||||
| "x-amz-content-sha256"
|
||||
) || name.as_str().starts_with("x-amz-checksum-")
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BodySecretReplacement {
|
||||
pub placeholder: String,
|
||||
pub secret: ProxySecretSource,
|
||||
}
|
||||
|
||||
/// Exact opaque placeholders scoped by their enclosing host/method/path MITM hook.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BodySecretSubstitutionConfig {
|
||||
pub replacements: Vec<BodySecretReplacement>,
|
||||
#[serde(default = "https_port")]
|
||||
pub port: u16,
|
||||
#[serde(default = "default_max_body_bytes")]
|
||||
pub max_body_bytes: usize,
|
||||
}
|
||||
|
||||
pub(crate) fn https_port() -> u16 {
|
||||
443
|
||||
}
|
||||
pub(crate) fn default_max_body_bytes() -> usize {
|
||||
8 * 1024 * 1024
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub(crate) struct BodySecretSubstitution {
|
||||
config: BodySecretSubstitutionConfig,
|
||||
secrets: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BodySecretSubstitution {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("BodySecretSubstitution")
|
||||
.field("config", &self.config)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl BodySecretSubstitutionConfig {
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
if self.port == 0
|
||||
|| self.max_body_bytes > 16 * 1024 * 1024
|
||||
|| self.replacements.is_empty()
|
||||
|| self.replacements.len() > 32
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"invalid body substitution port, bindings, or limit (maximum 16 MiB)"
|
||||
));
|
||||
}
|
||||
for (index, replacement) in self.replacements.iter().enumerate() {
|
||||
if !(16..=256).contains(&replacement.placeholder.len())
|
||||
|| !replacement.placeholder.is_ascii()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"body placeholders must be opaque ASCII markers of 16 to 256 bytes"
|
||||
));
|
||||
}
|
||||
replacement.secret.validate()?;
|
||||
if self.replacements[..index].iter().any(|previous| {
|
||||
previous.placeholder.contains(&replacement.placeholder)
|
||||
|| replacement.placeholder.contains(&previous.placeholder)
|
||||
}) {
|
||||
return Err(anyhow!("body substitution bindings overlap"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn compile(
|
||||
&self,
|
||||
env: &impl Fn(&str) -> Option<String>,
|
||||
file: &impl Fn(&AbsolutePathBuf) -> Result<String>,
|
||||
) -> Result<BodySecretSubstitution> {
|
||||
self.validate()?;
|
||||
let secrets = self
|
||||
.replacements
|
||||
.iter()
|
||||
.map(|replacement| {
|
||||
let secret = replacement.secret.resolve(env, file)?;
|
||||
if secret.len() > self.max_body_bytes
|
||||
|| self
|
||||
.replacements
|
||||
.iter()
|
||||
.any(|binding| secret.contains(&binding.placeholder))
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"body substitution secret exceeds limit or contains a placeholder"
|
||||
));
|
||||
}
|
||||
Ok(secret.into_bytes())
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(BodySecretSubstitution {
|
||||
config: self.clone(),
|
||||
secrets,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BodySecretSubstitution {
|
||||
pub(crate) async fn apply(&self, mut req: Request) -> Result<Request> {
|
||||
if req.uri().scheme_str() != Some("https")
|
||||
|| req.uri().port_u16().unwrap_or(443) != self.config.port
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"body substitution requires its configured HTTPS port"
|
||||
));
|
||||
}
|
||||
if req
|
||||
.extensions()
|
||||
.get::<OriginalBodyHeadersSupported>()
|
||||
.is_some_and(|original| !original.0)
|
||||
|| !body_substitution_headers_supported(req.headers())
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"body substitution does not support encoded, streaming-signed, or integrity-protected payloads"
|
||||
));
|
||||
}
|
||||
let _permit = crate::body_budget::reserve(&mut req).await?;
|
||||
let (mut parts, body) = req.into_parts();
|
||||
let (body, trailers) = tokio::time::timeout(
|
||||
Duration::from_secs(30),
|
||||
crate::body_budget::collect_body(body, self.config.max_body_bytes),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("body substitution read timed out"))?
|
||||
.map_err(|_| anyhow!("body substitution exceeds limit or cannot read payload"))?;
|
||||
if trailers.is_some() {
|
||||
return Err(anyhow!(
|
||||
"body substitution does not support request trailers"
|
||||
));
|
||||
}
|
||||
if !crate::body_budget::content_length_matches(&parts.headers, body.len()) {
|
||||
return Err(anyhow!(
|
||||
"body substitution content length does not match the request body"
|
||||
));
|
||||
}
|
||||
// Charge every window for its full length before searching, including failed matches.
|
||||
let search_bytes = self
|
||||
.config
|
||||
.replacements
|
||||
.iter()
|
||||
.try_fold(0usize, |work, binding| {
|
||||
let windows = body.len().saturating_sub(binding.placeholder.len() - 1);
|
||||
work.checked_add(windows.checked_mul(binding.placeholder.len())?)
|
||||
});
|
||||
if search_bytes.is_none_or(|work| work > MAX_SUBSTITUTION_SEARCH_BYTES) {
|
||||
return Err(anyhow!("body substitution search exceeds work limit"));
|
||||
}
|
||||
// Search the original bytes only. Replacements cannot recursively expand other bindings.
|
||||
let mut matches = Vec::new();
|
||||
for (index, binding) in self.config.replacements.iter().enumerate() {
|
||||
for (offset, window) in body.windows(binding.placeholder.len()).enumerate() {
|
||||
if window == binding.placeholder.as_bytes() {
|
||||
if matches.len() >= 65_536 {
|
||||
return Err(anyhow!("too many body substitution occurrences"));
|
||||
}
|
||||
matches.push((offset, offset + binding.placeholder.len(), index));
|
||||
}
|
||||
}
|
||||
}
|
||||
matches.sort_unstable();
|
||||
let mut cursor = 0;
|
||||
let mut size = body.len();
|
||||
for &(start, end, index) in &matches {
|
||||
if start < cursor {
|
||||
return Err(anyhow!("body substitution matches overlap"));
|
||||
}
|
||||
size = size
|
||||
.checked_sub(end - start)
|
||||
.and_then(|size| size.checked_add(self.secrets[index].len()))
|
||||
.ok_or_else(|| anyhow!("expanded body substitution exceeds limit"))?;
|
||||
cursor = end;
|
||||
}
|
||||
if size > self.config.max_body_bytes {
|
||||
return Err(anyhow!("expanded body substitution exceeds limit"));
|
||||
}
|
||||
let mut output = Vec::with_capacity(size);
|
||||
cursor = 0;
|
||||
for (start, end, index) in matches {
|
||||
output.extend_from_slice(&body[cursor..start]);
|
||||
output.extend_from_slice(&self.secrets[index]);
|
||||
cursor = end;
|
||||
}
|
||||
output.extend_from_slice(&body[cursor..]);
|
||||
parts.headers.remove("transfer-encoding");
|
||||
parts.headers.remove("trailer");
|
||||
parts.headers.insert(
|
||||
"content-length",
|
||||
HeaderValue::from_str(&output.len().to_string())?,
|
||||
);
|
||||
Ok(crate::body_budget::retain(Request::from_parts(
|
||||
parts,
|
||||
Body::from(output),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "secret_substitution_tests.rs"]
|
||||
mod tests;
|
||||
261
codex-rs/network-proxy/src/secret_substitution_tests.rs
Normal file
261
codex-rs/network-proxy/src/secret_substitution_tests.rs
Normal file
@@ -0,0 +1,261 @@
|
||||
//! Exact substitution preserves chunk boundaries, authorization scope, and signed wire bytes.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::bytes::Bytes;
|
||||
use rama_core::futures::stream;
|
||||
use rama_http::body::util::BodyExt;
|
||||
|
||||
const MARKER: &str = "codex-secret-0123456789abcdef";
|
||||
|
||||
fn config() -> BodySecretSubstitutionConfig {
|
||||
BodySecretSubstitutionConfig {
|
||||
replacements: vec![BodySecretReplacement {
|
||||
placeholder: MARKER.into(),
|
||||
secret: ProxySecretSource::EnvVar("SECRET".into()),
|
||||
}],
|
||||
port: 443,
|
||||
max_body_bytes: 1024,
|
||||
}
|
||||
}
|
||||
|
||||
fn compile(config: BodySecretSubstitutionConfig, secret: &str) -> BodySecretSubstitution {
|
||||
config
|
||||
.compile(&|_| Some(secret.into()), &|_| {
|
||||
panic!("unexpected file read")
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn substitutes_split_markers_and_updates_framing() {
|
||||
let body = Body::from_stream(stream::iter([
|
||||
Ok::<_, std::io::Error>(Bytes::from_static(b"before:codex-secret-0123")),
|
||||
Ok(Bytes::from_static(b"456789abcdef:after")),
|
||||
]));
|
||||
let request = Request::builder()
|
||||
.method("PUT")
|
||||
.uri("https://bucket.s3.amazonaws.com/object")
|
||||
.header("transfer-encoding", "chunked")
|
||||
.header("content-encoding", "Identity, identity")
|
||||
.header("content-encoding", "IDENTITY")
|
||||
.body(body)
|
||||
.unwrap();
|
||||
let substituted = compile(config(), "actual-secret")
|
||||
.apply(request)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(substituted.headers()["content-length"], "26");
|
||||
assert!(!substituted.headers().contains_key("transfer-encoding"));
|
||||
let payload = b"before:actual-secret:after";
|
||||
assert_eq!(
|
||||
substituted
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scope_overflow_encoding_trailers_and_ambiguous_matches_fail_closed() {
|
||||
let mut small = config();
|
||||
small.max_body_bytes = 40;
|
||||
let transform = compile(small, "long-replacement-value");
|
||||
for (uri, body) in [
|
||||
("http://example.com/", Body::from(MARKER)),
|
||||
("https://example.com:444/", Body::from(MARKER)),
|
||||
("https://example.com/", Body::from(vec![b'x'; 41])),
|
||||
(
|
||||
"https://example.com/",
|
||||
Body::empty().with_trailer_headers(rama_http::HeaderMap::new()),
|
||||
),
|
||||
] {
|
||||
let req = Request::builder().uri(uri).body(body).unwrap();
|
||||
assert!(transform.apply(req).await.is_err());
|
||||
}
|
||||
// Cover expansion and contraction in both orders at the final byte limit.
|
||||
let expanding_marker = "0123456789abcdef";
|
||||
let shrinking_marker = "fedcba9876543210";
|
||||
let mut mixed = config();
|
||||
mixed.max_body_bytes = 32;
|
||||
mixed.replacements[0].placeholder = expanding_marker.into();
|
||||
mixed.replacements.push(BodySecretReplacement {
|
||||
placeholder: shrinking_marker.into(),
|
||||
secret: ProxySecretSource::EnvVar("SHRINKING".into()),
|
||||
});
|
||||
for expanding_secret in ["x".repeat(30), "x".repeat(32)] {
|
||||
let transform = mixed
|
||||
.compile(
|
||||
&|name| match name {
|
||||
"SECRET" => Some(expanding_secret.clone()),
|
||||
"SHRINKING" => Some("y".into()),
|
||||
_ => None,
|
||||
},
|
||||
&|_| panic!("unexpected file read"),
|
||||
)
|
||||
.unwrap();
|
||||
for (body, expected) in [
|
||||
(
|
||||
format!("{expanding_marker}{shrinking_marker}"),
|
||||
format!("{expanding_secret}y"),
|
||||
),
|
||||
(
|
||||
format!("{shrinking_marker}{expanding_marker}"),
|
||||
format!("y{expanding_secret}"),
|
||||
),
|
||||
] {
|
||||
let result = transform
|
||||
.apply(
|
||||
Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.header("content-length", "32")
|
||||
.body(Body::from(body))
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
if expected.len() > mixed.max_body_bytes {
|
||||
assert_eq!(
|
||||
result.unwrap_err().to_string(),
|
||||
"expanded body substitution exceeds limit"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let substituted = result.unwrap();
|
||||
assert_eq!(substituted.headers()["content-length"], "31");
|
||||
assert!(!substituted.headers().contains_key("transfer-encoding"));
|
||||
assert_eq!(
|
||||
substituted
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.as_ref(),
|
||||
expected.as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for coding in [None, Some("chunked")] {
|
||||
let mut req = Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.header("content-length", "1");
|
||||
if let Some(coding) = coding {
|
||||
req = req.header("transfer-encoding", coding);
|
||||
}
|
||||
assert!(
|
||||
transform
|
||||
.apply(req.body(Body::from(MARKER)).unwrap())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
let mut overlaps = config();
|
||||
overlaps.replacements[0].placeholder = "0123456789abcdef0".into();
|
||||
let transform = compile(overlaps, "replacement");
|
||||
assert!(
|
||||
transform
|
||||
.apply(
|
||||
Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.body(Body::from("0123456789abcdef0123456789abcdef0"))
|
||||
.unwrap()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_bindings_recursive_values_and_redacts_secrets() {
|
||||
let mut duplicate = config();
|
||||
duplicate
|
||||
.replacements
|
||||
.push(duplicate.replacements[0].clone());
|
||||
assert!(duplicate.validate().is_err());
|
||||
assert!(
|
||||
config()
|
||||
.compile(&|_| Some(MARKER.into()), &|_| panic!("unexpected file"))
|
||||
.is_err()
|
||||
);
|
||||
let compiled = compile(config(), "do-not-log-this-secret");
|
||||
assert!(!format!("{compiled:?}").contains("do-not-log-this-secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_integrity_headers_and_preserves_original_validation() {
|
||||
let transform = compile(config(), "secret");
|
||||
for (name, value) in [
|
||||
(
|
||||
"content-type",
|
||||
"Application/Vnd.Amazon.Eventstream; version=1",
|
||||
),
|
||||
("content-encoding", "gzip"),
|
||||
("transfer-encoding", "gzip, chunked"),
|
||||
("trailer", "digest"),
|
||||
("x-amz-trailer", "x-amz-checksum-sha256"),
|
||||
("x-amz-decoded-content-length", "32"),
|
||||
("content-md5", "placeholder-digest"),
|
||||
("digest", "sha-256=placeholder-digest"),
|
||||
("content-digest", "sha-256=:placeholder-digest:"),
|
||||
("repr-digest", "sha-256=:placeholder-digest:"),
|
||||
("x-amz-content-sha256", "placeholder-digest"),
|
||||
("x-amz-checksum-sha256", "placeholder-digest"),
|
||||
("x-amz-checksum-crc32", "placeholder-digest"),
|
||||
] {
|
||||
for strip in [false, true] {
|
||||
let mut request = Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.header(name, value)
|
||||
.body(Body::from(MARKER))
|
||||
.unwrap();
|
||||
preserve_body_substitution_headers(&mut request);
|
||||
if strip {
|
||||
request.headers_mut().remove(name);
|
||||
preserve_body_substitution_headers(&mut request);
|
||||
}
|
||||
assert!(
|
||||
transform.apply(request).await.is_err(),
|
||||
"{name}, strip={strip}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut request = Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.body(Body::from(MARKER))
|
||||
.unwrap();
|
||||
preserve_body_substitution_headers(&mut request);
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("content-encoding", HeaderValue::from_static("gzip"));
|
||||
assert!(transform.apply(request).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_excessive_search_work_before_scanning_shared_prefixes() {
|
||||
let mut bounded = config();
|
||||
bounded.max_body_bytes = 1024 * 1024;
|
||||
bounded.replacements = (0..32)
|
||||
.map(|index| BodySecretReplacement {
|
||||
placeholder: format!("{}{:02}", "x".repeat(254), index),
|
||||
secret: ProxySecretSource::EnvVar("SECRET".into()),
|
||||
})
|
||||
.collect();
|
||||
let request = Request::builder()
|
||||
.uri("https://example.com/")
|
||||
.body(Body::from(vec![b'x'; bounded.max_body_bytes]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
compile(bounded, "secret")
|
||||
.apply(request)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"body substitution search exceeds work limit"
|
||||
);
|
||||
}
|
||||
36
codex-rs/network-proxy/src/socket_path.rs
Normal file
36
codex-rs/network-proxy/src/socket_path.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Executor-specific absolute socket path validation, independent of the controller OS.
|
||||
//! Socket support and native path normalization remain executor runtime concerns.
|
||||
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::Platform;
|
||||
|
||||
pub(crate) fn socket_path_is_absolute(platform: Platform, path: &str) -> bool {
|
||||
// Core also accepts Unix-style absolute paths on Windows, for portability.
|
||||
path.starts_with('/')
|
||||
|| match platform.path_convention() {
|
||||
Some(PathConvention::Posix) => false,
|
||||
// Legacy executors without OS metadata validate against their own
|
||||
// platform at launch; accept either absolute syntax here.
|
||||
Some(PathConvention::Windows) | None => windows_path_is_absolute(path),
|
||||
}
|
||||
}
|
||||
|
||||
// Match std::path's Windows absolute-path syntax without consulting the host.
|
||||
// Non-drive prefixes have an implicit root, including device and verbatim paths.
|
||||
fn windows_path_is_absolute(path: &str) -> bool {
|
||||
let bytes = path.as_bytes();
|
||||
if matches!(bytes, [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic()) {
|
||||
return true;
|
||||
}
|
||||
let [b'\\' | b'/', b'\\' | b'/', rest @ ..] = bytes else {
|
||||
return false;
|
||||
};
|
||||
if path.starts_with(r"\\?\") || matches!(rest, [b'.', b'\\' | b'/', ..]) {
|
||||
return true;
|
||||
}
|
||||
let mut components = rest.split(|byte| matches!(byte, b'\\' | b'/'));
|
||||
matches!(
|
||||
(components.next(), components.next()),
|
||||
(Some(server), Some(share)) if !server.is_empty() && !share.is_empty()
|
||||
)
|
||||
}
|
||||
1207
codex-rs/network-proxy/src/socks5.rs
Normal file
1207
codex-rs/network-proxy/src/socks5.rs
Normal file
File diff suppressed because it is too large
Load Diff
460
codex-rs/network-proxy/src/state.rs
Normal file
460
codex-rs/network-proxy/src/state.rs
Normal file
@@ -0,0 +1,460 @@
|
||||
use crate::config::NetworkDomainPermissions;
|
||||
use crate::config::NetworkMode;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::config::NetworkUnixSocketPermissions;
|
||||
use crate::mitm::MitmState;
|
||||
use crate::mitm::MitmUpstreamConfig;
|
||||
use crate::mitm_hook::MitmHookConfig;
|
||||
use crate::mitm_hook::compile_mitm_hooks;
|
||||
use crate::mitm_hook::validate_mitm_hook_config;
|
||||
use crate::policy::DomainPattern;
|
||||
use crate::policy::compile_allowlist;
|
||||
use crate::policy::compile_denylist;
|
||||
use crate::policy::is_global_wildcard_domain_pattern;
|
||||
use crate::runtime::ConfigState;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use crate::runtime::BlockedRequest;
|
||||
pub use crate::runtime::BlockedRequestArgs;
|
||||
pub use crate::runtime::NetworkProxyAuditMetadata;
|
||||
pub use crate::runtime::NetworkProxyState;
|
||||
#[cfg(test)]
|
||||
pub(crate) use crate::runtime::network_proxy_state_for_policy;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct NetworkProxyConstraints {
|
||||
pub enabled: Option<bool>,
|
||||
pub mode: Option<NetworkMode>,
|
||||
pub allow_upstream_proxy: Option<bool>,
|
||||
pub dangerously_allow_non_loopback_proxy: Option<bool>,
|
||||
pub dangerously_allow_all_unix_sockets: Option<bool>,
|
||||
pub allowed_domains: Option<Vec<String>>,
|
||||
pub allowlist_expansion_enabled: Option<bool>,
|
||||
pub denied_domains: Option<Vec<String>>,
|
||||
pub denylist_expansion_enabled: Option<bool>,
|
||||
pub allow_unix_sockets: Option<Vec<String>>,
|
||||
pub allow_local_binding: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct PartialNetworkProxyConfig {
|
||||
pub enabled: Option<bool>,
|
||||
pub mode: Option<NetworkMode>,
|
||||
pub allow_upstream_proxy: Option<bool>,
|
||||
pub dangerously_allow_non_loopback_proxy: Option<bool>,
|
||||
pub dangerously_allow_all_unix_sockets: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub domains: Option<NetworkDomainPermissions>,
|
||||
#[serde(default)]
|
||||
pub unix_sockets: Option<NetworkUnixSocketPermissions>,
|
||||
pub allow_local_binding: Option<bool>,
|
||||
pub mitm: Option<bool>,
|
||||
pub credential_broker: Option<bool>,
|
||||
pub dangerously_allow_plaintext_credential_injection: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub mitm_hooks: Option<Vec<MitmHookConfig>>,
|
||||
}
|
||||
|
||||
/// Compiles policy using the supplied executor OS, which may differ from this host.
|
||||
/// Socket paths are validated without native normalization or filesystem access.
|
||||
pub fn build_config_state(
|
||||
mut config: NetworkProxyConfig,
|
||||
constraints: NetworkProxyConstraints,
|
||||
executor_os: crate::Platform,
|
||||
) -> 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, executor_os)?;
|
||||
anyhow::ensure!(
|
||||
!config.credential_broker || config.mitm,
|
||||
"network.credential_broker requires network.mitm = true"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
config.mitm_ca.is_none() || config.mitm,
|
||||
"network.mitm_ca requires network.mitm = true"
|
||||
);
|
||||
let allowed_domains = config.allowed_domains().unwrap_or_default();
|
||||
let denied_domains = config.denied_domains().unwrap_or_default();
|
||||
validate_non_global_wildcard_domain_patterns("network.denied_domains", &denied_domains)
|
||||
.map_err(NetworkProxyConstraintError::into_anyhow)?;
|
||||
let deny_set = compile_denylist(&denied_domains)?;
|
||||
let allow_set = compile_allowlist(&allowed_domains)?;
|
||||
let review_set = compile_allowlist(&config.review_domains)?;
|
||||
let mitm_hooks = compile_mitm_hooks(&config)?;
|
||||
let mitm = if config.mitm {
|
||||
Some(Arc::new(MitmState::new(MitmUpstreamConfig {
|
||||
allow_upstream_proxy: config.allow_upstream_proxy,
|
||||
external_ca: config.mitm_ca.clone(),
|
||||
})?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ConfigState {
|
||||
executor_os,
|
||||
config,
|
||||
brokerage_created_default_allowlist,
|
||||
allow_set,
|
||||
deny_set,
|
||||
review_set,
|
||||
mitm,
|
||||
mitm_hooks,
|
||||
constraints,
|
||||
blocked: std::collections::VecDeque::new(),
|
||||
blocked_total: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate_policy_against_constraints(
|
||||
config: &NetworkProxyConfig,
|
||||
constraints: &NetworkProxyConstraints,
|
||||
) -> Result<(), NetworkProxyConstraintError> {
|
||||
fn invalid_value(
|
||||
field_name: &'static str,
|
||||
candidate: impl Into<String>,
|
||||
allowed: impl Into<String>,
|
||||
) -> NetworkProxyConstraintError {
|
||||
NetworkProxyConstraintError::InvalidValue {
|
||||
field_name,
|
||||
candidate: candidate.into(),
|
||||
allowed: allowed.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate<T>(
|
||||
candidate: T,
|
||||
validator: impl FnOnce(&T) -> Result<(), NetworkProxyConstraintError>,
|
||||
) -> Result<(), NetworkProxyConstraintError> {
|
||||
validator(&candidate)
|
||||
}
|
||||
|
||||
let enabled = config.enabled;
|
||||
let config_allowed_domains = config.allowed_domains().unwrap_or_default();
|
||||
let config_denied_domains = config.denied_domains().unwrap_or_default();
|
||||
let denied_domain_overrides: HashSet<String> = config_denied_domains
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
let config_allow_unix_sockets = config.allow_unix_sockets();
|
||||
validate_mitm_hook_config(config).map_err(invalid_mitm_hook_configuration)?;
|
||||
validate_non_global_wildcard_domain_patterns("network.denied_domains", &config_denied_domains)?;
|
||||
if let Some(max_enabled) = constraints.enabled {
|
||||
validate(enabled, move |candidate| {
|
||||
if *candidate && !max_enabled {
|
||||
Err(invalid_value(
|
||||
"network.enabled",
|
||||
"true",
|
||||
"false (disabled by managed config)",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
if let Some(max_mode) = constraints.mode {
|
||||
validate(config.mode, move |candidate| {
|
||||
if network_mode_rank(*candidate) > network_mode_rank(max_mode) {
|
||||
Err(invalid_value(
|
||||
"network.mode",
|
||||
format!("{candidate:?}"),
|
||||
format!("{max_mode:?} or more restrictive"),
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
let allow_upstream_proxy = constraints.allow_upstream_proxy;
|
||||
validate(
|
||||
config.allow_upstream_proxy,
|
||||
move |candidate| match allow_upstream_proxy {
|
||||
Some(true) | None => Ok(()),
|
||||
Some(false) => {
|
||||
if *candidate {
|
||||
Err(invalid_value(
|
||||
"network.allow_upstream_proxy",
|
||||
"true",
|
||||
"false (disabled by managed config)",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
let allow_non_loopback_proxy = constraints.dangerously_allow_non_loopback_proxy;
|
||||
validate(
|
||||
config.dangerously_allow_non_loopback_proxy,
|
||||
move |candidate| match allow_non_loopback_proxy {
|
||||
Some(true) | None => Ok(()),
|
||||
Some(false) => {
|
||||
if *candidate {
|
||||
Err(invalid_value(
|
||||
"network.dangerously_allow_non_loopback_proxy",
|
||||
"true",
|
||||
"false (disabled by managed config)",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
let allow_all_unix_sockets = constraints
|
||||
.dangerously_allow_all_unix_sockets
|
||||
.unwrap_or(constraints.allow_unix_sockets.is_none());
|
||||
validate(
|
||||
config.dangerously_allow_all_unix_sockets.unwrap_or(false),
|
||||
move |candidate| {
|
||||
if *candidate && !allow_all_unix_sockets {
|
||||
Err(invalid_value(
|
||||
"network.dangerously_allow_all_unix_sockets",
|
||||
"true",
|
||||
"false (disabled by managed config)",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
if let Some(allow_local_binding) = constraints.allow_local_binding {
|
||||
validate(config.allow_local_binding(), move |candidate| {
|
||||
if *candidate && !allow_local_binding {
|
||||
Err(invalid_value(
|
||||
"network.allow_local_binding",
|
||||
"true",
|
||||
"false (disabled by managed config)",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
if let Some(allowed_domains) = &constraints.allowed_domains {
|
||||
validate_non_global_wildcard_domain_patterns("network.allowed_domains", allowed_domains)?;
|
||||
match constraints.allowlist_expansion_enabled {
|
||||
Some(true) => {
|
||||
let required_set: HashSet<String> = allowed_domains
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
validate(config_allowed_domains, |candidate| {
|
||||
let candidate_set: HashSet<String> = candidate
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
let missing: Vec<String> = required_set
|
||||
.iter()
|
||||
.filter(|entry| {
|
||||
!candidate_set.contains(*entry)
|
||||
&& !denied_domain_overrides.contains(*entry)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.allowed_domains",
|
||||
"missing managed allowed_domains entries",
|
||||
format!("{missing:?}"),
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Some(false) => {
|
||||
let required_set: HashSet<String> = allowed_domains
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
validate(config_allowed_domains, |candidate| {
|
||||
let candidate_set: HashSet<String> = candidate
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
let expected_set: HashSet<String> = required_set
|
||||
.difference(&denied_domain_overrides)
|
||||
.cloned()
|
||||
.collect();
|
||||
if candidate_set == expected_set {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.allowed_domains",
|
||||
format!("{candidate:?}"),
|
||||
"must match managed allowed_domains",
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
None => {
|
||||
let managed_patterns: Vec<DomainPattern> = allowed_domains
|
||||
.iter()
|
||||
.map(|entry| DomainPattern::parse_for_constraints(entry))
|
||||
.collect();
|
||||
validate(config_allowed_domains, move |candidate| {
|
||||
let mut invalid = Vec::new();
|
||||
for entry in candidate {
|
||||
let candidate_pattern = DomainPattern::parse_for_constraints(entry);
|
||||
if !managed_patterns
|
||||
.iter()
|
||||
.any(|managed| managed.allows(&candidate_pattern))
|
||||
{
|
||||
invalid.push(entry.clone());
|
||||
}
|
||||
}
|
||||
if invalid.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.allowed_domains",
|
||||
format!("{invalid:?}"),
|
||||
"subset of managed allowed_domains",
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(denied_domains) = &constraints.denied_domains {
|
||||
validate_non_global_wildcard_domain_patterns("network.denied_domains", denied_domains)?;
|
||||
let required_set: HashSet<String> = denied_domains
|
||||
.iter()
|
||||
.map(|s| s.to_ascii_lowercase())
|
||||
.collect();
|
||||
match constraints.denylist_expansion_enabled {
|
||||
Some(false) => {
|
||||
validate(config_denied_domains, move |candidate| {
|
||||
let candidate_set: HashSet<String> = candidate
|
||||
.iter()
|
||||
.map(|entry| entry.to_ascii_lowercase())
|
||||
.collect();
|
||||
if candidate_set == required_set {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.denied_domains",
|
||||
format!("{candidate:?}"),
|
||||
"must match managed denied_domains",
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Some(true) | None => {
|
||||
validate(config_denied_domains, move |candidate| {
|
||||
let candidate_set: HashSet<String> =
|
||||
candidate.iter().map(|s| s.to_ascii_lowercase()).collect();
|
||||
let missing: Vec<String> = required_set
|
||||
.iter()
|
||||
.filter(|entry| !candidate_set.contains(*entry))
|
||||
.cloned()
|
||||
.collect();
|
||||
if missing.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.denied_domains",
|
||||
"missing managed denied_domains entries",
|
||||
format!("{missing:?}"),
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(allow_unix_sockets) = &constraints.allow_unix_sockets {
|
||||
let allowed_set: HashSet<&str> = allow_unix_sockets.iter().map(String::as_str).collect();
|
||||
validate(config_allow_unix_sockets, move |candidate| {
|
||||
let mut invalid = Vec::new();
|
||||
for entry in candidate {
|
||||
if !allowed_set.contains(entry.as_str()) {
|
||||
invalid.push(entry.clone());
|
||||
}
|
||||
}
|
||||
if invalid.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(
|
||||
"network.allow_unix_sockets",
|
||||
format!("{invalid:?}"),
|
||||
"subset of managed allow_unix_sockets",
|
||||
))
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid_mitm_hook_configuration(err: anyhow::Error) -> NetworkProxyConstraintError {
|
||||
NetworkProxyConstraintError::InvalidValue {
|
||||
field_name: "network.mitm_hooks",
|
||||
candidate: err.to_string(),
|
||||
allowed: "valid MITM hook configuration".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_non_global_wildcard_domain_patterns(
|
||||
field_name: &'static str,
|
||||
patterns: &[String],
|
||||
) -> Result<(), NetworkProxyConstraintError> {
|
||||
if let Some(pattern) = patterns
|
||||
.iter()
|
||||
.find(|pattern| is_global_wildcard_domain_pattern(pattern))
|
||||
{
|
||||
return Err(NetworkProxyConstraintError::InvalidValue {
|
||||
field_name,
|
||||
candidate: pattern.trim().to_string(),
|
||||
allowed: "exact hosts or scoped wildcards like *.example.com or **.example.com"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum NetworkProxyConstraintError {
|
||||
#[error("invalid value for {field_name}: {candidate} (allowed {allowed})")]
|
||||
InvalidValue {
|
||||
field_name: &'static str,
|
||||
candidate: String,
|
||||
allowed: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl NetworkProxyConstraintError {
|
||||
pub fn into_anyhow(self) -> anyhow::Error {
|
||||
anyhow::anyhow!(self)
|
||||
}
|
||||
}
|
||||
|
||||
fn network_mode_rank(mode: NetworkMode) -> u8 {
|
||||
match mode {
|
||||
NetworkMode::Limited => 0,
|
||||
NetworkMode::Full => 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {}
|
||||
56
codex-rs/network-proxy/src/system_dns.rs
Normal file
56
codex-rs/network-proxy/src/system_dns.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! This macOS-only module implements DNS resolution
|
||||
//! using macOS's native system resolver. We have to
|
||||
//! do this rather than relying on the default behavior
|
||||
//! (which reads /etc/resolv.conf) since default behavior
|
||||
//! breaks Codex's ability to interact with network paths
|
||||
//! that are provided by applications that modify / hook
|
||||
//! into macOS DNS behavior (i.e. proxies, VPNs, etc)
|
||||
use rama_dns::DnsResolver;
|
||||
use rama_net::address::Domain;
|
||||
use std::io;
|
||||
use std::net::IpAddr;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::Ipv6Addr;
|
||||
use tokio::net::lookup_host;
|
||||
|
||||
/// Resolve TCP destinations through macOS's native resolver, including supplemental
|
||||
/// resolvers and VPN split DNS that are not represented in `/etc/resolv.conf`.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct SystemDnsResolver;
|
||||
|
||||
impl DnsResolver for SystemDnsResolver {
|
||||
type Error = io::Error;
|
||||
|
||||
async fn ipv4_lookup(&self, domain: Domain) -> io::Result<Vec<Ipv4Addr>> {
|
||||
Ok(lookup_host((domain.as_str(), 0))
|
||||
.await?
|
||||
.filter_map(|addr| match addr.ip() {
|
||||
IpAddr::V4(ip) => Some(ip),
|
||||
IpAddr::V6(_) => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn ipv6_lookup(&self, domain: Domain) -> io::Result<Vec<Ipv6Addr>> {
|
||||
Ok(lookup_host((domain.as_str(), 0))
|
||||
.await?
|
||||
.filter_map(|addr| match addr.ip() {
|
||||
IpAddr::V4(_) => None,
|
||||
IpAddr::V6(ip) => Some(ip),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn txt_lookup(&self, _domain: Domain) -> io::Result<Vec<Vec<u8>>> {
|
||||
// TCP connectors only need address lookups. Do not silently fall back to
|
||||
// a resolver with different DNS routing for unsupported record types.
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"the system address resolver does not support TXT lookups",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "system_dns_tests.rs"]
|
||||
mod tests;
|
||||
95
codex-rs/network-proxy/src/system_dns_tests.rs
Normal file
95
codex-rs/network-proxy/src/system_dns_tests.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use super::*;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::connect_policy::TargetCheckedTcpConnector;
|
||||
use crate::state::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_core::Service;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_net::address::Host;
|
||||
use rama_net::address::HostWithPort;
|
||||
use rama_net::address::ProxyAddress;
|
||||
use rama_net::stream::Socket;
|
||||
use rama_tcp::client::Request;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_resolution_supports_both_address_families() {
|
||||
let domain: Domain = "localhost".parse().expect("valid domain");
|
||||
let (ipv4, ipv6) = tokio::join!(
|
||||
SystemDnsResolver.ipv4_lookup(domain.clone()),
|
||||
SystemDnsResolver.ipv6_lookup(domain),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
ipv4.expect("resolve IPv4 localhost"),
|
||||
vec![Ipv4Addr::LOCALHOST]
|
||||
);
|
||||
assert_eq!(
|
||||
ipv6.expect("resolve IPv6 localhost"),
|
||||
vec![Ipv6Addr::LOCALHOST]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connector_reaches_native_hostname_over_ipv4_and_ipv6() {
|
||||
for ip in [
|
||||
IpAddr::V4(Ipv4Addr::LOCALHOST),
|
||||
IpAddr::V6(Ipv6Addr::LOCALHOST),
|
||||
] {
|
||||
let listener = TcpListener::bind((ip, 0)).await.expect("bind listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxyConfig {
|
||||
allow_local_binding: Some(true),
|
||||
..NetworkProxyConfig::default()
|
||||
},
|
||||
)));
|
||||
let request = Request::new(HostWithPort::new(Host::LOCALHOST_NAME, target.port()));
|
||||
|
||||
let connection = connector
|
||||
.serve(request)
|
||||
.await
|
||||
.expect("connect to localhost");
|
||||
|
||||
assert_eq!(connection.conn.peer_addr().expect("peer addr"), target);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_resolution_preserves_local_network_rejection() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxyConfig::default(),
|
||||
)));
|
||||
let request = Request::new(HostWithPort::new(Host::LOCALHOST_NAME, target.port()));
|
||||
|
||||
connector
|
||||
.serve(request)
|
||||
.await
|
||||
.expect_err("resolved loopback addresses must still be checked against policy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connector_resolves_upstream_proxy_instead_of_destination() {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.expect("bind listener");
|
||||
let target = listener.local_addr().expect("local addr");
|
||||
let connector = TargetCheckedTcpConnector::new(Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxyConfig::default(),
|
||||
)));
|
||||
let mut request =
|
||||
Request::new(HostWithPort::try_from("destination.invalid:80").expect("valid destination"));
|
||||
request.extensions_mut().insert(
|
||||
ProxyAddress::try_from(format!("http://localhost:{}", target.port()))
|
||||
.expect("valid upstream proxy"),
|
||||
);
|
||||
|
||||
let connection = connector.serve(request).await.expect("connect to proxy");
|
||||
|
||||
assert_eq!(connection.conn.peer_addr().expect("peer addr"), target);
|
||||
}
|
||||
300
codex-rs/network-proxy/src/upstream.rs
Normal file
300
codex-rs/network-proxy/src/upstream.rs
Normal file
@@ -0,0 +1,300 @@
|
||||
use crate::connect_policy::TargetCheckedTcpConnector;
|
||||
use crate::connect_policy::is_non_public_target;
|
||||
use crate::policy::is_private_network_ip;
|
||||
use crate::state::NetworkProxyState;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use rama_core::Layer;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::error::ErrorExt as _;
|
||||
use rama_core::error::OpaqueError;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
use rama_core::extensions::ExtensionsRef;
|
||||
use rama_core::service::BoxService;
|
||||
use rama_http::Body;
|
||||
use rama_http::Request;
|
||||
use rama_http::Response;
|
||||
use rama_http::Version;
|
||||
use rama_http::layer::version_adapter::RequestVersionAdapter;
|
||||
use rama_http_backend::client::HttpClientService;
|
||||
use rama_http_backend::client::HttpConnector;
|
||||
use rama_http_backend::client::proxy::layer::HttpProxyConnectorLayer;
|
||||
use rama_net::address::Host;
|
||||
use rama_net::address::HostWithPort;
|
||||
use rama_net::address::ProxyAddress;
|
||||
use rama_net::client::EstablishedClientConnection;
|
||||
use rama_net::http::RequestContext;
|
||||
use rama_tls_rustls::client::TlsConnectorDataBuilder;
|
||||
use rama_tls_rustls::client::TlsConnectorLayer;
|
||||
use rama_tls_rustls::client::client_root_certs;
|
||||
use rama_tls_rustls::dep::rustls;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tracing::info;
|
||||
use tracing::warn;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use rama_unix::client::UnixConnector;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ProxyConfig {
|
||||
http: Option<ProxyAddress>,
|
||||
https: Option<ProxyAddress>,
|
||||
all: Option<ProxyAddress>,
|
||||
proxy_private_ips_via_upstream: bool,
|
||||
}
|
||||
|
||||
impl ProxyConfig {
|
||||
fn from_env(proxy_private_ips_via_upstream: bool) -> Self {
|
||||
let http = read_proxy_env(&["HTTP_PROXY", "http_proxy"]);
|
||||
let https = read_proxy_env(&["HTTPS_PROXY", "https_proxy"]);
|
||||
let all = read_proxy_env(&["ALL_PROXY", "all_proxy"]);
|
||||
Self {
|
||||
http,
|
||||
https,
|
||||
all,
|
||||
proxy_private_ips_via_upstream,
|
||||
}
|
||||
}
|
||||
|
||||
fn proxy_for_protocol(&self, is_secure: bool) -> Option<ProxyAddress> {
|
||||
if is_secure {
|
||||
self.https
|
||||
.clone()
|
||||
.or_else(|| self.http.clone())
|
||||
.or_else(|| self.all.clone())
|
||||
} else {
|
||||
self.http.clone().or_else(|| self.all.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn proxy_for_target(&self, target: &HostWithPort, is_secure: bool) -> Option<ProxyAddress> {
|
||||
let proxy_private_ip = self.proxy_private_ips_via_upstream
|
||||
&& matches!(&target.host, Host::Address(ip) if is_private_network_ip(*ip));
|
||||
if is_non_public_target(&target.host) && !proxy_private_ip {
|
||||
return None;
|
||||
}
|
||||
self.proxy_for_protocol(is_secure)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_proxy_env(keys: &[&str]) -> Option<ProxyAddress> {
|
||||
for key in keys {
|
||||
let Ok(value) = std::env::var(key) else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match ProxyAddress::try_from(value) {
|
||||
Ok(proxy) => {
|
||||
if proxy
|
||||
.protocol
|
||||
.as_ref()
|
||||
.map(rama_net::Protocol::is_http)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
return Some(proxy);
|
||||
}
|
||||
warn!("ignoring {key}: non-http proxy protocol");
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("ignoring {key}: invalid proxy address ({err})");
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn proxy_for_connect(
|
||||
target: &HostWithPort,
|
||||
state: &NetworkProxyState,
|
||||
) -> Option<ProxyAddress> {
|
||||
ProxyConfig::from_env(state.proxy_private_ips_via_upstream)
|
||||
.proxy_for_target(target, /*is_secure*/ true)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct UpstreamClient {
|
||||
connector: BoxService<
|
||||
Request<Body>,
|
||||
EstablishedClientConnection<HttpClientService<Body>, Request<Body>>,
|
||||
BoxError,
|
||||
>,
|
||||
proxy_config: ProxyConfig,
|
||||
}
|
||||
|
||||
impl UpstreamClient {
|
||||
pub(crate) fn direct(state: Arc<NetworkProxyState>) -> Self {
|
||||
Self::new(
|
||||
ProxyConfig::default(),
|
||||
TargetCheckedTcpConnector::new(state),
|
||||
client_root_certs(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn from_env_proxy(state: Arc<NetworkProxyState>) -> Self {
|
||||
Self::new(
|
||||
ProxyConfig::from_env(state.proxy_private_ips_via_upstream),
|
||||
TargetCheckedTcpConnector::new(state),
|
||||
client_root_certs(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn direct_with_tls_root_store(
|
||||
state: Arc<NetworkProxyState>,
|
||||
tls_root_store: Arc<rustls::RootCertStore>,
|
||||
) -> Self {
|
||||
Self::new(
|
||||
ProxyConfig::default(),
|
||||
TargetCheckedTcpConnector::new(state),
|
||||
tls_root_store,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn from_env_proxy_with_tls_root_store(
|
||||
state: Arc<NetworkProxyState>,
|
||||
tls_root_store: Arc<rustls::RootCertStore>,
|
||||
) -> Self {
|
||||
Self::new(
|
||||
ProxyConfig::from_env(state.proxy_private_ips_via_upstream),
|
||||
TargetCheckedTcpConnector::new(state),
|
||||
tls_root_store,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn unix_socket(path: &str) -> Self {
|
||||
let connector = build_unix_connector(path);
|
||||
Self {
|
||||
connector,
|
||||
proxy_config: ProxyConfig::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn new(
|
||||
proxy_config: ProxyConfig,
|
||||
transport: TargetCheckedTcpConnector,
|
||||
tls_root_store: Arc<rustls::RootCertStore>,
|
||||
) -> Self {
|
||||
let connector = build_http_connector(transport, tls_root_store);
|
||||
Self {
|
||||
connector,
|
||||
proxy_config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service<Request<Body>> for UpstreamClient {
|
||||
type Output = Response;
|
||||
type Error = OpaqueError;
|
||||
|
||||
async fn serve(&self, mut req: Request<Body>) -> Result<Self::Output, Self::Error> {
|
||||
let request_context = RequestContext::try_from(&req).ok();
|
||||
let authority = request_context
|
||||
.as_ref()
|
||||
.map(|ctx| ctx.host_with_port().to_string())
|
||||
.unwrap_or_else(|| "<unknown>".to_string());
|
||||
let proxy = request_context.as_ref().map_or_else(
|
||||
|| self.proxy_config.proxy_for_protocol(/*is_secure*/ false),
|
||||
|ctx| {
|
||||
self.proxy_config
|
||||
.proxy_for_target(&ctx.host_with_port(), ctx.protocol.is_secure())
|
||||
},
|
||||
);
|
||||
match proxy.as_ref() {
|
||||
Some(proxy) => info!(
|
||||
"HTTP upstream route selected (target={authority}, route=upstream_proxy, proxy={})",
|
||||
proxy.address
|
||||
),
|
||||
None => info!("HTTP upstream route selected (target={authority}, route=direct)"),
|
||||
}
|
||||
if let Some(proxy) = proxy {
|
||||
req.extensions_mut().insert(proxy);
|
||||
}
|
||||
|
||||
let connect_started_at = Instant::now();
|
||||
let EstablishedClientConnection {
|
||||
input: mut req,
|
||||
conn: http_connection,
|
||||
} = match self.connector.serve(req).await {
|
||||
Ok(connection) => {
|
||||
info!(
|
||||
"HTTP upstream connection established (target={authority}, elapsed_ms={})",
|
||||
connect_started_at.elapsed().as_millis()
|
||||
);
|
||||
connection
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"HTTP upstream connection failed (target={authority}, elapsed_ms={})",
|
||||
connect_started_at.elapsed().as_millis()
|
||||
);
|
||||
return Err(OpaqueError::from_boxed(err));
|
||||
}
|
||||
};
|
||||
|
||||
req.extensions_mut()
|
||||
.extend(http_connection.extensions().clone());
|
||||
|
||||
let request_started_at = Instant::now();
|
||||
match http_connection.serve(req).await {
|
||||
Ok(resp) => {
|
||||
info!(
|
||||
"HTTP upstream response headers received (target={authority}, elapsed_ms={})",
|
||||
request_started_at.elapsed().as_millis()
|
||||
);
|
||||
Ok(resp)
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
"HTTP upstream response headers failed (target={authority}, elapsed_ms={})",
|
||||
request_started_at.elapsed().as_millis()
|
||||
);
|
||||
Err(OpaqueError::from_boxed(err).context("HTTP upstream request failed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_http_connector(
|
||||
transport: TargetCheckedTcpConnector,
|
||||
tls_root_store: Arc<rustls::RootCertStore>,
|
||||
) -> BoxService<
|
||||
Request<Body>,
|
||||
EstablishedClientConnection<HttpClientService<Body>, Request<Body>>,
|
||||
BoxError,
|
||||
> {
|
||||
ensure_rustls_crypto_provider();
|
||||
let proxy = HttpProxyConnectorLayer::optional().into_layer(transport);
|
||||
let client_config = rustls::ClientConfig::builder_with_protocol_versions(rustls::ALL_VERSIONS)
|
||||
.with_root_certificates(tls_root_store)
|
||||
.with_no_client_auth();
|
||||
let tls_config = TlsConnectorDataBuilder::from(client_config)
|
||||
.with_alpn_protocols_http_auto()
|
||||
.build();
|
||||
let tls = TlsConnectorLayer::auto()
|
||||
.with_connector_data(tls_config)
|
||||
.into_layer(proxy);
|
||||
let tls = RequestVersionAdapter::new(tls).with_default_version(Version::HTTP_11);
|
||||
let connector = HttpConnector::new(tls);
|
||||
connector.boxed()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "upstream_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_unix_connector(
|
||||
path: &str,
|
||||
) -> BoxService<
|
||||
Request<Body>,
|
||||
EstablishedClientConnection<HttpClientService<Body>, Request<Body>>,
|
||||
BoxError,
|
||||
> {
|
||||
let transport = UnixConnector::fixed(path);
|
||||
let connector = HttpConnector::new(transport);
|
||||
connector.boxed()
|
||||
}
|
||||
161
codex-rs/network-proxy/src/upstream_tests.rs
Normal file
161
codex-rs/network-proxy/src/upstream_tests.rs
Normal file
@@ -0,0 +1,161 @@
|
||||
use super::*;
|
||||
use crate::config::NetworkProxyConfig;
|
||||
use crate::state::network_proxy_state_for_policy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rama_http::StatusCode;
|
||||
use rama_http::Version;
|
||||
use rama_net::address::Host;
|
||||
use rama_net::address::HostWithPort;
|
||||
use rama_tls_rustls::dep::pki_types::CertificateDer;
|
||||
use rama_tls_rustls::dep::pki_types::PrivateKeyDer;
|
||||
use rama_tls_rustls::dep::pki_types::pem::PemObject;
|
||||
use rama_tls_rustls::dep::rcgen::BasicConstraints;
|
||||
use rama_tls_rustls::dep::rcgen::CertificateParams;
|
||||
use rama_tls_rustls::dep::rcgen::DistinguishedName;
|
||||
use rama_tls_rustls::dep::rcgen::DnType;
|
||||
use rama_tls_rustls::dep::rcgen::ExtendedKeyUsagePurpose;
|
||||
use rama_tls_rustls::dep::rcgen::IsCa;
|
||||
use rama_tls_rustls::dep::rcgen::Issuer;
|
||||
use rama_tls_rustls::dep::rcgen::KeyPair;
|
||||
use rama_tls_rustls::dep::rcgen::KeyUsagePurpose;
|
||||
use rama_tls_rustls::dep::rcgen::PKCS_ECDSA_P256_SHA256;
|
||||
use rama_tls_rustls::dep::tokio_rustls::TlsAcceptor;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use tempfile::tempdir;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
fn generate_ca(common_name: &str) -> (String, KeyPair) {
|
||||
let mut params = CertificateParams::default();
|
||||
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
||||
params.key_usages = vec![
|
||||
KeyUsagePurpose::KeyCertSign,
|
||||
KeyUsagePurpose::DigitalSignature,
|
||||
KeyUsagePurpose::KeyEncipherment,
|
||||
];
|
||||
let mut distinguished_name = DistinguishedName::new();
|
||||
distinguished_name.push(DnType::CommonName, common_name);
|
||||
params.distinguished_name = distinguished_name;
|
||||
let key_pair = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
|
||||
let cert = params.self_signed(&key_pair).unwrap();
|
||||
(cert.pem(), key_pair)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mitm_upstream_client_trusts_startup_custom_ca() {
|
||||
ensure_rustls_crypto_provider();
|
||||
let temp_dir = tempdir().unwrap();
|
||||
let startup_ca_path = temp_dir.path().join("startup-ca.pem");
|
||||
let managed_ca_path = temp_dir.path().join("managed-ca.pem");
|
||||
let (startup_ca_pem, startup_ca_key) = generate_ca("startup CA");
|
||||
let (managed_ca_pem, _) = generate_ca("managed MITM CA");
|
||||
fs::write(&startup_ca_path, &startup_ca_pem).unwrap();
|
||||
fs::write(&managed_ca_path, managed_ca_pem).unwrap();
|
||||
|
||||
let issuer = Issuer::from_ca_cert_pem(&startup_ca_pem, startup_ca_key).unwrap();
|
||||
let mut server_params = CertificateParams::new(vec!["localhost".to_string()]).unwrap();
|
||||
server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
|
||||
server_params.key_usages = vec![
|
||||
KeyUsagePurpose::DigitalSignature,
|
||||
KeyUsagePurpose::KeyEncipherment,
|
||||
];
|
||||
let server_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256).unwrap();
|
||||
let server_cert = server_params.signed_by(&server_key, &issuer).unwrap();
|
||||
let server_cert = CertificateDer::from_pem_slice(server_cert.pem().as_bytes()).unwrap();
|
||||
let server_key = PrivateKeyDer::from_pem_slice(server_key.serialize_pem().as_bytes()).unwrap();
|
||||
let mut server_config =
|
||||
rustls::ServerConfig::builder_with_protocol_versions(rustls::ALL_VERSIONS)
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![server_cert], server_key)
|
||||
.unwrap();
|
||||
server_config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
|
||||
let env = HashMap::from([(
|
||||
"SSL_CERT_FILE",
|
||||
startup_ca_path.to_string_lossy().into_owned(),
|
||||
)]);
|
||||
let roots =
|
||||
crate::certs::upstream_tls_root_store_for_cert_path(&managed_ca_path, &env).unwrap();
|
||||
let baseline_roots =
|
||||
crate::certs::upstream_tls_root_store_for_cert_path(&managed_ca_path, &HashMap::new())
|
||||
.unwrap();
|
||||
assert_eq!(roots.len(), baseline_roots.len() + 1);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let acceptor = TlsAcceptor::from(Arc::new(server_config));
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut stream = acceptor.accept(stream).await.unwrap();
|
||||
let mut request = [0; 4096];
|
||||
let bytes_read = stream.read(&mut request).await.unwrap();
|
||||
assert!(bytes_read > 0);
|
||||
stream
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
|
||||
let mut config = NetworkProxyConfig::default();
|
||||
config.set_allowed_domains(vec!["localhost".to_string()]);
|
||||
let state = Arc::new(network_proxy_state_for_policy(config));
|
||||
let client = UpstreamClient::direct_with_tls_root_store(state, roots);
|
||||
let response = client
|
||||
.serve(
|
||||
Request::builder()
|
||||
.version(Version::HTTP_2)
|
||||
.uri(format!("https://localhost:{}/", address.port()))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_ip_upstream_routing_is_opt_in() {
|
||||
let proxy = ProxyAddress::try_from("http://127.0.0.1:43128").unwrap();
|
||||
for enabled in [false, true] {
|
||||
let config = ProxyConfig {
|
||||
http: Some(proxy.clone()),
|
||||
https: Some(proxy.clone()),
|
||||
proxy_private_ips_via_upstream: enabled,
|
||||
..ProxyConfig::default()
|
||||
};
|
||||
for (host, use_proxy) in [
|
||||
("10.0.0.1", enabled),
|
||||
("172.16.0.1", enabled),
|
||||
("192.168.0.1", enabled),
|
||||
("100.68.58.50", enabled),
|
||||
("fd00::1", enabled),
|
||||
("::ffff:100.68.58.50", enabled),
|
||||
("localhost", false),
|
||||
("127.0.0.1", false),
|
||||
("::1", false),
|
||||
("169.254.169.254", false),
|
||||
("fe80::1", false),
|
||||
("0.0.0.0", false),
|
||||
("224.0.0.1", false),
|
||||
("192.0.2.1", false),
|
||||
("240.0.0.1", false),
|
||||
("example.com", true),
|
||||
("100.63.255.255", true),
|
||||
("100.128.0.0", true),
|
||||
] {
|
||||
let target = HostWithPort::new(host.parse::<Host>().unwrap(), /*port*/ 443);
|
||||
for is_secure in [false, true] {
|
||||
assert_eq!(
|
||||
config.proxy_for_target(&target, is_secure),
|
||||
use_proxy.then(|| proxy.clone()),
|
||||
"host={host}, enabled={enabled}, secure={is_secure}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
368
codex-rs/network-proxy/src/windows_proxy_ingress.rs
Normal file
368
codex-rs/network-proxy/src/windows_proxy_ingress.rs
Normal file
@@ -0,0 +1,368 @@
|
||||
use crate::proxy::reserve_windows_managed_listeners;
|
||||
use crate::proxy::reserve_windows_managed_socks_listener;
|
||||
use crate::proxy::windows_managed_loopback_addr;
|
||||
use crate::windows_tcp_attribution::restricting_sids_for_tcp_connection;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::service::BoxService;
|
||||
use rama_net::stream::Socket;
|
||||
use rama_tcp::TcpStream;
|
||||
use rama_tcp::server::TcpListener;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
#[cfg(test)]
|
||||
use std::sync::Weak;
|
||||
use tokio::runtime::Handle;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::info;
|
||||
|
||||
pub(crate) type WindowsRouteService = BoxService<TcpStream, (), BoxError>;
|
||||
|
||||
// Production keeps the listeners alive for the process lifetime so their ports remain stable even
|
||||
// when no routes are registered. Crate tests use independent Tokio runtimes and requested ports, so
|
||||
// they retain only a weak reference and can tear each ingress down between tests.
|
||||
#[cfg(not(test))]
|
||||
static SHARED_INGRESS: LazyLock<Mutex<Option<Arc<WindowsProxyIngress>>>> =
|
||||
LazyLock::new(|| Mutex::new(None));
|
||||
#[cfg(test)]
|
||||
static SHARED_INGRESS: LazyLock<Mutex<Weak<WindowsProxyIngress>>> =
|
||||
LazyLock::new(|| Mutex::new(Weak::new()));
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RouteServices {
|
||||
http: WindowsRouteService,
|
||||
socks: Option<WindowsRouteService>,
|
||||
}
|
||||
|
||||
type RouteRegistry = Arc<Mutex<HashMap<String, Arc<RouteServices>>>>;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ProxyProtocol {
|
||||
Http,
|
||||
Socks,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct IngressDispatcher {
|
||||
routes: RouteRegistry,
|
||||
protocol: ProxyProtocol,
|
||||
}
|
||||
|
||||
impl Service<TcpStream> for IngressDispatcher {
|
||||
type Output = ();
|
||||
type Error = BoxError;
|
||||
|
||||
async fn serve(&self, stream: TcpStream) -> Result<(), BoxError> {
|
||||
let local_addr = stream.local_addr()?;
|
||||
let peer_addr = stream.peer_addr()?;
|
||||
let restricting_sids = restricting_sids_for_tcp_connection(local_addr, peer_addr)?;
|
||||
let route = {
|
||||
let routes = self
|
||||
.routes
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
registered_route_for_sids(&routes, &restricting_sids)?
|
||||
};
|
||||
let service = match self.protocol {
|
||||
ProxyProtocol::Http => route.http.clone(),
|
||||
ProxyProtocol::Socks => route.socks.clone().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"network proxy route does not enable SOCKS5",
|
||||
)
|
||||
})?,
|
||||
};
|
||||
service.serve(stream).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WindowsProxyIngress {
|
||||
http_addr: SocketAddr,
|
||||
routes: RouteRegistry,
|
||||
runtime: Handle,
|
||||
http_task: JoinHandle<()>,
|
||||
socks: Mutex<SocksListenerState>,
|
||||
}
|
||||
|
||||
struct SocksListenerState {
|
||||
addr: SocketAddr,
|
||||
task: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl WindowsProxyIngress {
|
||||
pub(crate) fn shared(
|
||||
requested_http_addr: SocketAddr,
|
||||
requested_socks_addr: SocketAddr,
|
||||
reserve_socks_listener: bool,
|
||||
) -> Result<Arc<Self>> {
|
||||
let requested_http_addr = windows_managed_loopback_addr(requested_http_addr);
|
||||
let requested_socks_addr = windows_managed_loopback_addr(requested_socks_addr);
|
||||
let mut shared = SHARED_INGRESS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
#[cfg(not(test))]
|
||||
if let Some(ingress) = shared.as_ref()
|
||||
&& ingress.is_running()
|
||||
{
|
||||
if reserve_socks_listener {
|
||||
ingress.ensure_socks_listener(requested_socks_addr)?;
|
||||
}
|
||||
return Ok(Arc::clone(ingress));
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
shared.take();
|
||||
#[cfg(test)]
|
||||
if let Some(ingress) = shared.upgrade()
|
||||
&& ingress.is_running()
|
||||
{
|
||||
if reserve_socks_listener {
|
||||
ingress.ensure_socks_listener(requested_socks_addr)?;
|
||||
}
|
||||
return Ok(ingress);
|
||||
}
|
||||
|
||||
let listeners = reserve_windows_managed_listeners(
|
||||
requested_http_addr,
|
||||
requested_socks_addr,
|
||||
reserve_socks_listener,
|
||||
)
|
||||
.context("reserve shared managed Windows proxy ingress")?;
|
||||
let http_addr = listeners.http_addr()?;
|
||||
let socks_addr = listeners.socks_addr(requested_socks_addr)?;
|
||||
let (http_listener, socks_listener) = listeners.into_listeners();
|
||||
let http_listener =
|
||||
TcpListener::try_from(http_listener).context("convert shared HTTP ingress listener")?;
|
||||
let socks_listener = socks_listener
|
||||
.map(TcpListener::try_from)
|
||||
.transpose()
|
||||
.context("convert shared SOCKS5 ingress listener")?;
|
||||
let runtime =
|
||||
Handle::try_current().context("start shared managed Windows proxy ingress")?;
|
||||
let routes = Arc::new(Mutex::new(HashMap::new()));
|
||||
let http_task = runtime.spawn(run_listener(
|
||||
http_listener,
|
||||
IngressDispatcher {
|
||||
routes: Arc::clone(&routes),
|
||||
protocol: ProxyProtocol::Http,
|
||||
},
|
||||
"HTTP",
|
||||
http_addr,
|
||||
));
|
||||
let socks_task = socks_listener
|
||||
.map(|listener| spawn_socks_listener(&runtime, &routes, listener, socks_addr));
|
||||
let ingress = Arc::new(Self {
|
||||
http_addr,
|
||||
routes,
|
||||
runtime,
|
||||
http_task,
|
||||
socks: Mutex::new(SocksListenerState {
|
||||
addr: socks_addr,
|
||||
task: socks_task,
|
||||
}),
|
||||
});
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
*shared = Some(Arc::clone(&ingress));
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
*shared = Arc::downgrade(&ingress);
|
||||
}
|
||||
Ok(ingress)
|
||||
}
|
||||
|
||||
pub(crate) fn http_addr(&self) -> SocketAddr {
|
||||
self.http_addr
|
||||
}
|
||||
|
||||
pub(crate) fn socks_addr(&self) -> SocketAddr {
|
||||
self.socks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.addr
|
||||
}
|
||||
|
||||
pub(crate) fn active_socks_addr(&self) -> Option<SocketAddr> {
|
||||
let socks = self
|
||||
.socks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
socks
|
||||
.task
|
||||
.as_ref()
|
||||
.filter(|task| !task.is_finished())
|
||||
.map(|_| socks.addr)
|
||||
}
|
||||
|
||||
pub(crate) fn register_route(
|
||||
self: &Arc<Self>,
|
||||
http: WindowsRouteService,
|
||||
socks: Option<WindowsRouteService>,
|
||||
) -> WindowsProxyRoute {
|
||||
let services = Arc::new(RouteServices { http, socks });
|
||||
let mut routes = self
|
||||
.routes
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let sid = loop {
|
||||
let sid = random_restricting_sid();
|
||||
if !routes.contains_key(&sid) {
|
||||
break sid;
|
||||
}
|
||||
};
|
||||
routes.insert(sid.clone(), Arc::clone(&services));
|
||||
WindowsProxyRoute {
|
||||
sid,
|
||||
services,
|
||||
ingress: Arc::clone(self),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_running(&self) -> bool {
|
||||
!self.http_task.is_finished()
|
||||
&& self
|
||||
.socks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.task
|
||||
.as_ref()
|
||||
.is_none_or(|task| !task.is_finished())
|
||||
}
|
||||
|
||||
fn ensure_socks_listener(&self, requested_addr: SocketAddr) -> Result<()> {
|
||||
let mut socks = self
|
||||
.socks
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(task) = socks.task.as_ref() {
|
||||
anyhow::ensure!(
|
||||
!task.is_finished(),
|
||||
"shared managed Windows SOCKS5 ingress stopped"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let listener = reserve_windows_managed_socks_listener(requested_addr)
|
||||
.context("reserve shared managed Windows SOCKS5 ingress")?;
|
||||
let addr = listener
|
||||
.local_addr()
|
||||
.context("read shared managed Windows SOCKS5 ingress address")?;
|
||||
let listener = {
|
||||
let _runtime = self.runtime.enter();
|
||||
TcpListener::try_from(listener)
|
||||
}
|
||||
.context("convert shared SOCKS5 ingress listener")?;
|
||||
let task = spawn_socks_listener(&self.runtime, &self.routes, listener, addr);
|
||||
socks.addr = addr;
|
||||
socks.task = Some(task);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WindowsProxyIngress {
|
||||
fn drop(&mut self) {
|
||||
self.http_task.abort();
|
||||
let socks = self
|
||||
.socks
|
||||
.get_mut()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(socks_task) = socks.task.as_ref() {
|
||||
socks_task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_socks_listener(
|
||||
runtime: &Handle,
|
||||
routes: &RouteRegistry,
|
||||
listener: TcpListener,
|
||||
addr: SocketAddr,
|
||||
) -> JoinHandle<()> {
|
||||
runtime.spawn(run_listener(
|
||||
listener,
|
||||
IngressDispatcher {
|
||||
routes: Arc::clone(routes),
|
||||
protocol: ProxyProtocol::Socks,
|
||||
},
|
||||
"SOCKS5",
|
||||
addr,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) struct WindowsProxyRoute {
|
||||
sid: String,
|
||||
services: Arc<RouteServices>,
|
||||
ingress: Arc<WindowsProxyIngress>,
|
||||
}
|
||||
|
||||
impl WindowsProxyRoute {
|
||||
pub(crate) fn sid(&self) -> &str {
|
||||
&self.sid
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WindowsProxyRoute {
|
||||
fn drop(&mut self) {
|
||||
let mut routes = self
|
||||
.ingress
|
||||
.routes
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if routes
|
||||
.get(&self.sid)
|
||||
.is_some_and(|services| Arc::ptr_eq(services, &self.services))
|
||||
{
|
||||
routes.remove(&self.sid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_listener(
|
||||
listener: TcpListener,
|
||||
dispatcher: IngressDispatcher,
|
||||
protocol: &'static str,
|
||||
addr: SocketAddr,
|
||||
) {
|
||||
info!("shared managed Windows {protocol} proxy ingress listening on {addr}");
|
||||
listener.serve(dispatcher).await;
|
||||
}
|
||||
|
||||
fn registered_route_for_sids(
|
||||
routes: &HashMap<String, Arc<RouteServices>>,
|
||||
restricting_sids: &[String],
|
||||
) -> io::Result<Arc<RouteServices>> {
|
||||
let mut matching_routes = restricting_sids
|
||||
.iter()
|
||||
.filter_map(|sid| routes.get(sid).cloned());
|
||||
let route = matching_routes.next().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"proxy client token has no registered network proxy route SID",
|
||||
)
|
||||
})?;
|
||||
if matching_routes.next().is_some() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"proxy client token has multiple registered network proxy route SIDs",
|
||||
));
|
||||
}
|
||||
Ok(route)
|
||||
}
|
||||
|
||||
fn random_restricting_sid() -> String {
|
||||
let a = rand::random::<u32>();
|
||||
let b = rand::random::<u32>();
|
||||
let c = rand::random::<u32>();
|
||||
let d = rand::random::<u32>();
|
||||
format!("S-1-5-21-{a}-{b}-{c}-{d}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_proxy_ingress_tests.rs"]
|
||||
mod tests;
|
||||
43
codex-rs/network-proxy/src/windows_proxy_ingress_tests.rs
Normal file
43
codex-rs/network-proxy/src/windows_proxy_ingress_tests.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use super::*;
|
||||
use rama_core::service::service_fn;
|
||||
|
||||
#[test]
|
||||
fn selects_exactly_one_registered_route() {
|
||||
let route = route_services();
|
||||
let routes = HashMap::from([("registered".to_string(), Arc::clone(&route))]);
|
||||
|
||||
let selected = registered_route_for_sids(
|
||||
&routes,
|
||||
&["unrelated".to_string(), "registered".to_string()],
|
||||
)
|
||||
.expect("one registered route should be selected");
|
||||
|
||||
assert!(Arc::ptr_eq(&selected, &route));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_ambiguous_registered_routes() {
|
||||
let first = route_services();
|
||||
let second = route_services();
|
||||
let routes = HashMap::from([("first".to_string(), first), ("second".to_string(), second)]);
|
||||
|
||||
let Err(missing) = registered_route_for_sids(&routes, &["missing".to_string()]) else {
|
||||
panic!("an unknown SID should fail closed");
|
||||
};
|
||||
let Err(ambiguous) =
|
||||
registered_route_for_sids(&routes, &["first".to_string(), "second".to_string()])
|
||||
else {
|
||||
panic!("multiple registered SIDs should fail closed");
|
||||
};
|
||||
|
||||
assert_eq!(missing.kind(), io::ErrorKind::PermissionDenied);
|
||||
assert_eq!(ambiguous.kind(), io::ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
fn route_services() -> Arc<RouteServices> {
|
||||
let service = service_fn(|_stream: TcpStream| async { Ok::<(), BoxError>(()) }).boxed();
|
||||
Arc::new(RouteServices {
|
||||
http: service,
|
||||
socks: None,
|
||||
})
|
||||
}
|
||||
309
codex-rs/network-proxy/src/windows_tcp_attribution.rs
Normal file
309
codex-rs/network-proxy/src/windows_tcp_attribution.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::mem::offset_of;
|
||||
use std::mem::size_of;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::SocketAddrV4;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
|
||||
use windows_sys::Win32::Foundation::GetLastError;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::HLOCAL;
|
||||
use windows_sys::Win32::Foundation::LocalFree;
|
||||
use windows_sys::Win32::Foundation::NO_ERROR;
|
||||
use windows_sys::Win32::NetworkManagement::IpHelper::GetExtendedTcpTable;
|
||||
use windows_sys::Win32::NetworkManagement::IpHelper::MIB_TCPROW_OWNER_PID;
|
||||
use windows_sys::Win32::NetworkManagement::IpHelper::MIB_TCPTABLE_OWNER_PID;
|
||||
use windows_sys::Win32::NetworkManagement::IpHelper::TCP_TABLE_OWNER_PID_CONNECTIONS;
|
||||
use windows_sys::Win32::Networking::WinSock::AF_INET;
|
||||
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
|
||||
use windows_sys::Win32::Security::GetTokenInformation;
|
||||
use windows_sys::Win32::Security::PSID;
|
||||
use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;
|
||||
use windows_sys::Win32::Security::TOKEN_GROUPS;
|
||||
use windows_sys::Win32::Security::TOKEN_QUERY;
|
||||
use windows_sys::Win32::Security::TokenRestrictedSids;
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
use windows_sys::Win32::System::Threading::OpenProcessToken;
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
|
||||
/// Returns the restricting SIDs on the process that opened an accepted loopback connection.
|
||||
///
|
||||
/// `accepted_local_addr` and `accepted_peer_addr` must come from the accepted server socket. The
|
||||
/// owning-PID table describes the client side in the opposite direction, so the lookup matches the
|
||||
/// exact reversed four-tuple.
|
||||
pub(crate) fn restricting_sids_for_tcp_connection(
|
||||
accepted_local_addr: SocketAddr,
|
||||
accepted_peer_addr: SocketAddr,
|
||||
) -> io::Result<Vec<String>> {
|
||||
let (SocketAddr::V4(accepted_local_addr), SocketAddr::V4(accepted_peer_addr)) =
|
||||
(accepted_local_addr, accepted_peer_addr)
|
||||
else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"Windows proxy connection attribution currently supports IPv4 only",
|
||||
));
|
||||
};
|
||||
|
||||
let process_id = owning_process_id(accepted_local_addr, accepted_peer_addr)?;
|
||||
restricting_sids_for_process(process_id)
|
||||
}
|
||||
|
||||
fn owning_process_id(
|
||||
accepted_local_addr: SocketAddrV4,
|
||||
accepted_peer_addr: SocketAddrV4,
|
||||
) -> io::Result<u32> {
|
||||
let mut byte_len = 0_u32;
|
||||
let result = unsafe {
|
||||
GetExtendedTcpTable(
|
||||
std::ptr::null_mut(),
|
||||
&mut byte_len,
|
||||
0,
|
||||
AF_INET as u32,
|
||||
TCP_TABLE_OWNER_PID_CONNECTIONS,
|
||||
0,
|
||||
)
|
||||
};
|
||||
if result != ERROR_INSUFFICIENT_BUFFER {
|
||||
return Err(win32_error("query IPv4 TCP owner table size", result));
|
||||
}
|
||||
|
||||
let buffer = loop {
|
||||
let mut buffer = aligned_buffer(byte_len as usize)?;
|
||||
let result = unsafe {
|
||||
GetExtendedTcpTable(
|
||||
buffer.as_mut_ptr().cast::<c_void>(),
|
||||
&mut byte_len,
|
||||
0,
|
||||
AF_INET as u32,
|
||||
TCP_TABLE_OWNER_PID_CONNECTIONS,
|
||||
0,
|
||||
)
|
||||
};
|
||||
match result {
|
||||
NO_ERROR => break buffer,
|
||||
ERROR_INSUFFICIENT_BUFFER => continue,
|
||||
_ => return Err(win32_error("read IPv4 TCP owner table", result)),
|
||||
}
|
||||
};
|
||||
|
||||
let rows = parse_tcp_owner_rows(&buffer, byte_len as usize)?;
|
||||
unique_client_process_id(rows, accepted_local_addr, accepted_peer_addr)
|
||||
}
|
||||
|
||||
fn parse_tcp_owner_rows(buffer: &[usize], byte_len: usize) -> io::Result<&[MIB_TCPROW_OWNER_PID]> {
|
||||
let rows_offset = offset_of!(MIB_TCPTABLE_OWNER_PID, table);
|
||||
if byte_len > size_of_val(buffer) || byte_len < rows_offset {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid IPv4 TCP owner table length",
|
||||
));
|
||||
}
|
||||
|
||||
let row_count = unsafe { std::ptr::read_unaligned(buffer.as_ptr().cast::<u32>()) } as usize;
|
||||
let rows_byte_len = row_count
|
||||
.checked_mul(size_of::<MIB_TCPROW_OWNER_PID>())
|
||||
.and_then(|len| rows_offset.checked_add(len))
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"IPv4 TCP owner table length overflow",
|
||||
)
|
||||
})?;
|
||||
if rows_byte_len > byte_len {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"truncated IPv4 TCP owner table",
|
||||
));
|
||||
}
|
||||
|
||||
let rows = unsafe {
|
||||
let rows_ptr = buffer
|
||||
.as_ptr()
|
||||
.cast::<u8>()
|
||||
.add(rows_offset)
|
||||
.cast::<MIB_TCPROW_OWNER_PID>();
|
||||
std::slice::from_raw_parts(rows_ptr, row_count)
|
||||
};
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
fn unique_client_process_id(
|
||||
rows: &[MIB_TCPROW_OWNER_PID],
|
||||
accepted_local_addr: SocketAddrV4,
|
||||
accepted_peer_addr: SocketAddrV4,
|
||||
) -> io::Result<u32> {
|
||||
let mut matching_process_ids = rows
|
||||
.iter()
|
||||
.filter(|row| client_row_matches(row, accepted_local_addr, accepted_peer_addr))
|
||||
.map(|row| row.dwOwningPid);
|
||||
let process_id = matching_process_ids.next().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"accepted connection is absent from the IPv4 TCP owner table",
|
||||
)
|
||||
})?;
|
||||
if matching_process_ids.next().is_some() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"accepted connection has multiple IPv4 TCP owner rows",
|
||||
));
|
||||
}
|
||||
Ok(process_id)
|
||||
}
|
||||
|
||||
fn client_row_matches(
|
||||
row: &MIB_TCPROW_OWNER_PID,
|
||||
accepted_local_addr: SocketAddrV4,
|
||||
accepted_peer_addr: SocketAddrV4,
|
||||
) -> bool {
|
||||
ipv4_addr_matches(row.dwLocalAddr, *accepted_peer_addr.ip())
|
||||
&& tcp_port(row.dwLocalPort) == accepted_peer_addr.port()
|
||||
&& ipv4_addr_matches(row.dwRemoteAddr, *accepted_local_addr.ip())
|
||||
&& tcp_port(row.dwRemotePort) == accepted_local_addr.port()
|
||||
}
|
||||
|
||||
fn ipv4_addr_matches(table_addr: u32, socket_addr: Ipv4Addr) -> bool {
|
||||
table_addr.to_ne_bytes() == socket_addr.octets()
|
||||
}
|
||||
|
||||
fn tcp_port(table_port: u32) -> u16 {
|
||||
u16::from_be(table_port as u16)
|
||||
}
|
||||
|
||||
fn restricting_sids_for_process(process_id: u32) -> io::Result<Vec<String>> {
|
||||
let process_handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, process_id) };
|
||||
let process = owned_handle(process_handle, "open proxy client process")?;
|
||||
|
||||
let mut token_handle = std::ptr::null_mut();
|
||||
let opened =
|
||||
unsafe { OpenProcessToken(process.as_raw_handle(), TOKEN_QUERY, &mut token_handle) };
|
||||
if opened == 0 {
|
||||
return Err(last_error("open proxy client process token"));
|
||||
}
|
||||
let token = owned_handle(token_handle, "open proxy client process token")?;
|
||||
|
||||
let mut byte_len = 0_u32;
|
||||
let queried = unsafe {
|
||||
GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
TokenRestrictedSids,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut byte_len,
|
||||
)
|
||||
};
|
||||
if queried != 0 || unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER {
|
||||
return Err(last_error("query proxy client restricting SID buffer size"));
|
||||
}
|
||||
|
||||
let mut buffer = aligned_buffer(byte_len as usize)?;
|
||||
let queried = unsafe {
|
||||
GetTokenInformation(
|
||||
token.as_raw_handle(),
|
||||
TokenRestrictedSids,
|
||||
buffer.as_mut_ptr().cast::<c_void>(),
|
||||
byte_len,
|
||||
&mut byte_len,
|
||||
)
|
||||
};
|
||||
if queried == 0 {
|
||||
return Err(last_error("read proxy client restricting SIDs"));
|
||||
}
|
||||
|
||||
parse_token_groups(&buffer, byte_len as usize)?
|
||||
.iter()
|
||||
.map(|entry| sid_to_string(entry.Sid))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn parse_token_groups(buffer: &[usize], byte_len: usize) -> io::Result<&[SID_AND_ATTRIBUTES]> {
|
||||
let groups_offset = offset_of!(TOKEN_GROUPS, Groups);
|
||||
if byte_len > size_of_val(buffer) || byte_len < groups_offset {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid restricting SID buffer length",
|
||||
));
|
||||
}
|
||||
|
||||
let group_count = unsafe { std::ptr::read_unaligned(buffer.as_ptr().cast::<u32>()) } as usize;
|
||||
let groups_byte_len = group_count
|
||||
.checked_mul(size_of::<SID_AND_ATTRIBUTES>())
|
||||
.and_then(|len| groups_offset.checked_add(len))
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"restricting SID buffer length overflow",
|
||||
)
|
||||
})?;
|
||||
if groups_byte_len > byte_len {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"truncated restricting SID buffer",
|
||||
));
|
||||
}
|
||||
|
||||
let groups = unsafe {
|
||||
let groups_ptr = buffer
|
||||
.as_ptr()
|
||||
.cast::<u8>()
|
||||
.add(groups_offset)
|
||||
.cast::<SID_AND_ATTRIBUTES>();
|
||||
std::slice::from_raw_parts(groups_ptr, group_count)
|
||||
};
|
||||
Ok(groups)
|
||||
}
|
||||
|
||||
fn sid_to_string(sid: PSID) -> io::Result<String> {
|
||||
let mut string_sid = std::ptr::null_mut();
|
||||
if unsafe { ConvertSidToStringSidW(sid, &mut string_sid) } == 0 {
|
||||
return Err(last_error("convert proxy client restricting SID to string"));
|
||||
}
|
||||
|
||||
let value = unsafe {
|
||||
let mut len = 0;
|
||||
while *string_sid.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(string_sid, len))
|
||||
};
|
||||
unsafe {
|
||||
LocalFree(string_sid as HLOCAL);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn aligned_buffer(byte_len: usize) -> io::Result<Vec<usize>> {
|
||||
if byte_len == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Windows API returned an empty buffer length",
|
||||
));
|
||||
}
|
||||
Ok(vec![0; byte_len.div_ceil(size_of::<usize>())])
|
||||
}
|
||||
|
||||
fn owned_handle(handle: HANDLE, operation: &str) -> io::Result<OwnedHandle> {
|
||||
if handle.is_null() {
|
||||
return Err(last_error(operation));
|
||||
}
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
|
||||
fn win32_error(operation: &str, error_code: u32) -> io::Error {
|
||||
let error = io::Error::from_raw_os_error(error_code as i32);
|
||||
io::Error::new(error.kind(), format!("{operation}: {error}"))
|
||||
}
|
||||
|
||||
fn last_error(operation: &str) -> io::Error {
|
||||
let error = io::Error::last_os_error();
|
||||
io::Error::new(error.kind(), format!("{operation}: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_tcp_attribution_tests.rs"]
|
||||
mod tests;
|
||||
112
codex-rs/network-proxy/src/windows_tcp_attribution_tests.rs
Normal file
112
codex-rs/network-proxy/src/windows_tcp_attribution_tests.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
|
||||
#[test]
|
||||
fn parses_owner_table_and_matches_reversed_client_tuple() -> io::Result<()> {
|
||||
let proxy_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3128);
|
||||
let client_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 49152);
|
||||
let rows = [
|
||||
tcp_row(proxy_addr, client_addr, 100),
|
||||
tcp_row(client_addr, proxy_addr, 200),
|
||||
];
|
||||
let (buffer, byte_len) = owner_table_buffer(&rows);
|
||||
|
||||
let parsed = parse_tcp_owner_rows(&buffer, byte_len)?;
|
||||
|
||||
assert_eq!(
|
||||
unique_client_process_id(parsed, proxy_addr, client_addr)?,
|
||||
200
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_multiple_matching_owner_rows() {
|
||||
let proxy_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3128);
|
||||
let client_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 49152);
|
||||
let rows = [
|
||||
tcp_row(client_addr, proxy_addr, 200),
|
||||
tcp_row(client_addr, proxy_addr, 201),
|
||||
];
|
||||
|
||||
let error = unique_client_process_id(&rows, proxy_addr, client_addr)
|
||||
.expect_err("duplicate connection rows should fail closed");
|
||||
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_owner_table() {
|
||||
let byte_len = offset_of!(MIB_TCPTABLE_OWNER_PID, table);
|
||||
let mut buffer = aligned_buffer(byte_len).expect("aligned table buffer");
|
||||
unsafe {
|
||||
std::ptr::write_unaligned(buffer.as_mut_ptr().cast::<u32>(), 1);
|
||||
}
|
||||
|
||||
let Err(error) = parse_tcp_owner_rows(&buffer, byte_len) else {
|
||||
panic!("truncated connection row should fail closed");
|
||||
};
|
||||
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_loopback_connection_to_current_process() -> io::Result<()> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let client = TcpStream::connect(listener.local_addr()?)?;
|
||||
let (accepted, _) = listener.accept()?;
|
||||
let local_addr = accepted.local_addr()?;
|
||||
let peer_addr = accepted.peer_addr()?;
|
||||
|
||||
let process_id = owning_process_id(socket_addr_v4(local_addr)?, socket_addr_v4(peer_addr)?)?;
|
||||
let restricting_sids = restricting_sids_for_tcp_connection(local_addr, peer_addr)?;
|
||||
|
||||
assert_eq!(process_id, std::process::id());
|
||||
assert!(restricting_sids.iter().all(|sid| sid.starts_with("S-")));
|
||||
drop(client);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn socket_addr_v4(addr: SocketAddr) -> io::Result<SocketAddrV4> {
|
||||
match addr {
|
||||
SocketAddr::V4(addr) => Ok(addr),
|
||||
SocketAddr::V6(_) => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"test listener unexpectedly used IPv6",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn tcp_row(
|
||||
local_addr: SocketAddrV4,
|
||||
remote_addr: SocketAddrV4,
|
||||
process_id: u32,
|
||||
) -> MIB_TCPROW_OWNER_PID {
|
||||
MIB_TCPROW_OWNER_PID {
|
||||
dwState: 0,
|
||||
dwLocalAddr: u32::from_ne_bytes(local_addr.ip().octets()),
|
||||
dwLocalPort: local_addr.port().to_be() as u32,
|
||||
dwRemoteAddr: u32::from_ne_bytes(remote_addr.ip().octets()),
|
||||
dwRemotePort: remote_addr.port().to_be() as u32,
|
||||
dwOwningPid: process_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_table_buffer(rows: &[MIB_TCPROW_OWNER_PID]) -> (Vec<usize>, usize) {
|
||||
let rows_offset = offset_of!(MIB_TCPTABLE_OWNER_PID, table);
|
||||
let rows_byte_len = size_of_val(rows);
|
||||
let byte_len = rows_offset + rows_byte_len;
|
||||
let mut buffer = aligned_buffer(byte_len).expect("aligned table buffer");
|
||||
unsafe {
|
||||
let buffer_ptr = buffer.as_mut_ptr().cast::<u8>();
|
||||
std::ptr::write_unaligned(buffer_ptr.cast::<u32>(), rows.len() as u32);
|
||||
std::ptr::copy_nonoverlapping(
|
||||
rows.as_ptr().cast::<u8>(),
|
||||
buffer_ptr.add(rows_offset),
|
||||
rows_byte_len,
|
||||
);
|
||||
}
|
||||
(buffer, byte_len)
|
||||
}
|
||||
Reference in New Issue
Block a user