webgates-tonic 1.0.0

Tonic server-side transport adapter for webgates authentication and authorization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Bearer-token gate for tonic services that verifies JWTs with a remote JWKS verifier.
//!
//! [`RemoteJwksBearerGate`] wraps a [`RemoteJwksVerifier`] into a tonic-compatible
//! tower [`Layer`] that authenticates gRPC requests via the `Authorization: Bearer`
//! metadata header and enforces an [`AccessPolicy`].
//!
//! # Examples
//!
//! ```rust,no_run
//! use std::sync::Arc;
//! use webgates::authz::access_policy::AccessPolicy;
//! use webgates::roles::Role;
//! use webgates::groups::Group;
//! use webgates::accounts::Account;
//! use webgates_codecs::jwt::{JwtClaims, remote_verifier::{RemoteJwksVerifier, RemoteJwksVerifierConfig}};
//! use webgates_tonic::gate::remote_jwks_bearer::RemoteJwksBearerGate;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! type AppClaims = JwtClaims<Account<Role, Group>>;
//!
//! let config = RemoteJwksVerifierConfig::from_jwks_url(
//!     "https://auth.example.com/.well-known/jwks.json",
//! );
//! let verifier = Arc::new(RemoteJwksVerifier::<AppClaims>::bootstrap(config).await?);
//! let _refresh = verifier.start_background_refresh();
//!
//! let layer = RemoteJwksBearerGate::new("auth-node", Arc::clone(&verifier))
//!     .with_policy(AccessPolicy::require_role(Role::Admin));
//!
//! // Wrap a tonic server with `.layer(layer)` before adding to a Router.
//! # Ok(())
//! # }
//! ```

use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use http::{Request, Response};
use serde::{Serialize, de::DeserializeOwned};
use tonic::Status;
use tonic::body::Body as TonicBody;
use tower::{Layer, Service};

use webgates::accounts::Account;
use webgates::authz::access_hierarchy::AccessHierarchy;
use webgates::authz::access_policy::AccessPolicy;
use webgates::authz::authorization_service::AuthorizationService;
use webgates::codecs::jwt::JwtClaims;
use webgates_codecs::jwt::remote_verifier::RemoteJwksVerifier;

use crate::context::JwtAuthContext;
use crate::errors::AuthError;

/// Tonic layer that authenticates gRPC requests via a remote JWKS-backed bearer token.
#[derive(Clone)]
pub struct RemoteJwksBearerGate<R, G>
where
    R: AccessHierarchy
        + Eq
        + std::fmt::Display
        + Clone
        + Serialize
        + DeserializeOwned
        + Send
        + Sync
        + 'static,
    G: Eq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    issuer: String,
    verifier: Arc<RemoteJwksVerifier<JwtClaims<Account<R, G>>>>,
    policy: AccessPolicy<R, G>,
}

impl<R, G> RemoteJwksBearerGate<R, G>
where
    R: AccessHierarchy
        + Eq
        + std::fmt::Display
        + Clone
        + Default
        + Serialize
        + DeserializeOwned
        + Send
        + Sync
        + 'static,
    G: Eq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    /// Returns a gate from an issuer string and a shared remote JWKS verifier.
    ///
    /// The gate starts with a `deny_all` policy. Call [`with_policy`](Self::with_policy)
    /// to configure access rules.
    pub fn new(
        issuer: impl Into<String>,
        verifier: Arc<RemoteJwksVerifier<JwtClaims<Account<R, G>>>>,
    ) -> Self {
        Self {
            issuer: issuer.into(),
            verifier,
            policy: AccessPolicy::deny_all(),
        }
    }

    /// Returns this gate with the given access policy.
    #[must_use]
    pub fn with_policy(mut self, policy: AccessPolicy<R, G>) -> Self {
        self.policy = policy;
        self
    }

    /// Allows any authenticated user (baseline role plus all supervisors).
    #[must_use]
    pub fn require_login(mut self) -> Self
    where
        R: Default,
    {
        let baseline = R::default();
        self.policy = AccessPolicy::require_role_or_supervisor(baseline);
        self
    }
}

