Policy

Struct Policy 

Source
pub struct Policy { /* private fields */ }
Expand description

A policy containing multiple rules

§Security

Fields are private to enforce validation through deserialization. Use Policy::new() or deserialize from TOML/JSON to create instances. The #[serde(try_from)] attribute ensures all deserialized policies are validated against T20 limits (max rules, max name length, etc.).

Implementations§

Source§

impl Policy

Source

pub fn name(&self) -> &str

Get the policy name

Examples found in repository?
examples/simple_auth_flow.rs (line 75)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("p47h Open Core - Simple Authorization Flow");
16    println!("-------------------------------------------");
17    println!();
18
19    // -------------------------------------------------------------------------
20    // Step 1: Create Identities
21    // -------------------------------------------------------------------------
22    // Each user or device in the network has a unique cryptographic identity.
23    // The identity is an Ed25519 keypair. We use the public key hash as the
24    // peer identifier for policy rules.
25
26    let mut rng = rand::thread_rng();
27
28    let alice = Identity::generate(&mut rng)?;
29    let alice_id = format!("alice-{}", hex::encode(&alice.public_key_hash()[..4]));
30
31    let bob = Identity::generate(&mut rng)?;
32    let bob_id = format!("bob-{}", hex::encode(&bob.public_key_hash()[..4]));
33
34    println!("Created identities:");
35    println!("  Alice: {}", alice_id);
36    println!("  Bob:   {}", bob_id);
37    println!();
38
39    // -------------------------------------------------------------------------
40    // Step 2: Define a Policy
41    // -------------------------------------------------------------------------
42    // A policy is a collection of rules that define who can do what on which
43    // resources. Each rule specifies:
44    //   - peer_id: The identity this rule applies to
45    //   - action: What operation is allowed (Read, Write, Execute, Delete, All)
46    //   - resource: What resource pattern this applies to (supports wildcards)
47
48    // Policy parameters:
49    //   - name: Human-readable identifier
50    //   - valid_duration: How long the policy is valid (in seconds)
51    //   - current_time: Unix timestamp when the policy was created
52    let current_time = 1700000000; // Fixed timestamp for reproducibility
53    let valid_duration = 86400; // 24 hours
54
55    let policy = Policy::new("file-access-policy", valid_duration, current_time)?
56        // Rule 1: Alice can read any file under /data/
57        .add_rule(PolicyRule::new(
58            alice_id.clone(),
59            Action::Read,
60            Resource::File("/data/*".into()),
61        ))?
62        // Rule 2: Alice can write to her personal directory
63        .add_rule(PolicyRule::new(
64            alice_id.clone(),
65            Action::Write,
66            Resource::File("/home/alice/*".into()),
67        ))?
68        // Rule 3: Bob has full access to the /shared/ directory
69        .add_rule(PolicyRule::new(
70            bob_id.clone(),
71            Action::All,
72            Resource::File("/shared/*".into()),
73        ))?;
74
75    println!("Created policy: {}", policy.name());
76    println!("  Rules: {}", policy.rules().len());
77    println!("  Valid until: {} (Unix timestamp)", policy.valid_until());
78    println!();
79
80    // -------------------------------------------------------------------------
81    // Step 3: Evaluate Access Requests
82    // -------------------------------------------------------------------------
83    // The PolicyAuthorizer evaluates whether a specific peer can perform a
84    // specific action on a specific resource. It checks all rules and returns
85    // true if at least one rule allows the access.
86
87    let authorizer = PolicyAuthorizer::new(policy.rules());
88
89    // Define test cases: (peer, action, resource, expected_result)
90    let test_cases = [
91        // Alice reading from /data/ - should be ALLOWED (Rule 1)
92        (&alice_id, Action::Read, "/data/report.txt", true),
93        // Alice writing to /data/ - should be DENIED (no rule allows this)
94        (&alice_id, Action::Write, "/data/report.txt", false),
95        // Alice writing to her home - should be ALLOWED (Rule 2)
96        (&alice_id, Action::Write, "/home/alice/notes.txt", true),
97        // Bob reading from /data/ - should be DENIED (no rule for Bob on /data/)
98        (&bob_id, Action::Read, "/data/report.txt", false),
99        // Bob writing to /shared/ - should be ALLOWED (Rule 3, Action::All)
100        (&bob_id, Action::Write, "/shared/document.pdf", true),
101        // Bob deleting from /shared/ - should be ALLOWED (Rule 3, Action::All)
102        (&bob_id, Action::Delete, "/shared/old-file.txt", true),
103        // Unknown user - should be DENIED (no rules match)
104        (
105            &"unknown-user".to_string(),
106            Action::Read,
107            "/data/file.txt",
108            false,
109        ),
110    ];
111
112    println!("Evaluating access requests:");
113    println!();
114
115    for (peer_id, action, resource_path, expected) in test_cases {
116        let resource = Resource::File(resource_path.into());
117        let allowed = authorizer.is_allowed(peer_id, &action, &resource);
118
119        // Verify our expectations match the actual result
120        let status = if allowed { "ALLOWED" } else { "DENIED" };
121        let check = if allowed == expected {
122            "OK"
123        } else {
124            "MISMATCH"
125        };
126
127        println!(
128            "  {} {:?} {} -> {} [{}]",
129            peer_id, action, resource_path, status, check
130        );
131    }
132
133    println!();
134    println!("-------------------------------------------");
135    println!("Authorization flow completed successfully.");
136
137    Ok(())
138}
Source

