use std::sync::Arc;
use greentic_secrets_lib::SecretsManager;
use reqwest::header::{AUTHORIZATION, HeaderName, HeaderValue};
use super::types::A2aRoute;
pub(super) const A2A_CATEGORY: &str = "a2a";
pub(super) struct CredentialScope {
secrets: Option<Arc<dyn SecretsManager>>,
tenant: String,
unit: Option<String>,
}
impl CredentialScope {
pub(super) fn new(
secrets: Option<Arc<dyn SecretsManager>>,
tenant: String,
unit: Option<String>,
) -> Self {
Self {
secrets,
tenant,
unit,
}
}
pub(super) fn none() -> Self {
Self::new(None, String::new(), None)
}
pub(super) async fn header_for(
&self,
route: &A2aRoute,
) -> Result<Option<(HeaderName, HeaderValue)>, String> {
if !route.requires_auth {
return Ok(None);
}
let agent_id = route.agent_id.as_str();
ensure_safe_agent_id(agent_id)?;
let team = route.auth_team.as_deref();
if let Some(team) = team.filter(|t| !t.is_empty() && *t != "_") {
ensure_safe_segment(agent_id, "auth_team", team)?;
}
let unit = self.unit.as_deref();
let Some(secrets) = self.secrets.as_ref() else {
let uris = crate::scoped_secrets::secret_uri_candidates(
A2A_CATEGORY,
&self.tenant,
team,
unit,
agent_id,
)
.unwrap_or_default();
return Err(format!(
"a2a agent {agent_id}: no credential at {} (no secrets manager is \
configured on this runner)",
uris.join(" or ")
));
};
let bytes = crate::scoped_secrets::read_secret_for_unit(
secrets.as_ref(),
A2A_CATEGORY,
&self.tenant,
team,
unit,
agent_id,
)
.await
.map_err(|miss| format!("a2a agent {agent_id}: {miss}"))?;
let token = String::from_utf8(bytes).map_err(|_| {
format!("a2a agent {agent_id}: the stored credential is not valid UTF-8")
})?;
let token = token.trim();
if token.is_empty() {
return Err(format!(
"a2a agent {agent_id}: the stored credential is empty"
));
}
auth_header(agent_id, route.auth_header_name.as_deref(), token).map(Some)
}
}
fn auth_header(
agent_id: &str,
header_name: Option<&str>,
token: &str,
) -> Result<(HeaderName, HeaderValue), String> {
let name = match header_name.map(str::trim).filter(|n| !n.is_empty()) {
None => AUTHORIZATION,
Some(raw) => HeaderName::from_bytes(raw.as_bytes()).map_err(|_| {
format!("a2a agent {agent_id}: '{raw}' is not a valid HTTP header name")
})?,
};
if RESERVED_HEADERS.contains(&name) {
return Err(format!(
"a2a agent {agent_id}: '{name}' frames or routes the request and cannot carry a credential"
));
}
let raw_value = if name == AUTHORIZATION {
format!("Bearer {token}")
} else {
token.to_string()
};
let mut value = HeaderValue::from_str(&raw_value).map_err(|_| {
format!(
"a2a agent {agent_id}: the stored credential cannot be sent as an HTTP header value"
)
})?;
value.set_sensitive(true);
Ok((name, value))
}
const RESERVED_HEADERS: [HeaderName; 9] = [
reqwest::header::HOST,
reqwest::header::CONTENT_LENGTH,
reqwest::header::CONTENT_TYPE,
reqwest::header::TRANSFER_ENCODING,
reqwest::header::CONNECTION,
reqwest::header::UPGRADE,
reqwest::header::TE,
reqwest::header::TRAILER,
reqwest::header::EXPECT,
];
pub(super) fn ensure_safe_agent_id(agent_id: &str) -> Result<(), String> {
if is_safe_segment(agent_id) {
return Ok(());
}
Err(format!(
"a2a agent id '{agent_id}' is not a safe secret name; refusing to look up its credential"
))
}
fn ensure_safe_segment(agent_id: &str, field: &str, value: &str) -> Result<(), String> {
if is_safe_segment(value) {
return Ok(());
}
Err(format!(
"a2a agent {agent_id}: {field} '{value}' is not a safe secret-path segment; \
refusing to look up its credential"
))
}
fn is_safe_segment(value: &str) -> bool {
let charset_ok = value
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
!value.is_empty() && charset_ok && !value.starts_with('.') && !value.contains("..")
}
pub(super) fn ensure_same_host(
agent_id: &str,
base_url: &str,
target: &url::Url,
) -> Result<(), String> {
let base = url::Url::parse(base_url).map_err(|_| {
format!("a2a agent {agent_id}: configured base url '{base_url}' is not a valid URL")
})?;
let same_host = match (base.host_str(), target.host_str()) {
(Some(configured), Some(interface)) => configured.eq_ignore_ascii_case(interface),
_ => false,
};
if same_host && base.port_or_known_default() == target.port_or_known_default() {
return Ok(());
}
Err(format!(
"a2a agent {agent_id}: interface host {} differs from configured host {}; \
refusing to send its credential",
authority(target),
authority(&base)
))
}
fn authority(url: &url::Url) -> String {
let host = url.host_str().unwrap_or("<no host>");
match url.port_or_known_default() {
Some(port) => format!("{host}:{port}"),
None => host.to_string(),
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod host_rule_tests {
use super::{ensure_safe_agent_id, ensure_same_host};
fn same(base: &str, target: &str) -> bool {
ensure_same_host("a", base, &url::Url::parse(target).unwrap()).is_ok()
}
#[test]
fn the_same_host_rule_normalises_what_url_normalises_and_nothing_more() {
let cases = [
(
"https://agent.example.com",
"https://agent.example.com/a2a",
true,
),
(
"https://agent.example.com",
"https://agent.example.com:443/a2a",
true,
),
(
"https://AGENT.example.com",
"https://agent.EXAMPLE.com/a2a",
true,
),
(
"https://agent.example.com",
"https://agent.example.com:8443/a2a",
false,
),
(
"https://agent.example.com",
"https://agent.example.com./a2a",
false,
),
(
"https://agent.example.com",
"https://api.example.com/a2a",
false,
),
("https://[::1]:9000", "https://[::1]:9000/a2a", true),
];
for (base, target, expected) in cases {
assert_eq!(same(base, target), expected, "{base} vs {target}");
}
}
#[test]
fn an_agent_id_that_could_leave_its_secret_key_is_refused() {
for bad in [
"", "../other", "a/b", "..", ".hidden", "a..b", "a b", "a\nb",
] {
assert!(
ensure_safe_agent_id(bad).is_err(),
"{bad:?} must be refused"
);
}
for good in [
"8d2f3c1a-0b7e-4c2f-9a61-2f4f0f1e9b10",
"recipe",
"recipe_v2.1",
] {
assert!(
ensure_safe_agent_id(good).is_ok(),
"{good:?} must be accepted"
);
}
}
}