auths-sdk 0.1.10

Application services layer for Auths identity operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Framework predicates over a compliance evidence pack.
//!
//! Renders an [`EvidencePack`] into the predicates auditors ask for — SLSA
//! Provenance v1 + a per-release SLSA VSA, an SPDX SBOM (pinned version, exact
//! bytes hashed), or a CRA obligation mapping (with NIST SSDF practice IDs) — each
//! as a single in-toto Statement that rides the **same** DSSE envelope, so one
//! verification path validates any of them.
//!
//! Two invariants travel through unchanged: point-in-time authority (each row's
//! [`AuthorityAtSigning`] is read from the already-classified pack, never
//! re-resolved against HEAD), and the honest witness ceiling
//! (`HonestyCeiling`) — a single-operator pack renders no third-party
//! non-equivocation claim, only the carried ceiling.

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

use chrono::{DateTime, Utc};
use serde::Serialize;
use sha2::{Digest, Sha256};

use super::query::{ComplianceFramework, ComplianceQueryError, EvidencePack, EvidenceRow};
use crate::domains::org::audit::AuthorityAtSigning;

/// in-toto Statement type URI.
pub const INTOTO_STATEMENT_TYPE: &str = "https://in-toto.io/Statement/v1";
/// SLSA Provenance v1 predicate type.
pub const SLSA_PROVENANCE_PREDICATE_TYPE: &str = "https://slsa.dev/provenance/v1";
/// SLSA Verification Summary Attestation predicate type.
pub const SLSA_VSA_PREDICATE_TYPE: &str = "https://slsa.dev/verification_summary/v1";
/// The pinned SPDX specification version emitted by the SBOM serializer.
pub const SPDX_VERSION: &str = "SPDX-2.3";
/// The Auths builder id recorded in SLSA provenance `runDetails`.
pub const AUTHS_BUILDER_ID: &str = "https://auths.dev/builder/compliance-query";
/// Aggregate SLSA report predicate type (carries per-artifact provenance + VSAs).
pub const SLSA_REPORT_PREDICATE_TYPE: &str = "https://auths.dev/compliance/slsa/v1";
/// SPDX SBOM report predicate type.
pub const SBOM_REPORT_PREDICATE_TYPE: &str = "https://auths.dev/compliance/sbom/v1";
/// CRA obligation-mapping report predicate type.
pub const CRA_REPORT_PREDICATE_TYPE: &str = "https://auths.dev/compliance/cra/v1";
/// SOC 2 Trust Services Criteria mapping report predicate type.
pub const SOC2_REPORT_PREDICATE_TYPE: &str = "https://auths.dev/compliance/soc2/v1";
/// ISO/IEC 27001:2022 Annex-A mapping report predicate type.
pub const ISO27001_REPORT_PREDICATE_TYPE: &str = "https://auths.dev/compliance/iso27001/v1";

/// Whether a fact is immutable build-level evidence or a point-in-time status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RowTimeliness {
    /// Build-level provenance — the artifact digest and who produced it never change.
    Timeless,
    /// A verification snapshot (signer not revoked at release) — valid as of the
    /// verification time, not a permanent claim.
    TimeSensitive,
}

/// A `(signer, verifier)` allow-list for the VSA root of trust.
///
/// Mirrors SLSA's pairing rule ("GitHub may sign for GitHub Actions, not for GCP
/// Deploy"). An **unconfigured** list permits any pairing; once a signer has
/// explicit verifiers, only those verifiers may vouch for it, and an unknown signer
/// fails closed.
#[derive(Debug, Clone, Default)]
pub struct SignerVerifierAllowList {
    pairs: BTreeMap<String, BTreeSet<String>>,
}

impl SignerVerifierAllowList {
    /// An empty (unconfigured) allow-list.
    pub fn new() -> Self {
        Self::default()
    }

    /// Permit `verifier` to vouch for `signer`.
    pub fn allow(mut self, signer: impl Into<String>, verifier: impl Into<String>) -> Self {
        self.pairs
            .entry(signer.into())
            .or_default()
            .insert(verifier.into());
        self
    }

