Skip to main content

hyprstream_k8s/
grant.rs

1//! Service-neutral tenant-grant boundary for the Kubernetes operator.
2//!
3//! This Apache-licensed module owns only the generic reconciliation contract:
4//! an AGPL service adapter may compile an authored [`TenantBinding`]
5//! entitlement and return opaque content-addressed references. Cryptographic
6//! issuer keys, signed grant verification, PDS allocation records, and their
7//! CID implementation belong downstream of this crate.
8
9use std::fmt;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use cid::{Cid, Version};
13use kube::Resource;
14
15use crate::mesh::{TenantBinding, TenantBindingStatus};
16
17/// A validated, canonical content identifier.
18///
19/// This service-neutral type validates only the content-addressing envelope:
20/// it deliberately knows nothing about UCANs, PDS records, or how their bytes
21/// are produced. Keeping the inner string private makes malformed successful
22/// service results unrepresentable.
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub struct ContentReference(String);
25
26impl ContentReference {
27    /// Parse a canonical CID string.
28    pub fn parse(value: impl Into<String>) -> Result<Self, TenantGrantServiceError> {
29        let value = value.into();
30        if value.trim() != value {
31            return Err(TenantGrantServiceError::new(
32                "content reference must not contain surrounding whitespace",
33            ));
34        }
35        let parsed = Cid::try_from(value.as_str()).map_err(|error| {
36            TenantGrantServiceError::new(format!("invalid content reference: {error}"))
37        })?;
38        if parsed.version() != Version::V1 {
39            return Err(TenantGrantServiceError::new(
40                "content reference must be CIDv1",
41            ));
42        }
43        if parsed.to_string() != value {
44            return Err(TenantGrantServiceError::new(
45                "content reference must use canonical lowercase base32 CIDv1 encoding",
46            ));
47        }
48        Ok(Self(value))
49    }
50
51    /// Borrow the canonical CID string.
52    pub fn as_str(&self) -> &str {
53        &self.0
54    }
55
56    fn into_string(self) -> String {
57        self.0
58    }
59}
60
61/// Validated references produced by a service-specific grant compiler.
62///
63/// The Kubernetes substrate records these values as observed status but never
64/// interprets their service-specific contents.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct TenantGrantArtifacts {
67    grant_cid: ContentReference,
68    allocation_cid: ContentReference,
69    epoch: u64,
70}
71
72impl TenantGrantArtifacts {
73    /// Validate both references before constructing a successful artifact pair.
74    pub fn new(
75        grant_cid: impl Into<String>,
76        allocation_cid: impl Into<String>,
77        epoch: u64,
78    ) -> Result<Self, TenantGrantServiceError> {
79        let grant_cid = ContentReference::parse(grant_cid)?;
80        let allocation_cid = ContentReference::parse(allocation_cid)?;
81        Ok(Self {
82            grant_cid,
83            allocation_cid,
84            epoch,
85        })
86    }
87
88    /// The validated grant CID.
89    pub fn grant_cid(&self) -> &ContentReference {
90        &self.grant_cid
91    }
92
93    /// The validated allocation CID.
94    pub fn allocation_cid(&self) -> &ContentReference {
95        &self.allocation_cid
96    }
97
98    /// The revocation epoch the service compiled.
99    pub fn epoch(&self) -> u64 {
100        self.epoch
101    }
102}
103
104/// A fail-closed service error safe to reflect in Kubernetes status.
105#[derive(Clone, Debug, Eq, PartialEq)]
106pub struct TenantGrantServiceError {
107    message: String,
108}
109
110impl TenantGrantServiceError {
111    pub fn new(message: impl Into<String>) -> Self {
112        Self {
113            message: message.into(),
114        }
115    }
116}
117
118impl fmt::Display for TenantGrantServiceError {
119    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
120        formatter.write_str(&self.message)
121    }
122}
123
124impl std::error::Error for TenantGrantServiceError {}
125
126/// Service behavior invoked by the generic `TenantBinding` reconciler.
127///
128/// Implementations are authority-bearing and therefore live in downstream
129/// service crates. They must validate the binding, issue/sign the grant, bind
130/// it to the allocation record, and fail closed on any error. The Apache
131/// operator receives only the resulting opaque content references.
132pub trait TenantGrantService: Send + Sync {
133    fn compile_grant(
134        &self,
135        binding: &TenantBinding,
136        epoch: u64,
137        now: u64,
138    ) -> Result<TenantGrantArtifacts, TenantGrantServiceError>;
139}
140
141/// Project a service result into the status written by the generic operator.
142///
143/// An authored entitlement without a configured service is rejected. A
144/// service error is also rejected and never leaves partial content references.
145pub fn compile_tenant_binding_status(
146    binding: &TenantBinding,
147    service: Option<&dyn TenantGrantService>,
148    epoch: u64,
149    now: u64,
150) -> TenantBindingStatus {
151    let generation = binding.meta().generation;
152    match binding.spec.entitlement.as_ref() {
153        None => TenantBindingStatus {
154            bound: Some(true),
155            phase: Some("Bound".to_owned()),
156            message: Some("namespace↔tenant mapping active; no entitlement to compile".to_owned()),
157            observed_generation: generation,
158            grant_cid: None,
159            allocation_cid: None,
160            epoch: None,
161        },
162        Some(_) => match service {
163            None => rejected_status(
164                generation,
165                "entitlement present but operator has no tenant-grant service configured",
166            ),
167            Some(service) => match service.compile_grant(binding, epoch, now) {
168                Ok(compiled) if compiled.epoch() != epoch => rejected_status(
169                    generation,
170                    &format!(
171                        "grant compilation failed: service returned epoch {} for requested epoch {epoch}",
172                        compiled.epoch()
173                    ),
174                ),
175                Ok(compiled) => {
176                    let TenantGrantArtifacts {
177                        grant_cid,
178                        allocation_cid,
179                        epoch,
180                    } = compiled;
181                    TenantBindingStatus {
182                        bound: Some(true),
183                        phase: Some("Bound".to_owned()),
184                        message: Some(format!(
185                            "compiled grant {} (allocation {}); PDS publish pending #910",
186                            grant_cid.as_str(),
187                            allocation_cid.as_str()
188                        )),
189                        observed_generation: generation,
190                        grant_cid: Some(grant_cid.into_string()),
191                        allocation_cid: Some(allocation_cid.into_string()),
192                        epoch: Some(epoch),
193                    }
194                }
195                Err(error) => {
196                    rejected_status(generation, &format!("grant compilation failed: {error}"))
197                }
198            },
199        },
200    }
201}
202
203fn rejected_status(generation: Option<i64>, message: &str) -> TenantBindingStatus {
204    TenantBindingStatus {
205        bound: Some(false),
206        phase: Some("Rejected".to_owned()),
207        message: Some(message.to_owned()),
208        observed_generation: generation,
209        grant_cid: None,
210        allocation_cid: None,
211        epoch: None,
212    }
213}
214
215/// Unix seconds used by the generic reconcile request.
216///
217/// Platforms without a usable wall clock return zero so downstream expiry
218/// validation fails closed.
219pub fn now_unix() -> u64 {
220    SystemTime::now()
221        .duration_since(UNIX_EPOCH)
222        .map(|duration| duration.as_secs())
223        .unwrap_or(0)
224}
225
226#[cfg(test)]
227mod tests {
228    #![allow(clippy::expect_used)]
229
230    use super::*;
231    use crate::mesh::{TenantBindingSpec, TenantEntitlement, TenantGrantClass};
232
233    const VALID_CID: &str = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3g3gd3lst2gq2r2a6y4m5x4zi";
234
235    struct RecordingService;
236
237    impl TenantGrantService for RecordingService {
238        fn compile_grant(
239            &self,
240            binding: &TenantBinding,
241            epoch: u64,
242            now: u64,
243        ) -> Result<TenantGrantArtifacts, TenantGrantServiceError> {
244            assert_eq!(binding.spec.tenant, "did:web:acme");
245            assert_eq!(epoch, 7);
246            assert_eq!(now, 1_700_000_000);
247            TenantGrantArtifacts::new(VALID_CID, VALID_CID, epoch)
248        }
249    }
250
251    fn entitled_binding() -> TenantBinding {
252        TenantBinding::new(
253            "acme",
254            TenantBindingSpec {
255                namespace: "acme".to_owned(),
256                tenant: "did:web:acme".to_owned(),
257                entitlement: Some(TenantEntitlement {
258                    unit: "compute-second".to_owned(),
259                    amount: 100,
260                    class: TenantGrantClass::Underwritten,
261                    expiration: None,
262                }),
263            },
264        )
265    }
266
267    #[test]
268    fn tenant_grant_service_boundary_is_required_for_entitlements() {
269        let rejected = compile_tenant_binding_status(&entitled_binding(), None, 7, 1_700_000_000);
270        assert_eq!(rejected.bound, Some(false));
271        assert_eq!(rejected.phase.as_deref(), Some("Rejected"));
272        assert!(rejected.grant_cid.is_none());
273        assert!(rejected.allocation_cid.is_none());
274
275        let compiled = compile_tenant_binding_status(
276            &entitled_binding(),
277            Some(&RecordingService),
278            7,
279            1_700_000_000,
280        );
281        assert_eq!(compiled.bound, Some(true));
282        assert_eq!(compiled.grant_cid.as_deref(), Some(VALID_CID));
283        assert_eq!(compiled.allocation_cid.as_deref(), Some(VALID_CID));
284        assert_eq!(compiled.epoch, Some(7));
285    }
286
287    struct FailingService;
288
289    impl TenantGrantService for FailingService {
290        fn compile_grant(
291            &self,
292            _binding: &TenantBinding,
293            _epoch: u64,
294            _now: u64,
295        ) -> Result<TenantGrantArtifacts, TenantGrantServiceError> {
296            Err(TenantGrantServiceError::new("issuer unavailable"))
297        }
298    }
299
300    #[test]
301    fn tenant_grant_service_errors_fail_closed_without_partial_references() {
302        let status = compile_tenant_binding_status(
303            &entitled_binding(),
304            Some(&FailingService),
305            7,
306            1_700_000_000,
307        );
308        assert_eq!(status.bound, Some(false));
309        assert_eq!(status.phase.as_deref(), Some("Rejected"));
310        assert!(status
311            .message
312            .as_deref()
313            .is_some_and(|message| message.contains("issuer unavailable")));
314        assert!(status.grant_cid.is_none());
315        assert!(status.allocation_cid.is_none());
316        assert!(status.epoch.is_none());
317    }
318
319    struct WrongEpochService;
320
321    impl TenantGrantService for WrongEpochService {
322        fn compile_grant(
323            &self,
324            _binding: &TenantBinding,
325            epoch: u64,
326            _now: u64,
327        ) -> Result<TenantGrantArtifacts, TenantGrantServiceError> {
328            TenantGrantArtifacts::new(VALID_CID, VALID_CID, epoch + 1)
329        }
330    }
331
332    #[test]
333    fn tenant_grant_service_cannot_bypass_requested_revocation_epoch() {
334        let status = compile_tenant_binding_status(
335            &entitled_binding(),
336            Some(&WrongEpochService),
337            7,
338            1_700_000_000,
339        );
340        assert_eq!(status.bound, Some(false));
341        assert_eq!(status.phase.as_deref(), Some("Rejected"));
342        assert!(status.grant_cid.is_none());
343        assert!(status.allocation_cid.is_none());
344        assert!(status.epoch.is_none());
345    }
346
347    #[test]
348    fn malformed_artifact_pairs_are_unrepresentable() {
349        const CID_V0: &str = "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n";
350        let parsed = Cid::try_from(VALID_CID).expect("fixture must be a valid CIDv1");
351        let uppercase = parsed
352            .to_string_of_base(cid::multibase::Base::Base32Upper)
353            .expect("base32 encoding");
354        let base58 = parsed
355            .to_string_of_base(cid::multibase::Base::Base58Btc)
356            .expect("base58 encoding");
357        let base64 = parsed
358            .to_string_of_base(cid::multibase::Base::Base64)
359            .expect("base64 encoding");
360        let ipfs_path = format!("/ipfs/{VALID_CID}");
361
362        for invalid in [
363            "",
364            " ",
365            "\t",
366            "not-a-cid",
367            CID_V0,
368            uppercase.as_str(),
369            base58.as_str(),
370            base64.as_str(),
371            ipfs_path.as_str(),
372        ] {
373            assert!(
374                TenantGrantArtifacts::new(invalid, VALID_CID, 7).is_err(),
375                "invalid grant reference unexpectedly accepted: {invalid:?}"
376            );
377            assert!(
378                TenantGrantArtifacts::new(VALID_CID, invalid, 7).is_err(),
379                "invalid allocation reference unexpectedly accepted: {invalid:?}"
380            );
381        }
382    }
383}