Skip to main content

rocketmq_security_api/
lib.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#![deny(missing_docs)]
16
17//! Runtime-neutral security contracts.
18
19mod error;
20/// Layered ingress and detailed authorization contracts.
21pub mod layered_authorization;
22pub mod maintenance;
23/// Resource pattern types and operations.
24pub mod resource_pattern;
25/// Resource type types and operations.
26pub 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/// Read-only peer metadata made available to security policies.
109#[derive(Clone, PartialEq, Eq)]
110pub struct PeerInfo {
111    address: SocketAddr,
112    tls: bool,
113    certificate_subject: Option<CheetahString>,
114}
115
116impl PeerInfo {
117    /// Creates a new `PeerInfo`.
118    pub fn new(address: SocketAddr, tls: bool) -> Self {
119        Self {
120            address,
121            tls,
122            certificate_subject: None,
123        }
124    }
125
126    /// Sets certificate subject and returns the updated value.
127    pub fn with_certificate_subject(mut self, subject: impl Into<CheetahString>) -> Self {
128        self.certificate_subject = Some(subject.into());
129        self
130    }
131
132    /// Returns the address.
133    pub fn address(&self) -> SocketAddr {
134        self.address
135    }
136
137    /// Returns whether tls.
138    pub fn is_tls(&self) -> bool {
139        self.tls
140    }
141
142    /// Returns the certificate subject.
143    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
161/// Header fields of a [`SecurityRequestView`], produced when a policy first reads them.
162///
163/// A transport can implement this over a request whose fields are still in their encoded form,
164/// so a policy that never calls [`SecurityRequestView::fields`] does not pay for building them.
165pub trait HeaderFields: Sync {
166    /// Returns the request's header fields.
167    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/// Minimal borrowed projection of an inbound or outbound request.
177#[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    /// Creates a new `SecurityRequestView`.
188    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    /// Creates a view whose header fields are produced by `fields` on the first call to
205    /// [`Self::fields`].
206    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    /// Returns the code.
223    pub fn code(&self) -> i32 {
224        self.code
225    }
226
227    /// Returns the version.
228    pub fn version(&self) -> i32 {
229        self.version
230    }
231
232    /// Returns the fields.
233    pub fn fields(&self) -> &'a HashMap<CheetahString, CheetahString> {
234        let fields: &'a dyn HeaderFields = self.fields;
235        fields.fields()
236    }
237
238    /// Returns the body.
239    pub fn body(&self) -> Option<&'a [u8]> {
240        self.body
241    }
242
243    /// Returns the peer.
244    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/// Authenticated identity without credential material.
262#[derive(Debug, Clone, PartialEq, Eq, Hash)]
263pub struct Principal {
264    id: CheetahString,
265}
266
267impl Principal {
268    /// Creates a new `Principal`.
269    pub fn new(id: impl Into<CheetahString>) -> Self {
270        Self { id: id.into() }
271    }
272
273    /// Returns the id.
274    pub fn id(&self) -> &str {
275        &self.id
276    }
277}
278
279/// Protected resource category.
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281pub enum ResourceKind {
282    /// Represents the topic case.
283    Topic,
284    /// Represents the consumer group case.
285    ConsumerGroup,
286    /// Represents the cluster case.
287    Cluster,
288    /// Represents the broker case.
289    Broker,
290    /// Represents the other case.
291    Other,
292}
293
294/// Resource selected for a policy decision.
295#[derive(Debug, Clone, PartialEq, Eq, Hash)]
296pub struct Resource {
297    kind: ResourceKind,
298    name: CheetahString,
299}
300
301impl Resource {
302    /// Creates a new `Resource`.
303    pub fn new(kind: ResourceKind, name: impl Into<CheetahString>) -> Self {
304        Self {
305            kind,
306            name: name.into(),
307        }
308    }
309
310    /// Creates the topic value.
311    pub fn topic(name: impl Into<CheetahString>) -> Self {
312        Self::new(ResourceKind::Topic, name)
313    }
314
315    /// Returns the kind.
316    pub fn kind(&self) -> ResourceKind {
317        self.kind
318    }
319
320    /// Returns the name.
321    pub fn name(&self) -> &str {
322        &self.name
323    }
324}
325
326/// Security-relevant operation requested on a resource.
327///
328/// Values `0..=9` preserve the RocketMQ ACL wire codes. The semantic
329/// `Publish`, `Subscribe`, `Describe`, and `Manage` variants are policy-level
330/// operations and intentionally have distinct codes.
331#[repr(u8)]
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
333pub enum Action {
334    /// Represents the unknown case.
335    Unknown = 0,
336    /// Represents the all case.
337    All = 1,
338    /// Represents the any case.
339    Any = 2,
340    /// Represents the pub case.
341    Pub = 3,
342    /// Represents the sub case.
343    Sub = 4,
344    /// Represents the create case.
345    Create = 5,
346    /// Represents the update case.
347    Update = 6,
348    /// Represents the delete case.
349    Delete = 7,
350    /// Represents the get case.
351    Get = 8,
352    /// Represents the list case.
353    List = 9,
354    /// Represents the publish case.
355    Publish = 10,
356    /// Represents the subscribe case.
357    Subscribe = 11,
358    /// Represents the describe case.
359    Describe = 12,
360    /// Represents the manage case.
361    Manage = 13,
362}
363
364impl Action {
365    /// Returns the code.
366    pub const fn code(self) -> u8 {
367        self as u8
368    }
369
370    /// Returns the name.
371    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    /// Returns by name.
391    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
442/// Complete security input before authentication has been required.
443pub 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    /// Creates a new `RequestContext`.
452    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    /// Returns the principal.
467    pub fn principal(&self) -> Option<&Principal> {
468        self.principal
469    }
470}
471
472/// Policy input for which the principal invariant has been established.
473#[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    /// Returns the request.
483    pub fn request(&self) -> SecurityRequestView<'a> {
484        self.request
485    }
486
487    /// Returns the principal.
488    pub fn principal(&self) -> &'a Principal {
489        self.principal
490    }
491
492    /// Returns the resource.
493    pub fn resource(&self) -> &'a Resource {
494        self.resource
495    }
496
497    /// Returns the action.
498    pub fn action(&self) -> Action {
499        self.action
500    }
501}
502
503/// Authorization policy that can only evaluate authenticated requests.
504pub trait RequestPolicy: Send + Sync {
505    /// Returns the final decision for an authenticated request.
506    fn evaluate_authenticated(&self, context: AuthenticatedRequestContext<'_>) -> AuthorizationDecision;
507}
508
509/// Applies the mandatory fail-closed identity gate before invoking a policy.
510///
511/// A missing principal resolves to [`AuthorizationDenial::SubjectUnknown`]
512/// without invoking the policy.
513pub 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
525/// Redacted signature fields produced by an outbound signer.
526pub struct Signature {
527    fields: Vec<(CheetahString, Secret<CheetahString>)>,
528}
529
530impl Signature {
531    /// Creates a new `Signature`.
532    pub fn new(fields: Vec<(CheetahString, Secret<CheetahString>)>) -> Self {
533        Self { fields }
534    }
535
536    /// Returns the fields.
537    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
550/// Contract implemented by transport-specific outbound signers in `rocketmq-auth`.
551pub trait OutboundSigner: Send + Sync {
552    /// Signs an outbound security request.
553    ///
554    /// # Errors
555    ///
556    /// Returns a redacted [`SecurityProviderError`] when the signing provider
557    /// cannot produce a signature safely.
558    fn sign(&self, request: SecurityRequestView<'_>) -> Result<Signature, SecurityProviderError>;
559}
560
561/// Sensitive value whose debug representation is always redacted.
562pub struct Secret<T>(T);
563
564impl<T> Secret<T> {
565    /// Creates a new `Secret`.
566    pub fn new(value: T) -> Self {
567        Self(value)
568    }
569
570    /// Returns the expose secret.
571    pub fn expose_secret(&self) -> &T {
572        &self.0
573    }
574
575    /// Converts this value into inner.
576    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/// Deployment security profile selected by configuration.
588#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589pub enum DeploymentProfile {
590    /// Represents the development case.
591    Development,
592    /// Represents the compatibility case.
593    Compatibility,
594    /// Represents the secure case.
595    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/// Borrowed configuration input for a side-effect-free readiness check.
612#[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    /// Creates a new `SecurityConfigView`.
623    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    /// Sets trust anchor and returns the updated value.
634    pub fn with_trust_anchor(mut self, path: &'a Path) -> Self {
635        self.trust_anchor = Some(path);
636        self
637    }
638
639    /// Sets secret file and returns the updated value.
640    pub fn with_secret_file(mut self, path: &'a Path) -> Self {
641        self.secret_file = Some(path);
642        self
643    }
644
645    /// Sets bootstrap expiry and returns the updated value.
646    pub fn with_bootstrap_expiry(mut self, expires_at: SystemTime) -> Self {
647        self.bootstrap_expires_at = Some(expires_at);
648        self
649    }
650
651    /// Sets insecure downgrade and returns the updated value.
652    pub fn with_insecure_downgrade(mut self, enabled: bool) -> Self {
653        self.insecure_downgrade = enabled;
654        self
655    }
656}
657
658/// Stable reasons why a profile is not ready.
659#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
660pub enum SecurityReadinessFailure {
661    /// Represents the unknown profile case.
662    UnknownProfile,
663    /// Represents the missing trust anchor case.
664    MissingTrustAnchor,
665    /// Represents the trust anchor unavailable case.
666    TrustAnchorUnavailable,
667    /// Represents the trust anchor not regular file case.
668    TrustAnchorNotRegularFile,
669    /// Represents the missing secret file case.
670    MissingSecretFile,
671    /// Represents the secret file unavailable case.
672    SecretFileUnavailable,
673    /// Represents the secret file not regular file case.
674    SecretFileNotRegularFile,
675    /// Represents the insecure secret file permissions case.
676    InsecureSecretFilePermissions,
677    /// Represents the missing bootstrap expiry case.
678    MissingBootstrapExpiry,
679    /// Represents the expired bootstrap case.
680    ExpiredBootstrap,
681    /// Represents the insecure downgrade case.
682    InsecureDowngrade,
683}
684
685/// Result of a side-effect-free security configuration dry run.
686#[derive(Debug, Clone, PartialEq, Eq)]
687pub struct SecurityReadinessReport {
688    profile: Option<DeploymentProfile>,
689    failures: Vec<SecurityReadinessFailure>,
690}
691
692impl SecurityReadinessReport {
693    /// Returns whether ready.
694    pub fn is_ready(&self) -> bool {
695        self.failures.is_empty()
696    }
697
698    /// Returns the profile.
699    pub fn profile(&self) -> Option<DeploymentProfile> {
700        self.profile
701    }
702
703    /// Returns the failures.
704    pub fn failures(&self) -> &[SecurityReadinessFailure] {
705        &self.failures
706    }
707}
708
709/// Validates a configuration snapshot without reading file contents or writing external state.
710pub 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/// Portable projection of secret-file permissions.
787#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788pub struct SecretFilePermissions {
789    /// Whether group access.
790    pub group_access: bool,
791    /// Whether other access.
792    pub other_access: bool,
793}
794
795impl SecretFilePermissions {
796    /// Returns whether owner only.
797    pub fn is_owner_only(self) -> bool {
798        !self.group_access && !self.other_access
799    }
800}
801
802/// Opens, permission-checks and reads a secret using the same file handle.
803///
804/// # Errors
805///
806/// Returns a redacted [`SecurityProviderError`] while retaining safe typed I/O
807/// sources. Insecure permissions are retained as a closed contract source.
808pub 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    // Windows ACL inspection is supplied by the deployment adapter. The portable contract stays
854    // fail-closed until that adapter provides an owner-only projection.
855    SecretFilePermissions {
856        group_access: true,
857        other_access: true,
858    }
859}