Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

24.5 KB
Raw Blame
//! The service itself: verify, resolve, stamp, forward.

use std::sync::Arc;

use http::header::AUTHORIZATION;
use http::{Method, Uri};
use http_body_util::{BodyExt, Full};

use crate::domain::approval::{
    HeldCall, MACRO_SERVER_SLUG, OwnerApprovals, RefuseHeldCalls, ToolsCall, spends_owner_access,
};
use crate::domain::error::EgressError;
use crate::domain::model::{
    EgressTarget, MAX_MCP_REQUEST_BYTES, McpDestination, McpResolution, ProxyRequest,
    ProxyResponse, SessionToken, TOOLS_CALL_METHOD, UpstreamCall, disconnected_tool_result,
    ensure_method_allowed, not_connected_tool_result, peek_json_rpc, sanitize_request_headers,
    sanitize_response_headers,
};
use crate::domain::observed_body::{ObservedBody, StreamIdentity};
use crate::domain::ports::{Forwarder, GithubTokens, McpCredentials, SessionAuthority};

#[cfg(test)]
mod test;

/// Proxy one request on a sandbox's behalf.
pub trait EgressService: Send + Sync {
    /// Verify `token`, resolve `target` against the session owner's own
    /// connections, and pass `request` through with the upstream credential
    /// stamped on in place of the sandbox's.
    fn proxy(
        &self,
        token: &SessionToken,
        target: EgressTarget,
        request: ProxyRequest,
    ) -> impl Future<Output = Result<ProxyResponse, EgressError>> + Send;
}

/// MCP exchanges for an in-process caller, such as a code execution's
/// connected-app route, that authorized its request against the session
/// itself rather than presenting the session's token.
pub trait SessionMcpExchange: Send + Sync {
    /// The session's grant, read by id. Refuses a closed session.
    fn session_grant(
        &self,
        session: crate::domain::model::AgentSessionId,
    ) -> impl Future<Output = Result<crate::domain::model::SessionGrant, EgressError>> + Send;

    /// One `tools/list` or `tools/call` on a connected app or custom server
    /// as `user`, an account the caller already settled the call may spend.
    /// Returns the MCP `result` payload.
    fn exchange_as(
        &self,
        grant: &crate::domain::model::SessionGrant,
        user: &macro_user_id::user_id::MacroUserIdStr<'static>,
        destination: &McpDestination,
        request: serde_json::Value,
    ) -> impl Future<Output = Result<serde_json::Value, EgressError>> + Send;
}

/// The service, over its ports.
///
/// Held tool calls are refused until [`Self::with_owner_approvals`] says how
/// to ask the owner, so a proxy wired without approvals fails closed.
pub struct EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals = RefuseHeldCalls> {
    sessions: Arc<Sessions>,
    credentials: Credentials,
    tokens: Tokens,
    forward: Arc<Forward>,
    preview_mcp: Option<(url::Url, bool)>,
    approvals: Approvals,
    actor_mcp: Option<Arc<dyn crate::domain::ports::ActorMcpTransport>>,
}

impl<Sessions, Credentials, Tokens, Forward>
    EgressServiceImpl<Sessions, Credentials, Tokens, Forward>
where
    Sessions: SessionAuthority,
    Credentials: McpCredentials,
    Tokens: GithubTokens,
    Forward: Forwarder,
{
    /// Configure the fixed internal preview MCP destination. Cleartext is local-only.
    pub fn with_preview_mcp(
        mut self,
        url: url::Url,
        local_cleartext: bool,
    ) -> Result<Self, EgressError> {
        if !local_cleartext {
            crate::domain::model::UpstreamCall::bearer(
                url.clone(),
                crate::domain::model::BearerToken::new("validation"),
            )?;
        }
        self.preview_mcp = Some((url, local_cleartext));
        Ok(self)
    }

    /// Build the service over its adapters.
    pub fn new(
        sessions: Sessions,
        credentials: Credentials,
        tokens: Tokens,
        forward: Forward,
    ) -> Self {
        Self {
            sessions: Arc::new(sessions),
            credentials,
            tokens,
            forward: Arc::new(forward),
            preview_mcp: None,
            approvals: RefuseHeldCalls,
            actor_mcp: None,
        }
    }
}

