Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/test-suite-registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -1378,6 +1378,19 @@
"status": "mapped",
"notes": "Existing nightly full-flake check runs test-sandbox over default workspace members; this crate's integration targets are distinct from the five explicit PR targets added by #10329."
},
{
"id": "id.rust.id-events.integration",
"paths": ["pkgs/id/crates/id-events/tests/append_list_state_machine.rs"],
"invocation": "nix flake check ./pkgs/id (check test-sandbox runs cargo nextest --all-features for default workspace members)",
"venue": {
"workflow": ".github/workflows/id-check.yml",
"job_step": "full-flake-check / Run full nix flake check",
"state": "active",
"dispatchable": true
},
"status": "mapped",
"notes": "Model-based append-admission state-machine oracle for A-GRAPH-9127-02 (#10237)."
},
{
"id": "id.rust.id-currency-registry.integration",
"paths": [
Expand Down
53 changes: 53 additions & 0 deletions pkgs/id/crates/id-core/src/graph/append_list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! Append-list submission vocabulary for A-GRAPH-9127-02 (#10237).
//!
//! This leaf owns only the signed-submission shape and state identifiers.
//! Admission, membership and revocation rechecks live in `id-events` so the
//! graph model cannot copy or weaken the authorization interface.

/// Stable identifier for a pending submission.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PendingId(String);

impl PendingId {
/// Borrow the stable identifier.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}

impl From<&str> for PendingId {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}

impl From<String> for PendingId {
fn from(value: String) -> Self {
Self(value)
}
}

/// A signed append submission after its signature verifier has run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttributeSubmission {
/// Stable submission identity.
pub id: String,
/// Caller-chosen idempotency key.
pub idempotency_key: String,
/// Exact signed bytes, retained for idempotency conflict checks.
pub bytes: Vec<u8>,
/// Signer identity bound by the verified evidence.
pub signer: String,
/// Result of the signature/evidence verifier.
pub signature_valid: bool,
}

/// Result of submitting a valid signed append.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AdmissionOutcome {
/// The submission waits for approval.
Pending(PendingId),
/// The submission was directly accepted.
Accepted,
}
1 change: 1 addition & 0 deletions pkgs/id/crates/id-core/src/graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! is not reachable from its crate root. A module that does not exist
//! yet is never declared.

pub mod append_list;
pub mod attribute;
pub mod cross_signing;
pub mod cursor;
Expand Down
142 changes: 142 additions & 0 deletions pkgs/id/crates/id-events/src/graph_admission.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//! Append-list admission state machine for A-GRAPH-9127-02 (#10237).
//!
//! Signature verification happens before this state machine. The policy is
//! supplied on every operation so approval rechecks current membership,
//! policy and revocation instead of trusting the snapshot seen at submit.

use std::collections::{BTreeMap, BTreeSet};

use id_core::graph::append_list::{AdmissionOutcome, AttributeSubmission, PendingId};
use id_core::graph::attribute::{AdmissionRule, AppendMode};
use thiserror::Error;

/// Current policy inputs used by submission and approval.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AdmissionPolicy {
/// Whether the attribute accepts submissions.
pub mode: AppendMode,
/// Which submitters can be accepted without moderation.
pub rule: AdmissionRule,
/// Current group members.
pub members: BTreeSet<String>,
/// Current group administrators.
pub admins: BTreeSet<String>,
/// Current revoked signers.
pub revoked: BTreeSet<String>,
/// Monotonic policy epoch used by callers for CAS fencing.
pub epoch: u64,
}

/// Admission failures; none mutate the accepted order.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum AdmissionError {
/// The signed evidence was invalid.
#[error("submission signature is invalid")]
InvalidSignature,
/// The attribute is closed.
#[error("attribute is closed")]
Closed,
/// The idempotency key was reused for different bytes.
#[error("idempotency key conflicts with different bytes")]
IdempotencyConflict,
/// The signer is not eligible under the current policy.
#[error("submitter is not currently eligible")]
NotEligible,
/// The signer was revoked after submit.
#[error("submitter is revoked")]
Revoked,
/// The named pending item does not exist.
#[error("pending submission not found")]
NotFound,
}

/// Deterministic append admission state.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AppendAdmission {
accepted: Vec<String>,
pending: BTreeMap<PendingId, AttributeSubmission>,
idempotency: BTreeMap<String, Vec<u8>>,
}

