sunbeam-g2v 0.3.3

Sunbeam Service Framework - A ConnectRPC-based framework for building microservices
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
//! Keto (Ory) permission middleware.
//!
//! Provides a [`KetoClient`] for issuing permission checks and writes against
//! Ory Keto's gRPC API, and a [`KetoLayer`] Tower middleware that enforces
//! those checks on every incoming request.
//!
//! In Keto v25, the read port (4466) exposes `CheckService` over gRPC and the
//! write port (4467) exposes `WriteService` over gRPC. Both use HTTP/2 with
//! prior knowledge (h2c).
//!
//! [`KetoLayer`] and [`KetoService`](crate::middleware::auth::keto::KetoService) are intended for use as
//! `axum::Router::layer(KetoLayer::new(...))`. They depend on
//! `axum::body::Body` as the concrete request/response body type.
//!
//! For non-axum Tower stacks use [`KetoClient`] directly.

use crate::error::{ServiceError, ServiceResult};
use axum::body::Body;
use axum::response::{IntoResponse, Response};
use connectrpc::{ConnectError, ErrorCode};
use serde::{Deserialize, Serialize};
use std::{
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context as TaskContext, Poll},
};
use tower::{Layer, Service};

use super::AuthContext;

/// Type alias for the function that extracts a Keto object from a request.
pub type ObjectExtractor = Arc<dyn Fn(&http::Request<()>) -> String + Send + Sync>;

// ============================================================================
// Config
// ============================================================================

/// Keto endpoint configuration.
///
/// Both endpoints use h2c (HTTP/2 cleartext) gRPC:
/// - `grpc_endpoint` (port 4466): `CheckService` for permission reads.
/// - `write_grpc_endpoint` (port 4467): `WriteService` for relation-tuple writes.
#[derive(Debug, Clone)]
pub struct KetoConfig {
    /// gRPC endpoint for Keto's read/check API (default port 4466).
    pub grpc_endpoint: String,
    /// gRPC endpoint for Keto's write API (default port 4467).
    pub write_grpc_endpoint: String,
}

impl Default for KetoConfig {
    fn default() -> Self {
        Self {
            grpc_endpoint: "http://localhost:4466".to_string(),
            write_grpc_endpoint: "http://localhost:4467".to_string(),
        }
    }
}

// ============================================================================
// Client
// ============================================================================

/// gRPC client for Ory Keto's CheckService and WriteService.
///
/// The channel is created lazily on first use so that constructing a
/// `KetoClient` outside a Tokio runtime context (e.g. in sync unit tests) is
/// safe. The underlying TCP connection is established on the first RPC call.
#[derive(Debug, Clone)]
pub struct KetoClient {
    config: KetoConfig,
}

impl KetoClient {
    /// Create a new client from configuration.
    pub fn new(config: KetoConfig) -> Self {
        Self { config }
    }

    /// Create a client pointing at the default local Keto instance.
    pub fn with_defaults() -> Self {
        Self::new(KetoConfig::default())
    }

    /// Return a reference to the current configuration.
    pub fn config(&self) -> &KetoConfig {
        &self.config
    }

    /// Build a fresh lazy-connect gRPC channel to the read endpoint (4466).
    ///
    /// Must be called from within a Tokio runtime context.
    fn channel(&self) -> tonic::transport::Channel {
        tonic::transport::Channel::from_shared(self.config.grpc_endpoint.clone())
            .expect("invalid keto grpc_endpoint URI")
            .connect_lazy()
    }

    /// Build a fresh lazy-connect gRPC channel to the write endpoint (4467).
    ///
    /// Must be called from within a Tokio runtime context.
    fn write_channel(&self) -> tonic::transport::Channel {
        tonic::transport::Channel::from_shared(self.config.write_grpc_endpoint.clone())
            .expect("invalid keto write_grpc_endpoint URI")
            .connect_lazy()
    }