impl<Sessions, Credentials, Tokens, Forward, Approvals>
    EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
{
    /// Enable explicit actor selection for model-facing MCP tools.
    pub fn with_actor_mcp(
        mut self,
        transport: Arc<dyn crate::domain::ports::ActorMcpTransport>,
    ) -> Self {
        self.actor_mcp = Some(transport);
        self
    }

    /// Hold the tool calls of turns somebody other than the owner prompted
    /// with `approvals`.
    pub fn with_owner_approvals<Next>(
        self,
        approvals: Next,
    ) -> EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Next> {
        EgressServiceImpl {
            sessions: self.sessions,
            credentials: self.credentials,
            tokens: self.tokens,
            forward: self.forward,
            preview_mcp: self.preview_mcp,
            approvals,
            actor_mcp: self.actor_mcp,
        }
    }
}

impl<Sessions, Credentials, Tokens, Forward, Approvals> EgressService
    for EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
where
    Sessions: SessionAuthority + 'static,
    Credentials: McpCredentials,
    Tokens: GithubTokens,
    Forward: Forwarder + 'static,
    Approvals: OwnerApprovals,
{
    #[tracing::instrument(skip_all, fields(
        destination = ?target,
        method = %request.method(),
        session = tracing::field::Empty,
        owner = tracing::field::Empty,
        upstream_status = tracing::field::Empty,
    ))]
    async fn proxy(
        &self,
        token: &SessionToken,
        target: EgressTarget,
        request: ProxyRequest,
    ) -> Result<ProxyResponse, EgressError> {
        self.authorize_and_forward(token, target, request)
            .await
            .inspect_err(log_proxy_error)
    }
}

impl<Sessions, Credentials, Tokens, Forward, Approvals>
    EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