impl AppendAdmission {
/// Submit verified evidence under the current policy.
pub fn submit(
&mut self,
submission: AttributeSubmission,
policy: AdmissionPolicy,
) -> Result<AdmissionOutcome, AdmissionError> {
if !submission.signature_valid {
return Err(AdmissionError::InvalidSignature);
}
if let Some(bytes) = self.idempotency.get(&submission.idempotency_key) {
if bytes != &submission.bytes {
return Err(AdmissionError::IdempotencyConflict);
}
let pending = PendingId::from(submission.id.as_str());
return if self.pending.contains_key(&pending) {
Ok(AdmissionOutcome::Pending(pending))
} else {
Ok(AdmissionOutcome::Accepted)
Comment on lines +75 to +79

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve idempotent retries using the original submission identity

When a pending submission is retried with the same idempotency key and bytes but a different id, this branch looks up the retry's ID and returns Accepted even though the original submission is still pending and nothing was accepted. AttributeSubmission exposes these fields independently, and this API neither validates their binding nor retains the original ID in the idempotency record. Store the original submission identity alongside the bytes and return its actual state, or reject inconsistent identities.

Useful? React with 👍 / 👎.

};
}
if !policy.mode.accepts_submissions() {
return Err(AdmissionError::Closed);
}
self.idempotency
.insert(submission.idempotency_key.clone(), submission.bytes.clone());
let pending = PendingId::from(submission.id.as_str());
if policy.mode == AppendMode::Open && eligible(&policy, &submission.signer) {
self.accepted.push(submission.id);
Ok(AdmissionOutcome::Accepted)
} else {
self.pending.insert(pending.clone(), submission);
Ok(AdmissionOutcome::Pending(pending))
}
}

/// Approve one pending submission after rechecking current policy state.
pub fn approve(&mut self, id: &str, policy: &AdmissionPolicy) -> Result<(), AdmissionError> {
let pending = self
.pending
.get(&PendingId::from(id))
.ok_or(AdmissionError::NotFound)?;
if policy.revoked.contains(&pending.signer) {
return Err(AdmissionError::Revoked);
}
if !eligible(policy, &pending.signer) {
return Err(AdmissionError::NotEligible);
}
Comment on lines +106 to +108

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Check reviewer eligibility separately from direct admission

For a non-group submitter on an open attribute, submit correctly creates a pending item, but this check prevents anyone from approving it unless the submitter first becomes eligible for direct acceptance. AdmissionRule is documented as controlling direct acceptance, and design §6.2 permits non-group submissions through member/admin approval. Approval needs a separately authorized reviewer rather than requiring the original signer to satisfy the direct-admission rule; otherwise the advertised moderation path cannot publish external submissions.

Useful? React with 👍 / 👎.

let pending = self
.pending
.remove(&PendingId::from(id))
.ok_or(AdmissionError::NotFound)?;
self.accepted.push(pending.id);
Comment on lines +109 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject approval after the attribute has been closed

If a member submits while the attribute is moderated and the owner subsequently changes its mode to Closed, approve still removes the pending item and appends it to the accepted list. This method never examines policy.mode, although it receives the current policy and promises to recheck it. Check the current append mode before committing acceptance so closing an attribute also prevents pending submissions from being appended.

Useful? React with 👍 / 👎.

Ok(())
}

/// Accepted IDs in authoritative append order.
#[must_use]
pub fn accepted(&self) -> &[String] {
&self.accepted
}

/// Pending submissions keyed by their stable IDs.
#[must_use]
pub fn pending(&self) -> &BTreeMap<PendingId, AttributeSubmission> {
&self.pending
}
}

fn eligible(policy: &AdmissionPolicy, signer: &str) -> bool {
if policy.revoked.contains(signer) {
return false;
}
match policy.rule {
AdmissionRule::OwnerOnly => policy.admins.contains(signer),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Distinguish the owner from group administrators

With AdmissionRule::OwnerOnly, any signer in policy.admins is directly accepted, exactly as with AdmissionRule::Admins. The existing enum explicitly defines OwnerOnly as accepting only the owner, so an administrator who is not the owner can bypass moderation under this policy. Carry the owner identity separately and compare against it for this rule.

Useful? React with 👍 / 👎.

AdmissionRule::Admins => policy.admins.contains(signer),
AdmissionRule::Members => policy.members.contains(signer),
AdmissionRule::AdminsAndMembers => {
policy.admins.contains(signer) || policy.members.contains(signer)
}
}
}
1 change: 1 addition & 0 deletions pkgs/id/crates/id-events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub use id_core::port;
pub mod attestation;
pub mod event_store;
pub mod event_sync;
pub mod graph_admission;
pub mod groups;
pub mod idset;
pub mod local_claims;
Expand Down
113 changes: 113 additions & 0 deletions pkgs/id/crates/id-events/tests/append_list_state_machine.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//! Model-based oracle for A-GRAPH-9127-02 (#10237).
//!
//! The model says invalid signatures never enter either state; open attributes
//! still hold non-group submissions in Pending; approval rechecks current
//! membership and revocation; idempotency keys conflict on different bytes;
//! and accepted order is append-only.
Comment on lines +1 to +6

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exercise admission transitions with a generated reference model