    /// Check whether `subject` has `relation` on `object` in `namespace`.
    ///
    /// Uses `CheckService.Check` over gRPC.
    ///
    /// - `Ok(true)` — Keto says the tuple exists (allowed).
    /// - `Ok(false)` — Keto says the tuple does not exist.
    /// - `Err(ServiceError::Internal(_))` — any unexpected upstream error.
    pub async fn check_permission(
        &self,
        namespace: &str,
        object: &str,
        relation: &str,
        subject: &str,
    ) -> ServiceResult<bool> {
        use super::keto_proto::{
            RelationTuple, check_service_client::CheckServiceClient,
        };

        let mut client = CheckServiceClient::new(self.channel());

        let tuple = RelationTuple {
            namespace: namespace.to_string(),
            object: object.to_string(),
            relation: relation.to_string(),
            subject: Some(parse_subject(subject)),
        };

        let request = tonic::Request::new(super::keto_proto::CheckRequest {
            tuple: Some(tuple),
            ..Default::default()
        });

        match client.check(request).await {
            Ok(resp) => Ok(resp.into_inner().allowed),
            Err(status) if status.code() == tonic::Code::PermissionDenied => Ok(false),
            Err(status) => Err(ServiceError::Internal(format!(
                "keto check_permission failed: {}",
                status
            ))),
        }
    }

    /// Grant `subject` the `relation` on `object` in `namespace` by inserting
    /// a relation tuple via `WriteService.TransactRelationTuples` over gRPC.
    pub async fn grant(
        &self,
        namespace: &str,
        object: &str,
        relation: &str,
        subject: &str,
    ) -> ServiceResult<()> {
        use super::keto_proto::{
            RelationTuple, RelationTupleDelta, TransactRelationTuplesRequest,
            relation_tuple_delta::Action, write_service_client::WriteServiceClient,
        };

        let mut client = WriteServiceClient::new(self.write_channel());

        let tuple = RelationTuple {
            namespace: namespace.to_string(),
            object: object.to_string(),
            relation: relation.to_string(),
            subject: Some(parse_subject(subject)),
        };

        let delta = RelationTupleDelta {
            action: Action::Insert as i32,
            relation_tuple: Some(tuple),
        };

        let request = tonic::Request::new(TransactRelationTuplesRequest {
            relation_tuple_deltas: vec![delta],
        });

        client
            .transact_relation_tuples(request)
            .await
            .map(|_| ())
            .map_err(|status| ServiceError::Internal(format!("keto grant failed: {}", status)))
    }

    /// List relation tuples matching the optional filters.
    ///
    /// Uses `ReadService.ListRelationTuples` over gRPC on the read endpoint
    /// (port 4466). `namespace` is required; all other filters are optional.
    pub async fn list_relation_tuples(
        &self,
        namespace: &str,
        object: Option<&str>,
        relation: Option<&str>,
        subject: Option<&str>,
    ) -> ServiceResult<Vec<RelationTuple>> {
        use super::keto_proto::{
            read_service_client::ReadServiceClient, ListRelationTuplesRequest, RelationQuery,
            Subject,
        };

        let mut client = ReadServiceClient::new(self.channel());

        let relation_query = Some(RelationQuery {
            namespace: Some(namespace.to_string()),
            object: object.map(ToString::to_string),
            relation: relation.map(ToString::to_string),
            subject: subject.map(|id| Subject {
                r#ref: Some(super::keto_proto::subject::Ref::Id(id.to_string())),
            }),
        });

        #[allow(deprecated)]
        let request = tonic::Request::new(ListRelationTuplesRequest {
            query: None,
            relation_query,
            snaptoken: String::new(),
            page_size: 0,
            page_token: String::new(),
        });

        let response = client
            .list_relation_tuples(request)
            .await
            .map_err(|status| ServiceError::Internal(format!("keto list_relation_tuples failed: {}", status)))?;

        Ok(response.into_inner().relation_tuples.into_iter().map(Into::into).collect())
    }