where
    Sessions: SessionAuthority + 'static,
    Credentials: McpCredentials,
    Tokens: GithubTokens,
    Forward: Forwarder + 'static,
    Approvals: OwnerApprovals,
{
    async fn authorize_and_forward(
        &self,
        token: &SessionToken,
        target: EgressTarget,
        mut request: ProxyRequest,
    ) -> Result<ProxyResponse, EgressError> {
        ensure_method_allowed(request.method())?;

        // Authorize before resolving: resolution reads the owner's connected
        // servers, and an unverified token must not be able to probe which
        // of those exist.
        let grant = self.sessions.authorize(token).await?;
        let span = tracing::Span::current();
        span.record("session", tracing::field::display(&grant.session));
        span.record("owner", tracing::field::display(&grant.owner));

        if self.actor_mcp.is_some()
            && matches!(&target, EgressTarget::McpServer(destination) if !matches!(destination, McpDestination::Preview))
            && *request.method() == Method::POST
        {
            let (mut parts, bytes) = read_mcp_body(request).await?;
            let mut body = bytes.clone();
            if let Some(rpc) = peek_json_rpc(&bytes)
                && matches!(rpc.method.as_str(), "tools/list" | "tools/call")
                && let EgressTarget::McpServer(destination) = &target
            {
                let mut value: serde_json::Value = serde_json::from_slice(&bytes)
                    .map_err(|error| EgressError::Internal(rootcause::report!(error).into()))?;
                let public = matches!(destination, McpDestination::Macro)
                    && rpc.method == "tools/call"
                    && !spends_owner_access(
                        MACRO_SERVER_SLUG,
                        value["params"]["name"].as_str().unwrap_or_default(),
                    );
                if public {
                    if let Some(arguments) = value["params"]["arguments"].as_object_mut() {
                        arguments.remove(ai_toolset::actor::ACTING_AS);
                    }
                } else if rpc.method == "tools/list" {
                    return self.actor_exchange(token, &grant, destination, value).await;
                } else {
                    match actor::owner_call_arguments(&grant, &value) {
                        Ok(Some(arguments)) => value["params"]["arguments"] = arguments,
                        Ok(None) => {
                            return self.actor_exchange(token, &grant, destination, value).await;
                        }
                        Err(error) => {
                            return Ok(crate::domain::model::tool_result_response(
                                rpc.id,
                                error.to_string(),
                            ));
                        }
                    }
                }
                body = serde_json::to_vec(&value)
                    .map_err(|error| EgressError::Internal(rootcause::report!(error).into()))?
                    .into();
                parts.headers.remove(http::header::CONTENT_LENGTH);
            }
            request = ProxyRequest::from_parts(parts, full_body(body));
        }

        let call = match &target {
            EgressTarget::McpServer(McpDestination::Preview) => {
                let (url, local) = self.preview_mcp.as_ref().ok_or_else(|| {
                    EgressError::Unroutable("preview service is not configured".into())
                })?;
                // Unlike user tools, this tool must retain the authenticated session identity.
                // The destination is deployment configuration, never supplied by an agent.
                let bearer = crate::domain::model::BearerToken::new(token.as_str());
                if *local {
                    crate::domain::model::UpstreamCall::bearer_over_local_cleartext(
                        url.clone(),
                        bearer,
                    )
                } else {
                    crate::domain::model::UpstreamCall::bearer(url.clone(), bearer)?
                }
            }

            EgressTarget::McpServer(
                destination @ (McpDestination::Macro
                | McpDestination::Connected(_)
                | McpDestination::Custom(_)),
            ) => {
                let (call, answer): (UpstreamCall, Option<Answer>) = match self
                    .credentials
                    .resolve(
                        &grant.owner,
                        grant.agent,
                        grant.session.as_uuid(),
                        destination,
                    )
                    .await?
                {
                    McpResolution::Connected(call) => (call, None),
                    // The owner has no grant for this app, but it can
                    // still be addressed for them: the handshake and tool
                    // listing go through, and a tool call is answered
                    // here with a result the model can act on. Only a
                    // Pipedream app resolves this way; Macro's own server
                    // has no grant to lack, and a custom server with no
                    // row is refused by its resolver outright.
                    McpResolution::Unconnected(call) => match destination {
                        McpDestination::Connected(slug) => {
                            let name = grant.display_name(slug);
                            let slug = slug.clone();
                            let answer: Answer = Box::new(move |id| {
                                tracing::info!(
                                    app = %slug,
                                    "answering tools/call for an app the owner has not connected"
                                );
                                not_connected_tool_result(&slug, &name, id)
                            });
                            (call, Some(answer))
                        }
                        _ => (call, None),
                    },
                    // The owner connected this server once and the grant
                    // has since died. Same treatment: the handshake is
                    // forwarded bare, in case the server allows it, and a
                    // tool call is answered with how to reconnect.
                    McpResolution::Disconnected { call, name } => {
                        let answer: Answer = Box::new(move |id| {
                            tracing::info!(
                                server = %name,
                                "answering tools/call for a server whose grant has died"
                            );
                            disconnected_tool_result(&name, id)
                        });
                        (call, Some(answer))
                    }
                };
                match answer {
                    None => call,
                    Some(answer) => match Self::answer_unconnected(answer, request).await? {
                        Unconnected::Answered(response) => return Ok(response),
                        Unconnected::Forward(forwarded) => {
                            request = forwarded;
                            call
                        }
                    },
                }
            }
            EgressTarget::GitHubGit { endpoint } => {
                // The repository is the grant's, never the request's: a
                // session works on exactly one, and the sandbox has no way to
                // name another because there is no place in the route to put
                // one.
                let repo = grant.repo.as_ref().ok_or(EgressError::Unauthenticated(
                    "the session has no repository for git access",
                ))?;
                let base = self.tokens.resolve(&grant.owner, repo).await?;

                // The endpoint comes from the allowlist, not from the port, so
                // no credential adapter can widen what the sandbox reaches.
                let url = base
                    .url()
                    .join(&endpoint.path_and_query())
                    .map_err(|error| {
                        EgressError::Internal(rootcause::report!(
                            "git endpoint is not a url: {error}"
                        ))
                    })?;
                base.redirected_to(url)?
            }
        };

        tracing::info!(
            session = %grant.session,
            owner = %grant.owner,
            upstream = %target.name(),
            method = %request.method(),
            "proxying",
        );

        *request.uri_mut() = call.url().as_str().parse::<Uri>().map_err(|error| {
            EgressError::Internal(rootcause::report!("upstream url is not a uri: {error}"))
        })?;

        // Strip first, stamp second, and never the other way round: the
        // sandbox's own `Authorization` is this session's token, and the
        // strip list contains `authorization` precisely so that no request
        // can carry it upstream. Doing it in this order means the header the
        // upstream sees is the one resolved for the owner, whatever the
        // sandbox sent.
        sanitize_request_headers(request.headers_mut());
        if let Some(authorization) = call.authorization().header_value()? {
            request.headers_mut().insert(AUTHORIZATION, authorization);
        }
        // Scoping headers are half of the credential - for Pipedream they are
        // what says whose account the bearer spends - so they get the same
        // treatment: stamped from the resolved call after the strip, never
        // taken from the request.
        for (name, value) in call.scope_headers() {
            request.headers_mut().insert(name.clone(), value.clone());
        }

        // A turn somebody other than the owner prompted spends the owner's
        // access only with their say-so, one tool call at a time. Checked
        // last, so the held request is already addressed and stamped, and an
        // app the owner has not connected was answered above without asking
        // anyone - nothing would run.
        if let (EgressTarget::McpServer(destination), Some(prompter)) =
            (&target, grant.held_prompter())
            && !matches!(destination, McpDestination::Preview)
            && *request.method() == Method::POST
        {
            let (parts, bytes) = read_mcp_body(request).await?;
            let (server_slug, server_name) = match destination {
                // Session-scoped previews spend nobody's access; exempt above.
                McpDestination::Macro | McpDestination::Preview => {
                    (MACRO_SERVER_SLUG.to_owned(), "Macro".to_owned())
                }
                McpDestination::Connected(slug) => {
                    (slug.as_str().to_owned(), grant.display_name(slug))
                }
                // Known only by the hash of its URL here; nothing on the path
                // carries the name the owner gave it.
                McpDestination::Custom(key) => {
                    (format!("custom-{key}"), "custom MCP server".to_owned())
                }
            };
            if let Some(call) = ToolsCall::parse(&bytes)
                .filter(|call| spends_owner_access(&server_slug, &call.name))
            {
                let forward = Arc::clone(&self.forward);
                let sessions = Arc::clone(&self.sessions);
                let token = SessionToken::new(token.as_str());
                let original_turn = grant.prompter.clone();
                let request_id = call.id.clone();
                return self
                    .approvals
                    .hold(HeldCall {
                        session: grant.session,
                        owner: grant.owner.clone(),
                        prompter: prompter.clone(),
                        server_slug,
                        server_name,
                        call,
                        request: ProxyRequest::from_parts(parts, full_body(bytes)),
                        forward: Box::new(move |request| {
                            Box::pin(async move {
                                let current = sessions.authorize(&token).await?;
                                if current.prompter != original_turn {
                                    return Ok(crate::domain::model::tool_result_response(
                                        request_id,
                                        "The original turn ended; this tool did not run.".into(),
                                    ));
                                }
                                let mut response = forward.forward(request).await?;
                                sanitize_response_headers(response.headers_mut());
                                Ok(response)
                            })
                        }),
                    })
                    .await;
            }
            // The agent giving up on a call it is waiting on: the hold has to
            // hear it too, or the owner is asked about a call nobody wants.
            if let Some(request_id) = cancelled_request_id(&bytes) {
                self.approvals.withdraw(grant.session, &request_id).await?;
            }
            request = ProxyRequest::from_parts(parts, full_body(bytes));
        }

        // A GET on an MCP target opens the server's event stream. Those are
        // the requests a client reopens in a loop when the upstream keeps
        // closing them, so its body is watched to its end - the one place the
        // upstream's side of the loop can be seen.
        let event_stream =
            matches!(target, EgressTarget::McpServer(_)) && *request.method() == Method::GET;

        let mut response = self.forward.forward(request).await?;
        sanitize_response_headers(response.headers_mut());

        let status = response.status();
        tracing::Span::current().record("upstream_status", status.as_u16());
        if status.is_success() {
            tracing::debug!(%status, "upstream answered");
        } else {
            tracing::warn!(
                session = %grant.session,
                upstream = %target.name(),
                %status,
                "upstream answered with a failure status"
            );
        }

        if event_stream {
            let identity = StreamIdentity {
                session: grant.session,
                upstream: target.name(),
                status: response.status().as_u16(),
                content_type: response
                    .headers()
                    .get(http::header::CONTENT_TYPE)
                    .and_then(|value| value.to_str().ok())
                    .map(str::to_owned),
            };
            tracing::info!(
                session = %identity.session,
                upstream = %identity.upstream,
                status = identity.status,
                content_type = identity.content_type.as_deref(),
                "MCP event stream opened"
            );
            return Ok(response.map(|body| ObservedBody::new(body, identity).boxed_unsync()));
        }

        Ok(response)
    }
}

