greentic-aw-runtime 1.2.2

Enterprise Agentic Worker runtime — Plan-Act-Observe loop, Redis state, tool dispatch via greentic-ext-runtime
Documentation
//! The credential an `a2a:` call carries: resolved per call from the secrets
//! store, never held by the source, never sent on the card fetch.
//!
//! URIs are the cross-repo contract's §5 candidates, built by
//! [`crate::scoped_secrets`] with category [`A2A_CATEGORY`]. The agent id is
//! used verbatim; it is a hyphenated UUID, and canonicalising it would read a
//! URI nothing writes.

use std::sync::Arc;

use greentic_secrets_lib::SecretsManager;
use reqwest::header::{AUTHORIZATION, HeaderName, HeaderValue};

use super::types::A2aRoute;
use crate::oauth::{AuthMode, ClientCredentials, TokenProvider, parse_auth_mode, route_token_key};
use crate::scoped_secrets::is_safe_segment;
use secrecy::ExposeSecret;

/// The secrets category A2A credentials are sealed under (contract §5/§6).
pub(super) const A2A_CATEGORY: &str = "a2a";

/// Where a credentialed route's token is looked up: the manager, and the
/// tenant and unit captured when the source was built.
pub(super) struct CredentialScope {
    secrets: Option<Arc<dyn SecretsManager>>,
    tenant: String,
    unit: Option<String>,
    provider: Arc<TokenProvider>,
}

impl CredentialScope {
    pub(super) fn new(
        secrets: Option<Arc<dyn SecretsManager>>,
        tenant: String,
        unit: Option<String>,
        provider: Arc<TokenProvider>,
    ) -> Self {
        Self {
            secrets,
            tenant,
            unit,
            provider,
        }
    }

    /// The scope of a source built with no credentials at all. Every route it
    /// holds has `requires_auth: false`, so it is never consulted.
    pub(super) fn none() -> Self {
        Self::new(None, String::new(), None, TokenProvider::shared())
    }

    /// The header to add to the `SendMessage` POST: `None` for a route that
    /// stores no credential, `Err` when one is expected and cannot be sent.
    ///
    /// Errors name the agent and the URIs looked in, and never the value.
    pub(super) async fn header_for(
        &self,
        route: &A2aRoute,
    ) -> Result<Option<(HeaderName, HeaderValue)>, String> {
        let agent_id = route.agent_id.as_str();
        // An unknown auth_mode refuses this agent even when `requires_auth` is
        // unset: the sidecar asked for something this runner cannot honour.
        let mode = parse_auth_mode(route.auth_mode.as_deref())
            .map_err(|detail| format!("a2a agent {agent_id}: {detail}"))?;
        if !route.requires_auth && mode == AuthMode::Static {
            return Ok(None);
        }
        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}"))?;
        if mode == AuthMode::OAuthClientCredentials {
            return self.oauth_header(route, &bytes).await.map(Some);
        }
        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"
            ));
        }
        if looks_like_client_credentials(token) {
            return Err(format!(
                "a2a agent {agent_id}: the stored secret holds OAuth client credentials but the \
                 route's auth_mode is not oauth_client_credentials; refusing to send it as a token"
            ));
        }
        auth_header(agent_id, route.auth_header_name.as_deref(), token).map(Some)
    }

    /// `Authorization: Bearer <access token>` for an OAuth route. The token
    /// endpoint is the sidecar's `oauth_endpoint`; nothing from the agent card
    /// reaches it.
    async fn oauth_header(
        &self,
        route: &A2aRoute,
        secret: &[u8],
    ) -> Result<(HeaderName, HeaderValue), String> {
        let agent_id = route.agent_id.as_str();
        let endpoint = route
            .oauth_endpoint
            .as_deref()
            .map(str::trim)
            .filter(|e| !e.is_empty())
            .ok_or_else(|| {
                format!("a2a agent {agent_id}: oauth_client_credentials needs an oauth_endpoint")
            })?;
        let creds = ClientCredentials::from_secret_bytes(secret)
            .map_err(|detail| format!("a2a agent {agent_id}: {detail}"))?;
        let clean = |v: &Option<String>| {
            v.as_deref()
                .map(str::trim)
                .filter(|v| !v.is_empty() && !v.chars().any(char::is_control))
                .map(str::to_string)
        };
        let access = self
            .provider
            .token_for(
                &self.token_key(route),
                endpoint,
                clean(&route.oauth_scope).as_deref(),
                clean(&route.oauth_audience).as_deref(),
                &creds.client_id,
                &creds.client_secret,
            )
            .await
            .map_err(|e| format!("a2a agent {agent_id}: {e}"))?;
        auth_header(agent_id, None, access.expose_secret())
    }

    fn token_key(&self, route: &A2aRoute) -> String {
        route_token_key(
            A2A_CATEGORY,
            &self.tenant,
            route.auth_team.as_deref(),
            self.unit.as_deref(),
            &route.agent_id,
        )
    }

    /// The resource answered 401 to the token: drop it so a retry fetches a
    /// new one.
    pub(super) async fn invalidate(&self, route: &A2aRoute) {
        self.provider.invalidate(&self.token_key(route)).await;
    }

    /// Whether `route` authenticates with an OAuth grant.
    pub(super) fn is_oauth(route: &A2aRoute) -> bool {
        matches!(
            parse_auth_mode(route.auth_mode.as_deref()),
            Ok(AuthMode::OAuthClientCredentials)
        )
    }
}

fn looks_like_client_credentials(secret: &str) -> bool {
    let trimmed = secret.trim();
    trimmed.starts_with('{')
        && serde_json::from_str::<serde_json::Value>(trimmed)
            .ok()
            .is_some_and(|v| v.get("client_secret").is_some())
}

/// The `(name, value)` pair for `token`, following greentic-mcp-client's
/// `McpAuth::header` rule: no name, or any spelling of `authorization`, sends
/// `Authorization: Bearer <token>`; any other name sends the raw token.
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))
}

/// Headers that frame or route the request itself. Carrying a token in one
/// would corrupt the request or send the token as a routing value, so an
/// admin-configured header name is refused when it is one of these.
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,
];

/// Refuse an `agent_id` that could step outside its own secret key.
///
/// The id becomes the last segment of `secrets://…/a2a/<agent_id>` verbatim.
/// Admin ids are UUIDs, so anything beyond `[A-Za-z0-9._-]`, a leading dot or
/// `..` can only come from a hand-built or crafted sidecar — refused rather
/// than looked up.
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"
    ))
}

/// The same rule for `auth_team`, which becomes the team segment of the same
/// URI and comes from the same sidecar.
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"
    ))
}

/// Refuse to carry a credential to any host other than the one the admin
/// configured.
///
/// The interface URL comes from the agent CARD, which the agent controls, and
/// `require_secure_interface` accepts any https host it names. Without this
/// rule a card could route the admin's token to a host nobody vetted. Host
/// and port must both equal the configured `base_url`'s (the port through
/// `port_or_known_default`, so `https://a` and `https://a:443` agree).
///
/// Called before the secrets store is read, so a mismatch never touches it.
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)
    ))
}

/// `host:port` for an error message, the port being the effective one.
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() {
        // (base, interface, same?)
        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"
            );
        }
    }
}