pub const fn version(&self) -> u64

Get the policy version

Source

pub const fn issued_at(&self) -> u64

Get the issuance timestamp

Source

pub const fn valid_until(&self) -> u64

Get the expiration timestamp

Examples found in repository?
examples/simple_auth_flow.rs (line 77)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("p47h Open Core - Simple Authorization Flow");
16    println!("-------------------------------------------");
17    println!();
18
19    // -------------------------------------------------------------------------
20    // Step 1: Create Identities
21    // -------------------------------------------------------------------------
22    // Each user or device in the network has a unique cryptographic identity.
23    // The identity is an Ed25519 keypair. We use the public key hash as the
24    // peer identifier for policy rules.
25
26    let mut rng = rand::thread_rng();
27
28    let alice = Identity::generate(&mut rng)?;
29    let alice_id = format!("alice-{}", hex::encode(&alice.public_key_hash()[..4]));
30
31    let bob = Identity::generate(&mut rng)?;
32    let bob_id = format!("bob-{}", hex::encode(&bob.public_key_hash()[..4]));
33
34    println!("Created identities:");
35    println!("  Alice: {}", alice_id);
36    println!("  Bob:   {}", bob_id);
37    println!();
38
39    // -------------------------------------------------------------------------
40    // Step 2: Define a Policy
41    // -------------------------------------------------------------------------
42    // A policy is a collection of rules that define who can do what on which
43    // resources. Each rule specifies:
44    //   - peer_id: The identity this rule applies to
45    //   - action: What operation is allowed (Read, Write, Execute, Delete, All)
46    //   - resource: What resource pattern this applies to (supports wildcards)
47
48    // Policy parameters:
49    //   - name: Human-readable identifier
50    //   - valid_duration: How long the policy is valid (in seconds)
51    //   - current_time: Unix timestamp when the policy was created
52    let current_time = 1700000000; // Fixed timestamp for reproducibility
53    let valid_duration = 86400; // 24 hours
54
55    let policy = Policy::new("file-access-policy", valid_duration, current_time)?
56        // Rule 1: Alice can read any file under /data/
57        .add_rule(PolicyRule::new(
58            alice_id.clone(),
59            Action::Read,
60            Resource::File("/data/*".into()),
61        ))?
62        // Rule 2: Alice can write to her personal directory
63        .add_rule(PolicyRule::new(
64            alice_id.clone(),
65            Action::Write,
66            Resource::File("/home/alice/*".into()),
67        ))?
68        // Rule 3: Bob has full access to the /shared/ directory
69        .add_rule(PolicyRule::new(
70            bob_id.clone(),
71            Action::All,
72            Resource::File("/shared/*".into()),
73        ))?;
74
75    println!("Created policy: {}", policy.name());
76    println!("  Rules: {}", policy.rules().len());
77    println!("  Valid until: {} (Unix timestamp)", policy.valid_until());
78    println!();
79
80    // -------------------------------------------------------------------------
81    // Step 3: Evaluate Access Requests
82    // -------------------------------------------------------------------------
83    // The PolicyAuthorizer evaluates whether a specific peer can perform a
84    // specific action on a specific resource. It checks all rules and returns
85    // true if at least one rule allows the access.
86
87    let authorizer = PolicyAuthorizer::new(policy.rules());
88
89    // Define test cases: (peer, action, resource, expected_result)
90    let test_cases = [
91        // Alice reading from /data/ - should be ALLOWED (Rule 1)
92        (&alice_id, Action::Read, "/data/report.txt", true),
93        // Alice writing to /data/ - should be DENIED (no rule allows this)
94        (&alice_id, Action::Write, "/data/report.txt", false),
95        // Alice writing to her home - should be ALLOWED (Rule 2)
96        (&alice_id, Action::Write, "/home/alice/notes.txt", true),
97        // Bob reading from /data/ - should be DENIED (no rule for Bob on /data/)
98        (&bob_id, Action::Read, "/data/report.txt", false),
99        // Bob writing to /shared/ - should be ALLOWED (Rule 3, Action::All)
100        (&bob_id, Action::Write, "/shared/document.pdf", true),
101        // Bob deleting from /shared/ - should be ALLOWED (Rule 3, Action::All)
102        (&bob_id, Action::Delete, "/shared/old-file.txt", true),
103        // Unknown user - should be DENIED (no rules match)
104        (
105            &"unknown-user".to_string(),
106            Action::Read,
107            "/data/file.txt",
108            false,
109        ),
110    ];
111
112    println!("Evaluating access requests:");
113    println!();
114
115    for (peer_id, action, resource_path, expected) in test_cases {
116        let resource = Resource::File(resource_path.into());
117        let allowed = authorizer.is_allowed(peer_id, &action, &resource);
118
119        // Verify our expectations match the actual result
120        let status = if allowed { "ALLOWED" } else { "DENIED" };
121        let check = if allowed == expected {
122            "OK"
123        } else {
124            "MISMATCH"
125        };
126
127        println!(
128            "  {} {:?} {} -> {} [{}]",
129            peer_id, action, resource_path, status, check
130        );
131    }
132
133    println!();
134    println!("-------------------------------------------");
135    println!("Authorization flow completed successfully.");
136
137    Ok(())
138}
Source