    /// Whether `verifier` may vouch for `signer` under this list.
    ///
    /// Args:
    /// * `signer`: The signer DID.
    /// * `verifier`: The verifier id.
    ///
    /// Usage:
    /// ```ignore
    /// assert!(allow_list.is_allowed("did:keri:E…", "auths-compliance"));
    /// ```
    pub fn is_allowed(&self, signer: &str, verifier: &str) -> bool {
        match self.pairs.get(signer) {
            Some(verifiers) => verifiers.contains(verifier),
            None => self.pairs.is_empty(),
        }
    }
}

/// Parameters for the SLSA Verification Summary Attestation.
#[derive(Debug, Clone)]
pub struct VsaParams {
    /// The verifier id recorded in each VSA.
    pub verifier_id: String,
    /// The verification timestamp (injected, never `Utc::now()`).
    pub time_verified: DateTime<Utc>,
    /// The `(signer, verifier)` allow-list enforced in the VSA root of trust.
    pub allow_list: SignerVerifierAllowList,
}

/// A rendered framework report — a single in-toto Statement (the DSSE payload).
#[derive(Debug, Clone)]
pub struct FrameworkReport {
    /// The framework this report targets.
    pub framework: ComplianceFramework,
    /// The report's in-toto predicate type.
    pub predicate_type: String,
    /// The full in-toto Statement (`_type`/`subject`/`predicateType`/`predicate`).
    pub statement: serde_json::Value,
    /// For SBOM reports, the SHA-256 of the exact canonical SPDX document bytes.
    pub sbom_sha256: Option<String>,
}

impl FrameworkReport {
    /// Canonicalize the in-toto Statement (`json-canon`) — the exact DSSE payload.
    pub fn to_intoto_statement(&self) -> Result<String, ComplianceQueryError> {
        json_canon::to_string(&self.statement)
            .map_err(|e| ComplianceQueryError::Canonicalize(e.to_string()))
    }
}

/// Render the framework predicate selected by `pack.framework`.
///
/// Point-in-time authority is preserved (each row's [`AuthorityAtSigning`] is read
/// from the pack, never re-resolved). The honest [`HonestyCeiling`] is carried, so a
/// single-operator pack emits no third-party non-equivocation claim.
///
/// Args:
/// * `pack`: The classified evidence pack.
/// * `vsa`: VSA verifier id, injected timestamp, and the signer/verifier allow-list.
///
/// Usage:
/// ```ignore
/// let report = build_framework_report(&pack, &vsa_params)?;
/// let envelope = sign_framework_report(&ctx, org_did, &alias, curve, &report)?;
/// ```
pub fn build_framework_report(
    pack: &EvidencePack,
    vsa: &VsaParams,
) -> Result<FrameworkReport, ComplianceQueryError> {
    match pack.framework {
        ComplianceFramework::Slsa => Ok(build_slsa(pack, vsa)),
        ComplianceFramework::Sbom => Ok(build_sbom(pack)),
        ComplianceFramework::Cra => Ok(build_cra(pack)),
        ComplianceFramework::Soc2 => Ok(build_soc2(pack)),
        ComplianceFramework::Iso27001 => Ok(build_iso27001(pack)),
    }
}

/// Compute the SHA-256 of the canonical bytes of an SPDX document (`sha256:<hex>`).
///
/// Anchoring this exact-bytes hash means a regenerated SBOM that differs by even one
/// byte is detected rather than silently accepted.
pub fn sbom_document_sha256(document: &serde_json::Value) -> Result<String, ComplianceQueryError> {
    let bytes = json_canon::to_vec(document)
        .map_err(|e| ComplianceQueryError::Canonicalize(e.to_string()))?;
    Ok(format!("sha256:{}", hex::encode(Sha256::digest(&bytes))))
}

// ── in-toto subject ──────────────────────────────────────────────────────────

/// in-toto `subject` entries for every row's artifact digest.
fn subjects(rows: &[EvidenceRow]) -> Vec<serde_json::Value> {
    rows.iter()
        .map(|r| {
            let digest = r
                .artifact_digest
                .strip_prefix("sha256:")
                .unwrap_or(&r.artifact_digest);
            serde_json::json!({ "name": r.artifact_digest, "digest": { "sha256": digest } })
        })
        .collect()
}

fn statement(
    rows: &[EvidenceRow],
    predicate_type: &str,
    predicate: serde_json::Value,
) -> serde_json::Value {
    serde_json::json!({
        "_type": INTOTO_STATEMENT_TYPE,
        "subject": subjects(rows),
        "predicateType": predicate_type,
        "predicate": predicate,
    })
}

// ── SLSA ─────────────────────────────────────────────────────────────────────

/// Whether an authority verdict authorizes the release (the VSA `PASSED` axis).
fn authority_authorized(authority: &AuthorityAtSigning) -> bool {
    matches!(authority, AuthorityAtSigning::AuthorizedBeforeRevocation)
}

fn slsa_provenance(row: &EvidenceRow) -> serde_json::Value {
    let digest = row
        .artifact_digest
        .strip_prefix("sha256:")
        .unwrap_or(&row.artifact_digest);
    serde_json::json!({
        "predicateType": SLSA_PROVENANCE_PREDICATE_TYPE,
        "subject": [{ "name": row.artifact_digest, "digest": { "sha256": digest } }],
        "timeliness": RowTimeliness::Timeless,
        "predicate": {
            "buildDefinition": {
                "buildType": "https://auths.dev/buildtypes/signed-release/v1",
                "externalParameters": { "artifact": row.artifact_digest },
                "internalParameters": { "signedAtSeq": row.signed_at.map(|s| s.to_string()) },
                "resolvedDependencies": []
            },
            "runDetails": {
                "builder": { "id": AUTHS_BUILDER_ID },
                "metadata": { "invocationId": row.signer.as_str() }
            }
        }
    })
}

fn slsa_vsa(row: &EvidenceRow, vsa: &VsaParams) -> serde_json::Value {
    let allowed = vsa
        .allow_list
        .is_allowed(row.signer.as_str(), &vsa.verifier_id);
    let passed = authority_authorized(&row.authority_at_release) && allowed;
    serde_json::json!({
        "predicateType": SLSA_VSA_PREDICATE_TYPE,
        "verifier": { "id": vsa.verifier_id },
        "timeVerified": vsa.time_verified,
        "resourceUri": row.artifact_digest,
        "signer": row.signer.as_str(),
        "policy": { "uri": "https://auths.dev/compliance/policy/authority-at-release/v1" },
        "verificationResult": if passed { "PASSED" } else { "FAILED" },
        "verifiedLevels": ["AUTHS_AUTHORITY_AT_RELEASE"],
        "signerVerifierAllowed": allowed,
        "authorityAtRelease": row.authority_at_release,
        "timeliness": RowTimeliness::TimeSensitive,
    })
}

fn build_slsa(pack: &EvidencePack, vsa: &VsaParams) -> FrameworkReport {
    let provenance: Vec<serde_json::Value> = pack.rows.iter().map(slsa_provenance).collect();
    let verification_summaries: Vec<serde_json::Value> =
        pack.rows.iter().map(|r| slsa_vsa(r, vsa)).collect();
    let predicate = serde_json::json!({
        "provenance": provenance,
        "verificationSummaries": verification_summaries,
        "equivocationVisibility": pack.equivocation_visibility,
    });
    FrameworkReport {
        framework: ComplianceFramework::Slsa,
        predicate_type: SLSA_REPORT_PREDICATE_TYPE.to_string(),
        statement: statement(&pack.rows, SLSA_REPORT_PREDICATE_TYPE, predicate),
        sbom_sha256: None,
    }
}

// ── SPDX SBOM ────────────────────────────────────────────────────────────────

fn spdx_document(pack: &EvidencePack) -> serde_json::Value {
    let packages: Vec<serde_json::Value> = pack
        .rows
        .iter()
        .enumerate()
        .map(|(i, r)| {
            let digest = r
                .artifact_digest
                .strip_prefix("sha256:")
                .unwrap_or(&r.artifact_digest);
            serde_json::json!({
                "SPDXID": format!("SPDXRef-Package-{i}"),
                "name": r.artifact_digest,
                "downloadLocation": "NOASSERTION",
                "checksums": [{ "algorithm": "SHA256", "checksumValue": digest }],
                "supplier": format!("Organization: {}", r.signer.as_str()),
            })
        })
        .collect();
    serde_json::json!({
        "spdxVersion": SPDX_VERSION,
        "dataLicense": "CC0-1.0",
        "SPDXID": "SPDXRef-DOCUMENT",
        "name": format!("auths-compliance-{}", pack.period),
        "documentNamespace": format!("https://auths.dev/spdx/{}", pack.period),
        "creationInfo": { "creators": [format!("Tool: {AUTHS_BUILDER_ID}")] },
        "packages": packages,
    })
}

fn build_sbom(pack: &EvidencePack) -> FrameworkReport {
    let document = spdx_document(pack);
    // Hash the exact canonical document bytes so a regenerated SBOM is detectable.
    let sha = sbom_document_sha256(&document).ok();
    let predicate = serde_json::json!({
        "spdxVersion": SPDX_VERSION,
        "document": document,
        "documentSha256": sha,
        "equivocationVisibility": pack.equivocation_visibility,
    });
    FrameworkReport {
        framework: ComplianceFramework::Sbom,
        predicate_type: SBOM_REPORT_PREDICATE_TYPE.to_string(),
        statement: statement(&pack.rows, SBOM_REPORT_PREDICATE_TYPE, predicate),
        sbom_sha256: sha,
    }
}

// ── CRA ──────────────────────────────────────────────────────────────────────

/// One CRA obligation mapped to the pack's evidence and NIST SSDF practice IDs.
#[derive(Debug, Clone, Serialize)]
struct CraObligation {
    id: &'static str,
    description: &'static str,
    ssdf_practices: &'static [&'static str],
    satisfied_by: &'static str,
    status: &'static str,
}

/// The CRA obligation map this evidence pack speaks to. Documentation + a typed
/// report shape, not a new trust primitive.
const CRA_OBLIGATIONS: &[CraObligation] = &[
    CraObligation {
        id: "CRA-Annex-I-2(1)",
        description: "Identify and document components (SBOM).",
        ssdf_practices: &["PS.3.2", "PW.4.1"],
        satisfied_by: "sbom",
        status: "covered",
    },
    CraObligation {
        id: "CRA-Annex-I-2(3)",
        description: "Apply security updates / off-board compromised signers.",
        ssdf_practices: &["RV.1.1", "PO.3.2"],
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    CraObligation {
        id: "CRA-Annex-I-1(2)(j)",
        description: "Record and verify the provenance of releases.",
        ssdf_practices: &["PS.3.1", "PS.2.1"],
        satisfied_by: "slsa_provenance",
        status: "covered",
    },
];

fn build_cra(pack: &EvidencePack) -> FrameworkReport {
    let predicate = serde_json::json!({
        "obligations": CRA_OBLIGATIONS,
        "releasesAssessed": pack.rows.len(),
        "equivocationVisibility": pack.equivocation_visibility,
        "note": "Maps the evidence pack to CRA obligations and NIST SSDF practices; \
                 it is a reporting mapping, not a new trust primitive.",
    });
    FrameworkReport {
        framework: ComplianceFramework::Cra,
        predicate_type: CRA_REPORT_PREDICATE_TYPE.to_string(),
        statement: statement(&pack.rows, CRA_REPORT_PREDICATE_TYPE, predicate),
        sbom_sha256: None,
    }
}

// ── SOC 2 (TSC) / ISO 27001 (Annex-A) ──────────────────────────────────────────

/// One control mapped from the pack's evidence to a framework's control ID.
///
/// The same shape serves SOC 2 (Trust Services Criteria, `id` like `CC6.3`) and
/// ISO 27001:2022 (Annex-A, `id` like `A.5.18`): each says which evidence the
/// pack already carries (`satisfied_by`) discharges which control, and at what
/// `status`. Documentation + a typed report shape over the already-classified
/// evidence — never a new trust primitive.
#[derive(Debug, Clone, Serialize)]
struct ControlMapping {
    id: &'static str,
    description: &'static str,
    satisfied_by: &'static str,
    status: &'static str,
}

/// SOC 2 Trust Services Criteria the evidence pack speaks to. Off-boarding a
/// compromised signer and refusing post-revocation authority is exactly the
/// logical-access removal CC6.2/CC6.3 test; provenance discharges CC7.x change
/// integrity.
const SOC2_CRITERIA: &[ControlMapping] = &[
    ControlMapping {
        id: "CC6.1",
        description: "Logical access security — identity and authority are bound to a self-certifying KEL.",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "CC6.2",
        description: "Register and authorize new internal/external users before granting access (member onboarding events).",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "CC6.3",
        description: "Remove access on role change/termination — off-boarding revokes a signer; post-revocation releases are rejected.",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "CC7.2",
        description: "Detect and act on anomalies — release provenance and the transparency log make tampering evident.",
        satisfied_by: "slsa_provenance",
        status: "covered",
    },
];

/// ISO/IEC 27001:2022 Annex-A controls the evidence pack speaks to. The 2022
/// revision's identity/access controls (A.5.16 identity management, A.5.18
/// access rights, A.8.4 access to source/build) are discharged by the same
/// authority-at-release evidence.
const ISO27001_ANNEX_A: &[ControlMapping] = &[
    ControlMapping {
        id: "A.5.16",
        description: "Identity management — each signer is a self-certifying KEL identity.",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "A.5.18",
        description: "Access rights are provisioned and revoked — off-boarding revokes a signer; post-revocation releases are rejected.",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "A.8.4",
        description: "Access to source code / build pipeline is authorized at release time, by KEL position.",
        satisfied_by: "authority_at_release",
        status: "covered",
    },
    ControlMapping {
        id: "A.8.28",
        description: "Secure development — release provenance binds each artifact to an authorized signer.",
        satisfied_by: "slsa_provenance",
        status: "covered",
    },
];

/// Render a control-mapping framework report (SOC 2 / ISO 27001) over the
/// already-classified pack — the one shape shared by the two control frameworks.
fn build_control_mapping(
    pack: &EvidencePack,
    framework: ComplianceFramework,
    predicate_type: &str,
    controls_field: &str,
    controls: &[ControlMapping],
    note: &str,
) -> FrameworkReport {
    let predicate = serde_json::json!({
        controls_field: controls,
        "releasesAssessed": pack.rows.len(),
        "equivocationVisibility": pack.equivocation_visibility,
        "note": note,
    });
    FrameworkReport {
        framework,
        predicate_type: predicate_type.to_string(),
        statement: statement(&pack.rows, predicate_type, predicate),
        sbom_sha256: None,
    }
}

fn build_soc2(pack: &EvidencePack) -> FrameworkReport {
    build_control_mapping(
        pack,
        ComplianceFramework::Soc2,
        SOC2_REPORT_PREDICATE_TYPE,
        "trustServicesCriteria",
        SOC2_CRITERIA,
        "Maps the evidence pack to SOC 2 Trust Services Criteria; it is a \
         reporting mapping over the classified evidence, not a new trust primitive.",
    )
}

fn build_iso27001(pack: &EvidencePack) -> FrameworkReport {
    build_control_mapping(
        pack,
        ComplianceFramework::Iso27001,
        ISO27001_REPORT_PREDICATE_TYPE,
        "annexAControls",
        ISO27001_ANNEX_A,
        "Maps the evidence pack to ISO/IEC 27001:2022 Annex-A controls; it is a \
         reporting mapping over the classified evidence, not a new trust primitive.",
    )
}