/// Logs a failed proxy call in the current span.
///
/// Unlike `#[instrument(err)]`, whose level is fixed, this keeps a closed
/// session at INFO: ending a session revokes its egress, and the session's MCP
/// clients still make a last reconnect or `DELETE` after it closes. Every other
/// refusal or failure stays at ERROR.
fn log_proxy_error(error: &EgressError) {
    match error {
        EgressError::SessionClosed => tracing::info!(error = %error),
        _ => tracing::error!(error = %error),
    }
}

/// What became of a request to a server the owner has no live grant for.
enum Unconnected {
    /// The proxy answered it itself; nothing goes upstream.
    Answered(ProxyResponse),
    /// Forward it, addressed for the owner, so the handshake and tool listing
    /// work. The body has been read and put back.
    Forward(ProxyRequest),
}

/// How a `tools/call` with the given JSON-RPC id is answered in the
/// upstream's place.
type Answer = Box<dyn FnOnce(serde_json::Value) -> ProxyResponse + Send>;

impl<Sessions, Credentials, Tokens, Forward, Approvals>
    EgressServiceImpl<Sessions, Credentials, Tokens, Forward, Approvals>
{
    /// A server the owner has no live grant for: forward everything except
    /// `tools/call`.
    ///
    /// `initialize`, `tools/list`, notifications, the GET event stream and
    /// DELETE all go to the upstream addressed for the owner, so the agent's
    /// client completes its handshake and sees the server's real tools from
    /// the first turn. A `tools/call` is answered here with `answer` - a tool
    /// result that names the server and how to connect it - and the moment
    /// the owner does, the same advertised server resolves as connected and
    /// calls flow through, with nothing re-attached.
    async fn answer_unconnected(
        answer: Answer,
        request: ProxyRequest,
    ) -> Result<Unconnected, EgressError> {
        if *request.method() != Method::POST {
            return Ok(Unconnected::Forward(request));
        }
        let (parts, bytes) = read_mcp_body(request).await?;

        if let Some(call) = peek_json_rpc(&bytes)
            && call.method == TOOLS_CALL_METHOD
        {
            return Ok(Unconnected::Answered(answer(call.id)));
        }

        Ok(Unconnected::Forward(ProxyRequest::from_parts(
            parts,
            full_body(bytes),
        )))
    }
}