pub fn rules(&self) -> &[PolicyRule]

Get a reference to the policy rules

Examples found in repository?
examples/simple_auth_flow.rs (line 76)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("p47h Open Core - Simple Authorization Flow");
16    println!("-------------------------------------------");
17    println!();
18
19    // -------------------------------------------------------------------------
20    // Step 1: Create Identities
21    // -------------------------------------------------------------------------
22    // Each user or device in the network has a unique cryptographic identity.
23    // The identity is an Ed25519 keypair. We use the public key hash as the
24    // peer identifier for policy rules.
25
26    let mut rng = rand::thread_rng();
27
28    let alice = Identity::generate(&mut rng)?;
29    let alice_id = format!("alice-{}", hex::encode(&alice.public_key_hash()[..4]));
30
31    let bob = Identity::generate(&mut rng)?;
32    let bob_id = format!("bob-{}", hex::encode(&bob.public_key_hash()[..4]));
33
34    println!("Created identities:");
35    println!("  Alice: {}", alice_id);
36    println!("  Bob:   {}", bob_id);
37    println!();
38
39    // -------------------------------------------------------------------------
40    // Step 2: Define a Policy
41    // -------------------------------------------------------------------------
42    // A policy is a collection of rules that define who can do what on which
43    // resources. Each rule specifies:
44    //   - peer_id: The identity this rule applies to
45    //   - action: What operation is allowed (Read, Write, Execute, Delete, All)
46    //   - resource: What resource pattern this applies to (supports wildcards)
47
48    // Policy parameters:
49    //   - name: Human-readable identifier
50    //   - valid_duration: How long the policy is valid (in seconds)
51    //   - current_time: Unix timestamp when the policy was created
52    let current_time = 1700000000; // Fixed timestamp for reproducibility
53    let valid_duration = 86400; // 24 hours
54
55    let policy = Policy::new("file-access-policy", valid_duration, current_time)?
56        // Rule 1: Alice can read any file under /data/
57        .add_rule(PolicyRule::new(
58            alice_id.clone(),
59            Action::Read,
60            Resource::File("/data/*".into()),
61        ))?
62        // Rule 2: Alice can write to her personal directory
63        .add_rule(PolicyRule::new(
64            alice_id.clone(),
65            Action::Write,
66            Resource::File("/home/alice/*".into()),
67        ))?
68        // Rule 3: Bob has full access to the /shared/ directory
69        .add_rule(PolicyRule::new(
70            bob_id.clone(),
71            Action::All,
72            Resource::File("/shared/*".into()),
73        ))?;
74
75    println!("Created policy: {}", policy.name());
76    println!("  Rules: {}", policy.rules().len());
77    println!("  Valid until: {} (Unix timestamp)", policy.valid_until());
78    println!();
79
80    // -------------------------------------------------------------------------
81    // Step 3: Evaluate Access Requests
82    // -------------------------------------------------------------------------
83    // The PolicyAuthorizer evaluates whether a specific peer can perform a
84    // specific action on a specific resource. It checks all rules and returns
85    // true if at least one rule allows the access.
86
87    let authorizer = PolicyAuthorizer::new(policy.rules());
88
89    // Define test cases: (peer, action, resource, expected_result)
90    let test_cases = [
91        // Alice reading from /data/ - should be ALLOWED (Rule 1)
92        (&alice_id, Action::Read, "/data/report.txt", true),
93        // Alice writing to /data/ - should be DENIED (no rule allows this)
94        (&alice_id, Action::Write, "/data/report.txt", false),
95        // Alice writing to her home - should be ALLOWED (Rule 2)
96        (&alice_id, Action::Write, "/home/alice/notes.txt", true),
97        // Bob reading from /data/ - should be DENIED (no rule for Bob on /data/)
98        (&bob_id, Action::Read, "/data/report.txt", false),
99        // Bob writing to /shared/ - should be ALLOWED (Rule 3, Action::All)
100        (&bob_id, Action::Write, "/shared/document.pdf", true),
101        // Bob deleting from /shared/ - should be ALLOWED (Rule 3, Action::All)
102        (&bob_id, Action::Delete, "/shared/old-file.txt", true),
103        // Unknown user - should be DENIED (no rules match)
104        (
105            &"unknown-user".to_string(),
106            Action::Read,
107            "/data/file.txt",
108            false,
109        ),
110    ];
111
112    println!("Evaluating access requests:");
113    println!();
114
115    for (peer_id, action, resource_path, expected) in test_cases {
116        let resource = Resource::File(resource_path.into());
117        let allowed = authorizer.is_allowed(peer_id, &action, &resource);
118
119        // Verify our expectations match the actual result
120        let status = if allowed { "ALLOWED" } else { "DENIED" };
121        let check = if allowed == expected {
122            "OK"
123        } else {
124            "MISMATCH"
125        };
126
127        println!(
128            "  {} {:?} {} -> {} [{}]",
129            peer_id, action, resource_path, status, check
130        );
131    }
132
133    println!();
134    println!("-------------------------------------------");
135    println!("Authorization flow completed successfully.");
136
137    Ok(())
138}
Source

