Base: codex-main originale (prima del fork aKode)
This commit is contained in:
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user