/// Read an MCP request body the proxy has to look inside, up to
/// [`MAX_MCP_REQUEST_BYTES`].
async fn read_mcp_body(
    request: ProxyRequest,
) -> Result<(http::request::Parts, bytes::Bytes), EgressError> {
    let (parts, mut body) = request.into_parts();
    let mut bytes = Vec::new();
    while let Some(frame) = body.frame().await {
        let frame = frame.map_err(|error| {
            EgressError::Internal(rootcause::report!(
                "could not read an MCP request body: {error}"
            ))
        })?;
        if let Ok(data) = frame.into_data() {
            if bytes.len() + data.len() > MAX_MCP_REQUEST_BYTES {
                return Err(EgressError::RequestTooLarge);
            }
            bytes.extend_from_slice(&data);
        }
    }
    Ok((parts, bytes::Bytes::from(bytes)))
}

fn full_body(bytes: bytes::Bytes) -> crate::domain::model::ProxyBody {
    Full::new(bytes)
        .map_err(|never| match never {})
        .boxed_unsync()
}

/// The request id a `notifications/cancelled` names.
fn cancelled_request_id(body: &[u8]) -> Option<serde_json::Value> {
    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
    if value.get("method")?.as_str()? != "notifications/cancelled" {
        return None;
    }
    value
        .get("params")?
        .get("requestId")
        .filter(|id| !id.is_null())
        .cloned()
}

mod actor;