pub fn metadata(&self) -> &BTreeMap<String, String>

Get a reference to the metadata

Source

pub fn new( name: impl Into<String>, valid_duration_secs: u64, current_time: u64, ) -> Result<Policy, PolicyError>

Create a new empty policy with version 1

§Arguments
  • name - Policy identifier
  • valid_duration_secs - How long this policy is valid (in seconds)
  • current_time - Current Unix timestamp (injected for purity/determinism)
§Errors

Returns PolicyError::NameTooLong if name exceeds MAX_POLICY_NAME_LENGTH

Examples found in repository?
examples/simple_auth_flow.rs (line 55)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("p47h Open Core - Simple Authorization Flow");
16    println!("-------------------------------------------");
17    println!();
18
19    // -------------------------------------------------------------------------
20    // Step 1: Create Identities
21    // -------------------------------------------------------------------------
22    // Each user or device in the network has a unique cryptographic identity.
23    // The identity is an Ed25519 keypair. We use the public key hash as the
24    // peer identifier for policy rules.
25
26    let mut rng = rand::thread_rng();
27
28    let alice = Identity::generate(&mut rng)?;
29    let alice_id = format!("alice-{}", hex::encode(&alice.public_key_hash()[..4]));
30
31    let bob = Identity::generate(&mut rng)?;
32    let bob_id = format!("bob-{}", hex::encode(&bob.public_key_hash()[..4]));
33
34    println!("Created identities:");
35    println!("  Alice: {}", alice_id);
36    println!("  Bob:   {}", bob_id);
37    println!();
38
39    // -------------------------------------------------------------------------
40    // Step 2: Define a Policy
41    // -------------------------------------------------------------------------
42    // A policy is a collection of rules that define who can do what on which
43    // resources. Each rule specifies:
44    //   - peer_id: The identity this rule applies to
45    //   - action: What operation is allowed (Read, Write, Execute, Delete, All)
46    //   - resource: What resource pattern this applies to (supports wildcards)
47
48    // Policy parameters:
49    //   - name: Human-readable identifier
50    //   - valid_duration: How long the policy is valid (in seconds)
51    //   - current_time: Unix timestamp when the policy was created
52    let current_time = 1700000000; // Fixed timestamp for reproducibility
53    let valid_duration = 86400; // 24 hours
54
55    let policy = Policy::new("file-access-policy", valid_duration, current_time)?
56        // Rule 1: Alice can read any file under /data/
57        .add_rule(PolicyRule::new(
58            alice_id.clone(),
59            Action::Read,
60            Resource::File("/data/*".into()),
61        ))?
62        // Rule 2: Alice can write to her personal directory
63        .add_rule(PolicyRule::new(
64            alice_id.clone(),
65            Action::Write,
66            Resource::File("/home/alice/*".into()),
67        ))?
68        // Rule 3: Bob has full access to the /shared/ directory
69        .add_rule(PolicyRule::new(
70            bob_id.clone(),
71            Action::All,
72            Resource::File("/shared/*".into()),
73        ))?;
74
75    println!("Created policy: {}", policy.name());
76    println!("  Rules: {}", policy.rules().len());
77    println!("  Valid until: {} (Unix timestamp)", policy.valid_until());
78    println!();
79
80    // -------------------------------------------------------------------------
81    // Step 3: Evaluate Access Requests
82    // -------------------------------------------------------------------------
83    // The PolicyAuthorizer evaluates whether a specific peer can perform a
84    // specific action on a specific resource. It checks all rules and returns
85    // true if at least one rule allows the access.
86
87    let authorizer = PolicyAuthorizer::new(policy.rules());
88
89    // Define test cases: (peer, action, resource, expected_result)
90    let test_cases = [
91        // Alice reading from /data/ - should be ALLOWED (Rule 1)
92        (&alice_id, Action::Read, "/data/report.txt", true),
93        // Alice writing to /data/ - should be DENIED (no rule allows this)
94        (&alice_id, Action::Write, "/data/report.txt", false),
95        // Alice writing to her home - should be ALLOWED (Rule 2)
96        (&alice_id, Action::Write, "/home/alice/notes.txt", true),
97        // Bob reading from /data/ - should be DENIED (no rule for Bob on /data/)
98        (&bob_id, Action::Read, "/data/report.txt", false),
99        // Bob writing to /shared/ - should be ALLOWED (Rule 3, Action::All)
100        (&bob_id, Action::Write, "/shared/document.pdf", true),
101        // Bob deleting from /shared/ - should be ALLOWED (Rule 3, Action::All)
102        (&bob_id, Action::Delete, "/shared/old-file.txt", true),
103        // Unknown user - should be DENIED (no rules match)
104        (
105            &"unknown-user".to_string(),
106            Action::Read,
107            "/data/file.txt",
108            false,
109        ),
110    ];
111
112    println!("Evaluating access requests:");
113    println!();
114
115    for (peer_id, action, resource_path, expected) in test_cases {
116        let resource = Resource::File(resource_path.into());
117        let allowed = authorizer.is_allowed(peer_id, &action, &resource);
118
119        // Verify our expectations match the actual result
120        let status = if allowed { "ALLOWED" } else { "DENIED" };
121        let check = if allowed == expected {
122            "OK"
123        } else {
124            "MISMATCH"
125        };
126
127        println!(
128            "  {} {:?} {} -> {} [{}]",
129            peer_id, action, resource_path, status, check
130        );
131    }
132
133    println!();
134    println!("-------------------------------------------");
135    println!("Authorization flow completed successfully.");
136
137    Ok(())
138}
Source

