Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(transport-http): JWT auth layer #1314

Merged
merged 20 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion crates/transport-http/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ http-body-util = { workspace = true, optional = true }
hyper = { workspace = true, default-features = false, optional = true }
hyper-util = { workspace = true, features = ["full"], optional = true }

# auth layer
alloy-rpc-types-engine = { workspace = true, optional = true }
jsonwebtoken = { version = "9.3.0", optional = true }

[features]
default = ["reqwest", "reqwest-default-tls"]
default = ["reqwest", "reqwest-default-tls", "hyper"]
reqwest = [
"dep:reqwest",
"dep:alloy-json-rpc",
Expand All @@ -51,6 +55,10 @@ hyper = [
"dep:serde_json",
"dep:tower",
"dep:tracing",
"dep:alloy-rpc-types-engine",
"alloy-rpc-types-engine/jwt",
"alloy-rpc-types-engine/serde",
"dep:jsonwebtoken",
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
]
reqwest-default-tls = ["reqwest?/default-tls"]
reqwest-native-tls = ["reqwest?/native-tls"]
Expand Down
7 changes: 5 additions & 2 deletions crates/transport-http/src/hyper_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,15 @@ impl<B, S> HyperClient<B, S> {
}
}

impl<B, S> Http<HyperClient<B, S>>
impl<B, S, ResBody> Http<HyperClient<B, S>>
where
S: Service<Request<B>, Response = HyperResponse> + Clone + Send + Sync + 'static,
S: Service<Request<B>, Response = Response<ResBody>> + Clone + Send + Sync + 'static,
S::Future: Send,
S::Error: std::error::Error + Send + Sync + 'static,
B: From<Vec<u8>> + Send + 'static + Clone,
ResBody: BodyExt + Send + 'static,
ResBody::Error: std::error::Error + Send + Sync + 'static,
ResBody::Data: Send,
{
/// Make a request to the server using the given service.
fn request_hyper(&self, req: RequestPacket) -> TransportFut<'static> {
Expand Down
125 changes: 125 additions & 0 deletions crates/transport-http/src/layers/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use crate::hyper::{
header::{HeaderMap, AUTHORIZATION},
Request, Response,
};
use alloy_rpc_types_engine::{Claims, JwtSecret};
use alloy_transport::{TransportError, TransportErrorKind};
use hyper::header::HeaderValue;
use std::{
future::Future,
pin::Pin,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tower::{Layer, Service};

/// The [`AuthLayer`] is a that validates whether the bearer token in the request is valid or not.
/// If invalid, it generates a valid token from the provided [`JwtSecret`] and inserts it into the
/// request.
///
/// This layer also inserts the [`AUTHORIZATION`] header into the request with a valid token if its
/// not already in the request.
#[derive(Clone, Debug)]
pub struct AuthLayer {
secret: JwtSecret,
}

impl AuthLayer {
/// Create a new [`AuthLayer`].
pub const fn new(secret: JwtSecret) -> Self {
Self { secret }
}
}

impl<S> Layer<S> for AuthLayer {
type Service = AuthService<S>;

fn layer(&self, inner: S) -> Self::Service {
AuthService::new(inner, self.secret)
}
}

/// A service that checks the jwt token in a request is valid. If invalid, it refreshes the token
/// using the provided [`JwtSecret`] and inserts it into the request.
#[derive(Clone, Debug)]
pub struct AuthService<S> {
inner: S,
secret: JwtSecret,
}

impl<S> AuthService<S> {
/// Create a new [`AuthService`] with the given inner service.
pub const fn new(inner: S, secret: JwtSecret) -> Self {
Self { inner, secret }
}
}

impl<S, B, ResBody> Service<Request<B>> for AuthService<S>
where
S: Service<hyper::Request<B>, Response = Response<ResBody>, Error = TransportError>
+ Clone
+ Send
+ Sync
+ 'static,
S::Future: Send,
S::Error: std::error::Error + Send + Sync + 'static,
B: From<Vec<u8>> + Send + 'static + Clone + Sync,
ResBody: hyper::body::Body + Send + 'static,
ResBody::Error: std::error::Error + Send + Sync + 'static,
ResBody::Data: Send,
{
type Response = Response<ResBody>;
type Error = TransportError;
type Future =
Pin<Box<dyn Future<Output = Result<Response<ResBody>, TransportError>> + Send + 'static>>;

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

fn call(&mut self, req: Request<B>) -> Self::Future {
let headers = req.headers();

match get_bearer_token(headers).and_then(|token| self.secret.validate(&token).ok()) {
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved
Some(_) => Box::pin(self.inner.call(req)),
None => {
// Generate a fresh token from the secret and insert it into the request.
match create_token_from_secret(&self.secret) {
Ok(token) => {
let mut req = req.clone();

req.headers_mut()
.insert(AUTHORIZATION, HeaderValue::from_str(&token).unwrap());
Box::pin(self.inner.call(req))
}
Err(e) => {
let e = TransportErrorKind::custom(e);

Box::pin(async move { Err(e) })
}
}
}
}
}
}

fn get_bearer_token(headers: &HeaderMap) -> Option<String> {
let header = headers.get(AUTHORIZATION)?;
let auth: &str = header.to_str().ok()?;
let prefix = "Bearer ";
let index = auth.find(prefix)?;
let token: &str = &auth[index + prefix.len()..];
Some(token.into())
}
yash-atreya marked this conversation as resolved.
Show resolved Hide resolved

fn create_token_from_secret(secret: &JwtSecret) -> Result<String, jsonwebtoken::errors::Error> {
let token = secret.encode(&Claims {
iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + Duration::from_secs(60))
.as_secs(),
exp: None,
})?;

Ok(format!("Bearer {}", token))
}
5 changes: 5 additions & 0 deletions crates/transport-http/src/layers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//! tower http like layer implementations that work over the http::Request type.
#![cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]

mod auth;
pub use auth::{AuthLayer, AuthService};
5 changes: 5 additions & 0 deletions crates/transport-http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ pub use hyper;
#[cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]
pub use hyper_util;

#[cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]
mod layers;
#[cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]
pub use layers::{AuthLayer, AuthService};

#[cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]
mod hyper_transport;
#[cfg(all(not(target_arch = "wasm32"), feature = "hyper"))]
Expand Down