turul-a2a 0.2.7

A2A Protocol v1.0 server framework
Documentation
//! Tower layer that validates `a2a-version` metadata and runs the shared
//! `MiddlewareStack` against a tonic server.
//!
//! Before authentication, every `A2AService` call must carry an
//! `a2a-version` the server speaks (spec Section 3.6.2); a missing, empty
//! or unsupported value is rejected with `FAILED_PRECONDITION` carrying
//! `VERSION_NOT_SUPPORTED`. Co-hosted services such as health and
//! reflection are not checked. This is the gRPC counterpart of the HTTP
//! transport-compliance layer.
//!
//! For authentication this is a transport adapter only — the *business logic*
//! lives in `crate::middleware::stack::MiddlewareStack` and is shared
//! verbatim with the HTTP path. The two transports differ only in:
//!   * request body type (`tonic::body::Body` vs. `axum::body::Body`)
//!   * error encoding (gRPC status codes with `ErrorInfo` vs. HTTP JSON
//!     error body)
//!
//! On auth success the layer injects a [`RequestContext`] into the HTTP
//! request's extensions; tonic surfaces those same extensions to the
//! service impl via `tonic::Request::extensions()`, so the gRPC adapter
//! reads the authenticated owner through `RequestContext::identity` —
//! exactly like the HTTP handlers do.
//!
//! On auth failure the layer produces a gRPC-formatted response carrying
//! the correct `tonic::Status` code. No `A2aError`, no JSON error body —
//! transport-level auth failures bypass the A2A error model.

use std::sync::Arc;
use std::task::{Context, Poll};

use http::{Request, Response};
use tonic::body::Body;
use tower::{Layer, Service};

use crate::middleware::context::RequestContext;
use crate::middleware::error::MiddlewareError;
use crate::middleware::stack::MiddlewareStack;

/// Tower layer that wraps a tonic service with the shared middleware stack.
#[derive(Clone)]
pub struct GrpcAuthLayer {
    stack: Arc<MiddlewareStack>,
}

impl GrpcAuthLayer {
    pub fn new(stack: Arc<MiddlewareStack>) -> Self {
        Self { stack }
    }
}

impl<S> Layer<S> for GrpcAuthLayer {
    type Service = GrpcAuthService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        GrpcAuthService {
            inner,
            stack: self.stack.clone(),
        }
    }
}

/// Tower service produced by [`GrpcAuthLayer`].
#[derive(Clone)]
pub struct GrpcAuthService<S> {
    inner: S,
    stack: Arc<MiddlewareStack>,
}

impl<S> Service<Request<Body>> for GrpcAuthService<S>
where
    S: Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
    S::Future: Send,
{
    type Response = Response<Body>;
    type Error = S::Error;
    type Future = std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
    >;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<Body>) -> Self::Future {
        let stack = self.stack.clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            if let Err(err) = check_a2a_version(&req) {
                return Ok(crate::grpc::error::a2a_to_status(err).into_http());
            }

            let headers = req.headers().clone();

            // Matches the HTTP layer's "no middleware configured" short
            // circuit — install an anonymous RequestContext so handlers
            // can read `identity.owner()` without conditional access.
            if stack.is_empty() {
                req.extensions_mut()
                    .insert(RequestContext::from_headers(headers));
                return inner.call(req).await;
            }

            let mut ctx = RequestContext::from_headers(headers);
            match stack.before_request(&mut ctx).await {
                Ok(()) => {
                    req.extensions_mut().insert(ctx);
                    inner.call(req).await
                }
                Err(err) => Ok(middleware_error_to_grpc_response(&err)),
            }
        })
    }
}

/// Validate the `a2a-version` metadata on A2AService calls, before auth —
/// the same order as the HTTP transport-compliance layer. Spec Section
/// 10.2: servers "SHOULD validate required service parameters (e.g.,
/// `A2A-Version`) from metadata"; Section 3.6.2 makes an unsupported
/// version a `VersionNotSupportedError`. Other services co-hosted on the
/// same server (health, reflection) are not A2A calls and are not checked.
fn check_a2a_version<B>(req: &Request<B>) -> Result<(), crate::error::A2aError> {
    use tonic::server::NamedService;
    let service =
        <turul_a2a_proto::grpc::A2aServiceServer<crate::grpc::GrpcService> as NamedService>::NAME;
    let is_a2a_call = req
        .uri()
        .path()
        .strip_prefix('/')
        .and_then(|p| p.strip_prefix(service))
        .is_some_and(|rest| rest.starts_with('/'));
    if !is_a2a_call {
        return Ok(());
    }
    let requested = req
        .headers()
        .get(turul_a2a_types::wire::protocol::VERSION_PARAM)
        .map(|v| v.to_str().unwrap_or_default());
    // gRPC never serves the 0.3 protocol, whatever features are enabled.
    crate::middleware::transport::check_version(requested, false)
}

/// Map a `MiddlewareError` to a gRPC-formatted HTTP response.
///
/// Uses `tonic::Status::into_http()` so the response carries proper
/// gRPC trailers (`grpc-status`, `grpc-message`) — `tonic::Status` is
/// the canonical encoding for transport-level auth failure.
///
/// Wire surface parity with the HTTP path: the `grpc-message` is the same
/// human-readable [`MiddlewareError::message`], and `Status.details` carry
/// the stable kind as an `ErrorInfo` reason in the turul auth domain.
/// `Internal(msg)` deliberately collapses to the fixed `INTERNAL_ERROR`
/// reason — the inner String payload is never exposed on the wire.
///
/// Status-code mapping:
/// - `Unauthenticated` / `HttpChallenge(*)` → `UNAUTHENTICATED`
/// - `HttpChallenge(InsufficientScope)` → `PERMISSION_DENIED`
///   (HTTP returns 403 here per RFC 6750 §3; gRPC has no 403 equivalent
///   under `UNAUTHENTICATED`, so the closest match is `PERMISSION_DENIED`
///   — the same code used for `Forbidden(*)`.)
/// - `Forbidden(*)` → `PERMISSION_DENIED`
/// - `Internal(_)` → `INTERNAL`
fn middleware_error_to_grpc_response(err: &MiddlewareError) -> Response<Body> {
    use tonic::Code;
    use tonic_types::{ErrorDetails, StatusExt};
    let code = match err {
        MiddlewareError::HttpChallenge(crate::middleware::AuthFailureKind::InsufficientScope) => {
            Code::PermissionDenied
        }
        MiddlewareError::Unauthenticated(_) | MiddlewareError::HttpChallenge(_) => {
            Code::Unauthenticated
        }
        MiddlewareError::Forbidden(_) => Code::PermissionDenied,
        MiddlewareError::Internal(_) => Code::Internal,
    };
    let details = ErrorDetails::with_error_info(
        err.reason(),
        turul_a2a_types::wire::errors::AUTH_ERROR_DOMAIN,
        [],
    );
    tonic::Status::with_error_details(code, err.message(), details).into_http()
}