pub fn new_unversioned(name: impl Into<String>) -> Result<Policy, PolicyError>

Create a policy without timestamps (for testing/legacy)

§Errors

Returns PolicyError::NameTooLong if name exceeds MAX_POLICY_NAME_LENGTH

Source

pub fn add_rule(self, rule: PolicyRule) -> Result<Policy, PolicyError>

Add a rule to this policy

§Errors

Returns PolicyError::TooManyRules if adding this rule would exceed MAX_RULES_PER_POLICY

Examples found in repository?
examples/simple_auth_flow.rs (lines 57-61)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("p47h Open Core - Simple Authorization Flow");
16    println!("-------------------------------------------");
17    println!();
18
19    // -------------------------------------------------------------------------
20    // Step 1: Create Identities
21    // -------------------------------------------------------------------------
22    // Each user or device in the network has a unique cryptographic identity.
23    // The identity is an Ed25519 keypair. We use the public key hash as the
24    // peer identifier for policy rules.
25
26    let mut rng = rand::thread_rng();
27
28    let alice = Identity::generate(&mut rng)?;
29    let alice_id = format!("alice-{}", hex::encode(&alice.public_key_hash()[..4]));
30
31    let bob = Identity::generate(&mut rng)?;
32    let bob_id = format!("bob-{}", hex::encode(&bob.public_key_hash()[..4]));
33
34    println!("Created identities:");
35    println!("  Alice: {}", alice_id);
36    println!("  Bob:   {}", bob_id);
37    println!();
38
39    // -------------------------------------------------------------------------
40    // Step 2: Define a Policy
41    // -------------------------------------------------------------------------
42    // A policy is a collection of rules that define who can do what on which
43    // resources. Each rule specifies:
44    //   - peer_id: The identity this rule applies to
45    //   - action: What operation is allowed (Read, Write, Execute, Delete, All)
46    //   - resource: What resource pattern this applies to (supports wildcards)
47
48    // Policy parameters:
49    //   - name: Human-readable identifier
50    //   - valid_duration: How long the policy is valid (in seconds)
51    //   - current_time: Unix timestamp when the policy was created
52    let current_time = 1700000000; // Fixed timestamp for reproducibility
53    let valid_duration = 86400; // 24 hours
54
55    let policy = Policy::new("file-access-policy", valid_duration, current_time)?
56        // Rule 1: Alice can read any file under /data/
57        .add_rule(PolicyRule::new(
58            alice_id.clone(),
59            Action::Read,
60            Resource::File("/data/*".into()),
61        ))?
62        // Rule 2: Alice can write to her personal directory
63        .add_rule(PolicyRule::new(
64            alice_id.clone(),
65            Action::Write,
66            Resource::File("/home/alice/*".into()),
67        ))?
68        // Rule 3: Bob has full access to the /shared/ directory
69        .add_rule(PolicyRule::new(
70            bob_id.clone(),
71            Action::All,
72            Resource::File("/shared/*".into()),
73        ))?;
74
75    println!("Created policy: {}", policy.name());
76    println!("  Rules: {}", policy.rules().len());
77    println!("  Valid until: {} (Unix timestamp)", policy.valid_until());
78    println!();
79
80    // -------------------------------------------------------------------------
81    // Step 3: Evaluate Access Requests
82    // -------------------------------------------------------------------------
83    // The PolicyAuthorizer evaluates whether a specific peer can perform a
84    // specific action on a specific resource. It checks all rules and returns
85    // true if at least one rule allows the access.
86
87    let authorizer = PolicyAuthorizer::new(policy.rules());
88
89    // Define test cases: (peer, action, resource, expected_result)
90    let test_cases = [
91        // Alice reading from /data/ - should be ALLOWED (Rule 1)
92        (&alice_id, Action::Read, "/data/report.txt", true),
93        // Alice writing to /data/ - should be DENIED (no rule allows this)
94        (&alice_id, Action::Write, "/data/report.txt", false),
95        // Alice writing to her home - should be ALLOWED (Rule 2)
96        (&alice_id, Action::Write, "/home/alice/notes.txt", true),
97        // Bob reading from /data/ - should be DENIED (no rule for Bob on /data/)
98        (&bob_id, Action::Read, "/data/report.txt", false),
99        // Bob writing to /shared/ - should be ALLOWED (Rule 3, Action::All)
100        (&bob_id, Action::Write, "/shared/document.pdf", true),
101        // Bob deleting from /shared/ - should be ALLOWED (Rule 3, Action::All)
102        (&bob_id, Action::Delete, "/shared/old-file.txt", true),
103        // Unknown user - should be DENIED (no rules match)
104        (
105            &"unknown-user".to_string(),
106            Action::Read,
107            "/data/file.txt",
108            false,
109        ),
110    ];
111
112    println!("Evaluating access requests:");
113    println!();
114
115    for (peer_id, action, resource_path, expected) in test_cases {
116        let resource = Resource::File(resource_path.into());
117        let allowed = authorizer.is_allowed(peer_id, &action, &resource);
118
119        // Verify our expectations match the actual result
120        let status = if allowed { "ALLOWED" } else { "DENIED" };
121        let check = if allowed == expected {
122            "OK"
123        } else {
124            "MISMATCH"
125        };
126
127        println!(
128            "  {} {:?} {} -> {} [{}]",
129            peer_id, action, resource_path, status, check
130        );
131    }
132
133    println!();
134    println!("-------------------------------------------");
135    println!("Authorization flow completed successfully.");
136
137    Ok(())
138}
Source