    /// Delete relation tuples matching the optional filters.
    ///
    /// Uses `WriteService.DeleteRelationTuples` over gRPC on the write endpoint
    /// (port 4467). `namespace` is required; all other filters are optional.
    ///
    /// # Warning
    ///
    /// Omitting filters deletes every tuple in the namespace. Always provide
    /// enough constraints to match only the intended tuples.
    pub async fn delete_relation_tuples(
        &self,
        namespace: &str,
        object: Option<&str>,
        relation: Option<&str>,
        subject: Option<&str>,
    ) -> ServiceResult<()> {
        use super::keto_proto::{
            write_service_client::WriteServiceClient, DeleteRelationTuplesRequest, RelationQuery,
            Subject,
        };

        let mut client = WriteServiceClient::new(self.write_channel());

        let relation_query = Some(RelationQuery {
            namespace: Some(namespace.to_string()),
            object: object.map(ToString::to_string),
            relation: relation.map(ToString::to_string),
            subject: subject.map(|id| Subject {
                r#ref: Some(super::keto_proto::subject::Ref::Id(id.to_string())),
            }),
        });

        #[allow(deprecated)]
        let request = tonic::Request::new(DeleteRelationTuplesRequest {
            query: None,
            relation_query,
        });

        client
            .delete_relation_tuples(request)
            .await
            .map(|_| ())
            .map_err(|status| ServiceError::Internal(format!("keto delete_relation_tuples failed: {}", status)))
    }

    /// TODO(keto): implement via ReadService
    pub async fn get_roles(&self, _subject: &str) -> ServiceResult<Vec<String>> {
        Ok(vec!["user".to_string()])
    }

    /// TODO(keto): implement via ReadService
    pub async fn get_permissions(&self, _subject: &str) -> ServiceResult<Vec<Permission>> {
        Ok(vec![])
    }
}

/// Parse a subject string into a Keto `Subject` reference.
///
/// Plain identifiers are treated as concrete subject IDs. Strings matching
/// `namespace:object` or `namespace:object#relation` are parsed into a
/// `SubjectSet`.
fn parse_subject(subject: &str) -> super::keto_proto::Subject {
    use super::keto_proto::{SubjectSet, subject::Ref as SubjectRef};

    let r#ref = if let Some((namespace, rest)) = subject.split_once(':') {
        let (object, relation) = rest.split_once('#').unwrap_or((rest, ""));
        SubjectRef::Set(SubjectSet {
            namespace: namespace.to_string(),
            object: object.to_string(),
            relation: relation.to_string(),
        })
    } else {
        SubjectRef::Id(subject.to_string())
    };

    super::keto_proto::Subject { r#ref: Some(r#ref) }
}

impl Default for KetoClient {
    fn default() -> Self {
        Self::with_defaults()
    }
}

// ============================================================================
// Permission type
// ============================================================================

/// A permission record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Permission {
    /// The resource (Keto `object`).
    pub resource: String,
    /// The action (Keto `relation`).
    pub action: String,
    /// Whether access is allowed.
    pub allowed: bool,
}

// ============================================================================
// Relation tuple types
// ============================================================================

/// A subject in a relation tuple.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Subject {
    /// A concrete subject id.
    Id(String),
    /// A subject set that expands to more subjects.
    Set {
        /// The namespace of the referenced object.
        namespace: String,
        /// The referenced object.
        object: String,
        /// The relation between the object and the subjects.
        relation: String,
    },
}

/// A relation tuple returned by Keto.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelationTuple {
    /// The namespace this relation tuple lives in.
    pub namespace: String,
    /// The object related by this tuple.
    pub object: String,
    /// The relation between the object and the subject.
    pub relation: String,
    /// The subject related by this tuple.
    pub subject: Subject,
}

