greentic-aw-runtime 1.2.0

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;

/// 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>,
}

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

    /// 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)
    }

    /// 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> {
        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)
    }
}

/// 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"
    ))
}

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("..")
}

/// 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"
            );
        }
    }
}