pub fn with_metadata( self, key: impl Into<String>, value: impl Into<String>, ) -> Policy

Add metadata to this policy

Source

pub fn is_allowed( &self, peer_id: &str, action: &Action, resource: &Resource, ) -> bool

Check if a peer is allowed to perform an action on a resource

This method delegates to PolicyAuthorizer (SRP - Single Responsibility Principle). The Policy struct focuses on construction and management, while authorization logic is handled by the dedicated PolicyAuthorizer.

Source

pub fn validate(&self) -> Result<(), PolicyError>

Validate policy (check for conflicts, invalid rules, etc.)

§Errors

Returns PolicyError::InvalidRule if:

  • Policy name is empty
  • Policy has no rules
  • Any rule has an empty peer ID
Source

pub fn from_toml(toml_str: &str) -> Result<Policy, PolicyError>

Load policy from TOML string

§Errors

Returns an error if:

  • TOML parsing fails
  • Validation fails (see validate())
Source

pub fn to_toml(&self) -> Result<String, PolicyError>

Serialize policy to TOML string

§Errors

Returns PolicyError::SerializationError if TOML serialization fails

Trait Implementations§

Source§

impl Clone for Policy

Source§

fn clone(&self) -> Policy

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Policy

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Policy

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Policy, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Policy

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryFrom<PolicyRaw> for Policy

Convert PolicyRaw to Policy with validation

This is called automatically during deserialization due to the #[serde(try_from = "PolicyRaw")] attribute on Policy.

§Errors

Returns PolicyError if validation fails:

  • TooManyRules: More than MAX_RULES_PER_POLICY rules
  • NameTooLong: Policy name exceeds MAX_POLICY_NAME_LENGTH
  • InvalidRule: Other validation failures (empty name, no rules, etc.)
Source§

type Error = PolicyError

The type returned in the event of a conversion error.
Source§

fn try_from(raw: PolicyRaw) -> Result<Policy, PolicyError>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Policy

§

impl RefUnwindSafe for Policy

§

impl Send for Policy

§

impl Sync for Policy

§

impl Unpin for Policy

§

impl UnwindSafe for Policy

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,