impl From<super::keto_proto::RelationTuple> for RelationTuple {
    fn from(proto: super::keto_proto::RelationTuple) -> Self {
        let subject = proto
            .subject
            .and_then(|s| s.r#ref)
            .map_or(Subject::Id(String::new()), |r| match r {
                super::keto_proto::subject::Ref::Id(id) => Subject::Id(id),
                super::keto_proto::subject::Ref::Set(set) => Subject::Set {
                    namespace: set.namespace,
                    object: set.object,
                    relation: set.relation,
                },
            });

        Self {
            namespace: proto.namespace,
            object: proto.object,
            relation: proto.relation,
            subject,
        }
    }
}

// ============================================================================
// Error helpers
// ============================================================================

fn unauthorized(message: &str) -> Response {
    ConnectError::new(ErrorCode::Unauthenticated, message).into_response()
}

fn forbidden(message: &str) -> Response {
    ConnectError::new(ErrorCode::PermissionDenied, message).into_response()
}

fn internal(message: impl std::fmt::Display) -> Response {
    ConnectError::new(ErrorCode::Internal, message.to_string()).into_response()
}

// ============================================================================
// KetoLayer — Tower Layer impl
// ============================================================================

/// Tower middleware layer that enforces a Keto permission check on every
/// request.
///
/// The layer requires that an [`AuthContext`] (injected by the upstream
/// [`super::jwt::JwtLayer`]) is present in request extensions.  If the context
/// is absent or the subject is unauthenticated the request is rejected with
/// **401**.  If the Keto check denies access the request is rejected with
/// **403**.
///
/// This layer is intended for use as `axum::Router::layer(KetoLayer::new(...))`.
/// It operates on `axum::body::Body` requests and returns `axum::response::Response`.
/// For non-axum Tower stacks use [`KetoClient`] directly.
///
/// # Construction
///
/// ```rust,no_run
/// # use sunbeam_g2v::middleware::auth::keto::{KetoLayer, KetoClient};
/// let layer = KetoLayer::new(KetoClient::with_defaults(), "documents", "read")
///     .skip_path("/health")
///     .skip_path("/metrics");
/// ```
#[derive(Clone)]
pub struct KetoLayer {
    client: Arc<KetoClient>,
    namespace: Arc<String>,
    relation: Arc<String>,
    skip_paths: Arc<Vec<String>>,
    object_extractor: ObjectExtractor,
}

impl std::fmt::Debug for KetoLayer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("KetoLayer")
            .field("namespace", &self.namespace)
            .field("relation", &self.relation)
            .field("skip_paths", &self.skip_paths)
            .finish()
    }
}

impl KetoLayer {
    /// Create a new layer that checks `relation` in `namespace`.
    ///
    /// The default object extractor returns `req.uri().path()`.
    pub fn new(
        client: KetoClient,
        namespace: impl Into<String>,
        relation: impl Into<String>,
    ) -> Self {
        Self {
            client: Arc::new(client),
            namespace: Arc::new(namespace.into()),
            relation: Arc::new(relation.into()),
            skip_paths: Arc::new(vec![]),
            object_extractor: Arc::new(|req| req.uri().path().to_string()),
        }
    }

    /// Create a layer from a [`KetoConfig`].
    pub fn from_config(
        config: KetoConfig,
        namespace: impl Into<String>,
        relation: impl Into<String>,
    ) -> Self {
        Self::new(KetoClient::new(config), namespace, relation)
    }

    /// Skip the permission check for any request whose path starts with
    /// `prefix`.
    pub fn skip_path(mut self, prefix: impl Into<String>) -> Self {
        Arc::make_mut(&mut self.skip_paths).push(prefix.into());
        self
    }

    /// Override the function that derives the Keto `object` from the request.
    ///
    /// The default is `req.uri().path()`.
    pub fn with_object_extractor(
        mut self,
        f: ObjectExtractor,
    ) -> Self {
        self.object_extractor = f;
        self
    }
}

impl<S> Layer<S> for KetoLayer {
    type Service = KetoService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        KetoService {
            inner,
            client: Arc::clone(&self.client),
            namespace: Arc::clone(&self.namespace),
            relation: Arc::clone(&self.relation),
            skip_paths: Arc::clone(&self.skip_paths),
            object_extractor: Arc::clone(&self.object_extractor),
        }
    }
}

// ============================================================================
// KetoService — Tower Service impl
// ============================================================================

/// Tower [`Service`] produced by [`KetoLayer`].
#[derive(Clone)]
pub struct KetoService<S> {
    inner: S,
    client: Arc<KetoClient>,
    namespace: Arc<String>,
    relation: Arc<String>,
    skip_paths: Arc<Vec<String>>,
    object_extractor: ObjectExtractor,
}

