use crate::stp::{with_current_token, with_login_id_scope, GarrisonUtil};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tonic::Status;
use tower::{Layer, Service};
#[derive(Debug, Clone, Copy, Default)]
pub struct GarrisonGrpcAuthLayer;
impl<S> Layer<S> for GarrisonGrpcAuthLayer {
type Service = GarrisonGrpcAuthService<S>;
fn layer(&self, inner: S) -> Self::Service {
GarrisonGrpcAuthService { inner }
}
}
#[derive(Debug, Clone)]
pub struct GarrisonGrpcAuthService<S> {
inner: S,
}
impl<S> Service<http::Request<tonic::body::Body>> for GarrisonGrpcAuthService<S>
where
S: Service<http::Request<tonic::body::Body>, Response = http::Response<tonic::body::Body>>
+ Send
+ 'static,
S::Future: Send + 'static,
{
type Response = http::Response<tonic::body::Body>;
type Error = S::Error;
type Future = Pin<Box<dyn 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, request: http::Request<tonic::body::Body>) -> Self::Future {
let token =
super::GarrisonGrpcInterceptor::extract_token_from_headers(request.headers()).ok();
let Some(token) = token else {
return Box::pin(async {
Ok(Status::unauthenticated(
"garrison-auth-layer::missing-or-malformed-authorization",
)
.into_http())
});
};
let response_fut = self.inner.call(request);
Box::pin(with_login_id_scope(with_current_token(token, async move {
match GarrisonUtil::check_login().await {
Ok(true) => response_fut.await,
_ => Ok(
Status::unauthenticated("garrison-auth-layer::invalid-or-expired-token")
.into_http(),
),
}
})))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dao::GarrisonDao;
use crate::manager::GarrisonManager;
use crate::stp::mock::{MockDao, MockInterface};
use http::Request;
use serial_test::serial;
use std::sync::Arc;
use tower::{Service, ServiceExt};
async fn init_global_manager() {
GarrisonManager::reset_for_test();
let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
let mut config = crate::config::GarrisonConfig::default_config();
config.throw_on_not_login = false;
let interface: Arc<dyn crate::stp::GarrisonInterface> = Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(Arc::new(config))
.interface(interface)
.build()
.await
.unwrap();
}
#[derive(Clone)]
struct EchoLoginService;
impl Service<http::Request<tonic::body::Body>> for EchoLoginService {
type Response = http::Response<tonic::body::Body>;
type Error = std::convert::Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: http::Request<tonic::body::Body>) -> Self::Future {
Box::pin(async {
let logged_in = GarrisonUtil::check_login().await.unwrap_or(false);
let mut resp = http::Response::new(tonic::body::Body::empty());
resp.extensions_mut().insert(logged_in);
Ok(resp)
})
}
}
fn grpc_request(token: Option<&str>) -> http::Request<tonic::body::Body> {
let mut builder = Request::builder()
.method(http::Method::POST)
.uri("/svc/method");
if let Some(t) = token {
builder = builder.header("authorization", format!("Bearer {t}"));
}
builder.body(tonic::body::Body::empty()).unwrap()
}
async fn assert_unauthenticated(resp: http::Response<tonic::body::Body>) {
assert_eq!(
resp.headers()
.get(tonic::Status::GRPC_STATUS)
.and_then(|v| v.to_str().ok()),
Some("16"),
"应返回 gRPC UNAUTHENTICATED(16),实际 headers: {:?}",
resp.headers()
);
}
#[tokio::test]
#[serial]
async fn auth_layer_missing_token_rejected() {
init_global_manager().await;
let mut svc = GarrisonGrpcAuthLayer.layer(EchoLoginService);
let resp = svc
.ready()
.await
.unwrap()
.call(grpc_request(None))
.await
.unwrap();
assert_unauthenticated(resp).await;
}
#[tokio::test]
#[serial]
async fn auth_layer_forged_token_rejected() {
init_global_manager().await;
let mut svc = GarrisonGrpcAuthLayer.layer(EchoLoginService);
let resp = svc
.ready()
.await
.unwrap()
.call(grpc_request(Some("forged-token-not-in-session")))
.await
.unwrap();
assert_unauthenticated(resp).await;
}
#[tokio::test]
#[serial]
async fn auth_layer_valid_token_passes_and_propagates_token() {
init_global_manager().await;
let token = GarrisonUtil::login_simple("1001").await.unwrap();
let mut svc = GarrisonGrpcAuthLayer.layer(EchoLoginService);
let resp = svc
.ready()
.await
.unwrap()
.call(grpc_request(Some(&token)))
.await
.unwrap();
assert!(
resp.extensions().get::<bool>().copied().unwrap_or(false),
"handler 应在 with_current_token 作用域内看到已登录 token"
);
}
}