hyprstream_k8s/mesh.rs
1//! `mesh.hyprstream.io/v1alpha1` — [`TenantBinding`].
2//!
3//! [`TenantBinding`] is the **confused-deputy fix** from the epic #778 threat
4//! table: an explicit, admin-created mapping between a Kubernetes namespace and
5//! a hyprstream tenant. Creating one is gated by the `federation:register`
6//! scope. The reconcilers (K5b) treat a binding as the *only* authority that
7//! lets a resource in namespace `N` reference tenant `T`; any cross-binding
8//! reference a `TenantBinding` does not cover is refused at admission.
9//!
10//! It is deliberately **cluster-scoped**: a tenant confined to its own
11//! namespace must not be able to author the very binding that would grant it a
12//! tenant identity. Only a cluster admin (holding `federation:register`) may
13//! create these.
14//!
15//! # CRD → grant compilation (#929)
16//!
17//! A `TenantBinding` is an **admin-authorable surface**, never itself the
18//! authority: when [`TenantBindingSpec::entitlement`] is set, the operator
19//! *compiles* it into an issuer-signed UCAN grant (the operator signs as issuer)
20//! and a PDS allocation record that lands in the
21//! tenant's inventory (PDS collection `ai.hyprstream.ledger.allocation`). The
22//! enforcers (#781/#787/#790/#793/#794/#527) verify the *presented grant*, not
23//! the CRD — the CRD only carries authorable intent. The compiled CIDs + epoch
24//! are recorded in [`TenantBindingStatus`] as observed truth.
25//!
26//! Non-goal (per #921): a Kubernetes `ResourceQuota` as a central counter. The
27//! grant is a held, offline-verifiable capability; accounting lives in the cell
28//! ledger, never in a cluster-wide quota object.
29
30use kube::CustomResource;
31use schemars::JsonSchema;
32use serde::{Deserialize, Serialize};
33
34/// Desired state of a [`TenantBinding`]: namespace ↔ hyprstream tenant.
35///
36/// # Validation
37/// - `namespace` must be a valid DNS-1123 label.
38/// - `tenant` must be non-empty.
39///
40/// # Security
41/// Creating/updating a binding requires the `federation:register` scope. This
42/// object is the trust anchor for cross-tenant reference checks; it is
43/// cluster-scoped so it cannot be forged from inside a tenant namespace.
44#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, JsonSchema)]
45#[kube(
46 group = "mesh.hyprstream.io",
47 version = "v1alpha1",
48 kind = "TenantBinding",
49 plural = "tenantbindings",
50 singular = "tenantbinding",
51 shortname = "hstb",
52 status = "TenantBindingStatus",
53 category = "hyprstream",
54 doc = "Explicit, admin-created namespace ↔ hyprstream-tenant binding (the confused-deputy guard, gated by federation:register). Cluster-scoped so a tenant cannot forge its own binding. When spec.entitlement is set, the operator compiles it into an issuer-signed grant that lands in the tenant's inventory (#929).",
55 printcolumn = r#"{"name":"Namespace","type":"string","jsonPath":".spec.namespace"}"#,
56 printcolumn = r#"{"name":"Tenant","type":"string","jsonPath":".spec.tenant"}"#,
57 printcolumn = r#"{"name":"Bound","type":"boolean","jsonPath":".status.bound"}"#,
58 printcolumn = r#"{"name":"Grant","type":"string","jsonPath":".status.grantCid"}"#,
59 // `namespace` is a CEL reserved word, so the apiserver requires the field
60 // to be referenced with the `__namespace__` escape (same rule as the Go
61 // apiserver's `apiserver/schema/cel/model` escaping).
62 validation = "self.spec.__namespace__.size() <= 63 && self.spec.__namespace__.matches('^[a-z0-9]([-a-z0-9]*[a-z0-9])?$')",
63 validation = "self.spec.tenant != ''",
64 validation = "has(self.spec.entitlement) ? self.spec.entitlement.amount >= 0 : true",
65 validation = "has(self.spec.entitlement) ? self.spec.entitlement.unit.size() > 0 : true",
66 cel
67)]
68#[serde(rename_all = "camelCase")]
69pub struct TenantBindingSpec {
70 /// The Kubernetes namespace this binding authorizes.
71 pub namespace: String,
72
73 /// The hyprstream tenant identifier (e.g. an atproto DID) the namespace is
74 /// bound to. When [`Self::entitlement`] is set, this DID is the **holder**
75 /// the compiled grant is issued to and the PDS whose inventory receives the
76 /// allocation record.
77 pub tenant: String,
78
79 /// The resource entitlement an admin authors here and the operator compiles
80 /// into an issuer-signed grant (#929).
81 ///
82 /// `None` (the default) leaves the binding as the pure namespace↔tenant
83 /// mapping (the confused-deputy guard only — no grant is compiled, nothing
84 /// lands in the tenant's inventory). `Some` makes the operator sign a UCAN
85 /// grant as issuer and publish an `ai.hyprstream.ledger.allocation` record
86 /// into the tenant's inventory on reconcile.
87 ///
88 /// This field is the **authoring surface**; it is never itself the
89 /// authority. The enforcers verify the compiled grant, not the CRD.
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub entitlement: Option<TenantEntitlement>,
92}
93
94/// The authorable entitlement carried by a [`TenantBindingSpec`].
95///
96/// This is the k8s-side, dependency-free mirror of the fields a downstream
97/// [`crate::grant::TenantGrantService`] lowers into its authority artifacts.
98/// It deliberately re-uses no `hyprstream-pds` / `hyprstream-rpc` types so the
99/// CRD schema keeps compiling with no features and no cluster; the compiler
100/// validates and maps these into the issuer-signed grant artifacts.
101#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, JsonSchema)]
102#[serde(rename_all = "camelCase")]
103pub struct TenantEntitlement {
104 /// The issuer-scoped credit unit code (e.g. `"compute-second"`,
105 /// `"gpu-hour"`). The unit's issuer is the **operator's issuer DID** (the
106 /// key the operator signs the grant with), bound by the compiler — credits
107 /// are the unit-issuer's liability (D8-1), so the CRD never names the
108 /// issuer: it is always the binding's operator.
109 pub unit: String,
110
111 /// Granted amount, in the unit's smallest quantum (`u64`).
112 pub amount: u64,
113
114 /// Grant class — the anonymity↔recourse coupling (#928 rule 4):
115 /// `prepaid` (bearer-like, lease/prevention-only) or `underwritten`
116 /// (issuer-relationship, the only detect-mode-eligible class).
117 #[serde(default = "default_grant_class")]
118 pub class: TenantGrantClass,
119
120 /// Optional grant expiry (unix seconds). `None` = epoch-bound only (revoked
121 /// by bumping the allocation epoch, not by wall-clock expiry).
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub expiration: Option<u64>,
124}
125
126fn default_grant_class() -> TenantGrantClass {
127 TenantGrantClass::Underwritten
128}
129
130/// Service-neutral grant classification.
131///
132/// Serialized as the lexicon string (`"prepaid"` / `"underwritten"`) so the
133/// value is stable on the wire; downstream adapters map it to service types.
134#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq, JsonSchema)]
135#[serde(rename_all = "lowercase")]
136pub enum TenantGrantClass {
137 /// Bearer-like: paid up front, issuable to a bare `did:key` with no
138 /// identity; restricted to lease/prevention spend mode.
139 Prepaid,
140 /// Postpaid: the issuer has a real bilateral relationship with the holder
141 /// and recovers from cheaters itself. The default, and the only
142 /// detect-mode-eligible class.
143 #[default]
144 Underwritten,
145}
146
147impl TenantGrantClass {
148 /// Stable service-neutral string form.
149 pub fn as_str(self) -> &'static str {
150 match self {
151 TenantGrantClass::Prepaid => "prepaid",
152 TenantGrantClass::Underwritten => "underwritten",
153 }
154 }
155}
156
157/// Observed truth for a [`TenantBinding`]. Written only by the operator.
158#[derive(Serialize, Deserialize, Clone, Debug, Default, JsonSchema)]
159#[serde(rename_all = "camelCase")]
160pub struct TenantBindingStatus {
161 /// Whether the operator has accepted and activated this binding.
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub bound: Option<bool>,
164
165 /// Coarse lifecycle phase (`Pending`, `Bound`, `Rejected`, ...).
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub phase: Option<String>,
168
169 /// Human-readable detail, e.g. why a binding was rejected.
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub message: Option<String>,
172
173 /// `metadata.generation` last reconciled.
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub observed_generation: Option<i64>,
176
177 /// The CIDv1 of the compiled UCAN grant (the issuer-signed capability the
178 /// operator mints from [`TenantBindingSpec::entitlement`]). Enforcers
179 /// present and verify *this* CID; the CRD is only the authoring surface.
180 /// `None` until the operator has compiled the entitlement (#929).
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub grant_cid: Option<String>,
183
184 /// The CIDv1 of the `ai.hyprstream.ledger.allocation` record landed in the
185 /// tenant's inventory. This is the durable inventory line the holder
186 /// controls; the grant field inside it references [`Self::grant_cid`].
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub allocation_cid: Option<String>,
189
190 /// The issuance epoch of the compiled grant. Revocation = bumping this
191 /// counter (stop renewing + reissue at a new epoch); enforcers honor the
192 /// epoch, never an unbounded bearer token (#921).
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub epoch: Option<u64>,
195}