impl<S, R, G> Layer<S> for RemoteJwksBearerGate<R, G>
where
    R: AccessHierarchy
        + Eq
        + std::fmt::Display
        + Clone
        + Default
        + Serialize
        + DeserializeOwned
        + Send
        + Sync
        + 'static,
    G: Eq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    type Service = RemoteJwksBearerService<S, R, G>;

    fn layer(&self, inner: S) -> Self::Service {
        RemoteJwksBearerService {
            inner,
            issuer: self.issuer.clone(),
            verifier: Arc::clone(&self.verifier),
            authorization: AuthorizationService::new(self.policy.clone()),
        }
    }
}

/// Tower service produced by [`RemoteJwksBearerGate`].
///
/// Most callers should configure and apply [`RemoteJwksBearerGate`] rather
/// than constructing this service directly.
#[derive(Clone)]
pub struct RemoteJwksBearerService<S, R, G>
where
    R: AccessHierarchy
        + Eq
        + std::fmt::Display
        + Clone
        + Serialize
        + DeserializeOwned
        + Send
        + Sync
        + 'static,
    G: Eq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    inner: S,
    issuer: String,
    verifier: Arc<RemoteJwksVerifier<JwtClaims<Account<R, G>>>>,
    authorization: AuthorizationService<R, G>,
}

impl<S, R, G> Service<Request<TonicBody>> for RemoteJwksBearerService<S, R, G>
where
    S: Service<Request<TonicBody>, Response = Response<TonicBody>, Error = Infallible>
        + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
    R: AccessHierarchy
        + Eq
        + std::fmt::Display
        + Clone
        + Serialize
        + DeserializeOwned
        + Send
        + Sync
        + 'static,
    G: Eq + Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
{
    type Response = Response<TonicBody>;
    type Error = Infallible;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + 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, mut req: Request<TonicBody>) -> Self::Future {
        let issuer = self.issuer.clone();
        let verifier = Arc::clone(&self.verifier);
        let authorization = self.authorization.clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // Extract bearer token from Authorization header.
            let token = match extract_bearer_token(&req) {
                Ok(Some(t)) => t.to_owned(),
                Ok(None) => {
                    let status = AuthError::MissingAuthorizationMetadata.into_status();
                    return Ok(status_to_response(status));
                }
                Err(err) => {
                    let status = err.into_status();
                    return Ok(status_to_response(status));
                }
            };

            // Verify the token against the remote JWKS key set (local, no network I/O).
            let claims = match verifier.verify_token(&token).await {
                Ok(claims) => claims,
                Err(error) => {
                    tracing::warn!(error = %error, "remote JWKS bearer token verification failed");
                    let status = AuthError::InvalidToken.into_status();
                    return Ok(status_to_response(status));
                }
            };

            // Validate issuer.
            if claims.registered_claims.issuer != issuer {
                tracing::warn!(
                    expected = %issuer,
                    actual = %claims.registered_claims.issuer,
                    "JWT issuer mismatch"
                );
                let status = AuthError::InvalidIssuer.into_status();
                return Ok(status_to_response(status));
            }

            // Enforce access policy.
            if !authorization.is_authorized(&claims.custom_claims) {
                let status = AuthError::PolicyDenied.into_status();
                return Ok(status_to_response(status));
            }

            // Inject auth context into request extensions.
            req.extensions_mut().insert(JwtAuthContext::new(
                claims.custom_claims,
                claims.registered_claims,
            ));

            inner.call(req).await
        })
    }
}

fn extract_bearer_token(req: &Request<TonicBody>) -> Result<Option<&str>, AuthError> {
    let Some(value) = req.headers().get(http::header::AUTHORIZATION) else {
        return Ok(None);
    };
    let text: &str = value
        .to_str()
        .map_err(|_| AuthError::MalformedAuthorizationMetadata)?
        .trim();
    let mut parts = text.split_whitespace();
    let scheme = parts
        .next()
        .ok_or(AuthError::MalformedAuthorizationMetadata)?;
    if !scheme.eq_ignore_ascii_case("Bearer") {
        return Err(AuthError::MalformedAuthorizationMetadata);
    }
    let token = parts
        .next()
        .ok_or(AuthError::MalformedAuthorizationMetadata)?;
    Ok(Some(token))
}

