Skip to main content

hyprstream_core/mac/
generated_dispatch.rs

1//! Schema-owned RPC labels for verified user and service identities.
2//!
3//! The same validated leaf inventory drives the signature policy and this
4//! mandatory label gate. No service-name, parent-path, or transitional-label
5//! fallback is allowed. Scope, tenant and mutation checks remain downstream.
6
7use anyhow::{ensure, Result};
8use hyprstream_rpc::auth::mac::{MacDecision, MacDenyReason, MacDispatchPep};
9use hyprstream_rpc::proof::policy::{
10    collect_generated_rows, validate_generated_rows, AuthenticationRequirement,
11    GeneratedMethodPolicyRow,
12};
13use hyprstream_rpc::service::EnvelopeContext;
14use std::collections::BTreeMap;
15
16pub(super) struct GeneratedDispatchPep {
17    rows: BTreeMap<&'static str, BTreeMap<&'static [u16], GeneratedMethodPolicyRow>>,
18}
19
20impl GeneratedDispatchPep {
21    pub(super) fn production() -> Result<Self> {
22        Self::from_rows(collect_generated_rows()?)
23    }
24
25    pub(super) fn is_declared(&self, service: &str, method: Option<&[u16]>) -> bool {
26        method.is_some_and(|path| {
27            self.rows
28                .get(service)
29                .is_some_and(|rows| rows.contains_key(path))
30        })
31    }
32
33    fn from_rows(rows: Vec<GeneratedMethodPolicyRow>) -> Result<Self> {
34        ensure!(
35            !rows.is_empty(),
36            "no generated RPC dispatch labels are linked"
37        );
38        validate_generated_rows(&rows)?;
39        let mut inventory: BTreeMap<_, BTreeMap<_, _>> = BTreeMap::new();
40        for row in rows {
41            inventory
42                .entry(row.service)
43                .or_default()
44                .insert(row.leaf_path, row);
45        }
46        Ok(Self { rows: inventory })
47    }
48}
49
50impl MacDispatchPep for GeneratedDispatchPep {
51    fn check(
52        &self,
53        ctx: &EnvelopeContext,
54        service_domain: &str,
55        method: Option<&[u16]>,
56    ) -> MacDecision {
57        hyprstream_rpc::auth::mac::remember_verified_subject(ctx);
58        let Some(row) = method.and_then(|path| self.rows.get(service_domain)?.get(path)) else {
59            return MacDecision::Deny(MacDenyReason::UnlabeledObject);
60        };
61        // Hybrid enrollment authenticates a workload; it is not permission to
62        // mint credentials or administer sessions for other principals. Keep the issuing-service
63        // boundary explicit even if a retained policy has the old service:*
64        // IssueToken grant. Human callers still require downstream policy.
65        if service_domain == "policy"
66            && matches!(
67                row.symbolic_path,
68                "issueToken"
69                    | "registerSession"
70                    | "revokeSession"
71                    | "revokeCredential"
72                    | "exchangeDelegated"
73                    | "exchangeWit"
74            )
75        {
76            let subject = ctx.subject();
77            // The merged MCP delegated-bearer exchange mints the caller's own
78            // verified subject through issueToken (mcp_service.rs
79            // delegated_resource_bearer); admit service:mcp for that leaf only.
80            // Session administration and the exchange endpoints stay confined
81            // to the two authority services. The operator-granted Casbin
82            // `policy:IssueToken manage` check in the target tenant remains the
83            // enforcement point (policy.rs).
84            let admitted = match row.symbolic_path {
85                "issueToken" => matches!(
86                    subject.name(),
87                    Some("service:oauth" | "service:policy" | "service:mcp")
88                ),
89                _ => matches!(subject.name(), Some("service:oauth" | "service:policy")),
90            };
91            if subject
92                .name()
93                .is_some_and(|name| name.starts_with("service:"))
94                && (subject.is_federated() || !admitted)
95            {
96                return MacDecision::Deny(MacDenyReason::NoClearance);
97            }
98        }
99        if row.authentication == AuthenticationRequirement::UnauthenticatedAllowed {
100            // Validation requires exactly SYSTEM_LOW, an explicit public reason
101            // and an unauthenticated-capable signature policy. The dispatch
102            // pipeline still verifies the declared signature policy first.
103            return MacDecision::Permit;
104        }
105        let Some(selected) = hyprstream_rpc::auth::mac::global_mac_activation_control()
106            .select_context(ctx.security_context())
107        else {
108            return MacDecision::Deny(MacDenyReason::NoClearance);
109        };
110        if selected.can_access(&row.target_label) {
111            MacDecision::Permit
112        } else {
113            MacDecision::Deny(MacDenyReason::FloorDeny)
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn invalid_inventory_is_rejected_before_installation() -> Result<()> {
124        assert!(GeneratedDispatchPep::from_rows(Vec::new()).is_err());
125        let rows = collect_generated_rows()?;
126        let row = rows
127            .first()
128            .ok_or_else(|| anyhow::anyhow!("missing generated inventory"))?
129            .clone();
130        assert!(GeneratedDispatchPep::from_rows(vec![row.clone(), row.clone()]).is_err());
131        let mut empty_path = row;
132        empty_path.leaf_path = &[];
133        assert!(GeneratedDispatchPep::from_rows(vec![empty_path]).is_err());
134        let mut public = rows
135            .into_iter()
136            .find(|row| row.authentication == AuthenticationRequirement::UnauthenticatedAllowed)
137            .ok_or_else(|| anyhow::anyhow!("missing public schema declaration"))?;
138        public.public_reason = None;
139        assert!(GeneratedDispatchPep::from_rows(vec![public]).is_err());
140        Ok(())
141    }
142
143    #[test]
144    fn public_declarations_do_not_create_anonymous_fallbacks() -> Result<()> {
145        let pep = GeneratedDispatchPep::production()?;
146        let ctx = EnvelopeContext::from_callback_service(0, "untrusted");
147        for rows in pep.rows.values() {
148            for row in rows.values() {
149                let expected =
150                    if row.authentication == AuthenticationRequirement::UnauthenticatedAllowed {
151                        MacDecision::Permit
152                    } else {
153                        MacDecision::Deny(MacDenyReason::NoClearance)
154                    };
155                assert_eq!(
156                    pep.check(&ctx, row.service, Some(row.leaf_path)),
157                    expected,
158                    "{}:{}",
159                    row.service,
160                    row.symbolic_path
161                );
162            }
163        }
164        for path in [
165            None,
166            Some(&[][..]),
167            Some(&[u16::MAX][..]),
168            Some(&[0, 0][..]),
169        ] {
170            assert_eq!(
171                pep.check(&ctx, "policy", path),
172                MacDecision::Deny(MacDenyReason::UnlabeledObject)
173            );
174        }
175        assert_eq!(
176            pep.check(&ctx, "/registry", Some(&[0])),
177            MacDecision::Deny(MacDenyReason::UnlabeledObject)
178        );
179        Ok(())
180    }
181}