dig_session/unlocked.rs
1//! The unlocked-key handle and the signing primitive it injects.
2
3use std::sync::Arc;
4
5use dig_constants::{DEK_SALT, IDENTITY_IKM_VERSION, SYMMETRIC_KEY_LEN};
6use dig_keystore::scheme::KeyScheme;
7use dig_keystore::SignerHandle;
8use hkdf::Hkdf;
9use sha2::Sha256;
10use zeroize::Zeroizing;
11
12// The DEK-derivation constants (`DEK_SALT`, `IDENTITY_IKM_VERSION`,
13// `SYMMETRIC_KEY_LEN`, and `PROFILE_DEK_LABEL` mentioned below) live in
14// dig-constants as the single source of truth for this frozen at-rest byte
15// contract (dig_ecosystem §5.1/§4.1/NC-5) — dig-app's
16// `dig-app-core/src/keystore/secrets.rs` and this crate both consume them from
17// there, so they can never drift apart. See dig-constants' `lib.rs` "Profile
18// DEK at-rest byte contract" section for the authoritative definition.
19
20/// A scheme-parameterized signing primitive: a plain callable that maps a
21/// message to a signature and carries no dig-session or dig-identity type.
22///
23/// This is the shape [`UnlockedIdentity::inject_into`] hands to a consumer, so
24/// the consumer's API surface mentions only `&[u8]` in and `K::Signature`
25/// (a `chia_bls::Signature` for the BLS schemes) out — never a session or
26/// identity type. That is what keeps a consumer such as `dig-wallet-backend`
27/// identity-agnostic (see dig_ecosystem #908).
28pub type SigningFn<K> = Arc<dyn Fn(&[u8]) -> <K as KeyScheme>::Signature + Send + Sync>;
29
30/// A live, in-memory identity whose secret key has been decrypted and is ready
31/// to sign.
32///
33/// Obtained from [`crate::Session::unlock`] or [`crate::Session::enroll_identity`].
34/// The secret bytes live inside the wrapped [`SignerHandle`], which stores them
35/// in a `Zeroizing` buffer and wipes them when this value is dropped — so the
36/// decrypted key never lingers in freed memory. The type deliberately does not
37/// implement `Clone` and its `Debug` impl redacts the secret, so an
38/// `UnlockedIdentity` cannot be duplicated into a log line or a debug dump.
39///
40/// # Boundaries
41///
42/// An `UnlockedIdentity` must never cross an IPC boundary: it holds raw key
43/// material and belongs solely to the user-app process that owns the identity
44/// (dig_ecosystem #908). Hand a downstream a [`SigningFn`] via
45/// [`inject_into`](Self::inject_into) instead of the handle itself.
46pub struct UnlockedIdentity<K: KeyScheme> {
47 signer: SignerHandle<K>,
48 public_key: K::PublicKey,
49}
50
51impl<K: KeyScheme> UnlockedIdentity<K> {
52 /// Wrap a freshly unlocked [`SignerHandle`], caching its public key.
53 pub(crate) fn new(signer: SignerHandle<K>) -> Self {
54 let public_key = signer.public_key().clone();
55 Self { signer, public_key }
56 }
57
58 /// The public key of this identity.
59 ///
60 /// For the identity scheme this is byte-identical to
61 /// `dig_identity::public_key_bytes(derive_identity_sk(master))`, i.e. the
62 /// key anchored in the DID profile — so signatures produced by this handle
63 /// verify against the published identity.
64 pub fn public_key(&self) -> &K::PublicKey {
65 &self.public_key
66 }
67
68 /// Sign `msg` with the unlocked secret key.
69 pub fn sign(&self, msg: &[u8]) -> K::Signature {
70 self.signer.sign(msg)
71 }
72
73 /// Produce a standalone [`SigningFn`] primitive that signs with this
74 /// identity's key.
75 ///
76 /// The returned closure owns its own zeroizing copy of the secret, so it
77 /// keeps working after this handle is dropped and wipes its copy when the
78 /// closure itself is dropped.
79 pub fn signing_fn(&self) -> SigningFn<K> {
80 let signer = self.signer.clone();
81 Arc::new(move |msg: &[u8]| signer.sign(msg))
82 }
83
84 /// Derive a per-profile symmetric key (a data-encryption key, "DEK") from
85 /// this unlocked identity, bound to `label`.
86 ///
87 /// The DEK is `HKDF-SHA256(salt = DEK_SALT, ikm = 0x02 || identity_scalar,
88 /// info = label)` expanded to 32 bytes. The identity scalar is the raw
89 /// secret; it is read into a zeroizing buffer, mixed into the KDF, and never
90 /// returned — only the *derived* key by `label` leaves the facade, so the
91 /// root secret stays inside (dig_ecosystem #908).
92 ///
93 /// # Byte-identical to dig-app (§5.1 at-rest back-compat)
94 ///
95 /// With `label = b"dig-app:profile-dek:v2"` this reproduces, byte-for-byte,
96 /// the DEK that dig-app's `dig-app-core/src/keystore/secrets.rs`
97 /// (`dek_password`, the `seal_data`/`open_data` key) already uses to seal
98 /// every profile blob at rest. The construction is pinned exactly:
99 ///
100 /// - hash: SHA-256 (`hkdf` 0.12 + `sha2` 0.10, RFC 5869);
101 /// - IKM: `0x02 || identity_scalar` — the same 33-byte versioned layout
102 /// dig-app feeds to HKDF (`to_sealed_bytes()`), NOT the bare scalar;
103 /// - salt: [`dig_constants::DEK_SALT`] (`b"dig-app:dek-salt:v1"`);
104 /// - info: `label` verbatim — pass [`dig_constants::PROFILE_DEK_LABEL`] to
105 /// reproduce dig-app's own profile DEK;
106 /// - output: 32 bytes ([`dig_constants::SYMMETRIC_KEY_LEN`]).
107 ///
108 /// Changing any of these would derive a different DEK and make already-sealed
109 /// profile data permanently unreadable, so they are frozen and covered by a
110 /// golden-vector test.
111 ///
112 /// The returned key and all intermediates are wrapped in [`Zeroizing`] and
113 /// wiped on drop.
114 pub fn derive_symmetric_key(&self, label: &[u8]) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
115 // The identity scalar is the raw stored secret for the identity scheme;
116 // it is mixed into the KDF and never leaves this method. The frozen
117 // construction lives in the shared [`derive_symmetric_key_from_scalar`]
118 // so the master-seed path (which re-derives the SAME scalar from the
119 // seed) produces a byte-identical DEK.
120 derive_symmetric_key_from_scalar(self.signer.expose_secret(), label)
121 }
122
123 /// Inject this identity's signing capability into a consumer as a bare
124 /// [`SigningFn`] primitive, returning whatever the consumer builds from it.
125 ///
126 /// The consumer receives only a callable — never an `UnlockedIdentity`,
127 /// a `SignerHandle`, or any identity type — which is how a downstream stays
128 /// identity-agnostic while still being able to sign.
129 pub fn inject_into<T>(&self, consumer: impl FnOnce(SigningFn<K>) -> T) -> T {
130 consumer(self.signing_fn())
131 }
132}
133
134/// Derive a per-profile symmetric key (DEK) from a raw 32-byte identity scalar,
135/// bound to `label`.
136///
137/// This is the single, frozen HKDF construction shared by every unlock path
138/// (the identity-scalar path via [`UnlockedIdentity::derive_symmetric_key`] and
139/// the master-seed path via [`crate::UnlockedMasterSeed::derive_symmetric_key`],
140/// which re-derives the SAME identity scalar from the seed first). Keeping ONE
141/// implementation is what guarantees both paths produce a byte-identical DEK for
142/// the same underlying identity (§5.1 at-rest back-compat):
143///
144/// - IKM: `IDENTITY_IKM_VERSION || identity_scalar` (the 33-byte versioned
145/// layout dig-app feeds to HKDF via `to_sealed_bytes()`);
146/// - salt: [`dig_constants::DEK_SALT`];
147/// - hash: HKDF-SHA256 (RFC 5869);
148/// - info: `label` verbatim;
149/// - output: [`dig_constants::SYMMETRIC_KEY_LEN`] bytes.
150///
151/// The IKM buffer and the returned key are wrapped in [`Zeroizing`] and wiped on
152/// drop; `scalar` is borrowed and never copied except into the zeroizing IKM.
153pub(crate) fn derive_symmetric_key_from_scalar(
154 scalar: &[u8],
155 label: &[u8],
156) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
157 let mut ikm = Zeroizing::new(Vec::with_capacity(1 + scalar.len()));
158 ikm.push(IDENTITY_IKM_VERSION);
159 ikm.extend_from_slice(scalar);
160
161 let hkdf = Hkdf::<Sha256>::new(Some(DEK_SALT), &ikm);
162 let mut dek = Zeroizing::new([0u8; SYMMETRIC_KEY_LEN]);
163 hkdf.expand(label, &mut *dek)
164 .expect("32 bytes is a valid HKDF-SHA256 output length");
165 dek
166}
167
168/// Redacting `Debug`: shows the type name only, never the secret (or even the
169/// public key, to avoid accidental correlation in logs).
170impl<K: KeyScheme> core::fmt::Debug for UnlockedIdentity<K> {
171 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
172 f.debug_struct("UnlockedIdentity")
173 .field("scheme", &K::NAME)
174 .field("secret", &"<redacted>")
175 .finish()
176 }
177}