1#![deny(missing_docs)]
16
17mod error;
20pub mod layered_authorization;
22pub mod maintenance;
23pub mod resource_pattern;
25pub mod resource_type;
27pub mod secret_provider;
28pub mod secure_deployment;
29
30pub use layered_authorization::combine_layered_authorization;
31pub use layered_authorization::AuthorizationDecision;
32pub use layered_authorization::AuthorizationDenial;
33pub use layered_authorization::DetailedDecision;
34pub use layered_authorization::IngressDecision;
35pub use layered_authorization::IngressPolicy;
36pub use layered_authorization::LayerEvaluation;
37pub use layered_authorization::LayerFailureKind;
38pub use layered_authorization::LayerRequirement;
39pub use maintenance::MaintenanceAuthorizationContext;
40pub use maintenance::MaintenanceAuthorizationDenial;
41pub use maintenance::MaintenanceAuthorizationGrant;
42pub use maintenance::MaintenanceAuthorizer;
43pub use maintenance::MaintenanceCapability;
44pub use maintenance::MaintenancePolicy;
45pub use maintenance::MaintenancePrincipalBinding;
46pub use maintenance::MaintenanceRequestClass;
47pub use maintenance::MaintenanceResourceBudget;
48pub use maintenance::MaintenanceRole;
49pub use maintenance::MaintenanceRoleGrant;
50pub use maintenance::ValidatedMaintenancePolicy;
51pub use maintenance::MAINTENANCE_POLICY_SCHEMA_VERSION;
52pub use resource_pattern::ResourcePattern;
53pub use resource_type::ResourceType;
54
55pub use error::MaintenancePolicyRule;
56pub use error::SecurityContractViolation;
57pub use error::SecurityIdentifierRule;
58pub use error::SecurityOperation;
59pub use error::SecurityProviderError;
60pub use error::SecurityProviderFailure;
61
62pub use secret_provider::SecretAccess;
63pub use secret_provider::SecretMaterial;
64pub use secret_provider::SecretName;
65pub use secret_provider::SecretPersistence;
66pub use secret_provider::SecretProvider;
67pub use secret_provider::SecretProviderCapabilities;
68pub use secret_provider::SecretProviderId;
69pub use secret_provider::SecretVersion;
70pub use secret_provider::SecretVersioning;
71pub use secret_provider::VersionedSecret;
72pub use secure_deployment::validate_deployment_security;
73pub use secure_deployment::validate_security_bootstrap_from_env;
74pub use secure_deployment::BootstrapReadinessView;
75pub use secure_deployment::DeploymentOrigin;
76pub use secure_deployment::DeploymentSecurityConfigView;
77pub use secure_deployment::DeploymentSecurityFailure;
78pub use secure_deployment::DeploymentSecurityReport;
79pub use secure_deployment::SecurityBootstrap;
80pub use secure_deployment::SecurityBootstrapConfig;
81pub use secure_deployment::SecurityBootstrapMaterial;
82pub use secure_deployment::SecurityBootstrapProfile;
83pub use secure_deployment::SecurityBootstrapValidation;
84pub use secure_deployment::SecurityMigrationStatus;
85pub use secure_deployment::SecurityProfileResolution;
86pub use secure_deployment::SecurityProfileSelection;
87pub use secure_deployment::ValidatedSecurityBootstrap;
88pub use secure_deployment::MOUNTED_FILES_SECRET_PROVIDER;
89pub use secure_deployment::SECURITY_ADMIN_IDENTITY_ENV;
90pub use secure_deployment::SECURITY_PROFILE_ENV;
91pub use secure_deployment::SECURITY_REQUEST_POLICY_ENV;
92pub use secure_deployment::SECURITY_SECRET_PROVIDER_ENV;
93pub use secure_deployment::SECURITY_TLS_CERT_ENV;
94pub use secure_deployment::SECURITY_TLS_KEY_ENV;
95pub use secure_deployment::SECURITY_TRUST_ANCHOR_ENV;
96
97use std::collections::HashMap;
98use std::fmt;
99use std::fs::File;
100use std::io::Read;
101use std::net::SocketAddr;
102use std::path::Path;
103use std::str::FromStr;
104use std::time::SystemTime;
105
106use cheetah_string::CheetahString;
107
108#[derive(Clone, PartialEq, Eq)]
110pub struct PeerInfo {
111 address: SocketAddr,
112 tls: bool,
113 certificate_subject: Option<CheetahString>,
114}
115
116impl PeerInfo {
117 pub fn new(address: SocketAddr, tls: bool) -> Self {
119 Self {
120 address,
121 tls,
122 certificate_subject: None,
123 }
124 }
125
126 pub fn with_certificate_subject(mut self, subject: impl Into<CheetahString>) -> Self {
128 self.certificate_subject = Some(subject.into());
129 self
130 }
131
132 pub fn address(&self) -> SocketAddr {
134 self.address
135 }
136
137 pub fn is_tls(&self) -> bool {
139 self.tls
140 }
141
142 pub fn certificate_subject(&self) -> Option<&str> {
144 self.certificate_subject.as_deref()
145 }
146}
147
148impl fmt::Debug for PeerInfo {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.debug_struct("PeerInfo")
151 .field("address", &self.address)
152 .field("tls", &self.tls)
153 .field(
154 "certificate_subject",
155 &self.certificate_subject.as_ref().map(|_| "[REDACTED]"),
156 )
157 .finish()
158 }
159}
160
161pub trait HeaderFields: Sync {
166 fn fields(&self) -> &HashMap<CheetahString, CheetahString>;
168}
169
170impl HeaderFields for HashMap<CheetahString, CheetahString> {
171 fn fields(&self) -> &HashMap<CheetahString, CheetahString> {
172 self
173 }
174}
175
176#[derive(Clone, Copy)]
178pub struct SecurityRequestView<'a> {
179 code: i32,
180 version: i32,
181 fields: &'a dyn HeaderFields,
182 body: Option<&'a [u8]>,
183 peer: Option<&'a PeerInfo>,
184}
185
186impl<'a> SecurityRequestView<'a> {
187 pub fn new(
189 code: i32,
190 version: i32,
191 fields: &'a HashMap<CheetahString, CheetahString>,
192 body: Option<&'a [u8]>,
193 peer: Option<&'a PeerInfo>,
194 ) -> Self {
195 Self {
196 code,
197 version,
198 fields,
199 body,
200 peer,
201 }
202 }
203
204 pub fn with_header_fields(
207 code: i32,
208 version: i32,
209 fields: &'a dyn HeaderFields,
210 body: Option<&'a [u8]>,
211 peer: Option<&'a PeerInfo>,
212 ) -> Self {
213 Self {
214 code,
215 version,
216 fields,
217 body,
218 peer,
219 }
220 }
221
222 pub fn code(&self) -> i32 {
224 self.code
225 }
226
227 pub fn version(&self) -> i32 {
229 self.version
230 }
231
232 pub fn fields(&self) -> &'a HashMap<CheetahString, CheetahString> {
234 let fields: &'a dyn HeaderFields = self.fields;
235 fields.fields()
236 }
237
238 pub fn body(&self) -> Option<&'a [u8]> {
240 self.body
241 }
242
243 pub fn peer(&self) -> Option<&'a PeerInfo> {
245 self.peer
246 }
247}
248
249impl fmt::Debug for SecurityRequestView<'_> {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 f.debug_struct("SecurityRequestView")
252 .field("code", &self.code)
253 .field("version", &self.version)
254 .field("field_count", &self.fields().len())
255 .field("body_len", &self.body.map(<[u8]>::len))
256 .field("peer", &self.peer)
257 .finish()
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Hash)]
263pub struct Principal {
264 id: CheetahString,
265}
266
267impl Principal {
268 pub fn new(id: impl Into<CheetahString>) -> Self {
270 Self { id: id.into() }
271 }
272
273 pub fn id(&self) -> &str {
275 &self.id
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281pub enum ResourceKind {
282 Topic,
284 ConsumerGroup,
286 Cluster,
288 Broker,
290 Other,
292}
293
294#[derive(Debug, Clone, PartialEq, Eq, Hash)]
296pub struct Resource {
297 kind: ResourceKind,
298 name: CheetahString,
299}
300
301impl Resource {
302 pub fn new(kind: ResourceKind, name: impl Into<CheetahString>) -> Self {
304 Self {
305 kind,
306 name: name.into(),
307 }
308 }
309
310 pub fn topic(name: impl Into<CheetahString>) -> Self {
312 Self::new(ResourceKind::Topic, name)
313 }
314
315 pub fn kind(&self) -> ResourceKind {
317 self.kind
318 }
319
320 pub fn name(&self) -> &str {
322 &self.name
323 }
324}
325
326#[repr(u8)]
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
333pub enum Action {
334 Unknown = 0,
336 All = 1,
338 Any = 2,
340 Pub = 3,
342 Sub = 4,
344 Create = 5,
346 Update = 6,
348 Delete = 7,
350 Get = 8,
352 List = 9,
354 Publish = 10,
356 Subscribe = 11,
358 Describe = 12,
360 Manage = 13,
362}
363
364impl Action {
365 pub const fn code(self) -> u8 {
367 self as u8
368 }
369
370 pub const fn name(self) -> &'static str {
372 match self {
373 Self::Unknown => "Unknown",
374 Self::All => "All",
375 Self::Any => "Any",
376 Self::Pub => "Pub",
377 Self::Sub => "Sub",
378 Self::Create => "Create",
379 Self::Update => "Update",
380 Self::Delete => "Delete",
381 Self::Get => "Get",
382 Self::List => "List",
383 Self::Publish => "Publish",
384 Self::Subscribe => "Subscribe",
385 Self::Describe => "Describe",
386 Self::Manage => "Manage",
387 }
388 }
389
390 pub fn get_by_name(name: &str) -> Option<Self> {
392 match name.trim().to_ascii_lowercase().as_str() {
393 "unknown" => Some(Self::Unknown),
394 "all" => Some(Self::All),
395 "any" => Some(Self::Any),
396 "pub" => Some(Self::Pub),
397 "sub" => Some(Self::Sub),
398 "create" => Some(Self::Create),
399 "update" => Some(Self::Update),
400 "delete" => Some(Self::Delete),
401 "get" => Some(Self::Get),
402 "list" => Some(Self::List),
403 "publish" => Some(Self::Publish),
404 "subscribe" => Some(Self::Subscribe),
405 "describe" => Some(Self::Describe),
406 "manage" => Some(Self::Manage),
407 _ => None,
408 }
409 }
410}
411
412impl TryFrom<u8> for Action {
413 type Error = ();
414
415 fn try_from(value: u8) -> Result<Self, Self::Error> {
416 match value {
417 0 => Ok(Self::Unknown),
418 1 => Ok(Self::All),
419 2 => Ok(Self::Any),
420 3 => Ok(Self::Pub),
421 4 => Ok(Self::Sub),
422 5 => Ok(Self::Create),
423 6 => Ok(Self::Update),
424 7 => Ok(Self::Delete),
425 8 => Ok(Self::Get),
426 9 => Ok(Self::List),
427 10 => Ok(Self::Publish),
428 11 => Ok(Self::Subscribe),
429 12 => Ok(Self::Describe),
430 13 => Ok(Self::Manage),
431 _ => Err(()),
432 }
433 }
434}
435
436impl fmt::Display for Action {
437 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
438 formatter.write_str(self.name())
439 }
440}
441
442pub struct RequestContext<'a> {
444 request: SecurityRequestView<'a>,
445 principal: Option<&'a Principal>,
446 resource: Resource,
447 action: Action,
448}
449
450impl<'a> RequestContext<'a> {
451 pub fn new(
453 request: SecurityRequestView<'a>,
454 principal: Option<&'a Principal>,
455 resource: Resource,
456 action: Action,
457 ) -> Self {
458 Self {
459 request,
460 principal,
461 resource,
462 action,
463 }
464 }
465
466 pub fn principal(&self) -> Option<&Principal> {
468 self.principal
469 }
470}
471
472#[derive(Clone, Copy)]
474pub struct AuthenticatedRequestContext<'a> {
475 request: SecurityRequestView<'a>,
476 principal: &'a Principal,
477 resource: &'a Resource,
478 action: Action,
479}
480
481impl<'a> AuthenticatedRequestContext<'a> {
482 pub fn request(&self) -> SecurityRequestView<'a> {
484 self.request
485 }
486
487 pub fn principal(&self) -> &'a Principal {
489 self.principal
490 }
491
492 pub fn resource(&self) -> &'a Resource {
494 self.resource
495 }
496
497 pub fn action(&self) -> Action {
499 self.action
500 }
501}
502
503pub trait RequestPolicy: Send + Sync {
505 fn evaluate_authenticated(&self, context: AuthenticatedRequestContext<'_>) -> AuthorizationDecision;
507}
508
509pub fn evaluate_request(policy: &dyn RequestPolicy, context: &RequestContext<'_>) -> AuthorizationDecision {
514 let Some(principal) = context.principal else {
515 return AuthorizationDecision::Deny(AuthorizationDenial::SubjectUnknown);
516 };
517 policy.evaluate_authenticated(AuthenticatedRequestContext {
518 request: context.request,
519 principal,
520 resource: &context.resource,
521 action: context.action,
522 })
523}
524
525pub struct Signature {
527 fields: Vec<(CheetahString, Secret<CheetahString>)>,
528}
529
530impl Signature {
531 pub fn new(fields: Vec<(CheetahString, Secret<CheetahString>)>) -> Self {
533 Self { fields }
534 }
535
536 pub fn fields(&self) -> &[(CheetahString, Secret<CheetahString>)] {
538 &self.fields
539 }
540}
541
542impl fmt::Debug for Signature {
543 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 f.debug_struct("Signature")
545 .field("field_count", &self.fields.len())
546 .finish()
547 }
548}
549
550pub trait OutboundSigner: Send + Sync {
552 fn sign(&self, request: SecurityRequestView<'_>) -> Result<Signature, SecurityProviderError>;
559}
560
561pub struct Secret<T>(T);
563
564impl<T> Secret<T> {
565 pub fn new(value: T) -> Self {
567 Self(value)
568 }
569
570 pub fn expose_secret(&self) -> &T {
572 &self.0
573 }
574
575 pub fn into_inner(self) -> T {
577 self.0
578 }
579}
580
581impl<T> fmt::Debug for Secret<T> {
582 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583 f.write_str("[REDACTED]")
584 }
585}
586
587#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589pub enum DeploymentProfile {
590 Development,
592 Compatibility,
594 Secure,
596}
597
598impl FromStr for DeploymentProfile {
599 type Err = SecurityContractViolation;
600
601 fn from_str(value: &str) -> Result<Self, Self::Err> {
602 match value.to_ascii_lowercase().as_str() {
603 "development" => Ok(Self::Development),
604 "compatibility" => Ok(Self::Compatibility),
605 "secure" => Ok(Self::Secure),
606 _ => Err(SecurityContractViolation::UnknownSecurityProfile),
607 }
608 }
609}
610
611#[derive(Debug, Clone, Copy)]
613pub struct SecurityConfigView<'a> {
614 profile: &'a str,
615 trust_anchor: Option<&'a Path>,
616 secret_file: Option<&'a Path>,
617 bootstrap_expires_at: Option<SystemTime>,
618 insecure_downgrade: bool,
619}
620
621impl<'a> SecurityConfigView<'a> {
622 pub fn new(profile: &'a str) -> Self {
624 Self {
625 profile,
626 trust_anchor: None,
627 secret_file: None,
628 bootstrap_expires_at: None,
629 insecure_downgrade: false,
630 }
631 }
632
633 pub fn with_trust_anchor(mut self, path: &'a Path) -> Self {
635 self.trust_anchor = Some(path);
636 self
637 }
638
639 pub fn with_secret_file(mut self, path: &'a Path) -> Self {
641 self.secret_file = Some(path);
642 self
643 }
644
645 pub fn with_bootstrap_expiry(mut self, expires_at: SystemTime) -> Self {
647 self.bootstrap_expires_at = Some(expires_at);
648 self
649 }
650
651 pub fn with_insecure_downgrade(mut self, enabled: bool) -> Self {
653 self.insecure_downgrade = enabled;
654 self
655 }
656}
657
658#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
660pub enum SecurityReadinessFailure {
661 UnknownProfile,
663 MissingTrustAnchor,
665 TrustAnchorUnavailable,
667 TrustAnchorNotRegularFile,
669 MissingSecretFile,
671 SecretFileUnavailable,
673 SecretFileNotRegularFile,
675 InsecureSecretFilePermissions,
677 MissingBootstrapExpiry,
679 ExpiredBootstrap,
681 InsecureDowngrade,
683}
684
685#[derive(Debug, Clone, PartialEq, Eq)]
687pub struct SecurityReadinessReport {
688 profile: Option<DeploymentProfile>,
689 failures: Vec<SecurityReadinessFailure>,
690}
691
692impl SecurityReadinessReport {
693 pub fn is_ready(&self) -> bool {
695 self.failures.is_empty()
696 }
697
698 pub fn profile(&self) -> Option<DeploymentProfile> {
700 self.profile
701 }
702
703 pub fn failures(&self) -> &[SecurityReadinessFailure] {
705 &self.failures
706 }
707}
708
709pub fn validate_security_config(view: SecurityConfigView<'_>, now: SystemTime) -> SecurityReadinessReport {
711 let Ok(profile) = DeploymentProfile::from_str(view.profile) else {
712 return SecurityReadinessReport {
713 profile: None,
714 failures: vec![SecurityReadinessFailure::UnknownProfile],
715 };
716 };
717 let mut failures = Vec::new();
718 if profile == DeploymentProfile::Secure {
719 match view.trust_anchor {
720 None => failures.push(SecurityReadinessFailure::MissingTrustAnchor),
721 Some(path) => inspect_readable_file(
722 path,
723 SecurityReadinessFailure::TrustAnchorUnavailable,
724 SecurityReadinessFailure::TrustAnchorNotRegularFile,
725 false,
726 &mut failures,
727 ),
728 }
729 match view.secret_file {
730 None => failures.push(SecurityReadinessFailure::MissingSecretFile),
731 Some(path) => inspect_readable_file(
732 path,
733 SecurityReadinessFailure::SecretFileUnavailable,
734 SecurityReadinessFailure::SecretFileNotRegularFile,
735 true,
736 &mut failures,
737 ),
738 }
739 match view.bootstrap_expires_at {
740 None => failures.push(SecurityReadinessFailure::MissingBootstrapExpiry),
741 Some(expiry) if expiry <= now => failures.push(SecurityReadinessFailure::ExpiredBootstrap),
742 Some(_) => {}
743 }
744 if view.insecure_downgrade {
745 failures.push(SecurityReadinessFailure::InsecureDowngrade);
746 }
747 }
748 SecurityReadinessReport {
749 profile: Some(profile),
750 failures,
751 }
752}
753
754fn inspect_readable_file(
755 path: &Path,
756 unavailable: SecurityReadinessFailure,
757 not_regular_file: SecurityReadinessFailure,
758 require_owner_only_permissions: bool,
759 failures: &mut Vec<SecurityReadinessFailure>,
760) {
761 let Ok(path_metadata) = path.metadata() else {
762 failures.push(unavailable);
763 return;
764 };
765 if !path_metadata.is_file() {
766 failures.push(not_regular_file);
767 return;
768 }
769 let Ok(file) = File::open(path) else {
770 failures.push(unavailable);
771 return;
772 };
773 let Ok(metadata) = file.metadata() else {
774 failures.push(unavailable);
775 return;
776 };
777 if !metadata.is_file() {
778 failures.push(not_regular_file);
779 return;
780 }
781 if require_owner_only_permissions && !platform_secret_file_permissions(&metadata).is_owner_only() {
782 failures.push(SecurityReadinessFailure::InsecureSecretFilePermissions);
783 }
784}
785
786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788pub struct SecretFilePermissions {
789 pub group_access: bool,
791 pub other_access: bool,
793}
794
795impl SecretFilePermissions {
796 pub fn is_owner_only(self) -> bool {
798 !self.group_access && !self.other_access
799 }
800}
801
802pub fn read_secret_file(path: &Path) -> Result<Secret<Vec<u8>>, SecurityProviderError> {
809 let mut file = File::open(path).map_err(|source| {
810 SecurityProviderError::caused_by(
811 SecurityProviderFailure::Unavailable,
812 SecurityOperation::ReadSecret,
813 source,
814 )
815 })?;
816 let metadata = file.metadata().map_err(|source| {
817 SecurityProviderError::caused_by(
818 SecurityProviderFailure::OperationFailed,
819 SecurityOperation::InspectSecret,
820 source,
821 )
822 })?;
823 if !platform_secret_file_permissions(&metadata).is_owner_only() {
824 return Err(SecurityProviderError::contract(
825 SecurityOperation::InspectSecret,
826 SecurityContractViolation::SecretStoragePermissionsInsecure,
827 ));
828 }
829 let mut value = Vec::new();
830 file.read_to_end(&mut value).map_err(|source| {
831 SecurityProviderError::caused_by(
832 SecurityProviderFailure::OperationFailed,
833 SecurityOperation::ReadSecret,
834 source,
835 )
836 })?;
837 Ok(Secret::new(value))
838}
839
840#[cfg(unix)]
841fn platform_secret_file_permissions(metadata: &std::fs::Metadata) -> SecretFilePermissions {
842 use std::os::unix::fs::PermissionsExt;
843
844 let mode = metadata.permissions().mode();
845 SecretFilePermissions {
846 group_access: mode & 0o070 != 0,
847 other_access: mode & 0o007 != 0,
848 }
849}
850
851#[cfg(windows)]
852fn platform_secret_file_permissions(_metadata: &std::fs::Metadata) -> SecretFilePermissions {
853 SecretFilePermissions {
856 group_access: true,
857 other_access: true,
858 }
859}