This suite describes itself as model-based, but all four tests are fixed examples against the implementation; there is no independent transition model or generated command sequence. The repository's testing doctrine explicitly requires PBT for state-machine invariants and MBT where a specification exists. Add a reference model and generate submit, approve, retry, and policy-change sequences, comparing results and state after each operation; the current examples do not exercise successful approval or interacting transitions.

AGENTS.md reference: AGENTS.md:L36-L39

Useful? React with 👍 / 👎.


use std::collections::BTreeSet;

use id_core::graph::append_list::{AdmissionOutcome, AttributeSubmission, PendingId};
use id_core::graph::attribute::{AdmissionRule, AppendMode};
use id_events::graph_admission::{AdmissionError, AdmissionPolicy, AppendAdmission};

fn policy(mode: AppendMode, members: &[&str]) -> AdmissionPolicy {
AdmissionPolicy {
mode,
rule: AdmissionRule::Members,
members: members.iter().map(|value| (*value).to_owned()).collect(),
admins: BTreeSet::new(),
revoked: BTreeSet::new(),
epoch: 1,
}
}

fn submission(id: &str, key: &str, bytes: &[u8], signer: &str) -> AttributeSubmission {
AttributeSubmission {
id: id.to_owned(),
idempotency_key: key.to_owned(),
bytes: bytes.to_vec(),
signer: signer.to_owned(),
signature_valid: true,
}
}

#[test]
fn invalid_signatures_never_enter_pending_or_accepted() {
let mut admission = AppendAdmission::default();
let mut bad = submission("bad", "k1", b"bad", "alice");
bad.signature_valid = false;

assert_eq!(
admission
.submit(bad, policy(AppendMode::Open, &[]))
.unwrap_err(),
AdmissionError::InvalidSignature
);
assert!(admission.pending().is_empty());
assert!(admission.accepted().is_empty());
}

#[test]
fn open_non_member_waits_but_member_can_be_accepted_directly() {
let mut admission = AppendAdmission::default();
let pending = admission
.submit(
submission("p", "p", b"pending", "bob"),
policy(AppendMode::Open, &["alice"]),
)
.unwrap();
assert_eq!(pending, AdmissionOutcome::Pending(PendingId::from("p")));

let accepted = admission
.submit(
submission("a", "a", b"accepted", "alice"),
policy(AppendMode::Open, &["alice"]),
)
.unwrap();
assert_eq!(accepted, AdmissionOutcome::Accepted);
assert_eq!(admission.accepted(), &["a"]);
}

#[test]
fn approval_rechecks_membership_and_revocation() {
let mut admission = AppendAdmission::default();
admission
.submit(
submission("p", "p", b"pending", "bob"),
policy(AppendMode::Open, &["alice"]),
)
.unwrap();

let mut removed = policy(AppendMode::Open, &["alice"]);
assert_eq!(
admission.approve("p", &removed).unwrap_err(),
AdmissionError::NotEligible
);

removed.members.insert("bob".to_owned());
removed.revoked.insert("bob".to_owned());
assert_eq!(
admission.approve("p", &removed).unwrap_err(),
AdmissionError::Revoked
);
}

#[test]
fn idempotency_conflict_and_order_are_deterministic() {
let mut admission = AppendAdmission::default();
let open = policy(AppendMode::Open, &["alice"]);
admission
.submit(submission("one", "same", b"one", "alice"), open.clone())
.unwrap();
assert_eq!(
admission
.submit(submission("two", "same", b"two", "alice"), open.clone())
.unwrap_err(),
AdmissionError::IdempotencyConflict
);
admission
.submit(submission("three", "three", b"three", "alice"), open)
.unwrap();
assert_eq!(admission.accepted(), &["one", "three"]);
}