use tonic::service::Interceptor;
use tonic::Status;
use super::{GarrisonGrpcInterceptor, GarrisonGrpcToken, GarrisonGrpcTokenValidator};
pub const MAX_TOKEN_LEN: usize = 4096;
impl GarrisonGrpcInterceptor {
pub fn new() -> Self {
Self { validator: None }
}
pub fn with_token_validator(validator: std::sync::Arc<dyn GarrisonGrpcTokenValidator>) -> Self {
Self {
validator: Some(validator),
}
}
#[allow(clippy::result_large_err)]
pub fn extract_token(metadata: &tonic::metadata::MetadataMap) -> Result<String, Status> {
let auth_header = metadata
.get("authorization")
.ok_or_else(|| Status::unauthenticated("missing Authorization metadata"))?
.to_str()
.map_err(|_| Status::unauthenticated("Authorization metadata is not valid UTF-8"))?;
Self::parse_bearer(auth_header)
}
#[allow(clippy::result_large_err)]
pub fn extract_token_from_headers(headers: &http::HeaderMap) -> Result<String, Status> {
let auth_header = headers
.get("authorization")
.ok_or_else(|| Status::unauthenticated("missing Authorization metadata"))?
.to_str()
.map_err(|_| Status::unauthenticated("Authorization metadata is not valid UTF-8"))?;
Self::parse_bearer(auth_header)
}
#[allow(clippy::result_large_err)]
fn parse_bearer(auth_header: &str) -> Result<String, Status> {
let token = auth_header
.get(..7)
.filter(|prefix| prefix.eq_ignore_ascii_case("Bearer "))
.map(|_| &auth_header[7..])
.ok_or_else(|| Status::unauthenticated("Authorization scheme must be Bearer"))?;
if token.is_empty() {
return Err(Status::unauthenticated("empty token after Bearer prefix"));
}
if token.len() > MAX_TOKEN_LEN {
return Err(Status::unauthenticated("token exceeds maximum length"));
}
Ok(token.to_string())
}
}
impl Interceptor for GarrisonGrpcInterceptor {
#[allow(clippy::result_large_err)]
fn call(&mut self, mut request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
let token = Self::extract_token(request.metadata())?;
request
.extensions_mut()
.insert(GarrisonGrpcToken(token.clone()));
if let Some(validator) = &self.validator {
validator.validate(&token)?;
} else {
tracing::debug!(
"garrison grpc interceptor: no token validator configured; \
only Bearer format is enforced here"
);
}
Ok(request)
}
}