kaymyg commited on
Commit
9679e2d
·
1 Parent(s): 1332403

Add CI, contributor essentials, and full T3/T4 demo coverage

Browse files

- GitHub Actions CI: fmt check, clippy (-D warnings), build, test, release smoke test
- Dependabot for cargo + github-actions
- CONTRIBUTING.md, SECURITY.md, issue templates, PR template
- CHANGELOG.md
- Extend main.rs walkthrough to genuinely exercise T3/T4 elevation and D2/D3
capability issuance (was previously untested dead code, now real coverage)
- Document intentional clippy/dead_code allowances instead of suppressing
blindly
- README: CI/license/rust badges, live demo link, contributing/security/changelog sections
- Remove HF-only YAML frontmatter from the shared README (GitHub renders it
literally; license is now set via HF's dataset settings UI instead)

.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Report unexpected behavior, a build failure, or a broken test
4
+ title: "[Bug] "
5
+ labels: bug
6
+ ---
7
+
8
+ **Describe the bug**
9
+ A clear, concise description of what's wrong.
10
+
11
+ **To reproduce**
12
+ Steps or a minimal code snippet that triggers it.
13
+
14
+ **Expected behavior**
15
+ What you expected to happen instead.
16
+
17
+ **Environment**
18
+ - OS:
19
+ - Rust version (`rustc --version`):
20
+ - Commit/tag:
21
+
22
+ **Additional context**
23
+ Anything else relevant — logs, `cargo test` output, etc.
.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ blank_issues_enabled: true
2
+ contact_links:
3
+ - name: Security vulnerability
4
+ url: https://github.com/kaymyg/ubda-engine/security/advisories/new
5
+ about: Please report security issues privately — see SECURITY.md
.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an addition or improvement to the architecture or code
4
+ title: "[Feature] "
5
+ labels: enhancement
6
+ ---
7
+
8
+ **What are you trying to do?**
9
+ Describe the use case or gap you've noticed.
10
+
11
+ **Proposed approach**
12
+ If you have one in mind — a new module, a change to an existing trait, etc.
13
+
14
+ **Alternatives considered**
15
+ Any other ways to solve this you thought about and ruled out.
16
+
17
+ **Additional context**
18
+ Links, references, or related issues.
.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## What does this change do?
2
+
3
+ <!-- Brief description -->
4
+
5
+ ## Checklist
6
+
7
+ - [ ] `cargo fmt --check` passes
8
+ - [ ] `cargo clippy --all-targets --all-features -- -D warnings` passes
9
+ - [ ] `cargo test` passes
10
+ - [ ] Updated `docs/ARCHITECTURE.md` or `README.md` if this changes behavior or structure
11
+ - [ ] Added/updated tests for the change, where applicable
12
+
13
+ ## Related issue
14
+
15
+ <!-- Closes #123, if applicable -->
.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "cargo"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
7
+ open-pull-requests-limit: 5
8
+ - package-ecosystem: "github-actions"
9
+ directory: "/"
10
+ schedule:
11
+ interval: "weekly"
.github/workflows/ci.yml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ env:
10
+ CARGO_TERM_COLOR: always
11
+
12
+ jobs:
13
+ fmt:
14
+ name: Format check
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - name: Install stable toolchain with rustfmt
19
+ run: rustup component add rustfmt
20
+ - name: Check formatting
21
+ run: cargo fmt --check
22
+
23
+ clippy:
24
+ name: Clippy lints
25
+ runs-on: ubuntu-latest
26
+ steps:
27
+ - uses: actions/checkout@v4
28
+ - name: Install stable toolchain with clippy
29
+ run: rustup component add clippy
30
+ - name: Cache cargo registry
31
+ uses: actions/cache@v4
32
+ with:
33
+ path: |
34
+ ~/.cargo/registry
35
+ ~/.cargo/git
36
+ target
37
+ key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
38
+ - name: Run clippy
39
+ run: cargo clippy --all-targets --all-features -- -D warnings
40
+
41
+ test:
42
+ name: Build & test
43
+ runs-on: ubuntu-latest
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ - name: Cache cargo registry
47
+ uses: actions/cache@v4
48
+ with:
49
+ path: |
50
+ ~/.cargo/registry
51
+ ~/.cargo/git
52
+ target
53
+ key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
54
+ - name: Build
55
+ run: cargo build --locked --verbose
56
+ - name: Run tests
57
+ run: cargo test --locked --verbose
58
+ - name: Run release walkthrough (smoke test)
59
+ run: cargo run --locked --release
CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
+
6
+ ## [1.2.0-alpha] - 2026-08-28
7
+
8
+ ### Added
9
+ - Initial public release of the UBDA trust-state engine: `TrustState` /
10
+ `DataClassification` model, `SystemStateMachine`, `BehavioralTrustEngine`,
11
+ `MockHardwareAuthorizer` (`KeyAuthority`), `KeyBroker`, and `ReplayStore`.
12
+ - End-to-end CLI walkthrough (`cargo run`) exercising the full T0→T4 trust
13
+ lifecycle, including D0–D3 capability issuance, replay defense, signature
14
+ tamper detection, and compromise lockout/recovery.
15
+ - 17-test unit suite covering state transitions, capability issuance,
16
+ key-broker verification (signature, expiry, replay, session binding,
17
+ operation matching), and derived-key determinism.
18
+ - Architecture documentation (`docs/ARCHITECTURE.md`) with trust-state and
19
+ component-isolation diagrams.
20
+ - Live Gradio demo Space and a Hugging Face dataset backup of the source.
21
+ - CI (fmt, clippy, build, test), issue/PR templates, security policy,
22
+ contributing guide, and Dependabot config.
23
+
24
+ ### Notes
25
+ - `MockHardwareAuthorizer` is a software stand-in for a real hardware/TEE key
26
+ authority — see the README's prototype-status warning.
CONTRIBUTING.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to UBDA
2
+
3
+ Thanks for your interest in this project — it started as a self-teaching
4
+ exercise in capability-based access-control design, and contributions,
5
+ questions, and critiques are all welcome.
6
+
7
+ ## Getting set up
8
+
9
+ Requires a stable Rust toolchain (2021 edition; tested against rustc 1.75+).
10
+
11
+ ```bash
12
+ git clone https://github.com/kaymyg/ubda-engine.git
13
+ cd ubda-engine
14
+ cargo build
15
+ cargo test
16
+ cargo run
17
+ ```
18
+
19
+ ## Before opening a PR
20
+
21
+ Please run the same checks CI runs, so review focuses on the actual change:
22
+
23
+ ```bash
24
+ cargo fmt --check
25
+ cargo clippy --all-targets --all-features -- -D warnings
26
+ cargo test
27
+ ```
28
+
29
+ If `cargo fmt --check` fails, just run `cargo fmt` to fix it in place.
30
+
31
+ ## What to work on
32
+
33
+ Good starting points:
34
+
35
+ - Anything in the "Known simplifications" section of
36
+ [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
37
+ - Additional unit tests for edge cases not yet covered
38
+ - Clearer error messages or documentation
39
+ - A real (non-mock) `KeyAuthority` backend, e.g. against a software TEE
40
+ simulator
41
+
42
+ For anything bigger than a small fix, please open an issue first to discuss
43
+ the approach before investing time in a PR.
44
+
45
+ ## Commit style
46
+
47
+ Small, focused commits with a clear one-line summary are preferred over one
48
+ large commit. No strict format is enforced beyond that.
49
+
50
+ ## Reporting bugs / requesting features
51
+
52
+ Use the issue templates under `.github/ISSUE_TEMPLATE/`. For security-relevant
53
+ findings, please see [`SECURITY.md`](SECURITY.md) instead of opening a public
54
+ issue.
55
+
56
+ ## Code of conduct
57
+
58
+ Be respectful and constructive. This is a small educational project — the bar
59
+ is "would a reasonable person feel welcome contributing here."
README.md CHANGED
@@ -1,9 +1,9 @@
1
- ---
2
- license: mit
3
- ---
4
-
5
  # UBDA — Unified Behavioral Data Access (V1.2-alpha)
6
 
 
 
 
 
7
  UBDA is a prototype **capability-based data access architecture** written in Rust. It
8
  models a system where a software behavioral-trust engine can *influence* trust
9
  levels, but only a separate hardware/TEE-style authority can ever mint the
@@ -16,6 +16,9 @@ explore the design pattern — not to ship a production security product.
16
  > is used as a placeholder for a future post-quantum signature scheme. Do not
17
  > use this as-is to protect real secrets.
18
 
 
 
 
19
  ## Concept
20
 
21
  * **Trust states (`T-1`…`T4`)** describe how strongly the system currently
@@ -66,7 +69,8 @@ cargo test
66
  Expected `cargo run` output walks through: reaching T2 via behavioral
67
  continuity, a rejected over-privileged request, a full issue → verify →
68
  derive-key cycle, a blocked replay attempt, a blocked signature-tampering
69
- attempt, and a compromise lockout + recovery reset.
 
70
 
71
  ## Requirements
72
 
@@ -77,3 +81,18 @@ attempt, and a compromise lockout + recovery reset.
77
  ## License
78
 
79
  MIT — see [`LICENSE`](LICENSE).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # UBDA — Unified Behavioral Data Access (V1.2-alpha)
2
 
3
+ [![CI](https://github.com/kaymyg/ubda-engine/actions/workflows/ci.yml/badge.svg)](https://github.com/kaymyg/ubda-engine/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+ [![Rust 2021](https://img.shields.io/badge/rust-2021_edition-orange.svg)](Cargo.toml)
6
+
7
  UBDA is a prototype **capability-based data access architecture** written in Rust. It
8
  models a system where a software behavioral-trust engine can *influence* trust
9
  levels, but only a separate hardware/TEE-style authority can ever mint the
 
16
  > is used as a placeholder for a future post-quantum signature scheme. Do not
17
  > use this as-is to protect real secrets.
18
 
19
+ **Try it live:** [UBDA Engine Demo on Hugging Face Spaces](https://huggingface.co/spaces/sahek/ubda-engine)
20
+ — click "Run protocol walkthrough" to execute the real compiled engine in your browser.
21
+
22
  ## Concept
23
 
24
  * **Trust states (`T-1`…`T4`)** describe how strongly the system currently
 
69
  Expected `cargo run` output walks through: reaching T2 via behavioral
70
  continuity, a rejected over-privileged request, a full issue → verify →
71
  derive-key cycle, a blocked replay attempt, a blocked signature-tampering
72
+ attempt, full elevation through T3/T4 with real D2/D3 capability issuance, and
73
+ a compromise lockout + recovery reset.
74
 
75
  ## Requirements
76
 
 
81
  ## License
82
 
83
  MIT — see [`LICENSE`](LICENSE).
84
+
85
+ ## Contributing
86
+
87
+ Bug reports, feature ideas, and PRs are welcome — see
88
+ [`CONTRIBUTING.md`](CONTRIBUTING.md) for setup and the checks CI runs.
89
+
90
+ ## Security
91
+
92
+ Found a design or implementation flaw? Please see
93
+ [`SECURITY.md`](SECURITY.md) for how to report it responsibly rather than
94
+ opening a public issue.
95
+
96
+ ## Changelog
97
+
98
+ See [`CHANGELOG.md`](CHANGELOG.md).
SECURITY.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Project status
4
+
5
+ UBDA is a **prototype / educational project** exploring a capability-based
6
+ data access architecture. It is not audited, not hardened, and not intended
7
+ to protect real secrets in production. See the warning at the top of the
8
+ [README](README.md) for details — in particular, `MockHardwareAuthorizer`
9
+ uses an in-process Ed25519 keypair and a hard-coded demo secret in place of a
10
+ real HSM/TEE.
11
+
12
+ That said, if you find a genuine flaw in the *design* (e.g. a way to bypass
13
+ trust-state enforcement, forge a capability, or defeat replay protection
14
+ within the model as specified), that's a meaningful and welcome finding.
15
+
16
+ ## Reporting a vulnerability
17
+
18
+ Please **do not** open a public GitHub issue for security findings.
19
+
20
+ Instead, use GitHub's private vulnerability reporting for this repository
21
+ (Security tab → "Report a vulnerability"), or reach out directly to the
22
+ maintainer. Please include:
23
+
24
+ - A description of the issue and its potential impact
25
+ - Steps to reproduce, or a minimal example
26
+ - Whether it affects the architectural design itself vs. this specific
27
+ prototype implementation
28
+
29
+ ## Response expectations
30
+
31
+ This is a small, self-taught, part-time project — please expect a best-effort
32
+ response rather than a guaranteed SLA. Reports will be acknowledged as soon
33
+ as reasonably possible.
rustfmt.toml ADDED
@@ -0,0 +1 @@
 
 
1
+ edition = "2021"
src/bte_interface.rs CHANGED
@@ -17,7 +17,8 @@ impl BehavioralTrustEngine {
17
  ) -> PolicyAssertion {
18
  let inferred_state = if telemetry.anomaly_score >= self.anomaly_threshold {
19
  TrustState::Compromised
20
- } else if telemetry.anomaly_score < 0.20 && current_state == TrustState::DeviceAuthenticated {
 
21
  TrustState::BehavioralContinuity
22
  } else {
23
  current_state
 
17
  ) -> PolicyAssertion {
18
  let inferred_state = if telemetry.anomaly_score >= self.anomaly_threshold {
19
  TrustState::Compromised
20
+ } else if telemetry.anomaly_score < 0.20 && current_state == TrustState::DeviceAuthenticated
21
+ {
22
  TrustState::BehavioralContinuity
23
  } else {
24
  current_state
src/hardware_authorizer.rs CHANGED
@@ -1,5 +1,6 @@
1
  use crate::types::{
2
- AccessOperation, DataClassification, DataAccessCapability, EphemeralSessionKey, PolicyAssertion, TrustState
 
3
  };
4
  use ring::hkdf;
5
  use ring::rand::SystemRandom;
@@ -15,6 +16,9 @@ pub enum AuthorizerError {
15
  classification: DataClassification,
16
  },
17
  #[error("Signature generation failed.")]
 
 
 
18
  SigningFailure,
19
  #[error("Key derivation failed.")]
20
  DerivationFailure,
@@ -23,6 +27,10 @@ pub enum AuthorizerError {
23
  pub trait KeyAuthority {
24
  fn public_key_bytes(&self) -> &[u8];
25
 
 
 
 
 
26
  fn issue_dac(
27
  &self,
28
  assertion: &PolicyAssertion,
@@ -74,6 +82,7 @@ impl KeyAuthority for MockHardwareAuthorizer {
74
  &self.public_key
75
  }
76
 
 
77
  fn issue_dac(
78
  &self,
79
  assertion: &PolicyAssertion,
@@ -182,7 +191,10 @@ mod tests {
182
  60,
183
  1,
184
  );
185
- assert!(matches!(dac, Err(AuthorizerError::InsufficientTrustState { .. })));
 
 
 
186
  }
187
 
188
  #[test]
@@ -191,10 +203,26 @@ mod tests {
191
  let assertion = low_risk_assertion("s1", TrustState::BehavioralContinuity);
192
 
193
  let dac_a = authorizer
194
- .issue_dac(&assertion, "a.enc".to_string(), DataClassification::D1, AccessOperation::Read, 0, 60, 1)
 
 
 
 
 
 
 
 
195
  .unwrap();
196
  let dac_b = authorizer
197
- .issue_dac(&assertion, "b.enc".to_string(), DataClassification::D1, AccessOperation::Read, 0, 60, 2)
 
 
 
 
 
 
 
 
198
  .unwrap();
199
 
200
  let key_a = authorizer.derive_session_key(&dac_a).unwrap();
@@ -207,7 +235,15 @@ mod tests {
207
  let authorizer = MockHardwareAuthorizer::new();
208
  let assertion = low_risk_assertion("s1", TrustState::BehavioralContinuity);
209
  let dac = authorizer
210
- .issue_dac(&assertion, "a.enc".to_string(), DataClassification::D1, AccessOperation::Read, 0, 60, 1)
 
 
 
 
 
 
 
 
211
  .unwrap();
212
 
213
  let key1 = authorizer.derive_session_key(&dac).unwrap();
 
1
  use crate::types::{
2
+ AccessOperation, DataAccessCapability, DataClassification, EphemeralSessionKey,
3
+ PolicyAssertion, TrustState,
4
  };
5
  use ring::hkdf;
6
  use ring::rand::SystemRandom;
 
16
  classification: DataClassification,
17
  },
18
  #[error("Signature generation failed.")]
19
+ // Ring's Ed25519 signing is currently infallible, so this variant isn't reachable yet.
20
+ // It's kept for forward compatibility with a fallible hardware/HSM or PQC signer.
21
+ #[allow(dead_code)]
22
  SigningFailure,
23
  #[error("Key derivation failed.")]
24
  DerivationFailure,
 
27
  pub trait KeyAuthority {
28
  fn public_key_bytes(&self) -> &[u8];
29
 
30
+ // 8 args mirrors the signed DAC envelope's field set (resource, classification,
31
+ // operation, timing, nonce) one-to-one; a request-object refactor is tracked as a
32
+ // possible future cleanup, not urgent for a prototype of this size.
33
+ #[allow(clippy::too_many_arguments)]
34
  fn issue_dac(
35
  &self,
36
  assertion: &PolicyAssertion,
 
82
  &self.public_key
83
  }
84
 
85
+ #[allow(clippy::too_many_arguments)]
86
  fn issue_dac(
87
  &self,
88
  assertion: &PolicyAssertion,
 
191
  60,
192
  1,
193
  );
194
+ assert!(matches!(
195
+ dac,
196
+ Err(AuthorizerError::InsufficientTrustState { .. })
197
+ ));
198
  }
199
 
200
  #[test]
 
203
  let assertion = low_risk_assertion("s1", TrustState::BehavioralContinuity);
204
 
205
  let dac_a = authorizer
206
+ .issue_dac(
207
+ &assertion,
208
+ "a.enc".to_string(),
209
+ DataClassification::D1,
210
+ AccessOperation::Read,
211
+ 0,
212
+ 60,
213
+ 1,
214
+ )
215
  .unwrap();
216
  let dac_b = authorizer
217
+ .issue_dac(
218
+ &assertion,
219
+ "b.enc".to_string(),
220
+ DataClassification::D1,
221
+ AccessOperation::Read,
222
+ 0,
223
+ 60,
224
+ 2,
225
+ )
226
  .unwrap();
227
 
228
  let key_a = authorizer.derive_session_key(&dac_a).unwrap();
 
235
  let authorizer = MockHardwareAuthorizer::new();
236
  let assertion = low_risk_assertion("s1", TrustState::BehavioralContinuity);
237
  let dac = authorizer
238
+ .issue_dac(
239
+ &assertion,
240
+ "a.enc".to_string(),
241
+ DataClassification::D1,
242
+ AccessOperation::Read,
243
+ 0,
244
+ 60,
245
+ 1,
246
+ )
247
  .unwrap();
248
 
249
  let key1 = authorizer.derive_session_key(&dac).unwrap();
src/key_broker.rs CHANGED
@@ -9,13 +9,23 @@ pub enum KeyBrokerError {
9
  #[error("Invalid capability signature or canonical payload tampered.")]
10
  InvalidSignature,
11
  #[error("Time bounds invalid. Current: {current}, Issued: {issued}, Expires: {expires}")]
12
- InvalidTimeBounds { current: i64, issued: i64, expires: i64 },
 
 
 
 
13
  #[error("Capability replayed! Cap ID or nonce consumed.")]
14
  ReplayDetected,
15
  #[error("Operation requested ({requested:?}) does not match DAC permission ({permitted:?}).")]
16
- OperationMismatch { requested: AccessOperation, permitted: AccessOperation },
 
 
 
17
  #[error("System trust state ({current:?}) is lower than required DAC state ({required:?}).")]
18
- StateRequirementNotMet { current: TrustState, required: TrustState },
 
 
 
19
  #[error("Session ID mismatch. Key Broker bound to {expected}, DAC issued to {found}.")]
20
  SessionMismatch { expected: String, found: String },
21
  #[error("Underlying Key Authority error.")]
@@ -72,7 +82,10 @@ impl<'a> KeyBroker<'a> {
72
  });
73
  }
74
 
75
- if !self.replay_store.check_and_register(&dac.cap_id, &dac.session_id, dac.nonce) {
 
 
 
76
  return Err(KeyBrokerError::ReplayDetected);
77
  }
78
 
@@ -96,7 +109,12 @@ mod tests {
96
  use crate::hardware_authorizer::MockHardwareAuthorizer;
97
  use crate::types::{BehavioralTelemetry, DataClassification};
98
 
99
- fn setup() -> (MockHardwareAuthorizer, DataAccessCapability, i64, &'static str) {
 
 
 
 
 
100
  let authorizer = MockHardwareAuthorizer::new();
101
  let bte = BehavioralTrustEngine::new(0.7);
102
  let session_id = "test_session";
@@ -108,7 +126,8 @@ mod tests {
108
  spatial_risk_factor: 0.01,
109
  timestamp: now,
110
  };
111
- let assertion = bte.process_telemetry(session_id, telemetry, TrustState::DeviceAuthenticated);
 
112
 
113
  let dac = authorizer
114
  .issue_dac(
@@ -144,7 +163,13 @@ mod tests {
144
  let (authorizer, dac, now, session_id) = setup();
145
  let mut broker = KeyBroker::new(&authorizer);
146
  broker
147
- .execute_key_use(&dac, session_id, AccessOperation::Read, now, TrustState::BehavioralContinuity)
 
 
 
 
 
 
148
  .unwrap();
149
 
150
  let replay = broker.execute_key_use(
@@ -184,7 +209,10 @@ mod tests {
184
  now,
185
  TrustState::DeviceAuthenticated, // below required T2
186
  );
187
- assert!(matches!(result, Err(KeyBrokerError::StateRequirementNotMet { .. })));
 
 
 
188
  }
189
 
190
  #[test]
@@ -198,7 +226,10 @@ mod tests {
198
  now + 301, // past TTL
199
  TrustState::BehavioralContinuity,
200
  );
201
- assert!(matches!(result, Err(KeyBrokerError::InvalidTimeBounds { .. })));
 
 
 
202
  }
203
 
204
  #[test]
@@ -212,7 +243,10 @@ mod tests {
212
  now,
213
  TrustState::BehavioralContinuity,
214
  );
215
- assert!(matches!(result, Err(KeyBrokerError::OperationMismatch { .. })));
 
 
 
216
  }
217
 
218
  #[test]
@@ -226,6 +260,9 @@ mod tests {
226
  now,
227
  TrustState::BehavioralContinuity,
228
  );
229
- assert!(matches!(result, Err(KeyBrokerError::SessionMismatch { .. })));
 
 
 
230
  }
231
  }
 
9
  #[error("Invalid capability signature or canonical payload tampered.")]
10
  InvalidSignature,
11
  #[error("Time bounds invalid. Current: {current}, Issued: {issued}, Expires: {expires}")]
12
+ InvalidTimeBounds {
13
+ current: i64,
14
+ issued: i64,
15
+ expires: i64,
16
+ },
17
  #[error("Capability replayed! Cap ID or nonce consumed.")]
18
  ReplayDetected,
19
  #[error("Operation requested ({requested:?}) does not match DAC permission ({permitted:?}).")]
20
+ OperationMismatch {
21
+ requested: AccessOperation,
22
+ permitted: AccessOperation,
23
+ },
24
  #[error("System trust state ({current:?}) is lower than required DAC state ({required:?}).")]
25
+ StateRequirementNotMet {
26
+ current: TrustState,
27
+ required: TrustState,
28
+ },
29
  #[error("Session ID mismatch. Key Broker bound to {expected}, DAC issued to {found}.")]
30
  SessionMismatch { expected: String, found: String },
31
  #[error("Underlying Key Authority error.")]
 
82
  });
83
  }
84
 
85
+ if !self
86
+ .replay_store
87
+ .check_and_register(&dac.cap_id, &dac.session_id, dac.nonce)
88
+ {
89
  return Err(KeyBrokerError::ReplayDetected);
90
  }
91
 
 
109
  use crate::hardware_authorizer::MockHardwareAuthorizer;
110
  use crate::types::{BehavioralTelemetry, DataClassification};
111
 
112
+ fn setup() -> (
113
+ MockHardwareAuthorizer,
114
+ DataAccessCapability,
115
+ i64,
116
+ &'static str,
117
+ ) {
118
  let authorizer = MockHardwareAuthorizer::new();
119
  let bte = BehavioralTrustEngine::new(0.7);
120
  let session_id = "test_session";
 
126
  spatial_risk_factor: 0.01,
127
  timestamp: now,
128
  };
129
+ let assertion =
130
+ bte.process_telemetry(session_id, telemetry, TrustState::DeviceAuthenticated);
131
 
132
  let dac = authorizer
133
  .issue_dac(
 
163
  let (authorizer, dac, now, session_id) = setup();
164
  let mut broker = KeyBroker::new(&authorizer);
165
  broker
166
+ .execute_key_use(
167
+ &dac,
168
+ session_id,
169
+ AccessOperation::Read,
170
+ now,
171
+ TrustState::BehavioralContinuity,
172
+ )
173
  .unwrap();
174
 
175
  let replay = broker.execute_key_use(
 
209
  now,
210
  TrustState::DeviceAuthenticated, // below required T2
211
  );
212
+ assert!(matches!(
213
+ result,
214
+ Err(KeyBrokerError::StateRequirementNotMet { .. })
215
+ ));
216
  }
217
 
218
  #[test]
 
226
  now + 301, // past TTL
227
  TrustState::BehavioralContinuity,
228
  );
229
+ assert!(matches!(
230
+ result,
231
+ Err(KeyBrokerError::InvalidTimeBounds { .. })
232
+ ));
233
  }
234
 
235
  #[test]
 
243
  now,
244
  TrustState::BehavioralContinuity,
245
  );
246
+ assert!(matches!(
247
+ result,
248
+ Err(KeyBrokerError::OperationMismatch { .. })
249
+ ));
250
  }
251
 
252
  #[test]
 
260
  now,
261
  TrustState::BehavioralContinuity,
262
  );
263
+ assert!(matches!(
264
+ result,
265
+ Err(KeyBrokerError::SessionMismatch { .. })
266
+ ));
267
  }
268
  }
src/main.rs CHANGED
@@ -23,7 +23,7 @@ fn main() {
23
  let now = chrono::Utc::now().timestamp();
24
 
25
  // 1. Establish State T0 -> T1 -> T2
26
- println!("\n[1/6] Transitioning State: T0 -> T1 -> T2...");
27
  state_machine.handle_device_authenticated().unwrap();
28
 
29
  let telemetry = BehavioralTelemetry {
@@ -33,14 +33,20 @@ fn main() {
33
  timestamp: now,
34
  };
35
 
36
- let assertion = bte.process_telemetry(session_id, telemetry.clone(), state_machine.current_state());
37
- state_machine.handle_behavioral_assertion(&telemetry).unwrap();
 
 
 
38
 
39
- assert_eq!(state_machine.current_state(), TrustState::BehavioralContinuity);
 
 
 
40
  println!(" -> Active State: T2 (BehavioralContinuity)");
41
 
42
  // 2. Reject Insufficient Classification (T2 requesting D2 data)
43
- println!("\n[2/6] Testing Classification Policy Enforcement (T2 requesting D2 data)...");
44
  let d2_issuance = mock_authorizer.issue_dac(
45
  &assertion,
46
  "financial_records.enc".to_string(),
@@ -59,7 +65,7 @@ fn main() {
59
  }
60
 
61
  // 3. Valid D1 Capability Cycle
62
- println!("\n[3/6] Issuing & Consuming Valid D1 Capability...");
63
  let valid_dac = mock_authorizer
64
  .issue_dac(
65
  &assertion,
@@ -73,13 +79,22 @@ fn main() {
73
  .expect("D1 DAC issuance failed");
74
 
75
  let key = key_broker
76
- .execute_key_use(&valid_dac, session_id, AccessOperation::Read, now, state_machine.current_state())
 
 
 
 
 
 
77
  .expect("Key derivation failed");
78
 
79
- println!(" -> PASS: Derived Ephemeral Key (Digest: {:?})", &key.key_bytes[0..4]);
 
 
 
80
 
81
  // 4. Anti-Replay Enforcement
82
- println!("\n[4/6] Testing Replay Defense...");
83
  let replay_result = key_broker.execute_key_use(
84
  &valid_dac,
85
  session_id,
@@ -96,7 +111,7 @@ fn main() {
96
  }
97
 
98
  // 5. Signature Tamper Verification
99
- println!("\n[5/6] Testing Signature Integrity Verification...");
100
  let mut tampered_dac = mock_authorizer
101
  .issue_dac(
102
  &assertion,
@@ -122,13 +137,73 @@ fn main() {
122
 
123
  match tamper_result {
124
  Err(key_broker::KeyBrokerError::InvalidSignature) => {
125
- println!(" -> PASS: Key Broker detected field modification via canonical verification.");
 
 
126
  }
127
  _ => panic!(" -> FAIL: Tampered capability signature validated!"),
128
  }
129
 
130
- // 6. Hard Anomaly Lockout & Controlled Recovery
131
- println!("\n[6/6] Injecting Hard Anomaly Interrupt (T_-1 Lockout)...");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  state_machine.trigger_compromise();
133
  assert_eq!(state_machine.current_state(), TrustState::Compromised);
134
 
 
23
  let now = chrono::Utc::now().timestamp();
24
 
25
  // 1. Establish State T0 -> T1 -> T2
26
+ println!("\n[1/7] Transitioning State: T0 -> T1 -> T2...");
27
  state_machine.handle_device_authenticated().unwrap();
28
 
29
  let telemetry = BehavioralTelemetry {
 
33
  timestamp: now,
34
  };
35
 
36
+ let assertion =
37
+ bte.process_telemetry(session_id, telemetry.clone(), state_machine.current_state());
38
+ state_machine
39
+ .handle_behavioral_assertion(&telemetry)
40
+ .unwrap();
41
 
42
+ assert_eq!(
43
+ state_machine.current_state(),
44
+ TrustState::BehavioralContinuity
45
+ );
46
  println!(" -> Active State: T2 (BehavioralContinuity)");
47
 
48
  // 2. Reject Insufficient Classification (T2 requesting D2 data)
49
+ println!("\n[2/7] Testing Classification Policy Enforcement (T2 requesting D2 data)...");
50
  let d2_issuance = mock_authorizer.issue_dac(
51
  &assertion,
52
  "financial_records.enc".to_string(),
 
65
  }
66
 
67
  // 3. Valid D1 Capability Cycle
68
+ println!("\n[3/7] Issuing & Consuming Valid D1 Capability...");
69
  let valid_dac = mock_authorizer
70
  .issue_dac(
71
  &assertion,
 
79
  .expect("D1 DAC issuance failed");
80
 
81
  let key = key_broker
82
+ .execute_key_use(
83
+ &valid_dac,
84
+ session_id,
85
+ AccessOperation::Read,
86
+ now,
87
+ state_machine.current_state(),
88
+ )
89
  .expect("Key derivation failed");
90
 
91
+ println!(
92
+ " -> PASS: Derived Ephemeral Key (Digest: {:?})",
93
+ &key.key_bytes[0..4]
94
+ );
95
 
96
  // 4. Anti-Replay Enforcement
97
+ println!("\n[4/7] Testing Replay Defense...");
98
  let replay_result = key_broker.execute_key_use(
99
  &valid_dac,
100
  session_id,
 
111
  }
112
 
113
  // 5. Signature Tamper Verification
114
+ println!("\n[5/7] Testing Signature Integrity Verification...");
115
  let mut tampered_dac = mock_authorizer
116
  .issue_dac(
117
  &assertion,
 
137
 
138
  match tamper_result {
139
  Err(key_broker::KeyBrokerError::InvalidSignature) => {
140
+ println!(
141
+ " -> PASS: Key Broker detected field modification via canonical verification."
142
+ );
143
  }
144
  _ => panic!(" -> FAIL: Tampered capability signature validated!"),
145
  }
146
 
147
+ // 6. Full Elevation to T3/T4 and Issuing High-Classification Capabilities
148
+ println!("\n[6/7] Elevating T2 -> T3 -> T4 and Issuing D2/D3 Capabilities...");
149
+ state_machine.handle_step_up_auth().unwrap();
150
+ assert_eq!(state_machine.current_state(), TrustState::HighAssurance);
151
+ println!(" -> Active State: T3 (HighAssurance)");
152
+
153
+ let d2_assertion =
154
+ bte.process_telemetry(session_id, telemetry.clone(), state_machine.current_state());
155
+ let d2_dac = mock_authorizer
156
+ .issue_dac(
157
+ &d2_assertion,
158
+ "financial_records.enc".to_string(),
159
+ DataClassification::D2,
160
+ AccessOperation::Read,
161
+ now,
162
+ 300,
163
+ 2004,
164
+ )
165
+ .expect("D2 DAC issuance failed at T3");
166
+ key_broker
167
+ .execute_key_use(
168
+ &d2_dac,
169
+ session_id,
170
+ AccessOperation::Read,
171
+ now,
172
+ state_machine.current_state(),
173
+ )
174
+ .expect("D2 key derivation failed at T3");
175
+ println!(" -> PASS: Issued & consumed D2 capability under T3 trust level.");
176
+
177
+ state_machine.handle_critical_elevation().unwrap();
178
+ assert_eq!(state_machine.current_state(), TrustState::CriticalElevation);
179
+ println!(" -> Active State: T4 (CriticalElevation)");
180
+
181
+ let d3_assertion =
182
+ bte.process_telemetry(session_id, telemetry.clone(), state_machine.current_state());
183
+ let d3_dac = mock_authorizer
184
+ .issue_dac(
185
+ &d3_assertion,
186
+ "root_signing_key.enc".to_string(),
187
+ DataClassification::D3,
188
+ AccessOperation::Read,
189
+ now,
190
+ 300,
191
+ 2005,
192
+ )
193
+ .expect("D3 DAC issuance failed at T4");
194
+ key_broker
195
+ .execute_key_use(
196
+ &d3_dac,
197
+ session_id,
198
+ AccessOperation::Read,
199
+ now,
200
+ state_machine.current_state(),
201
+ )
202
+ .expect("D3 key derivation failed at T4");
203
+ println!(" -> PASS: Issued & consumed D3 (master key) capability under T4 trust level.");
204
+
205
+ // 7. Hard Anomaly Lockout & Controlled Recovery
206
+ println!("\n[7/7] Injecting Hard Anomaly Interrupt (T_-1 Lockout)...");
207
  state_machine.trigger_compromise();
208
  assert_eq!(state_machine.current_state(), TrustState::Compromised);
209
 
src/state_machine.rs CHANGED
@@ -43,7 +43,10 @@ impl SystemStateMachine {
43
  Ok(self.current_state)
44
  }
45
 
46
- pub fn handle_behavioral_assertion(&mut self, telemetry: &BehavioralTelemetry) -> Result<TrustState, StateMachineError> {
 
 
 
47
  self.assert_not_compromised()?;
48
 
49
  if telemetry.anomaly_score >= self.anomaly_threshold {
@@ -134,7 +137,8 @@ mod tests {
134
  sm.handle_device_authenticated().unwrap();
135
  assert_eq!(sm.current_state(), TrustState::DeviceAuthenticated);
136
 
137
- sm.handle_behavioral_assertion(&low_risk_telemetry()).unwrap();
 
138
  assert_eq!(sm.current_state(), TrustState::BehavioralContinuity);
139
 
140
  sm.handle_step_up_auth().unwrap();
@@ -173,7 +177,9 @@ mod tests {
173
  sm.trigger_compromise();
174
 
175
  assert!(sm.handle_device_authenticated().is_err());
176
- assert!(sm.handle_behavioral_assertion(&low_risk_telemetry()).is_err());
 
 
177
  assert!(sm.handle_step_up_auth().is_err());
178
  assert!(sm.handle_critical_elevation().is_err());
179
 
 
43
  Ok(self.current_state)
44
  }
45
 
46
+ pub fn handle_behavioral_assertion(
47
+ &mut self,
48
+ telemetry: &BehavioralTelemetry,
49
+ ) -> Result<TrustState, StateMachineError> {
50
  self.assert_not_compromised()?;
51
 
52
  if telemetry.anomaly_score >= self.anomaly_threshold {
 
137
  sm.handle_device_authenticated().unwrap();
138
  assert_eq!(sm.current_state(), TrustState::DeviceAuthenticated);
139
 
140
+ sm.handle_behavioral_assertion(&low_risk_telemetry())
141
+ .unwrap();
142
  assert_eq!(sm.current_state(), TrustState::BehavioralContinuity);
143
 
144
  sm.handle_step_up_auth().unwrap();
 
177
  sm.trigger_compromise();
178
 
179
  assert!(sm.handle_device_authenticated().is_err());
180
+ assert!(sm
181
+ .handle_behavioral_assertion(&low_risk_telemetry())
182
+ .is_err());
183
  assert!(sm.handle_step_up_auth().is_err());
184
  assert!(sm.handle_critical_elevation().is_err());
185
 
src/types.rs CHANGED
@@ -4,21 +4,21 @@ use zeroize::{Zeroize, ZeroizeOnDrop};
4
  #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
5
  pub enum TrustState {
6
  Compromised = -1, // T_-1: Hard Isolation / Containment
7
- Unauthenticated = 0, // T_0: Unauthenticated / Raw Boot
8
- DeviceAuthenticated = 1, // T_1: Hardened Device Access
9
- BehavioralContinuity = 2,// T_2: BTE Telemetry Verified
10
- HighAssurance = 3, // T_3: Biometric / Step-Up Verified
11
- CriticalElevation = 4, // T_4: Out-of-Band / Hardware Token
12
  }
13
 
14
  impl TrustState {
15
  /// Enforces the minimum trust state required for each data classification level.
16
  pub fn minimum_required_for(classification: DataClassification) -> Self {
17
  match classification {
18
- DataClassification::D0 => TrustState::DeviceAuthenticated, // D0 -> T1
19
- DataClassification::D1 => TrustState::BehavioralContinuity, // D1 -> T2
20
- DataClassification::D2 => TrustState::HighAssurance, // D2 -> T3
21
- DataClassification::D3 => TrustState::CriticalElevation, // D3 -> T4
22
  }
23
  }
24
  }
 
4
  #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
5
  pub enum TrustState {
6
  Compromised = -1, // T_-1: Hard Isolation / Containment
7
+ Unauthenticated = 0, // T_0: Unauthenticated / Raw Boot
8
+ DeviceAuthenticated = 1, // T_1: Hardened Device Access
9
+ BehavioralContinuity = 2, // T_2: BTE Telemetry Verified
10
+ HighAssurance = 3, // T_3: Biometric / Step-Up Verified
11
+ CriticalElevation = 4, // T_4: Out-of-Band / Hardware Token
12
  }
13
 
14
  impl TrustState {
15
  /// Enforces the minimum trust state required for each data classification level.
16
  pub fn minimum_required_for(classification: DataClassification) -> Self {
17
  match classification {
18
+ DataClassification::D0 => TrustState::DeviceAuthenticated, // D0 -> T1
19
+ DataClassification::D1 => TrustState::BehavioralContinuity, // D1 -> T2
20
+ DataClassification::D2 => TrustState::HighAssurance, // D2 -> T3
21
+ DataClassification::D3 => TrustState::CriticalElevation, // D3 -> T4
22
  }
23
  }
24
  }