impl<S> Service<http::Request<Body>> for KetoService<S>
where
    S: Service<http::Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

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

    fn call(&mut self, req: http::Request<Body>) -> Self::Future {
        let path = req.uri().path().to_string();

        // Skip-path fast path — forward without a Keto call.
        for prefix in self.skip_paths.iter() {
            if path.starts_with(prefix.as_str()) {
                return Box::pin(self.inner.call(req));
            }
        }

        // Pull AuthContext from extensions (requires JwtLayer upstream).
        let auth_ctx = req.extensions().get::<AuthContext>().cloned();

        let subject = match auth_ctx {
            None
            | Some(AuthContext {
                is_authenticated: false,
                ..
            }) => {
                let resp = unauthorized("unauthenticated");
                return Box::pin(async move { Ok(resp) });
            }
            Some(ctx) => ctx.subject.unwrap_or_default(),
        };

        // Derive the Keto object using the extractor.  We build a unit-body
        // request from the parts so the extractor fn doesn't need to know B.
        let (parts, body) = req.into_parts();
        let unit_req = http::Request::from_parts(parts.clone(), ());
        let object = (self.object_extractor)(&unit_req);
        let req = http::Request::from_parts(parts, body);

        let client = Arc::clone(&self.client);
        let namespace = Arc::clone(&self.namespace);
        let relation = Arc::clone(&self.relation);
        let mut inner = self.inner.clone();

        Box::pin(async move {
            match client
                .check_permission(&namespace, &object, &relation, &subject)
                .await
            {
                Ok(true) => inner.call(req).await,
                Ok(false) => Ok(forbidden("permission denied")),
                Err(e) => Ok(internal(e)),
            }
        })
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Extract the raw Bearer token string from request headers.
///
/// This is a lower-level helper; prefer reading [`AuthContext`] from request
/// extensions (set by [`super::jwt::JwtLayer`]) in middleware.
pub fn extract_subject(headers: &http::HeaderMap) -> Option<String> {
    headers
        .get("Authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer ").map(str::to_string))
}