fn status_to_response(status: Status) -> Response<TonicBody> {
    status.into_http::<TonicBody>()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::sync::Arc;

    use http::Request;
    use tower::ServiceExt as _;
    use webgates::accounts::Account;
    use webgates::codecs::jwt::JwtClaims;
    use webgates::groups::Group;
    use webgates::roles::Role;
    use webgates_codecs::jwt::remote_verifier::{RemoteJwksVerifier, RemoteJwksVerifierConfig};

    type AppClaims = JwtClaims<Account<Role, Group>>;

    async fn make_verifier() -> Arc<RemoteJwksVerifier<AppClaims>> {
        use axum::Router;
        use axum::routing::get;
        use webgates_codecs::jwt::jwks::{EcP384Jwk, JwksDocument};

        const PUBLIC_PEM: &[u8] = br#"-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEsjQ/XkOUJO2bXkhDzKRMW1SXp0VsMqGx
MSTG+tppqd3gOxbM8vLgWy4/B0Qdest0Gy3E8QgaKJXQV3zRczNd9zrk1dmwVl6u
Yd+JfgNIeIFP6HWeu/C3wIJ60WDBuGY1
-----END PUBLIC KEY-----
"#;

        let key = EcP384Jwk::from_public_key_pem("dev-kid", PUBLIC_PEM).unwrap();
        let doc = JwksDocument { keys: vec![key] };
        let doc_json = serde_json::to_string(&doc).unwrap();

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let doc_json_clone = doc_json.clone();
        tokio::spawn(async move {
            let app = Router::new().route(
                "/.well-known/jwks.json",
                get(move || {
                    let body = doc_json_clone.clone();
                    async move {
                        axum::response::Response::builder()
                            .header("content-type", "application/json")
                            .body(axum::body::Body::from(body))
                            .unwrap()
                    }
                }),
            );
            axum::serve(listener, app).await.unwrap();
        });

        let url = format!("http://{addr}/.well-known/jwks.json");
        let config = RemoteJwksVerifierConfig::from_jwks_url(url);
        let verifier = RemoteJwksVerifier::<AppClaims>::bootstrap(config)
            .await
            .expect("bootstrap should succeed");
        Arc::new(verifier)
    }

    fn echo_service() -> impl Service<
        Request<TonicBody>,
        Response = Response<TonicBody>,
        Error = Infallible,
        Future = impl Future<Output = Result<Response<TonicBody>, Infallible>> + Send + 'static,
    > + Clone {
        tower::service_fn(|_req: Request<TonicBody>| async {
            Ok::<_, Infallible>(Response::new(TonicBody::empty()))
        })
    }

    fn make_request_no_auth() -> Request<TonicBody> {
        Request::builder()
            .uri("/test.Service/Method")
            .body(TonicBody::empty())
            .unwrap()
    }

    fn make_request_with_bearer(token: &str) -> Request<TonicBody> {
        Request::builder()
            .uri("/test.Service/Method")
            .header(http::header::AUTHORIZATION, format!("Bearer {token}"))
            .body(TonicBody::empty())
            .unwrap()
    }

    #[tokio::test]
    async fn gate_rejects_missing_token() {
        let verifier = make_verifier().await;
        let gate = RemoteJwksBearerGate::new("auth-node", verifier).require_login();

        let svc = gate.layer(echo_service());
        let resp = svc.oneshot(make_request_no_auth()).await.unwrap();
        let grpc_status = resp
            .headers()
            .get("grpc-status")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u32>().ok());
        // UNAUTHENTICATED = 16
        assert_eq!(grpc_status, Some(16));
    }

    #[tokio::test]
    async fn gate_rejects_invalid_token() {
        let verifier = make_verifier().await;
        let gate = RemoteJwksBearerGate::new("auth-node", verifier).require_login();

        let svc = gate.layer(echo_service());
        let resp = svc
            .oneshot(make_request_with_bearer("not-a-valid-jwt"))
            .await
            .unwrap();
        let grpc_status = resp
            .headers()
            .get("grpc-status")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u32>().ok());
        // UNAUTHENTICATED = 16
        assert_eq!(grpc_status, Some(16));
    }

    #[tokio::test]
    async fn gate_rejects_deny_all_policy() {
        let verifier = make_verifier().await;
        // No policy set — defaults to deny_all.
        let gate: RemoteJwksBearerGate<Role, Group> =
            RemoteJwksBearerGate::new("auth-node", verifier);

        let svc = gate.layer(echo_service());
        let resp = svc
            .oneshot(make_request_with_bearer("any-token"))
            .await
            .unwrap();
        let grpc_status = resp
            .headers()
            .get("grpc-status")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u32>().ok());
        // UNAUTHENTICATED = 16 (token is invalid, fails before policy check)
        assert_eq!(grpc_status, Some(16));
    }
}