Skip to main content

hyprstream_core/services/
discovery.rs

1//! Discovery service — re-exports from `hyprstream-discovery`.
2//!
3//! The DiscoveryService implementation has moved to the `hyprstream-discovery` crate.
4//! This module provides a `PolicyAuthProvider` that wraps `PolicyClient` to implement
5//! the `AuthorizationProvider` trait expected by DiscoveryService.
6
7pub use hyprstream_discovery::{AuthorizationProvider, DiscoveryService};
8
9use async_trait::async_trait;
10use hyprstream_rpc_std::policy_client::PolicyCheck;
11
12/// Policy-based authorization provider wrapping PolicyClient.
13///
14/// Bridges the `AuthorizationProvider` trait from `hyprstream-discovery`
15/// to the `PolicyClient` generated in this crate.
16pub struct PolicyAuthProvider {
17    client: hyprstream_rpc_std::policy_client::PolicyClient,
18}
19
20impl PolicyAuthProvider {
21    /// Create a new policy-based authorization provider.
22    pub fn new(client: hyprstream_rpc_std::policy_client::PolicyClient) -> Self {
23        Self { client }
24    }
25}
26
27#[async_trait(?Send)]
28impl AuthorizationProvider for PolicyAuthProvider {
29    async fn check_context(
30        &self,
31        ctx: &hyprstream_rpc::service::EnvelopeContext,
32        resource: &str,
33        operation: &str,
34    ) -> anyhow::Result<bool> {
35        let subject = ctx.subject();
36        let request = PolicyCheck {
37            subject: subject.to_string(),
38            domain: String::new(),
39            resource: resource.to_owned(),
40            operation: operation.to_owned(),
41        };
42        crate::services::policy::check_with_holder_evidence(
43            &self.client,
44            &request,
45            ctx.jwt_token(),
46            &subject,
47            ctx.original_holder_evidence(),
48        )
49        .await
50    }
51
52    async fn check_batch_context(
53        &self,
54        ctx: &hyprstream_rpc::service::EnvelopeContext,
55        resources: &[String],
56        operation: &str,
57    ) -> anyhow::Result<Vec<bool>> {
58        anyhow::ensure!(resources.len() <= 256, "authorization batch exceeds 256");
59        let subject = ctx.subject();
60        if ctx.jwt_token().is_some()
61            && !subject.is_federated()
62            && subject
63                .name()
64                .is_some_and(|name| name.starts_with("service:"))
65        {
66            let mut decisions = Vec::with_capacity(resources.len());
67            for resource in resources {
68                decisions.push(self.check_context(ctx, resource, operation).await?);
69            }
70            Ok(decisions)
71        } else {
72            self.check_batch(
73                &subject.to_string(),
74                "*",
75                resources,
76                operation,
77                ctx.jwt_token(),
78            )
79            .await
80        }
81    }
82
83    async fn check_batch(
84        &self,
85        subject: &str,
86        domain: &str,
87        resources: &[String],
88        operation: &str,
89        bearer: Option<&str>,
90    ) -> anyhow::Result<Vec<bool>> {
91        use hyprstream_rpc_std::policy_client::PolicyCheckBatch;
92        anyhow::ensure!(resources.len() <= 256, "authorization batch exceeds 256");
93        let client = match bearer {
94            Some(token) => self.client.clone().with_delegated_bearer(token.to_owned()),
95            None => {
96                let upstream = hyprstream_rpc::envelope::Subject::new(subject);
97                anyhow::ensure!(
98                    !upstream.is_federated()
99                        && upstream
100                            .name()
101                            .is_some_and(|name| name == "system" || name.starts_with("service:")),
102                    "service-mediated user policy check requires verified bearer"
103                );
104                self.client.clone()
105            }
106        };
107        let request = PolicyCheckBatch {
108            checks: resources
109                .iter()
110                .map(|resource| PolicyCheck {
111                    subject: subject.to_owned(),
112                    domain: domain.to_owned(),
113                    resource: resource.clone(),
114                    operation: operation.to_owned(),
115                })
116                .collect(),
117        };
118        let result = client.check_batch(&request).await?;
119        anyhow::ensure!(
120            result.allowed.len() == resources.len(),
121            "invalid policy batch decision count"
122        );
123        Ok(result.allowed)
124    }
125
126    async fn check(
127        &self,
128        subject: &str,
129        domain: &str,
130        resource: &str,
131        operation: &str,
132        bearer: Option<&str>,
133    ) -> anyhow::Result<bool> {
134        let request = PolicyCheck {
135            subject: subject.to_owned(),
136            domain: domain.to_owned(),
137            resource: resource.to_owned(),
138            operation: operation.to_owned(),
139        };
140        crate::services::policy::check_with_verified_bearer(
141            &self.client,
142            &request,
143            bearer,
144            &hyprstream_rpc::envelope::Subject::new(subject),
145        )
146        .await
147    }
148}
149
150// The durable PDS record store and its publisher/resolver/ingest stack only
151// compile when the `rocksdb` feature carries the dependency. Everything is
152// re-exported unchanged, so callers keep the `services::discovery::*` paths.
153#[cfg(feature = "rocksdb")]
154pub use crate::services::pds_record_rocksdb::*;