// ============================================================================
// Unit tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_keto_config_default() {
        let config = KetoConfig::default();
        assert_eq!(config.grpc_endpoint, "http://localhost:4466");
        assert_eq!(config.write_grpc_endpoint, "http://localhost:4467");
    }

    #[test]
    fn test_keto_client_new() {
        let config = KetoConfig {
            grpc_endpoint: "http://keto:4466".to_string(),
            write_grpc_endpoint: "http://keto:4467".to_string(),
        };
        let client = KetoClient::new(config);
        assert_eq!(client.config.grpc_endpoint, "http://keto:4466");
        assert_eq!(client.config.write_grpc_endpoint, "http://keto:4467");
    }

    #[test]
    fn test_keto_client_with_defaults() {
        let client = KetoClient::with_defaults();
        assert_eq!(client.config().grpc_endpoint, "http://localhost:4466");
    }

    #[test]
    fn test_keto_layer_skip_path_builder() {
        let layer = KetoLayer::new(KetoClient::with_defaults(), "ns", "read")
            .skip_path("/health")
            .skip_path("/metrics");
        assert_eq!(layer.skip_paths.len(), 2);
        assert_eq!(layer.skip_paths[0], "/health");
        assert_eq!(layer.skip_paths[1], "/metrics");
    }

    #[test]
    fn test_keto_layer_namespace_relation() {
        let layer = KetoLayer::new(KetoClient::with_defaults(), "docs", "write");
        assert_eq!(layer.namespace.as_str(), "docs");
        assert_eq!(layer.relation.as_str(), "write");
    }

    #[test]
    fn test_extract_subject_bearer() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            "Authorization",
            http::HeaderValue::from_static("Bearer mytoken"),
        );
        assert_eq!(extract_subject(&headers), Some("mytoken".to_string()));
    }

    #[test]
    fn test_extract_subject_non_bearer() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            "Authorization",
            http::HeaderValue::from_static("Basic credentials"),
        );
        assert_eq!(extract_subject(&headers), None);
    }

    #[test]
    fn test_extract_subject_missing() {
        let headers = http::HeaderMap::new();
        assert_eq!(extract_subject(&headers), None);
    }

    // -------------------------------------------------------------------------
    // KetoService unit tests — no network, exercising skip-path + auth logic
    // -------------------------------------------------------------------------

    use axum::body::Body;
    use axum::response::{IntoResponse, Response};
    use tower::{ServiceBuilder, ServiceExt};

    fn ok_service() -> impl Service<
        http::Request<Body>,
        Response = Response,
        Error = std::convert::Infallible,
        Future = impl Future<Output = Result<Response, std::convert::Infallible>>,
    > + Clone {
        tower::service_fn(|_req: http::Request<Body>| async {
            Ok::<_, std::convert::Infallible>(
                http::Response::builder()
                    .status(http::StatusCode::OK)
                    .body(Body::empty())
                    .unwrap()
                    .into_response(),
            )
        })
    }

    #[tokio::test]
    async fn test_keto_layer_skip_path_forwards() {
        // Requests to /health should bypass the Keto check entirely.
        // The client points at a non-existent server; if any gRPC call were made
        // the test would fail with a connection error.
        let layer = KetoLayer::new(
            KetoClient::new(KetoConfig {
                grpc_endpoint: "http://127.0.0.1:1".to_string(), // deliberately unreachable
                write_grpc_endpoint: "http://127.0.0.1:1".to_string(),
            }),
            "ns",
            "read",
        )
        .skip_path("/health");

        let mut svc = ServiceBuilder::new().layer(layer).service(ok_service());

        let req = http::Request::builder()
            .uri("/health")
            .body(Body::empty())
            .unwrap();

        let resp = svc.ready().await.unwrap().call(req).await.unwrap();
        assert_eq!(resp.status(), http::StatusCode::OK);
    }

    #[tokio::test]
    async fn test_keto_layer_missing_auth_context_returns_401() {
        let layer = KetoLayer::new(KetoClient::with_defaults(), "ns", "read");
        let mut svc = ServiceBuilder::new().layer(layer).service(ok_service());

        // No AuthContext in extensions → should get 401.
        let req = http::Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        let resp = svc.ready().await.unwrap().call(req).await.unwrap();
        assert_eq!(resp.status(), http::StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_keto_layer_unauthenticated_context_returns_401() {
        let layer = KetoLayer::new(KetoClient::with_defaults(), "ns", "read");
        let mut svc = ServiceBuilder::new().layer(layer).service(ok_service());

        let mut req = http::Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();
        req.extensions_mut().insert(AuthContext::unauthenticated());

        let resp = svc.ready().await.unwrap().call(req).await.unwrap();
        assert_eq!(resp.status(), http::StatusCode::UNAUTHORIZED);
    }

    // -------------------------------------------------------------------------
    // Subject parsing tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_parse_subject_plain_id() {
        use crate::middleware::auth::keto_proto::subject::Ref as SubjectRef;

        let subject = parse_subject("user-123");
        let r#ref = subject.r#ref.expect("subject ref is present");
        assert!(matches!(r#ref, SubjectRef::Id(id) if id == "user-123"));
    }

    #[test]
    fn test_parse_subject_set_without_relation() {
        use crate::middleware::auth::keto_proto::subject::Ref as SubjectRef;

        let subject = parse_subject("groups:admins");
        let r#ref = subject.r#ref.expect("subject ref is present");
        match r#ref {
            SubjectRef::Set(set) => {
                assert_eq!(set.namespace, "groups");
                assert_eq!(set.object, "admins");
                assert_eq!(set.relation, "");
            }
            _ => panic!("expected SubjectSet"),
        }
    }

    #[test]
    fn test_parse_subject_set_with_relation() {
        use crate::middleware::auth::keto_proto::subject::Ref as SubjectRef;

        let subject = parse_subject("groups:admins#members");
        let r#ref = subject.r#ref.expect("subject ref is present");
        match r#ref {
            SubjectRef::Set(set) => {
                assert_eq!(set.namespace, "groups");
                assert_eq!(set.object, "admins");
                assert_eq!(set.relation, "members");
            }
            _ => panic!("expected SubjectSet"),
        }
    }
}