mirror of
https://github.com/TECHNOFAB11/jwt-authorizer.git
synced 2026-02-02 09:25:09 +01:00
Revert "chore: remove tonic temporarily (waiting hyperium/tonic/#1595)"
This reverts commit 5f71827bf2.
This commit is contained in:
parent
d87b7ef909
commit
31c625b499
5 changed files with 956 additions and 322 deletions
1010
Cargo.lock
generated
1010
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -6,8 +6,6 @@ JWT authorizer Layer for Axum.
|
||||||
[](https://crates.io/crates/jwt-authorizer)
|
[](https://crates.io/crates/jwt-authorizer)
|
||||||
[](https://docs.rs/jwt-authorizer)
|
[](https://docs.rs/jwt-authorizer)
|
||||||
|
|
||||||
> **Tonic support is temporarily removed** (waiting upgrade to hyper 1 and axum 0.7 hyperium/tonic/#1584)
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- JWT token verification (Bearer)
|
- JWT token verification (Bearer)
|
||||||
|
|
@ -21,7 +19,7 @@ JWT authorizer Layer for Axum.
|
||||||
- into custom deserializable structs or into `RegisteredClaims` (default)
|
- into custom deserializable structs or into `RegisteredClaims` (default)
|
||||||
- Claims checker
|
- Claims checker
|
||||||
- Tracing support (error logging)
|
- Tracing support (error logging)
|
||||||
- ~~*tonic* support~~
|
- *tonic* support
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -28,12 +28,14 @@ tower-layer = "0.3"
|
||||||
tower-service = "0.3"
|
tower-service = "0.3"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
tonic = { version = "0.10", optional = true }
|
||||||
time = { version = "0.3", optional = true }
|
time = { version = "0.3", optional = true }
|
||||||
http-body-util = "0.1.1"
|
http-body-util = "0.1.1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
hyper = { version = "1.3.1", features = ["full"] }
|
hyper = { version = "1.3.1", features = ["full"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
|
prost = "0.12"
|
||||||
tower = { version = "0.4.13", features = ["util", "buffer"] }
|
tower = { version = "0.4.13", features = ["util", "buffer"] }
|
||||||
wiremock = "0.6.0"
|
wiremock = "0.6.0"
|
||||||
|
|
||||||
|
|
@ -49,3 +51,7 @@ rustls-tls-webpki-roots = ["reqwest/rustls-tls-webpki-roots"]
|
||||||
rustls-tls-native-roots = ["reqwest/rustls-tls-native-roots"]
|
rustls-tls-native-roots = ["reqwest/rustls-tls-native-roots"]
|
||||||
time = ["dep:time"]
|
time = ["dep:time"]
|
||||||
chrono = ["dep:chrono"]
|
chrono = ["dep:chrono"]
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "tonic"
|
||||||
|
required-features = ["tonic"]
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,55 @@ fn response_500() -> Response<Body> {
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "tonic")]
|
||||||
|
impl From<AuthError> for Response<tonic::body::BoxBody> {
|
||||||
|
fn from(e: AuthError) -> Self {
|
||||||
|
match e {
|
||||||
|
AuthError::JwksRefreshError(err) => {
|
||||||
|
tracing::error!("AuthErrors::JwksRefreshError: {}", err);
|
||||||
|
tonic::Status::internal("")
|
||||||
|
}
|
||||||
|
AuthError::InvalidKey(err) => {
|
||||||
|
tracing::error!("AuthErrors::InvalidKey: {}", err);
|
||||||
|
tonic::Status::internal("")
|
||||||
|
}
|
||||||
|
AuthError::JwksSerialisationError(err) => {
|
||||||
|
tracing::error!("AuthErrors::JwksSerialisationError: {}", err);
|
||||||
|
tonic::Status::internal("")
|
||||||
|
}
|
||||||
|
AuthError::InvalidKeyAlg(err) => {
|
||||||
|
debug!("AuthErrors::InvalidKeyAlg: {:?}", err);
|
||||||
|
tonic::Status::unauthenticated("error=\"invalid_token\", error_description=\"invalid key algorithm\"")
|
||||||
|
}
|
||||||
|
AuthError::InvalidKid(err) => {
|
||||||
|
debug!("AuthErrors::InvalidKid: {}", err);
|
||||||
|
tonic::Status::unauthenticated("error=\"invalid_token\", error_description=\"invalid kid\"")
|
||||||
|
}
|
||||||
|
AuthError::InvalidToken(err) => {
|
||||||
|
debug!("AuthErrors::InvalidToken: {}", err);
|
||||||
|
tonic::Status::unauthenticated("error=\"invalid_token\"")
|
||||||
|
}
|
||||||
|
AuthError::MissingToken() => {
|
||||||
|
debug!("AuthErrors::MissingToken");
|
||||||
|
tonic::Status::unauthenticated("")
|
||||||
|
}
|
||||||
|
AuthError::InvalidClaims() => {
|
||||||
|
debug!("AuthErrors::InvalidClaims");
|
||||||
|
tonic::Status::unauthenticated("error=\"insufficient_scope\"")
|
||||||
|
}
|
||||||
|
AuthError::NoAuthorizer() => {
|
||||||
|
debug!("AuthErrors::NoAuthorizer");
|
||||||
|
tonic::Status::unauthenticated("error=\"invalid_token\"")
|
||||||
|
}
|
||||||
|
AuthError::NoAuthorizerLayer() => {
|
||||||
|
debug!("AuthErrors::NoAuthorizerLayer");
|
||||||
|
tonic::Status::unauthenticated("error=\"no_authorizer_layer\"")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.to_http()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<AuthError> for Response {
|
impl From<AuthError> for Response {
|
||||||
fn from(e: AuthError) -> Self {
|
fn from(e: AuthError) -> Self {
|
||||||
e.into_response()
|
e.into_response()
|
||||||
|
|
|
||||||
209
jwt-authorizer/tests/tonic.rs
Normal file
209
jwt-authorizer/tests/tonic.rs
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
use std::{sync::Once, task::Poll};
|
||||||
|
|
||||||
|
use axum::body::HttpBody;
|
||||||
|
use futures_core::future::BoxFuture;
|
||||||
|
use http::header::AUTHORIZATION;
|
||||||
|
use jwt_authorizer::{layer::AuthorizationService, IntoLayer, JwtAuthorizer, Validation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tonic::{server::UnaryService, transport::NamedService, IntoRequest, Status};
|
||||||
|
use tower::{buffer::Buffer, Service};
|
||||||
|
|
||||||
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
|
use crate::common::{JWT_RSA1_OK, JWT_RSA2_OK};
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
/// Static variable to ensure that logging is only initialized once.
|
||||||
|
pub static INITIALIZED: Once = Once::new();
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
struct User {
|
||||||
|
sub: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(prost::Message)]
|
||||||
|
struct HelloMessage {
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
struct SayHelloMethod {}
|
||||||
|
impl UnaryService<HelloMessage> for SayHelloMethod {
|
||||||
|
type Response = HelloMessage;
|
||||||
|
type Future = BoxFuture<'static, Result<tonic::Response<Self::Response>, Status>>;
|
||||||
|
|
||||||
|
fn call(&mut self, request: tonic::Request<HelloMessage>) -> Self::Future {
|
||||||
|
Box::pin(async move {
|
||||||
|
let hi = request.into_inner();
|
||||||
|
let reply = HelloMessage {
|
||||||
|
message: format!("Hello, {}", hi.message),
|
||||||
|
};
|
||||||
|
Ok(tonic::Response::new(reply))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
struct GreeterServer {
|
||||||
|
expected_sub: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service<http::Request<tonic::transport::Body>> for GreeterServer {
|
||||||
|
type Response = http::Response<tonic::body::BoxBody>;
|
||||||
|
type Error = std::convert::Infallible;
|
||||||
|
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: http::Request<tonic::transport::Body>) -> Self::Future {
|
||||||
|
let token = req.extensions().get::<jsonwebtoken::TokenData<User>>().unwrap();
|
||||||
|
assert_eq!(token.claims.sub, self.expected_sub);
|
||||||
|
match req.uri().path() {
|
||||||
|
"/hello/SayHello" => Box::pin(async move {
|
||||||
|
let mut grpc = tonic::server::Grpc::new(tonic::codec::ProstCodec::default());
|
||||||
|
Ok(grpc.unary(SayHelloMethod::default(), req).await)
|
||||||
|
}),
|
||||||
|
p => {
|
||||||
|
let p = p.to_string();
|
||||||
|
Box::pin(async move { Ok(Status::unimplemented(p).to_http()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NamedService for GreeterServer {
|
||||||
|
const NAME: &'static str = "hello";
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn app(
|
||||||
|
jwt_auth: JwtAuthorizer<User>,
|
||||||
|
expected_sub: String,
|
||||||
|
) -> AuthorizationService<Buffer<tonic::transport::server::Routes, http::Request<tonic::transport::Body>>, User> {
|
||||||
|
let layer = jwt_auth.build().await.unwrap().into_layer();
|
||||||
|
tonic::transport::Server::builder()
|
||||||
|
.layer(layer)
|
||||||
|
.layer(tower::buffer::BufferLayer::new(1))
|
||||||
|
.add_service(GreeterServer { expected_sub })
|
||||||
|
.into_service()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_test() {
|
||||||
|
INITIALIZED.call_once(|| {
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(tracing_subscriber::EnvFilter::new(
|
||||||
|
std::env::var("RUST_LOG").unwrap_or_else(|_| "info,jwt-authorizer=debug,tower_http=debug".into()),
|
||||||
|
))
|
||||||
|
.with(tracing_subscriber::fmt::layer())
|
||||||
|
.init();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// The grpc client produces a http request with a tonic boxbody that the transport is meant to sent out, while the server side
|
||||||
|
// expects to receive a http request with a hyper body.. This simple wrapper converts from one to
|
||||||
|
// the other.
|
||||||
|
struct GrpcWrapper<S>
|
||||||
|
where
|
||||||
|
S: Service<http::Request<axum::body::Body>> + Clone,
|
||||||
|
{
|
||||||
|
inner: S,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Service<http::Request<tonic::body::BoxBody>> for GrpcWrapper<S>
|
||||||
|
where
|
||||||
|
S: Service<http::Request<axum::body::Body>> + Clone + Send + 'static,
|
||||||
|
S::Future: Send,
|
||||||
|
{
|
||||||
|
type Response = S::Response;
|
||||||
|
type Error = S::Error;
|
||||||
|
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||||
|
self.inner.poll_ready(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: http::Request<tonic::body::BoxBody>) -> Self::Future {
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
// take the service that was ready
|
||||||
|
let mut inner = std::mem::replace(&mut self.inner, inner);
|
||||||
|
Box::pin(async move {
|
||||||
|
let (parts, mut body) = req.into_parts();
|
||||||
|
let mut data = Vec::new();
|
||||||
|
while let Some(d) = body.data().await {
|
||||||
|
let d = d.unwrap();
|
||||||
|
data.extend_from_slice(&d)
|
||||||
|
}
|
||||||
|
inner
|
||||||
|
.call(http::Request::from_parts(parts, axum::body::Body::from(data)))
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn make_protected_request<S: Clone>(
|
||||||
|
app: AuthorizationService<S, User>,
|
||||||
|
bearer: Option<&str>,
|
||||||
|
message: &str,
|
||||||
|
) -> Result<tonic::Response<HelloMessage>, Status>
|
||||||
|
where
|
||||||
|
S: Service<
|
||||||
|
http::Request<tonic::transport::Body>,
|
||||||
|
Response = http::Response<tonic::body::BoxBody>,
|
||||||
|
Error = tower::BoxError,
|
||||||
|
> + Send
|
||||||
|
+ 'static,
|
||||||
|
S::Future: Send,
|
||||||
|
{
|
||||||
|
let mut grpc = tonic::client::Grpc::new(GrpcWrapper { inner: app });
|
||||||
|
|
||||||
|
let mut request = HelloMessage {
|
||||||
|
message: message.to_string(),
|
||||||
|
}
|
||||||
|
.into_request();
|
||||||
|
|
||||||
|
if let Some(bearer) = bearer {
|
||||||
|
let headers = request.metadata_mut();
|
||||||
|
headers.insert(AUTHORIZATION.as_str(), format!("Bearer {bearer}").parse().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
grpc.ready().await.unwrap();
|
||||||
|
grpc.unary(
|
||||||
|
request,
|
||||||
|
http::uri::PathAndQuery::from_static("/hello/SayHello"),
|
||||||
|
tonic::codec::ProstCodec::default(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn successfull_auth() {
|
||||||
|
init_test();
|
||||||
|
let auth: JwtAuthorizer<User> =
|
||||||
|
JwtAuthorizer::from_rsa_pem("../config/rsa-public1.pem").validation(Validation::new().aud(&["aud1"]));
|
||||||
|
let app = app(auth, "b@b.com".to_string()).await;
|
||||||
|
let r = make_protected_request(app.clone(), Some(JWT_RSA1_OK), "world").await.unwrap();
|
||||||
|
assert_eq!(r.get_ref().message, "Hello, world");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn wrong_token() {
|
||||||
|
init_test();
|
||||||
|
let auth: JwtAuthorizer<User> = JwtAuthorizer::from_rsa_pem("../config/rsa-public1.pem");
|
||||||
|
let app = app(auth, "b@b.com".to_string()).await;
|
||||||
|
let status = make_protected_request(app.clone(), Some(JWT_RSA2_OK), "world")
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert_eq!(status.code(), tonic::Code::Unauthenticated);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_token() {
|
||||||
|
init_test();
|
||||||
|
let auth: JwtAuthorizer<User> = JwtAuthorizer::from_rsa_pem("../config/rsa-public1.pem");
|
||||||
|
let app = app(auth, "b@b.com".to_string()).await;
|
||||||
|
let status = make_protected_request(app.clone(), None, "world").await.unwrap_err();
|
||||||
|
assert_eq!(status.code(), tonic::Code::Unauthenticated);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue