polyc-crypto 2026.10.4

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
//! Wallet-session step-up assertions and the signed audit record
//! (POLY-547).
//!
//! `WalletSessionService.StartCeremony` lets a signed-in account ask for a
//! wallet ceremony with no emailed or chat link. The destructive `RETIRE`
//! action needs proof that the account holder just re-authenticated. The
//! Uno sign-in service gives that proof as a step-up assertion. This module
//! holds two things.
//!
//! - The step-up claim and its verifier ([`verify_step_up`]). The claim binds
//!   an account, a sign-in, and an action, and it has an age limit.
//! - The signed audit record ([`wallet_session_event_payload`]). The control
//!   plane appends one record for each mint or retire to the
//!   `wallet-session/{persona_id}` partition.

use serde::Serialize;

use crate::signed::{Envelope, canonical_bytes};
use crate::signing_role::ApprovalSigner;

/// Domain tag that opens every step-up message. It stops a signature made
/// for another purpose from passing as a step-up assertion.
pub const STEP_UP_DOMAIN: &str = "polychrome.wallet-session.step-up.v1";

/// The oldest a step-up assertion may be, in milliseconds. Five minutes.
pub const STEP_UP_MAX_AGE_MS: u64 = 5 * 60 * 1_000;

/// How far ahead of the control plane clock an assertion may be dated, in
/// milliseconds. It absorbs clock skew between the issuer and this process.
pub const STEP_UP_CLOCK_SKEW_MS: u64 = 30 * 1_000;

/// What a step-up assertion proves, named at the call site.
///
/// A positional list of same-typed strings invites a silent swap, so each
/// field has a name.
#[derive(Debug, Clone, Copy)]
pub struct StepUpClaim<'a> {
    /// The signed-in account the assertion covers.
    pub account_id: &'a str,
    /// The sign-in session the assertion covers.
    pub sign_in_id: &'a str,
    /// The wallet action the assertion allows, for example `retire`.
    pub action: &'a str,
    /// When the issuer made the assertion, in unix milliseconds.
    pub issued_at_ms: u64,
}

/// Why [`verify_step_up`] refused an assertion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum StepUpRefusal {
    /// The signature does not verify against the configured public key for
    /// this exact account, sign-in, action, and time.
    #[error("the step-up signature does not verify")]
    BadSignature,
    /// The assertion is older than [`STEP_UP_MAX_AGE_MS`].
    #[error("the step-up assertion is too old")]
    Expired,
    /// The assertion is dated later than [`STEP_UP_CLOCK_SKEW_MS`] allows.
    #[error("the step-up assertion is dated in the future")]
    FromTheFuture,
}

/// The frozen step-up message. The field order is the signed contract.
#[derive(Serialize)]
struct StepUpCanonical<'a> {
    domain: &'a str,
    account_id: &'a str,
    sign_in_id: &'a str,
    action: &'a str,
    issued_at_ms: u64,
}

/// The exact bytes the issuer signs for `claim`.
#[must_use]
pub fn step_up_message(claim: &StepUpClaim<'_>) -> Vec<u8> {
    canonical_bytes(&StepUpCanonical {
        domain: STEP_UP_DOMAIN,
        account_id: claim.account_id,
        sign_in_id: claim.sign_in_id,
        action: claim.action,
        issued_at_ms: claim.issued_at_ms,
    })
}

/// Sign `claim` the way an issuer does. Tests and issuers use it. The control
/// plane only verifies.
#[must_use]
pub fn sign_step_up(signer: &crate::Signer, claim: &StepUpClaim<'_>) -> Vec<u8> {
    signer.sign(&step_up_message(claim))
}

/// Verify a step-up assertion.
///
/// # Errors
///
/// Returns [`StepUpRefusal`] when the signature fails, the assertion is older
/// than [`STEP_UP_MAX_AGE_MS`], or it is dated in the future.
pub fn verify_step_up(
    public_key: &[u8],
    claim: &StepUpClaim<'_>,
    signature: &[u8],
    now_ms: u64,
) -> Result<(), StepUpRefusal> {
    // The signature check comes first. A caller then learns nothing about the
    // clock from an assertion it could not have signed.
    if !crate::verify(public_key, &step_up_message(claim), signature) {
        return Err(StepUpRefusal::BadSignature);
    }
    if claim.issued_at_ms > now_ms.saturating_add(STEP_UP_CLOCK_SKEW_MS) {
        return Err(StepUpRefusal::FromTheFuture);
    }
    if now_ms.saturating_sub(claim.issued_at_ms) > STEP_UP_MAX_AGE_MS {
        return Err(StepUpRefusal::Expired);
    }
    Ok(())
}

/// The field set of one `wallet_session_event`, named at the call site.
#[derive(Debug, Clone, Copy)]
pub struct WalletSessionEventPayload<'a> {
    /// The event kind (always `polyc_proto::kinds::WALLET_SESSION_EVENT`).
    pub kind: &'a str,
    /// The requested action, for example `link`.
    pub action: &'a str,
    /// What the service did, for example `minted` or `live_link_exists`.
    pub outcome: &'a str,
    /// The persona the request resolved to.
    pub subject: &'a str,
    /// The credential id of the calling backend.
    pub caller: &'a str,
    /// The account the request named.
    pub account_id: &'a str,
    /// The sign-in session the request named.
    pub sign_in_id: &'a str,
    /// Decimal unix seconds when the service recorded the event.
    pub timestamp: &'a str,
}

/// A `wallet_session_event` payload after signature verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedWalletSessionEvent {
    /// The signed event kind.
    pub kind: String,
    /// The requested action.
    pub action: String,
    /// What the service did.
    pub outcome: String,
    /// The persona the request resolved to.
    pub subject: String,
    /// The credential id of the calling backend.
    pub caller: String,
    /// The account the request named.
    pub account_id: String,
    /// The sign-in session the request named.
    pub sign_in_id: String,
    /// Decimal unix seconds when the service recorded the event.
    pub timestamp: String,
    /// The verified signer's public key.
    pub signer_public_key: Vec<u8>,
}

/// The frozen `wallet_session_event` field set. The field order is the
/// signed contract.
#[derive(Serialize)]
struct EventCanonical<'a> {
    kind: &'a str,
    action: &'a str,
    outcome: &'a str,
    subject: &'a str,
    caller: &'a str,
    account_id: &'a str,
    sign_in_id: &'a str,
    timestamp: &'a str,
}

impl<'a> From<&WalletSessionEventPayload<'a>> for EventCanonical<'a> {
    fn from(fields: &WalletSessionEventPayload<'a>) -> Self {
        Self {
            kind: fields.kind,
            action: fields.action,
            outcome: fields.outcome,
            subject: fields.subject,
            caller: fields.caller,
            account_id: fields.account_id,
            sign_in_id: fields.sign_in_id,
            timestamp: fields.timestamp,
        }
    }
}

/// Build the signed JSON payload of a `wallet_session_event`.
///
/// Returns `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn wallet_session_event_payload(
    fields: &WalletSessionEventPayload<'_>,
    signer: &ApprovalSigner,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(EventCanonical::from(fields), signer.as_signer())
}

/// Verify a stored `wallet_session_event` payload against a trusted-signer
/// allow-list. Returns `None` for a malformed payload, an unknown signer, or
/// a bad signature.
#[must_use]
pub fn verify_signed_wallet_session_event(
    payload: &[u8],
    trusted_signers: &[Vec<u8>],
) -> Option<VerifiedWalletSessionEvent> {
    let value: serde_json::Value = serde_json::from_slice(payload).ok()?;
    let text = |key: &str| value.get(key)?.as_str().map(str::to_owned);
    let kind = text("kind")?;
    let action = text("action")?;
    let outcome = text("outcome")?;
    let subject = text("subject")?;
    let caller = text("caller")?;
    let account_id = text("account_id")?;
    let sign_in_id = text("sign_in_id")?;
    let timestamp = text("timestamp")?;
    let public_key = crate::hex::decode(value.get("signed_by")?.as_str()?)?;
    let signature = crate::hex::decode(value.get("signature_hex")?.as_str()?)?;
    if !trusted_signers
        .iter()
        .any(|key| key.as_slice() == public_key.as_slice())
    {
        return None;
    }
    let canonical = canonical_bytes(&EventCanonical {
        kind: &kind,
        action: &action,
        outcome: &outcome,
        subject: &subject,
        caller: &caller,
        account_id: &account_id,
        sign_in_id: &sign_in_id,
        timestamp: &timestamp,
    });
    crate::verify(&public_key, &canonical, &signature).then_some(VerifiedWalletSessionEvent {
        kind,
        action,
        outcome,
        subject,
        caller,
        account_id,
        sign_in_id,
        timestamp,
        signer_public_key: public_key,
    })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;
    use crate::Signer;

    const NOW: u64 = 1_800_000_000_000;

    fn claim(issued_at_ms: u64) -> StepUpClaim<'static> {
        StepUpClaim {
            account_id: "acct-1",
            sign_in_id: "sign-in-1",
            action: "retire",
            issued_at_ms,
        }
    }

    #[test]
    fn step_up_message_is_the_frozen_canonical() {
        assert_eq!(
            String::from_utf8(step_up_message(&claim(NOW))).unwrap(),
            r#"{"domain":"polychrome.wallet-session.step-up.v1","account_id":"acct-1","sign_in_id":"sign-in-1","action":"retire","issued_at_ms":1800000000000}"#
        );
    }

    #[test]
    fn a_fresh_assertion_verifies() {
        let signer = Signer::from_seed(7);
        let signature = sign_step_up(&signer, &claim(NOW));
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(NOW), &signature, NOW),
            Ok(())
        );
    }

    #[test]
    fn an_assertion_exactly_five_minutes_old_verifies() {
        let signer = Signer::from_seed(7);
        let issued = NOW - STEP_UP_MAX_AGE_MS;
        let signature = sign_step_up(&signer, &claim(issued));
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(issued), &signature, NOW),
            Ok(())
        );
    }

    #[test]
    fn an_assertion_older_than_five_minutes_is_expired() {
        let signer = Signer::from_seed(7);
        let issued = NOW - STEP_UP_MAX_AGE_MS - 1;
        let signature = sign_step_up(&signer, &claim(issued));
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(issued), &signature, NOW),
            Err(StepUpRefusal::Expired)
        );
    }

    #[test]
    fn an_assertion_dated_beyond_the_skew_is_refused() {
        let signer = Signer::from_seed(7);
        let issued = NOW + STEP_UP_CLOCK_SKEW_MS + 1;
        let signature = sign_step_up(&signer, &claim(issued));
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(issued), &signature, NOW),
            Err(StepUpRefusal::FromTheFuture)
        );
    }

    #[test]
    fn an_assertion_dated_inside_the_skew_verifies() {
        let signer = Signer::from_seed(7);
        let issued = NOW + STEP_UP_CLOCK_SKEW_MS;
        let signature = sign_step_up(&signer, &claim(issued));
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(issued), &signature, NOW),
            Ok(())
        );
    }

    #[test]
    fn each_bound_field_changes_the_verdict() {
        let signer = Signer::from_seed(7);
        let signature = sign_step_up(&signer, &claim(NOW));
        let pk = signer.public_key_bytes();
        for tampered in [
            StepUpClaim {
                account_id: "acct-2",
                ..claim(NOW)
            },
            StepUpClaim {
                sign_in_id: "sign-in-2",
                ..claim(NOW)
            },
            StepUpClaim {
                action: "revoke",
                ..claim(NOW)
            },
            claim(NOW - 1),
        ] {
            assert_eq!(
                verify_step_up(&pk, &tampered, &signature, NOW),
                Err(StepUpRefusal::BadSignature),
                "{tampered:?}"
            );
        }
    }

    #[test]
    fn another_key_and_a_garbage_signature_are_refused() {
        let signer = Signer::from_seed(7);
        let other = Signer::from_seed(8);
        let signature = sign_step_up(&signer, &claim(NOW));
        assert_eq!(
            verify_step_up(&other.public_key_bytes(), &claim(NOW), &signature, NOW),
            Err(StepUpRefusal::BadSignature)
        );
        assert_eq!(
            verify_step_up(&signer.public_key_bytes(), &claim(NOW), b"garbage", NOW),
            Err(StepUpRefusal::BadSignature)
        );
        assert_eq!(
            verify_step_up(b"not a key", &claim(NOW), &signature, NOW),
            Err(StepUpRefusal::BadSignature)
        );
    }

    fn event<'a>() -> WalletSessionEventPayload<'a> {
        WalletSessionEventPayload {
            kind: "wallet_session_event",
            action: "link",
            outcome: "minted",
            subject: "persona-1",
            caller: "uno-api",
            account_id: "acct-1",
            sign_in_id: "sign-in-1",
            timestamp: "1800000000",
        }
    }

    #[test]
    fn a_signed_event_round_trips_and_carries_every_field() {
        let signer = ApprovalSigner::from_seed(9);
        let (payload, _signature, public_key) = wallet_session_event_payload(&event(), &signer);
        let verified =
            verify_signed_wallet_session_event(&payload, std::slice::from_ref(&public_key))
                .expect("a payload this signer made verifies");
        assert_eq!(
            verified,
            VerifiedWalletSessionEvent {
                kind: "wallet_session_event".to_owned(),
                action: "link".to_owned(),
                outcome: "minted".to_owned(),
                subject: "persona-1".to_owned(),
                caller: "uno-api".to_owned(),
                account_id: "acct-1".to_owned(),
                sign_in_id: "sign-in-1".to_owned(),
                timestamp: "1800000000".to_owned(),
                signer_public_key: public_key,
            }
        );
    }

    #[test]
    fn a_tampered_or_untrusted_event_does_not_verify() {
        let signer = ApprovalSigner::from_seed(9);
        let (payload, _signature, public_key) = wallet_session_event_payload(&event(), &signer);
        let tampered = String::from_utf8(payload.clone())
            .unwrap()
            .replace("minted", "retired")
            .into_bytes();
        assert!(
            verify_signed_wallet_session_event(&tampered, std::slice::from_ref(&public_key))
                .is_none()
        );
        assert!(verify_signed_wallet_session_event(&payload, &[vec![0; 32]]).is_none());
        assert!(verify_signed_wallet_session_event(b"{}", &[public_key]).is_none());
    }

    #[test]
    fn the_event_canonical_is_frozen() {
        let canonical = canonical_bytes(&EventCanonical::from(&event()));
        assert_eq!(
            String::from_utf8(canonical).unwrap(),
            r#"{"kind":"wallet_session_event","action":"link","outcome":"minted","subject":"persona-1","caller":"uno-api","account_id":"acct-1","sign_in_id":"sign-in-1","timestamp":"1800000000"}"#
        );
    }
}