Issue #44: implement Rust client session values errors and CLI
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
use std::fmt;
|
||||
|
||||
use tonic::metadata::MetadataValue;
|
||||
use tonic::service::Interceptor;
|
||||
use tonic::{Request, Status};
|
||||
|
||||
/// API key wrapper that avoids exposing raw credentials in formatted output.
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
pub struct ApiKey(String);
|
||||
@@ -28,3 +32,56 @@ impl fmt::Display for ApiKey {
|
||||
formatter.write_str("<redacted>")
|
||||
}
|
||||
}
|
||||
|
||||
/// `tonic` interceptor that attaches gateway API key metadata.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct AuthInterceptor {
|
||||
api_key: Option<ApiKey>,
|
||||
}
|
||||
|
||||
impl AuthInterceptor {
|
||||
pub fn new(api_key: Option<ApiKey>) -> Self {
|
||||
Self { api_key }
|
||||
}
|
||||
}
|
||||
|
||||
impl Interceptor for AuthInterceptor {
|
||||
fn call(&mut self, mut request: Request<()>) -> Result<Request<()>, Status> {
|
||||
if let Some(api_key) = &self.api_key {
|
||||
let header_value = format!("Bearer {}", api_key.expose_secret())
|
||||
.parse::<MetadataValue<_>>()
|
||||
.map_err(|_| Status::unauthenticated("invalid API key metadata"))?;
|
||||
request.metadata_mut().insert("authorization", header_value);
|
||||
}
|
||||
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tonic::service::Interceptor;
|
||||
use tonic::Request;
|
||||
|
||||
use super::{ApiKey, AuthInterceptor};
|
||||
|
||||
#[test]
|
||||
fn api_key_debug_is_redacted() {
|
||||
let key = ApiKey::new("mxgw_visible_secret");
|
||||
|
||||
assert_eq!(format!("{key:?}"), "ApiKey(\"<redacted>\")");
|
||||
assert!(!format!("{key:?}").contains("visible_secret"));
|
||||
assert_eq!(key.to_string(), "<redacted>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interceptor_attaches_bearer_metadata() {
|
||||
let mut interceptor = AuthInterceptor::new(Some(ApiKey::new("mxgw_fixture_secret")));
|
||||
let request = interceptor.call(Request::new(())).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
request.metadata().get("authorization").unwrap(),
|
||||
"Bearer mxgw_fixture_secret"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user