Skip to main content

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        // Assemble IKM = version-byte || identity-scalar in a zeroizing buffer so
116        // the copied scalar is wiped when this call returns. The scalar itself
117        // never leaves this method.
118        let scalar = self.signer.expose_secret();
119        let mut ikm = Zeroizing::new(Vec::with_capacity(1 + scalar.len()));
120        ikm.push(IDENTITY_IKM_VERSION);
121        ikm.extend_from_slice(scalar);
122
123        let hkdf = Hkdf::<Sha256>::new(Some(DEK_SALT), &ikm);
124        let mut dek = Zeroizing::new([0u8; SYMMETRIC_KEY_LEN]);
125        hkdf.expand(label, &mut *dek)
126            .expect("32 bytes is a valid HKDF-SHA256 output length");
127        dek
128    }
129
130    /// Inject this identity's signing capability into a consumer as a bare
131    /// [`SigningFn`] primitive, returning whatever the consumer builds from it.
132    ///
133    /// The consumer receives only a callable — never an `UnlockedIdentity`,
134    /// a `SignerHandle`, or any identity type — which is how a downstream stays
135    /// identity-agnostic while still being able to sign.
136    pub fn inject_into<T>(&self, consumer: impl FnOnce(SigningFn<K>) -> T) -> T {
137        consumer(self.signing_fn())
138    }
139}
140
141/// Redacting `Debug`: shows the type name only, never the secret (or even the
142/// public key, to avoid accidental correlation in logs).
143impl<K: KeyScheme> core::fmt::Debug for UnlockedIdentity<K> {
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145        f.debug_struct("UnlockedIdentity")
146            .field("scheme", &K::NAME)
147            .field("secret", &"<redacted>")
148            .finish()
149    }
150}