1use hyprstream_rpc::auth::mac::{
48 Assurance, CompartmentSet, Level, MacDecision, MacDenyReason, MacDispatchPep,
49 RpcObjectLabelResolver, SecurityContext, SecurityLabel,
50};
51use hyprstream_rpc::service::EnvelopeContext;
52
53pub const SERVICE_SUBJECT_PREFIX: &str = "service:";
59
60pub mod policy_methods {
69 pub const CHECK: u16 = 0;
74 pub const ISSUE_TOKEN: u16 = 1;
78 pub const GET_POLICY: u16 = 3;
80 pub const APPLY_TEMPLATE: u16 = 4;
82 pub const APPLY_DRAFT: u16 = 5;
84 pub const ROLLBACK: u16 = 6;
86 pub const GET_HISTORY: u16 = 7;
88 pub const GET_DIFF: u16 = 8;
90 pub const GET_DRAFT_STATUS: u16 = 9;
92 pub const ADD_GROUPING: u16 = 10;
94 pub const REMOVE_GROUPING: u16 = 11;
96 pub const REGISTER_SERVICE_KEY: u16 = 18;
99 pub const REFRESH_SERVICE_TOKEN: u16 = 19;
103}
104
105pub mod discovery_methods {
107 pub const ANNOUNCE: u16 = 8;
109}
110
111pub mod inference_methods {
123 pub const GENERATE_STREAM: u16 = 0;
125 pub const MODEL_INFO: u16 = 1;
126 pub const IS_READY: u16 = 2;
127 pub const APPLY_CHAT_TEMPLATE: u16 = 3;
128 pub const CREATE_LORA: u16 = 4;
129 pub const LOAD_LORA: u16 = 5;
130 pub const SAVE_LORA: u16 = 6;
131 pub const UNLOAD_LORA: u16 = 7;
132 pub const HAS_LORA: u16 = 8;
133 pub const SET_SESSION: u16 = 9;
134 pub const CLEAR_SESSION: u16 = 10;
135 pub const RELEASE_SESSION: u16 = 11;
136 pub const HEALTH_CHECK: u16 = 12;
137 pub const SHUTDOWN: u16 = 13;
139 pub const TTT_WRITEBACK: u16 = 14;
140 pub const TTT_EVICT: u16 = 15;
141 pub const TRAIN_STEP: u16 = 16;
142 pub const TTT_ZERO: u16 = 17;
143 pub const GET_DELTA_STATUS: u16 = 18;
144 pub const SAVE_ADAPTATION: u16 = 19;
145 pub const SNAPSHOT_DELTA: u16 = 20;
146 pub const TRAIN_STEP_STREAM: u16 = 21;
147 pub const EXPORT_PEFT_ADAPTER: u16 = 22;
148 pub const MERGE_LORA: u16 = 23;
149 pub const CREATE_LORA_STREAM: u16 = 24;
150 pub const LOAD_LORA_STREAM: u16 = 25;
151 pub const SAVE_LORA_STREAM: u16 = 26;
152 pub const SAVE_ADAPTATION_STREAM: u16 = 27;
153 pub const SNAPSHOT_DELTA_STREAM: u16 = 28;
154 pub const EXPORT_PEFT_ADAPTER_STREAM: u16 = 29;
155 pub const MERGE_LORA_STREAM: u16 = 30;
156 pub const EMBED: u16 = 31;
157 pub const GET_LAYER_PROFILE: u16 = 32;
158}
159
160pub const BOOTSTRAP_SERVICE_CLEARANCE: SecurityLabel = SecurityLabel {
166 level: Level::Internal,
167 assurance: Assurance::Classical,
168 compartments: CompartmentSet::EMPTY,
169};
170
171pub const OAUTH_ISSUANCE_LABEL: SecurityLabel = SecurityLabel {
179 level: Level::Internal,
180 assurance: Assurance::PqHybrid,
181 compartments: CompartmentSet::EMPTY,
182};
183
184pub const INFERENCE_METHOD_LABEL: SecurityLabel = SecurityLabel {
194 level: Level::Internal,
195 assurance: Assurance::PqHybrid,
196 compartments: CompartmentSet::EMPTY,
197};
198
199pub const HYBRID_SERVICE_CLEARANCE: SecurityLabel = SecurityLabel {
205 level: Level::Internal,
206 assurance: Assurance::PqHybrid,
207 compartments: CompartmentSet::EMPTY,
208};
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
214pub struct DispatchMethodId {
215 pub service: &'static str,
217 pub method: u16,
219}
220
221#[derive(Debug, Clone, Copy)]
224pub struct DispatchMethodPolicy {
225 pub id: DispatchMethodId,
227 pub method_name: &'static str,
230 pub label: SecurityLabel,
233 pub justification: &'static str,
235}
236
237#[derive(Debug, Clone, Copy)]
241pub struct ServiceSubjectClearance {
242 pub service: &'static str,
244 pub clearance: SecurityLabel,
247 pub justification: &'static str,
249}
250
251#[derive(Debug, Clone, Copy)]
256pub struct DeclaredDispatchTable {
257 methods: &'static [DispatchMethodPolicy],
258 clearances: &'static [ServiceSubjectClearance],
259}
260
261impl DeclaredDispatchTable {
262 #[must_use]
271 pub fn production() -> &'static Self {
272 &PRODUCTION_TABLE
273 }
274
275 #[must_use]
278 pub const fn from_rows(
279 methods: &'static [DispatchMethodPolicy],
280 clearances: &'static [ServiceSubjectClearance],
281 ) -> Self {
282 Self {
283 methods,
284 clearances,
285 }
286 }
287
288 #[must_use]
290 pub fn methods(&self) -> &'static [DispatchMethodPolicy] {
291 self.methods
292 }
293
294 #[must_use]
296 pub fn clearances(&self) -> &'static [ServiceSubjectClearance] {
297 self.clearances
298 }
299
300 #[must_use]
307 pub fn resolve_row(
308 &self,
309 service_domain: &str,
310 method: Option<&[u16]>,
311 ) -> Option<&DispatchMethodPolicy> {
312 let [method] = method? else {
315 return None;
316 };
317 self.methods
318 .iter()
319 .find(|row| row.id.service == service_domain && row.id.method == *method)
320 }
321
322 #[must_use]
328 pub fn service_clearance(&self, service: &str) -> Option<SecurityLabel> {
329 self.clearances
330 .iter()
331 .find(|row| row.service == service)
332 .map(|row| row.clearance)
333 }
334}
335
336impl RpcObjectLabelResolver for DeclaredDispatchTable {
337 fn resolve(&self, service_domain: &str, method: Option<&[u16]>) -> Option<SecurityLabel> {
341 self.resolve_row(service_domain, method)
342 .map(|row| row.label)
343 }
344}
345
346pub struct DeclaredDispatchPep {
372 table: &'static DeclaredDispatchTable,
373 activation_controlled: bool,
374}
375
376impl DeclaredDispatchPep {
377 #[must_use]
383 pub fn new(table: &'static DeclaredDispatchTable) -> Self {
384 Self {
385 table,
386 activation_controlled: false,
387 }
388 }
389
390 #[must_use]
393 pub fn with_activation_control(mut self) -> Self {
394 self.activation_controlled = true;
395 self
396 }
397
398 #[must_use]
400 pub fn table(&self) -> &'static DeclaredDispatchTable {
401 self.table
402 }
403
404 pub(crate) fn check_with_explicit_context(
412 &self,
413 ctx: &EnvelopeContext,
414 service_domain: &str,
415 method: Option<&[u16]>,
416 selected: SecurityContext,
417 ) -> MacDecision {
418 hyprstream_rpc::auth::mac::remember_verified_subject(ctx);
419 self.check_selected_context(ctx, service_domain, method, selected)
420 }
421
422 fn check_selected_context(
423 &self,
424 ctx: &EnvelopeContext,
425 service_domain: &str,
426 method: Option<&[u16]>,
427 selected: SecurityContext,
428 ) -> MacDecision {
429 let Some(service_name) = declared_service_subject(ctx) else {
430 return MacDecision::Deny(MacDenyReason::NoClearance);
431 };
432 let Some(declared_clearance) = self.table.service_clearance(&service_name) else {
433 return MacDecision::Deny(MacDenyReason::NoClearance);
434 };
435 let service_ctx =
436 SecurityContext::from_clearance(declared_clearance, ctx.verified_key_material());
437
438 let Some(row) = self.table.resolve_row(service_domain, method) else {
439 return MacDecision::Deny(MacDenyReason::UnlabeledObject);
440 };
441
442 if selected.can_access(&row.label) && service_ctx.can_access(&row.label) {
443 MacDecision::Permit
444 } else {
445 MacDecision::Deny(MacDenyReason::FloorDeny)
446 }
447 }
448}
449
450fn declared_service_subject(ctx: &EnvelopeContext) -> Option<String> {
458 ctx.authenticated_signer_key()?;
459 let subject = ctx.subject();
460 let name = subject.name()?;
461 name.strip_prefix(SERVICE_SUBJECT_PREFIX)
462 .filter(|suffix| !suffix.is_empty())
463 .map(str::to_owned)
464}
465
466impl MacDispatchPep for DeclaredDispatchPep {
467 fn check(
468 &self,
469 ctx: &EnvelopeContext,
470 service_domain: &str,
471 method: Option<&[u16]>,
472 ) -> MacDecision {
473 hyprstream_rpc::auth::mac::remember_verified_subject(ctx);
477
478 let selected = if self.activation_controlled {
481 hyprstream_rpc::auth::mac::global_mac_activation_control()
482 .select_context(ctx.security_context())
483 } else {
484 ctx.security_context()
485 };
486 let Some(selected) = selected else {
487 return MacDecision::Deny(MacDenyReason::NoClearance);
488 };
489
490 self.check_selected_context(ctx, service_domain, method, selected)
494 }
495}
496
497static BOOTSTRAP_METHODS: &[DispatchMethodPolicy] = &[
500 DispatchMethodPolicy {
501 id: DispatchMethodId {
502 service: "discovery",
503 method: discovery_methods::ANNOUNCE,
504 },
505 method_name: "announce",
506 label: HYBRID_SERVICE_CLEARANCE,
507 justification: "native endpoint publication requires the schema-declared internal:pq-hybrid context; Discovery additionally verifies the service credential, signer binding, and accepted current identity state",
508 },
509 DispatchMethodPolicy {
510 id: DispatchMethodId {
511 service: "inference",
512 method: inference_methods::GENERATE_STREAM,
513 },
514 method_name: "generateStream",
515 label: INFERENCE_METHOD_LABEL,
516 justification: "tenant-authorized generation/embedding against the admitted engine; the handler enforces tenant binding, model admission, and the spend ledger (infer scope; schema-declared internal:pq-hybrid)",
517 },
518 DispatchMethodPolicy {
519 id: DispatchMethodId {
520 service: "inference",
521 method: inference_methods::MODEL_INFO,
522 },
523 method_name: "modelInfo",
524 label: INFERENCE_METHOD_LABEL,
525 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
526 },
527 DispatchMethodPolicy {
528 id: DispatchMethodId {
529 service: "inference",
530 method: inference_methods::IS_READY,
531 },
532 method_name: "isReady",
533 label: INFERENCE_METHOD_LABEL,
534 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
535 },
536 DispatchMethodPolicy {
537 id: DispatchMethodId {
538 service: "inference",
539 method: inference_methods::APPLY_CHAT_TEMPLATE,
540 },
541 method_name: "applyChatTemplate",
542 label: INFERENCE_METHOD_LABEL,
543 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
544 },
545 DispatchMethodPolicy {
546 id: DispatchMethodId {
547 service: "inference",
548 method: inference_methods::CREATE_LORA,
549 },
550 method_name: "createLora",
551 label: INFERENCE_METHOD_LABEL,
552 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
553 },
554 DispatchMethodPolicy {
555 id: DispatchMethodId {
556 service: "inference",
557 method: inference_methods::LOAD_LORA,
558 },
559 method_name: "loadLora",
560 label: INFERENCE_METHOD_LABEL,
561 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
562 },
563 DispatchMethodPolicy {
564 id: DispatchMethodId {
565 service: "inference",
566 method: inference_methods::SAVE_LORA,
567 },
568 method_name: "saveLora",
569 label: INFERENCE_METHOD_LABEL,
570 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
571 },
572 DispatchMethodPolicy {
573 id: DispatchMethodId {
574 service: "inference",
575 method: inference_methods::UNLOAD_LORA,
576 },
577 method_name: "unloadLora",
578 label: INFERENCE_METHOD_LABEL,
579 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
580 },
581 DispatchMethodPolicy {
582 id: DispatchMethodId {
583 service: "inference",
584 method: inference_methods::HAS_LORA,
585 },
586 method_name: "hasLora",
587 label: INFERENCE_METHOD_LABEL,
588 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
589 },
590 DispatchMethodPolicy {
591 id: DispatchMethodId {
592 service: "inference",
593 method: inference_methods::SET_SESSION,
594 },
595 method_name: "setSession",
596 label: INFERENCE_METHOD_LABEL,
597 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
598 },
599 DispatchMethodPolicy {
600 id: DispatchMethodId {
601 service: "inference",
602 method: inference_methods::CLEAR_SESSION,
603 },
604 method_name: "clearSession",
605 label: INFERENCE_METHOD_LABEL,
606 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
607 },
608 DispatchMethodPolicy {
609 id: DispatchMethodId {
610 service: "inference",
611 method: inference_methods::RELEASE_SESSION,
612 },
613 method_name: "releaseSession",
614 label: INFERENCE_METHOD_LABEL,
615 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
616 },
617 DispatchMethodPolicy {
618 id: DispatchMethodId {
619 service: "inference",
620 method: inference_methods::HEALTH_CHECK,
621 },
622 method_name: "healthCheck",
623 label: INFERENCE_METHOD_LABEL,
624 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
625 },
626 DispatchMethodPolicy {
627 id: DispatchMethodId {
628 service: "inference",
629 method: inference_methods::SHUTDOWN,
630 },
631 method_name: "shutdown",
632 label: INFERENCE_METHOD_LABEL,
633 justification: "engine lifecycle management restricted to the verified hybrid model-service authority; the handler retains its own admission checks (manage scope; schema-declared internal:pq-hybrid)",
634 },
635 DispatchMethodPolicy {
636 id: DispatchMethodId {
637 service: "inference",
638 method: inference_methods::TTT_WRITEBACK,
639 },
640 method_name: "tttWriteback",
641 label: INFERENCE_METHOD_LABEL,
642 justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
643 },
644 DispatchMethodPolicy {
645 id: DispatchMethodId {
646 service: "inference",
647 method: inference_methods::TTT_EVICT,
648 },
649 method_name: "tttEvict",
650 label: INFERENCE_METHOD_LABEL,
651 justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
652 },
653 DispatchMethodPolicy {
654 id: DispatchMethodId {
655 service: "inference",
656 method: inference_methods::TRAIN_STEP,
657 },
658 method_name: "trainStep",
659 label: INFERENCE_METHOD_LABEL,
660 justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
661 },
662 DispatchMethodPolicy {
663 id: DispatchMethodId {
664 service: "inference",
665 method: inference_methods::TTT_ZERO,
666 },
667 method_name: "tttZero",
668 label: INFERENCE_METHOD_LABEL,
669 justification: "engine lifecycle management restricted to the verified hybrid model-service authority; the handler retains its own admission checks (manage scope; schema-declared internal:pq-hybrid)",
670 },
671 DispatchMethodPolicy {
672 id: DispatchMethodId {
673 service: "inference",
674 method: inference_methods::GET_DELTA_STATUS,
675 },
676 method_name: "getDeltaStatus",
677 label: INFERENCE_METHOD_LABEL,
678 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
679 },
680 DispatchMethodPolicy {
681 id: DispatchMethodId {
682 service: "inference",
683 method: inference_methods::SAVE_ADAPTATION,
684 },
685 method_name: "saveAdaptation",
686 label: INFERENCE_METHOD_LABEL,
687 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
688 },
689 DispatchMethodPolicy {
690 id: DispatchMethodId {
691 service: "inference",
692 method: inference_methods::SNAPSHOT_DELTA,
693 },
694 method_name: "snapshotDelta",
695 label: INFERENCE_METHOD_LABEL,
696 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
697 },
698 DispatchMethodPolicy {
699 id: DispatchMethodId {
700 service: "inference",
701 method: inference_methods::TRAIN_STEP_STREAM,
702 },
703 method_name: "trainStepStream",
704 label: INFERENCE_METHOD_LABEL,
705 justification: "TTT training/adaptation step against the tenant-bound engine; the handler enforces tenant binding (train scope; schema-declared internal:pq-hybrid)",
706 },
707 DispatchMethodPolicy {
708 id: DispatchMethodId {
709 service: "inference",
710 method: inference_methods::EXPORT_PEFT_ADAPTER,
711 },
712 method_name: "exportPeftAdapter",
713 label: INFERENCE_METHOD_LABEL,
714 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
715 },
716 DispatchMethodPolicy {
717 id: DispatchMethodId {
718 service: "inference",
719 method: inference_methods::MERGE_LORA,
720 },
721 method_name: "mergeLora",
722 label: INFERENCE_METHOD_LABEL,
723 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
724 },
725 DispatchMethodPolicy {
726 id: DispatchMethodId {
727 service: "inference",
728 method: inference_methods::CREATE_LORA_STREAM,
729 },
730 method_name: "createLoraStream",
731 label: INFERENCE_METHOD_LABEL,
732 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
733 },
734 DispatchMethodPolicy {
735 id: DispatchMethodId {
736 service: "inference",
737 method: inference_methods::LOAD_LORA_STREAM,
738 },
739 method_name: "loadLoraStream",
740 label: INFERENCE_METHOD_LABEL,
741 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
742 },
743 DispatchMethodPolicy {
744 id: DispatchMethodId {
745 service: "inference",
746 method: inference_methods::SAVE_LORA_STREAM,
747 },
748 method_name: "saveLoraStream",
749 label: INFERENCE_METHOD_LABEL,
750 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
751 },
752 DispatchMethodPolicy {
753 id: DispatchMethodId {
754 service: "inference",
755 method: inference_methods::SAVE_ADAPTATION_STREAM,
756 },
757 method_name: "saveAdaptationStream",
758 label: INFERENCE_METHOD_LABEL,
759 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
760 },
761 DispatchMethodPolicy {
762 id: DispatchMethodId {
763 service: "inference",
764 method: inference_methods::SNAPSHOT_DELTA_STREAM,
765 },
766 method_name: "snapshotDeltaStream",
767 label: INFERENCE_METHOD_LABEL,
768 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
769 },
770 DispatchMethodPolicy {
771 id: DispatchMethodId {
772 service: "inference",
773 method: inference_methods::EXPORT_PEFT_ADAPTER_STREAM,
774 },
775 method_name: "exportPeftAdapterStream",
776 label: INFERENCE_METHOD_LABEL,
777 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
778 },
779 DispatchMethodPolicy {
780 id: DispatchMethodId {
781 service: "inference",
782 method: inference_methods::MERGE_LORA_STREAM,
783 },
784 method_name: "mergeLoraStream",
785 label: INFERENCE_METHOD_LABEL,
786 justification: "tenant-scoped engine/adaptation lifecycle; the handler enforces tenant binding, admission, and rollback windows (write scope; schema-declared internal:pq-hybrid)",
787 },
788 DispatchMethodPolicy {
789 id: DispatchMethodId {
790 service: "inference",
791 method: inference_methods::EMBED,
792 },
793 method_name: "embed",
794 label: INFERENCE_METHOD_LABEL,
795 justification: "tenant-authorized generation/embedding against the admitted engine; the handler enforces tenant binding, model admission, and the spend ledger (infer scope; schema-declared internal:pq-hybrid)",
796 },
797 DispatchMethodPolicy {
798 id: DispatchMethodId {
799 service: "inference",
800 method: inference_methods::GET_LAYER_PROFILE,
801 },
802 method_name: "getLayerProfile",
803 label: INFERENCE_METHOD_LABEL,
804 justification: "read-only introspection of the admitted engine; the handler retains tenant binding and readiness gating (query scope; schema-declared internal:pq-hybrid)",
805 },
806 DispatchMethodPolicy {
807 id: DispatchMethodId { service: "policy", method: policy_methods::CHECK },
808 method_name: "check",
809 label: SecurityLabel::bottom(),
810 justification: "authenticated declared services mediate PolicyService authorization checks; the handler derives subject and domain from the verified envelope and Casbin retains the federation decision",
811 },
812 DispatchMethodPolicy {
813 id: DispatchMethodId { service: "policy", method: policy_methods::ISSUE_TOKEN },
814 method_name: "issueToken",
815 label: OAUTH_ISSUANCE_LABEL,
816 justification: "the OAuth authority mints a session-bound credential through the schema-declared internal:pq-hybrid signing boundary; only a verified hybrid service:oauth envelope can dominate this row, while PolicyService retains target-tenant policy:IssueToken/manage, subject, tenant, audience, scope, session, client, confirmation, and signing checks",
817 },
818 DispatchMethodPolicy {
819 id: DispatchMethodId { service: "policy", method: policy_methods::GET_POLICY },
820 method_name: "getPolicy",
821 label: SecurityLabel::bottom(),
822 justification: "verified local PolicyService control-plane read; only the tokenless policy authority reaches this row",
823 },
824 DispatchMethodPolicy {
825 id: DispatchMethodId { service: "policy", method: policy_methods::APPLY_TEMPLATE },
826 method_name: "applyTemplate",
827 label: SecurityLabel::bottom(),
828 justification: "verified local PolicyService installs a reviewed bootstrap template; the handler still enforces Casbin writeback",
829 },
830 DispatchMethodPolicy {
831 id: DispatchMethodId { service: "policy", method: policy_methods::APPLY_DRAFT },
832 method_name: "applyDraft",
833 label: SecurityLabel::bottom(),
834 justification: "verified local PolicyService commits a local draft; the handler still enforces Casbin writeback",
835 },
836 DispatchMethodPolicy {
837 id: DispatchMethodId { service: "policy", method: policy_methods::ROLLBACK },
838 method_name: "rollback",
839 label: SecurityLabel::bottom(),
840 justification: "verified local PolicyService restores a local revision; the handler still enforces Casbin writeback",
841 },
842 DispatchMethodPolicy {
843 id: DispatchMethodId { service: "policy", method: policy_methods::GET_HISTORY },
844 method_name: "getHistory",
845 label: SecurityLabel::bottom(),
846 justification: "verified local PolicyService control-plane history read; only the tokenless policy authority reaches this row",
847 },
848 DispatchMethodPolicy {
849 id: DispatchMethodId { service: "policy", method: policy_methods::GET_DIFF },
850 method_name: "getDiff",
851 label: SecurityLabel::bottom(),
852 justification: "verified local PolicyService control-plane draft inspection; only the tokenless policy authority reaches this row",
853 },
854 DispatchMethodPolicy {
855 id: DispatchMethodId { service: "policy", method: policy_methods::GET_DRAFT_STATUS },
856 method_name: "getDraftStatus",
857 label: SecurityLabel::bottom(),
858 justification: "verified local PolicyService draft-state inspection; only the tokenless policy authority reaches this row",
859 },
860 DispatchMethodPolicy {
861 id: DispatchMethodId { service: "policy", method: policy_methods::ADD_GROUPING },
862 method_name: "addGrouping",
863 label: SecurityLabel::bottom(),
864 justification: "verified local PolicyService role update; the handler still enforces Casbin writeback",
865 },
866 DispatchMethodPolicy {
867 id: DispatchMethodId { service: "policy", method: policy_methods::REMOVE_GROUPING },
868 method_name: "removeGrouping",
869 label: SecurityLabel::bottom(),
870 justification: "verified local PolicyService role removal; the handler still enforces Casbin writeback",
871 },
872 DispatchMethodPolicy {
873 id: DispatchMethodId {
874 service: "policy",
875 method: policy_methods::REGISTER_SERVICE_KEY,
876 },
877 method_name: "registerServiceKey",
878 label: SecurityLabel::bottom(),
879 justification: "a keyed service installs its identity with the CA; \
880 bootstrap-critical (it precedes identity standing) and reachable \
881 only by declared service subjects; handler-level CA-JWT, subject, \
882 and cnf binding checks are unchanged",
883 },
884 DispatchMethodPolicy {
885 id: DispatchMethodId {
886 service: "policy",
887 method: policy_methods::REFRESH_SERVICE_TOKEN,
888 },
889 method_name: "refreshServiceToken",
890 label: SecurityLabel::bottom(),
891 justification: "a registered service renews the identity registration \
892 created; same bootstrap identity-lifecycle class — the handler \
893 re-binds cnf to the verified caller key and requires prior \
894 registration",
895 },
896];
897
898static BOOTSTRAP_SERVICE_CLEARANCES: &[ServiceSubjectClearance] = &[
899 ServiceSubjectClearance {
900 service: "discovery",
901 clearance: HYBRID_SERVICE_CLEARANCE,
902 justification: "the hybrid-enrolled discovery identity publishes its accepted native endpoint; verified envelope material clamps assurance",
903 },
904 ServiceSubjectClearance {
905 service: "event",
906 clearance: HYBRID_SERVICE_CLEARANCE,
907 justification: "the hybrid-enrolled event service publishes its accepted native endpoint; verified envelope material clamps assurance",
908 },
909 ServiceSubjectClearance {
910 service: "inference",
911 clearance: HYBRID_SERVICE_CLEARANCE,
912 justification: "the hybrid-enrolled engine service answers the declared \
913 internal:pq-hybrid inference rows; its handler retains tenant \
914 binding, admission, and spend-ledger checks",
915 },
916 ServiceSubjectClearance {
917 service: "model",
918 clearance: HYBRID_SERVICE_CLEARANCE,
919 justification: "the hybrid-enrolled model service mediates tenant- \
920 authorized generation to the schema-declared internal:pq-hybrid \
921 inference surface; its load/tenant admission checks are unchanged",
922 },
923 ServiceSubjectClearance {
924 service: "oai",
925 clearance: HYBRID_SERVICE_CLEARANCE,
926 justification: "the hybrid-enrolled OpenAI-compatible API bridges \
927 verified browser sessions to the schema-declared internal:pq- \
928 hybrid model/inference surfaces; session and tenant authorization \
929 run at this layer",
930 },
931 ServiceSubjectClearance {
932 service: "oauth",
933 clearance: OAUTH_ISSUANCE_LABEL,
934 justification: "the verified hybrid OAuth authority performs the declared internal:pq-hybrid session-token issuance boundary; its exact typed row and PolicyService authorization remain mandatory",
935 },
936 ServiceSubjectClearance {
937 service: "policy",
938 clearance: HYBRID_SERVICE_CLEARANCE,
939 justification: "the CA itself; its local control-plane rows are separately \
940 restricted to the verified tokenless service:policy authority",
941 },
942 ServiceSubjectClearance {
943 service: "registry",
944 clearance: HYBRID_SERVICE_CLEARANCE,
945 justification: "service/model registration is part of boot; registry \
946 registers its key at boot",
947 },
948 ServiceSubjectClearance {
949 service: "streams",
950 clearance: HYBRID_SERVICE_CLEARANCE,
951 justification: "the hybrid-enrolled streams service publishes its accepted native endpoint; stream authorization remains in its handler",
952 },
953];
954
955static PRODUCTION_TABLE: DeclaredDispatchTable =
956 DeclaredDispatchTable::from_rows(BOOTSTRAP_METHODS, BOOTSTRAP_SERVICE_CLEARANCES);
957
958#[cfg(test)]
959#[allow(clippy::unwrap_used, clippy::expect_used)]
960mod tests {
961 use super::*;
962
963 fn service_subject_ctx(service: &str, key_byte: u8) -> EnvelopeContext {
966 let signer = ed25519_dalek::SigningKey::from_bytes(&[key_byte; 32]);
967 let claims = hyprstream_rpc::auth::Claims::new(format!("service:{service}"), 1, i64::MAX)
968 .with_clearance(BOOTSTRAP_SERVICE_CLEARANCE);
969 EnvelopeContext::for_test_authenticated_subject_with_claims(
970 hyprstream_rpc::Subject::new(format!("service:{service}")),
971 "test-tenant",
972 signer.verifying_key(),
973 claims,
974 )
975 }
976
977 fn user_subject_ctx() -> EnvelopeContext {
978 let signer = ed25519_dalek::SigningKey::from_bytes(&[0x77; 32]);
979 EnvelopeContext::for_test_authenticated_subject(
980 hyprstream_rpc::Subject::new("did:web:alice"),
981 signer.verifying_key(),
982 )
983 }
984
985 fn production_pep() -> DeclaredDispatchPep {
988 DeclaredDispatchPep::new(DeclaredDispatchTable::production()).with_activation_control()
989 }
990
991 #[test]
994 fn every_declared_call_resolves_to_the_intended_typed_label_and_clearance() {
995 let table = DeclaredDispatchTable::production();
996
997 let expected: &[(u16, &str)] = &[
1002 (policy_methods::CHECK, "check"),
1003 (policy_methods::ISSUE_TOKEN, "issueToken"),
1004 (policy_methods::GET_POLICY, "getPolicy"),
1005 (policy_methods::APPLY_TEMPLATE, "applyTemplate"),
1006 (policy_methods::APPLY_DRAFT, "applyDraft"),
1007 (policy_methods::ROLLBACK, "rollback"),
1008 (policy_methods::GET_HISTORY, "getHistory"),
1009 (policy_methods::GET_DIFF, "getDiff"),
1010 (policy_methods::GET_DRAFT_STATUS, "getDraftStatus"),
1011 (policy_methods::ADD_GROUPING, "addGrouping"),
1012 (policy_methods::REMOVE_GROUPING, "removeGrouping"),
1013 (policy_methods::REGISTER_SERVICE_KEY, "registerServiceKey"),
1014 (policy_methods::REFRESH_SERVICE_TOKEN, "refreshServiceToken"),
1015 ];
1016 assert!(
1017 table.methods().len() > expected.len(),
1018 "the table must also carry the inference surface declared below"
1019 );
1020 for (method, name) in expected {
1021 let row = table
1022 .resolve_row("policy", Some(&[*method]))
1023 .unwrap_or_else(|| panic!("declared row for policy.{name} must resolve"));
1024 assert_eq!(row.method_name, *name);
1025 assert_eq!(row.id.service, "policy");
1026 let expected_label = if *method == policy_methods::ISSUE_TOKEN {
1027 OAUTH_ISSUANCE_LABEL
1028 } else {
1029 SecurityLabel::bottom()
1030 };
1031 assert_eq!(
1032 row.label, expected_label,
1033 "declared row {name} must retain its reviewed schema/bootstrap label"
1034 );
1035 assert!(!row.justification.is_empty());
1036 }
1037
1038 const INFERENCE_EXPECTED: &[(u16, &str)] = &[
1040 (inference_methods::GENERATE_STREAM, "generateStream"),
1041 (inference_methods::MODEL_INFO, "modelInfo"),
1042 (inference_methods::IS_READY, "isReady"),
1043 (inference_methods::APPLY_CHAT_TEMPLATE, "applyChatTemplate"),
1044 (inference_methods::CREATE_LORA, "createLora"),
1045 (inference_methods::LOAD_LORA, "loadLora"),
1046 (inference_methods::SAVE_LORA, "saveLora"),
1047 (inference_methods::UNLOAD_LORA, "unloadLora"),
1048 (inference_methods::HAS_LORA, "hasLora"),
1049 (inference_methods::SET_SESSION, "setSession"),
1050 (inference_methods::CLEAR_SESSION, "clearSession"),
1051 (inference_methods::RELEASE_SESSION, "releaseSession"),
1052 (inference_methods::HEALTH_CHECK, "healthCheck"),
1053 (inference_methods::SHUTDOWN, "shutdown"),
1054 (inference_methods::TTT_WRITEBACK, "tttWriteback"),
1055 (inference_methods::TTT_EVICT, "tttEvict"),
1056 (inference_methods::TRAIN_STEP, "trainStep"),
1057 (inference_methods::TTT_ZERO, "tttZero"),
1058 (inference_methods::GET_DELTA_STATUS, "getDeltaStatus"),
1059 (inference_methods::SAVE_ADAPTATION, "saveAdaptation"),
1060 (inference_methods::SNAPSHOT_DELTA, "snapshotDelta"),
1061 (inference_methods::TRAIN_STEP_STREAM, "trainStepStream"),
1062 (inference_methods::EXPORT_PEFT_ADAPTER, "exportPeftAdapter"),
1063 (inference_methods::MERGE_LORA, "mergeLora"),
1064 (inference_methods::CREATE_LORA_STREAM, "createLoraStream"),
1065 (inference_methods::LOAD_LORA_STREAM, "loadLoraStream"),
1066 (inference_methods::SAVE_LORA_STREAM, "saveLoraStream"),
1067 (
1068 inference_methods::SAVE_ADAPTATION_STREAM,
1069 "saveAdaptationStream",
1070 ),
1071 (
1072 inference_methods::SNAPSHOT_DELTA_STREAM,
1073 "snapshotDeltaStream",
1074 ),
1075 (
1076 inference_methods::EXPORT_PEFT_ADAPTER_STREAM,
1077 "exportPeftAdapterStream",
1078 ),
1079 (inference_methods::MERGE_LORA_STREAM, "mergeLoraStream"),
1080 (inference_methods::EMBED, "embed"),
1081 (inference_methods::GET_LAYER_PROFILE, "getLayerProfile"),
1082 ];
1083 for (method, name) in INFERENCE_EXPECTED {
1084 let row = table
1085 .resolve_row("inference", Some(&[*method]))
1086 .unwrap_or_else(|| panic!("declared row for inference.{name} must resolve"));
1087 assert_eq!(row.method_name, *name);
1088 assert_eq!(row.id.service, "inference");
1089 assert_eq!(
1090 row.label, INFERENCE_METHOD_LABEL,
1091 "inference.{name} must retain its schema-declared hybrid label"
1092 );
1093 assert!(!row.justification.is_empty());
1094 }
1095
1096 let mut services: Vec<&str> = table.clearances().iter().map(|row| row.service).collect();
1100 services.sort_unstable();
1101 assert_eq!(
1102 services,
1103 [
1104 "discovery",
1105 "event",
1106 "inference",
1107 "model",
1108 "oai",
1109 "oauth",
1110 "policy",
1111 "registry",
1112 "streams"
1113 ]
1114 );
1115 const HYBRID_SERVICES: &[&str] = &[
1118 "discovery",
1119 "event",
1120 "inference",
1121 "model",
1122 "oai",
1123 "oauth",
1124 "policy",
1125 "registry",
1126 "streams",
1127 ];
1128 for row in table.clearances() {
1129 let is_hybrid = HYBRID_SERVICES.contains(&row.service);
1130 let expected_clearance = match row.service {
1131 "oauth" => OAUTH_ISSUANCE_LABEL,
1132 "discovery" | "event" | "model" | "oai" | "inference" | "policy" | "registry"
1133 | "streams" => HYBRID_SERVICE_CLEARANCE,
1134 _ => BOOTSTRAP_SERVICE_CLEARANCE,
1135 };
1136 assert_eq!(row.clearance, expected_clearance);
1137 assert_eq!(
1138 table.service_clearance(row.service),
1139 Some(row.clearance),
1140 "clearance lookup by canonical name"
1141 );
1142 assert!(!row.justification.is_empty());
1143 for method in table.methods() {
1144 let ctx = SecurityContext::from_clearance(
1145 row.clearance,
1146 if is_hybrid {
1147 hyprstream_rpc::auth::mac::VerifiedKeyMaterial::PqHybrid
1148 } else {
1149 hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical
1150 },
1151 );
1152 let expected = is_hybrid || method.label == SecurityLabel::bottom();
1158 assert_eq!(
1159 ctx.can_access(&method.label),
1160 expected,
1161 "{} against {} ({})",
1162 row.service,
1163 method.label,
1164 method.method_name
1165 );
1166 }
1167 }
1168 }
1169
1170 #[test]
1171 fn table_has_no_duplicate_or_unsorted_rows() {
1172 let table = DeclaredDispatchTable::production();
1173 let ids: Vec<DispatchMethodId> = table.methods().iter().map(|row| row.id).collect();
1174 let mut sorted = ids.clone();
1175 sorted.sort();
1176 sorted.dedup();
1177 assert_eq!(ids, sorted, "method rows must be sorted and unique");
1178 let services: Vec<&str> = table.clearances().iter().map(|row| row.service).collect();
1179 let mut sorted_services = services.clone();
1180 sorted_services.sort_unstable();
1181 sorted_services.dedup();
1182 assert_eq!(
1183 services, sorted_services,
1184 "clearance rows must be sorted and unique"
1185 );
1186 }
1187
1188 #[test]
1189 fn native_announce_row_matches_schema_and_requires_hybrid_identity() {
1190 let mut message = capnp::message::Builder::new_default();
1191 message
1192 .init_root::<hyprstream_rpc_std::discovery_capnp::discovery_request::Builder>()
1193 .init_announce();
1194 let bytes = capnp::serialize::write_message_to_words(&message);
1195 let method =
1196 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap();
1197 assert_eq!(method, discovery_methods::ANNOUNCE);
1198 let table = DeclaredDispatchTable::production();
1199 let row = table.resolve_row("discovery", Some(&[method])).unwrap();
1200 assert_eq!(row.method_name, "announce");
1201 assert_eq!(row.label, HYBRID_SERVICE_CLEARANCE);
1202 let pep = DeclaredDispatchPep::new(table);
1203 for service in [
1204 "policy",
1205 "discovery",
1206 "registry",
1207 "event",
1208 "streams",
1209 "model",
1210 "oai",
1211 "oauth",
1212 ] {
1213 let clearance = table.service_clearance(service).unwrap();
1214 assert!(SecurityContext::from_clearance(
1215 clearance,
1216 hyprstream_rpc::auth::mac::VerifiedKeyMaterial::PqHybrid
1217 )
1218 .can_access(&row.label));
1219 assert!(!SecurityContext::from_clearance(
1220 clearance,
1221 hyprstream_rpc::auth::mac::VerifiedKeyMaterial::Classical
1222 )
1223 .can_access(&row.label));
1224 let ctx = EnvelopeContext::for_test_authenticated_subject(
1225 hyprstream_rpc::Subject::new(format!("service:{service}")),
1226 ed25519_dalek::SigningKey::from_bytes(&[0x31; 32]).verifying_key(),
1227 );
1228 assert_eq!(
1229 pep.check(&ctx, "discovery", Some(&[method])),
1230 MacDecision::Deny(MacDenyReason::NoClearance),
1231 "bearerless identity cannot announce"
1232 );
1233 }
1234 assert!(table.resolve_row("discovery", Some(&[method, 0])).is_none());
1235 assert!(table.resolve_row("discovery", Some(&[u16::MAX])).is_none());
1236 }
1237
1238 #[test]
1241 fn unknown_service_unknown_leaf_and_vfs_alias_resolve_to_none() {
1242 let table = DeclaredDispatchTable::production();
1243
1244 assert!(table
1246 .resolve_row("ghost", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1247 .is_none());
1248 assert!(table.resolve_row("policy", Some(&[17])).is_none());
1252 assert!(table.resolve_row("policy", Some(&[u16::MAX])).is_none());
1254 assert!(table.resolve_row("policy", None).is_none());
1257 for alias in ["/srv/policy", "srv/policy", "/policy", "policy/", "/"] {
1259 assert!(
1260 table
1261 .resolve_row(alias, Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1262 .is_none(),
1263 "VFS-shaped alias {alias:?} must not resolve"
1264 );
1265 }
1266 assert!(table
1268 .resolve_row("Policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1269 .is_none());
1270 assert!(table
1271 .resolve_row(" policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1272 .is_none());
1273 assert!(table.service_clearance("ghost").is_none());
1275 assert!(table.service_clearance("metrics").is_none());
1276
1277 let resolver: &dyn RpcObjectLabelResolver = table;
1279 assert!(resolver
1280 .resolve("policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1281 .is_some());
1282 assert!(resolver.resolve("policy", Some(&[17])).is_none());
1283 assert!(resolver
1284 .resolve("/srv/policy", Some(&[policy_methods::REGISTER_SERVICE_KEY]))
1285 .is_none());
1286 }
1287
1288 #[test]
1291 fn declared_call_permits_and_identical_undeclared_call_denies() {
1292 let pep = production_pep();
1293 let caller = service_subject_ctx("discovery", 0x61);
1294
1295 let declared = pep.check(
1297 &caller,
1298 "policy",
1299 Some(&[policy_methods::REGISTER_SERVICE_KEY]),
1300 );
1301 assert_eq!(
1302 declared,
1303 MacDecision::Permit,
1304 "declared (policy, registerServiceKey) from declared discovery must permit"
1305 );
1306
1307 let undeclared = pep.check(&caller, "policy", Some(&[17]));
1309 assert_eq!(
1310 undeclared,
1311 MacDecision::Deny(MacDenyReason::UnlabeledObject),
1312 "an otherwise identical undeclared call must deny UnlabeledObject"
1313 );
1314
1315 assert_eq!(
1317 pep.check(
1318 &caller,
1319 "ghost",
1320 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1321 ),
1322 MacDecision::Deny(MacDenyReason::UnlabeledObject)
1323 );
1324
1325 assert_eq!(
1328 pep.check(
1329 &caller,
1330 "/srv/policy",
1331 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1332 ),
1333 MacDecision::Deny(MacDenyReason::UnlabeledObject)
1334 );
1335
1336 assert_eq!(
1338 pep.check(&caller, "policy", None),
1339 MacDecision::Deny(MacDenyReason::UnlabeledObject)
1340 );
1341 }
1342
1343 #[test]
1344 fn authenticated_oauth_policy_methods_require_exact_declared_hybrid_authority() {
1345 let pep = production_pep();
1346 let oauth = service_subject_ctx("oauth", 0x66);
1347
1348 assert_eq!(
1352 pep.check(&oauth, "policy", Some(&[policy_methods::CHECK])),
1353 MacDecision::Permit,
1354 "verified service:oauth must reach the declared policy.check leaf"
1355 );
1356
1357 assert_eq!(
1361 pep.check(&oauth, "policy", Some(&[policy_methods::ISSUE_TOKEN])),
1362 MacDecision::Deny(MacDenyReason::FloorDeny),
1363 "a classical envelope must not reach the PQ-hybrid token issuer"
1364 );
1365
1366 let ghost = service_subject_ctx("ghost", 0x67);
1370 assert_eq!(
1371 pep.check(&ghost, "policy", Some(&[policy_methods::CHECK])),
1372 MacDecision::Deny(MacDenyReason::NoClearance)
1373 );
1374 let user = user_subject_ctx();
1375 assert_eq!(
1376 pep.check(&user, "policy", Some(&[policy_methods::CHECK])),
1377 MacDecision::Deny(MacDenyReason::NoClearance)
1378 );
1379 let callback = EnvelopeContext::from_callback_service(1, "oauth");
1380 assert_eq!(
1381 pep.check(&callback, "policy", Some(&[policy_methods::CHECK])),
1382 MacDecision::Deny(MacDenyReason::NoClearance)
1383 );
1384 }
1385
1386 #[test]
1387 fn permit_requires_the_deliberate_service_clearance_not_the_anonymous_floor() {
1388 let pep = production_pep();
1389
1390 let ghost = service_subject_ctx("ghost", 0x62);
1394 assert_eq!(
1395 pep.check(
1396 &ghost,
1397 "policy",
1398 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1399 ),
1400 MacDecision::Deny(MacDenyReason::NoClearance),
1401 "undeclared service subject must deny NoClearance"
1402 );
1403
1404 let user = user_subject_ctx();
1406 assert_eq!(
1407 pep.check(
1408 &user,
1409 "policy",
1410 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1411 ),
1412 MacDecision::Deny(MacDenyReason::NoClearance)
1413 );
1414
1415 let callback = EnvelopeContext::from_callback_service(1, "discovery");
1419 assert_eq!(
1420 pep.check(
1421 &callback,
1422 "policy",
1423 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1424 ),
1425 MacDecision::Deny(MacDenyReason::NoClearance),
1426 "keyless callback contexts must not claim a service clearance"
1427 );
1428
1429 for service in [
1433 "discovery",
1434 "event",
1435 "model",
1436 "oai",
1437 "oauth",
1438 "policy",
1439 "registry",
1440 ] {
1441 let ctx = service_subject_ctx(service, 0x63);
1442 assert_eq!(
1443 pep.check(
1444 &ctx,
1445 "policy",
1446 Some(&[policy_methods::REGISTER_SERVICE_KEY])
1447 ),
1448 MacDecision::Permit,
1449 "declared service:{service} must permit the declared bootstrap call"
1450 );
1451 }
1452 }
1453
1454 #[test]
1455 fn floor_deny_when_declared_clearance_cannot_dominate_the_label() {
1456 static SECRET_ROW: &[DispatchMethodPolicy] = &[DispatchMethodPolicy {
1460 id: DispatchMethodId {
1461 service: "policy",
1462 method: 7,
1463 },
1464 method_name: "fixture",
1465 label: SecurityLabel {
1466 level: Level::Secret,
1467 assurance: Assurance::Unverified,
1468 compartments: CompartmentSet::EMPTY,
1469 },
1470 justification: "test fixture: label deliberately above the declared clearance",
1471 }];
1472 static TABLE: DeclaredDispatchTable =
1473 DeclaredDispatchTable::from_rows(SECRET_ROW, BOOTSTRAP_SERVICE_CLEARANCES);
1474 let pep = DeclaredDispatchPep::new(&TABLE).with_activation_control();
1475 let caller = service_subject_ctx("discovery", 0x64);
1476 assert_eq!(
1477 pep.check(&caller, "policy", Some(&[7])),
1478 MacDecision::Deny(MacDenyReason::FloorDeny),
1479 "a label above the declared clearance must FloorDeny"
1480 );
1481 }
1482
1483 #[test]
1494 fn declared_policy_discriminants_match_the_serialized_schema() {
1495 use capnp::message::Builder;
1496
1497 let mut message = Builder::new_default();
1499 {
1500 let mut req =
1501 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1502 req.set_id(1);
1503 let mut check = req.reborrow().init_check();
1504 check.set_subject("service:oauth");
1505 check.set_domain("");
1506 check.set_resource("federation:register:https://signup.example.test");
1507 check.set_operation("check");
1508 }
1509 let bytes = capnp::serialize::write_message_to_words(&message);
1510 assert_eq!(
1511 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1512 policy_methods::CHECK,
1513 "the declared check discriminant must match the schema union ordinal"
1514 );
1515
1516 let mut message = Builder::new_default();
1518 {
1519 let mut req =
1520 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1521 req.set_id(1);
1522 req.reborrow().init_issue_token();
1523 }
1524 let bytes = capnp::serialize::write_message_to_words(&message);
1525 assert_eq!(
1526 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1527 policy_methods::ISSUE_TOKEN,
1528 "the declared issueToken discriminant must match the schema union ordinal"
1529 );
1530
1531 let mut message = Builder::new_default();
1533 {
1534 let mut req =
1535 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1536 req.set_id(1);
1537 req.set_get_policy(());
1538 }
1539 let bytes = capnp::serialize::write_message_to_words(&message);
1540 assert_eq!(
1541 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1542 policy_methods::GET_POLICY,
1543 "the declared getPolicy discriminant must match the schema union ordinal"
1544 );
1545
1546 let mut message = Builder::new_default();
1548 {
1549 let mut req =
1550 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1551 req.set_id(1);
1552 req.reborrow().init_apply_template().set_name("public-read");
1553 }
1554 let bytes = capnp::serialize::write_message_to_words(&message);
1555 assert_eq!(
1556 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1557 policy_methods::APPLY_TEMPLATE,
1558 "the declared applyTemplate discriminant must match the schema union ordinal"
1559 );
1560
1561 let mut message = Builder::new_default();
1563 {
1564 let mut req =
1565 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1566 req.set_id(1);
1567 req.reborrow().init_apply_draft();
1568 }
1569 let bytes = capnp::serialize::write_message_to_words(&message);
1570 assert_eq!(
1571 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1572 policy_methods::APPLY_DRAFT,
1573 "the declared applyDraft discriminant must match the schema union ordinal"
1574 );
1575
1576 let mut message = Builder::new_default();
1578 {
1579 let mut req =
1580 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1581 req.set_id(1);
1582 req.reborrow().init_rollback().set_git_ref("HEAD");
1583 }
1584 let bytes = capnp::serialize::write_message_to_words(&message);
1585 assert_eq!(
1586 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1587 policy_methods::ROLLBACK,
1588 "the declared rollback discriminant must match the schema union ordinal"
1589 );
1590
1591 let mut message = Builder::new_default();
1593 {
1594 let mut req =
1595 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1596 req.set_id(1);
1597 req.reborrow().init_get_history().set_count(1);
1598 }
1599 let bytes = capnp::serialize::write_message_to_words(&message);
1600 assert_eq!(
1601 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1602 policy_methods::GET_HISTORY,
1603 "the declared getHistory discriminant must match the schema union ordinal"
1604 );
1605
1606 let mut message = Builder::new_default();
1608 {
1609 let mut req =
1610 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1611 req.set_id(1);
1612 req.reborrow().init_get_diff();
1613 }
1614 let bytes = capnp::serialize::write_message_to_words(&message);
1615 assert_eq!(
1616 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1617 policy_methods::GET_DIFF,
1618 "the declared getDiff discriminant must match the schema union ordinal"
1619 );
1620
1621 let mut message = Builder::new_default();
1623 {
1624 let mut req =
1625 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1626 req.set_id(1);
1627 req.set_get_draft_status(());
1628 }
1629 let bytes = capnp::serialize::write_message_to_words(&message);
1630 assert_eq!(
1631 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1632 policy_methods::GET_DRAFT_STATUS,
1633 "the declared getDraftStatus discriminant must match the schema union ordinal"
1634 );
1635
1636 let mut message = Builder::new_default();
1638 {
1639 let mut req =
1640 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1641 req.set_id(1);
1642 let mut call = req.reborrow().init_add_grouping();
1643 call.set_user("bootstrap-user");
1644 call.set_role("viewer");
1645 }
1646 let bytes = capnp::serialize::write_message_to_words(&message);
1647 assert_eq!(
1648 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1649 policy_methods::ADD_GROUPING,
1650 "the declared addGrouping discriminant must match the schema union ordinal"
1651 );
1652
1653 let mut message = Builder::new_default();
1655 {
1656 let mut req =
1657 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1658 req.set_id(1);
1659 let mut call = req.reborrow().init_remove_grouping();
1660 call.set_user("bootstrap-user");
1661 call.set_role("viewer");
1662 }
1663 let bytes = capnp::serialize::write_message_to_words(&message);
1664 assert_eq!(
1665 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1666 policy_methods::REMOVE_GROUPING,
1667 "the declared removeGrouping discriminant must match the schema union ordinal"
1668 );
1669
1670 let mut message = Builder::new_default();
1672 {
1673 let mut req =
1674 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1675 req.set_id(1);
1676 let mut call = req.reborrow().init_register_service_key();
1677 call.set_service_name("discovery");
1678 call.set_verifying_key(&[0x42; 32]);
1679 call.set_service_jwt("header.payload.signature");
1680 }
1681 let bytes = capnp::serialize::write_message_to_words(&message);
1682 assert_eq!(
1683 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1684 policy_methods::REGISTER_SERVICE_KEY,
1685 "the declared registerServiceKey discriminant must match the schema union ordinal"
1686 );
1687
1688 let mut message = Builder::new_default();
1690 {
1691 let mut req =
1692 message.init_root::<hyprstream_rpc_std::policy_capnp::policy_request::Builder>();
1693 req.set_id(1);
1694 req.reborrow()
1695 .init_refresh_service_token()
1696 .set_ttl_seconds(2_592_000);
1697 }
1698 let bytes = capnp::serialize::write_message_to_words(&message);
1699 assert_eq!(
1700 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1701 policy_methods::REFRESH_SERVICE_TOKEN,
1702 "the declared refreshServiceToken discriminant must match the schema union ordinal"
1703 );
1704
1705 let mut message = Builder::new_default();
1708 {
1709 let mut req = message
1710 .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1711 req.set_id(1);
1712 req.reborrow().init_generate_stream();
1713 }
1714 let bytes = capnp::serialize::write_message_to_words(&message);
1715 assert_eq!(
1716 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1717 inference_methods::GENERATE_STREAM,
1718 "the declared generateStream discriminant must match the schema union ordinal"
1719 );
1720
1721 let mut message = Builder::new_default();
1723 {
1724 let mut req = message
1725 .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1726 req.set_id(1);
1727 req.set_health_check(());
1728 }
1729 let bytes = capnp::serialize::write_message_to_words(&message);
1730 assert_eq!(
1731 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1732 inference_methods::HEALTH_CHECK,
1733 "the declared healthCheck discriminant must match the schema union ordinal"
1734 );
1735
1736 let mut message = Builder::new_default();
1738 {
1739 let mut req = message
1740 .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1741 req.set_id(1);
1742 req.reborrow().init_embed();
1743 }
1744 let bytes = capnp::serialize::write_message_to_words(&message);
1745 assert_eq!(
1746 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1747 inference_methods::EMBED,
1748 "the declared embed discriminant must match the schema union ordinal"
1749 );
1750
1751 let mut message = Builder::new_default();
1753 {
1754 let mut req = message
1755 .init_root::<hyprstream_rpc_std::inference_capnp::inference_request::Builder>();
1756 req.set_id(1);
1757 req.set_get_layer_profile(());
1758 }
1759 let bytes = capnp::serialize::write_message_to_words(&message);
1760 assert_eq!(
1761 hyprstream_rpc::browser_provisioning::canonical_method_discriminator(&bytes).unwrap(),
1762 inference_methods::GET_LAYER_PROFILE,
1763 "the declared getLayerProfile discriminant must match the schema union ordinal"
1764 );
1765 }
1766
1767 #[test]
1770 fn declared_bootstrap_services_are_registered_factories() {
1771 let registered: Vec<&str> = hyprstream_service::list_factories()
1772 .map(|factory| factory.name)
1773 .collect();
1774 for row in DeclaredDispatchTable::production().clearances() {
1775 assert!(
1776 registered.contains(&row.service),
1777 "declared bootstrap service {} must be a registered service factory",
1778 row.service
1779 );
1780 }
1781 for row in DeclaredDispatchTable::production().methods() {
1782 assert!(
1783 registered.contains(&row.id.service),
1784 "declared dispatch target {} must be a registered service factory",
1785 row.id.service
1786 );
1787 }
1788 }
1789}