lys-core 0.3.1

Domain-agnostic cryptographic trust primitives — certificate authority, Merkle transparency log, signed attestations, sealed envelopes, and Ed25519 key management.
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
//! Ed25519 identity keypair — the cryptographic root of trust.
//!
//! **Invariant:** the signing key (private seed) NEVER appears in `Debug`
//! output, log lines, or error messages. The custom `Debug` impl redacts it
//! unconditionally; key-management errors carry only operational context, not
//! key material.
//!
//! **Key-acceptance invariant:** there is exactly one rule in this crate for
//! whether 32 bytes are an Ed25519 public key at all —
//! `is_usable_ed25519_public_key` — and [`Ed25519Identity::verify`] admits a
//! key if and only if that predicate does. In particular a **non-canonical
//! encoding is not a key**: `y` and `y + p` are two spellings of one point, and
//! `ed25519_dalek::VerifyingKey::from_bytes` reduces rather than rejects, so
//! the check has to be made here. Anything that decides key-ness by some other
//! means is a second copy of this rule and free to drift from it.
//!
//! Identities are obtained via [`Ed25519Identity::load_or_generate`]
//! (file-backed) or [`Ed25519Identity::from_env`] (env-var-backed, for
//! containers and CI). The two paths are independent — neither calls the
//! other.
//!
//! **Concurrency invariant:** when multiple callers — threads in one process
//! or separate processes — race `load_or_generate` on the same missing path,
//! exactly one generated seed is ever persisted and every caller returns the
//! identity for that persisted seed. Each generator writes its candidate
//! seed to a uniquely named temp file (pid + per-process counter) and
//! publishes it with a no-clobber `hard_link`; the first publisher wins, and
//! losers discard their candidate seed and load the winner's file. The key
//! file at a given path therefore never changes once created.
//!
//! Sealed payload transport uses X25519 key agreement, but the long-term keys
//! here are Ed25519. [`Ed25519Identity::x25519_static_secret`] and
//! [`Ed25519Identity::x25519_public_key`] derive the X25519 keypair from the
//! Ed25519 signing key via the standard clamped-scalar conversion, so one
//! keypair serves both signing and key agreement.

use std::fmt;
use std::path::Path;

use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use ed25519_dalek::Signer;
use zeroize::Zeroizing;

use crate::error::{TrustError, TrustResult};

mod persist;

use persist::{generate_and_persist, load_existing};

/// Name of the environment variable read by [`Ed25519Identity::from_env`].
const KEY_ENV_VAR: &str = "LYS_IDENTITY_KEY";

/// Ed25519 identity keypair.
///
/// This is the cryptographic root of trust for the consuming domain. The
/// signing key never appears in `Debug` output. Obtain one via
/// [`Self::load_or_generate`] (file-backed) or [`Self::from_env`]
/// (env-var-backed).
pub struct Ed25519Identity {
    signing_key: ed25519_dalek::SigningKey,
    verifying_key: ed25519_dalek::VerifyingKey,
}

impl fmt::Debug for Ed25519Identity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Ed25519Identity")
            .field("signing_key", &"[REDACTED]")
            .field("verifying_key", &self.public_key_bytes_hex())
            .finish()
    }
}

impl Ed25519Identity {
    /// Make a fresh signing identity held only in memory for ephemeral work.
    #[must_use]
    pub fn ephemeral() -> Self {
        use rand::RngCore;
        let mut seed = Zeroizing::new([0u8; 32]);
        rand::rng().fill_bytes(&mut *seed);
        Self::from_seed(&seed)
    }

    /// Returns the 32-byte Ed25519 verifying (public) key.
    pub fn public_key_bytes(&self) -> [u8; 32] {
        self.verifying_key.to_bytes()
    }

    /// Signs a message with the identity's Ed25519 signing key.
    ///
    /// Returns the 64-byte detached signature. Ed25519 deterministic signing
    /// is infallible in dalek 2.
    pub fn sign(&self, message: &[u8]) -> [u8; 64] {
        self.signing_key.sign(message).to_bytes()
    }

    /// Verifies an Ed25519 signature against a public key using **strict**
    /// verification (`verify_strict`), over a public key this crate considers
    /// usable at all — see `is_usable_ed25519_public_key` (crate-private:
    /// key-ness is this crate's rule to state, not a knob for consumers).
    ///
    /// Static method (no `&self`) so callers can verify against any public
    /// key without holding an [`Ed25519Identity`] instance.
    ///
    /// Strict verification rejects signature malleability (non-canonical
    /// scalar and group-element encodings) and small-order/torsion public
    /// keys and `R` components, which plain `verify` accepts. This crate is
    /// an audit trust foundation: non-repudiation requires that a given
    /// (message, public key) pair has a unique valid signature and that weak
    /// keys — for which signatures can be forged for arbitrary messages —
    /// are categorically rejected.
    ///
    /// # The public key must also be *canonically encoded*, which
    /// `verify_strict` does not check
    ///
    /// `VerifyingKey::from_bytes` **reduces the y-coordinate modulo `p`
    /// instead of rejecting one that is out of range** — measured, not
    /// inferred: all-`0xff` decodes, reports `is_weak() == false`, and hands
    /// back a key whose `to_bytes()` is the all-`0xff` input verbatim. So
    /// without the check below, `y` and `y + p` are two 32-byte strings
    /// denoting one key, and an identity with two spellings is one that
    /// compares unequal to itself. Every wire format this crate owns refuses
    /// second spellings; the primitive underneath them now does too.
    ///
    /// The rule is stated once, in `is_usable_ed25519_public_key`, and
    /// applied both here and by the artifact decoders that *name* a key
    /// without verifying with it, so the two can no longer drift apart. Its
    /// small-order clause deliberately overlaps `verify_strict`'s own: the
    /// overlap is across a dependency boundary, and this crate does not want
    /// its key-acceptance rule to be whatever the dependency happens to do
    /// this release.
    ///
    /// # Errors
    ///
    /// Returns [`TrustError::InvalidSignature`] if the signature is not
    /// exactly 64 bytes, the public key is not a canonically encoded Ed25519
    /// point, the public key or the signature's `R` component is a
    /// small-order point, or the signature does not strictly verify against
    /// the message.
    pub fn verify(public_key: &[u8; 32], message: &[u8], signature: &[u8]) -> TrustResult<()> {
        let sig_bytes: &[u8; 64] = signature
            .try_into()
            .map_err(|_err| TrustError::InvalidSignature)?;
        let signature = ed25519_dalek::Signature::from_bytes(sig_bytes);
        if !is_usable_ed25519_public_key(public_key) {
            return Err(TrustError::InvalidSignature);
        }
        let vk = ed25519_dalek::VerifyingKey::from_bytes(public_key)
            .map_err(|_err| TrustError::InvalidSignature)?;
        vk.verify_strict(message, &signature)
            .map_err(|_err| TrustError::InvalidSignature)
    }

    /// Derives the X25519 static secret from the Ed25519 signing key.
    ///
    /// This is the standard Ed25519-to-X25519 conversion: the secret is the
    /// low 32 bytes of SHA-512 over the Ed25519 seed, obtained here via
    /// dalek's `to_scalar_bytes`. That function returns the scalar
    /// **unreduced and unclamped** — clamping is applied downstream by
    /// `x25519-dalek`, when the bytes are used for public-key derivation or
    /// Diffie-Hellman. The end-to-end conversion is therefore correct, but
    /// the clamping does not happen at this call site and this method must
    /// not be read as performing it.
    ///
    /// Deterministic: the same Ed25519 identity always yields the same X25519
    /// secret. Used as the long-term key for sealed payload key agreement.
    ///
    /// The intermediate scalar is held in [`Zeroizing`] so the buffer is
    /// wiped when this call returns. `to_scalar_bytes` hands back a bare
    /// `[u8; 32]`, and an unwrapped temporary would be dropped intact,
    /// leaving the X25519 private scalar as stack residue — the one seed
    /// buffer in this file not covered by the M4 discipline. The returned
    /// [`x25519_dalek::StaticSecret`] wipes its own copy on drop (its
    /// `zeroize` feature is enabled through the default feature set).
    ///
    /// This narrows residue; it is not a defence against an adversary who
    /// can read live process memory. Such an adversary already holds
    /// `signing_key`, and this scalar is a deterministic function of it, so
    /// they can recompute it at will. The benefit is confined to material
    /// that outlives the process — core dumps, swap, hibernation images —
    /// where a stale stack page can persist long after the structured secret
    /// is gone.
    pub fn x25519_static_secret(&self) -> x25519_dalek::StaticSecret {
        let scalar = Zeroizing::new(self.signing_key.to_scalar_bytes());
        x25519_dalek::StaticSecret::from(*scalar)
    }

    /// Returns the Montgomery-form X25519 public key derived from this
    /// identity, matching the public key of [`Self::x25519_static_secret`].
    pub fn x25519_public_key(&self) -> [u8; 32] {
        x25519_dalek::PublicKey::from(&self.x25519_static_secret()).to_bytes()
    }

    /// Loads or generates the identity from a file.
    ///
    /// File format: raw 32-byte Ed25519 seed (not base64, not PEM). On Unix,
    /// generated files are mode `0600`. Existing files with looser
    /// permissions emit a `tracing::warn!` but still load (an operator may
    /// have a legitimate reason).
    ///
    /// Safe under concurrency: racing callers (threads or processes) on the
    /// same missing path all return the identity of the single seed that
    /// wins the atomic no-clobber publish — no caller ever holds an identity
    /// that differs from the persisted file. See the module docs for the
    /// mechanism.
    ///
    /// # Errors
    ///
    /// Returns [`TrustError::KeyManagement`] if the existing file cannot be
    /// read, its length is not exactly 32 bytes, the path has no filename
    /// component, or the parent directory or file cannot be written.
    pub fn load_or_generate(path: &Path) -> TrustResult<Self> {
        if path.exists() {
            load_existing(path)
        } else {
            generate_and_persist(path)
        }
    }

    /// Loads the identity from an existing key file, never generating one.
    ///
    /// The load-only counterpart of [`Self::load_or_generate`], for callers
    /// that consume an identity (signing, unsealing) rather than provision
    /// one: a missing file is an error, not a trigger to mint a fresh key.
    /// Because existence is never pre-checked and then acted on separately,
    /// there is no window in which a vanished file can be silently replaced
    /// by a new identity.
    ///
    /// Same file format and permission handling as
    /// [`Self::load_or_generate`]: raw 32-byte seed, `tracing::warn!` on
    /// loose Unix permissions.
    ///
    /// # Errors
    ///
    /// Returns [`TrustError::KeyManagement`] if the file cannot be read
    /// (including when it does not exist) or its length is not exactly
    /// 32 bytes.
    pub fn load(path: &Path) -> TrustResult<Self> {
        load_existing(path)
    }

    /// Loads the identity from the `LYS_IDENTITY_KEY` environment variable.
    ///
    /// The value is a base64-encoded 32-byte seed. Both standard and
    /// URL-safe-no-pad base64 encodings are accepted, and surrounding
    /// whitespace is trimmed. Independent of [`Self::load_or_generate`].
    ///
    /// # Errors
    ///
    /// Returns [`TrustError::KeyManagement`] if the variable is unset,
    /// contains invalid base64, or decodes to a length other than 32 bytes.
    pub fn from_env() -> TrustResult<Self> {
        Self::from_env_value(std::env::var(KEY_ENV_VAR))
    }

    /// Builds the identity from the result of reading `LYS_IDENTITY_KEY`.
    ///
    /// Holds every rule [`Self::from_env`] applies to the variable's value,
    /// so tests reach those rules without writing the process environment.
    fn from_env_value(read: Result<String, std::env::VarError>) -> TrustResult<Self> {
        let raw = read.map_err(|_err| TrustError::KeyManagement {
            reason: format!("environment variable {KEY_ENV_VAR} not set"),
        })?;
        let trimmed = raw.trim();
        let decoded = Zeroizing::new(
            URL_SAFE_NO_PAD
                .decode(trimmed.trim_end_matches('='))
                .or_else(|_err| STANDARD.decode(trimmed))
                .map_err(|_err| TrustError::KeyManagement {
                    reason: format!("environment variable {KEY_ENV_VAR} contains invalid base64"),
                })?,
        );
        let n = decoded.len();
        if n != 32 {
            return Err(TrustError::KeyManagement {
                reason: format!(
                    "environment variable {KEY_ENV_VAR} decoded to {n} bytes, expected 32"
                ),
            });
        }
        let mut seed = Zeroizing::new([0u8; 32]);
        seed.copy_from_slice(&decoded);
        Ok(Self::from_seed(&seed))
    }

    /// Constructs an identity from a raw 32-byte seed.
    ///
    /// Takes the seed wrapped in [`Zeroizing`] so every caller's copy is
    /// guaranteed to be overwritten when it goes out of scope; only the
    /// [`SigningKey`]'s own internal copy survives.
    ///
    /// Private to the crate; tests in the same module use it to build
    /// deterministic identities. Not part of the public API, so no
    /// constructor accepting private key material is exposed to consumers.
    ///
    /// [`SigningKey`]: ed25519_dalek::SigningKey
    pub fn from_seed(seed: &Zeroizing<[u8; 32]>) -> Self {
        let signing_key = ed25519_dalek::SigningKey::from_bytes(seed);
        let verifying_key = signing_key.verifying_key();
        Self {
            signing_key,
            verifying_key,
        }
    }

    /// Lowercase hex encoding of the verifying key, for `Debug` output.
    fn public_key_bytes_hex(&self) -> String {
        crate::hex_lower(&self.verifying_key.to_bytes())
    }
}

/// The prime `p = 2²⁵⁵ − 19`, little-endian — the field modulus a canonical
/// Ed25519 y-coordinate must be strictly below (RFC 8032 §5.1.2).
///
/// ⛔ **This was `#[cfg(feature = "unstable-anchor")]`, on the reasoning that
/// "the only artifact class that names a key it does not itself verify with is
/// the gated `delegation` format".** The premise was true and the conclusion did
/// not follow: [`Ed25519Identity::verify`] *does* verify with the key, and it
/// was accepting a non-canonical encoding of one. The gate meant the default
/// build — the shape consumers actually get — could not have enforced the rule
/// even if it had wanted to.
const CURVE25519_FIELD_MODULUS_LE: [u8; 32] = [
    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
];

/// Whether the y-coordinate in a compressed Ed25519 point encoding is canonical
/// — strictly less than `p` once the sign bit is masked off.
///
/// **This is checked here because `VerifyingKey::from_bytes` does not check it**,
/// which is not what one would assume from the name. Measured rather than
/// inferred: `from_bytes` accepts all-`0xff` and reports it as non-weak,
/// because decompression reduces the y-coordinate modulo `p` instead of
/// rejecting an out-of-range one. A non-canonical encoding is a second spelling
/// of a point that already has one, which is the same defect class this crate
/// refuses everywhere else in its wire formats.
///
/// **The sign bit is masked off and not otherwise checked.** `x = 0` with the
/// sign bit set is a second non-canonical spelling, of the two points with
/// `x = 0` — `y = 1` (the identity) and `y = p − 1` (the order-2 point). Both
/// are small-order, so [`is_usable_ed25519_public_key`]'s third condition
/// refuses them under either spelling and there is no encoding this masking
/// lets through. Stated because it is a gap in *this* function that another
/// condition closes, which is exactly the kind of thing that stops being true
/// silently.
fn is_canonical_y_coordinate(bytes: &[u8; 32]) -> bool {
    let mut y = *bytes;
    // The top bit of the last byte is the x-coordinate's sign, not part of y.
    y[31] &= 0x7f;
    // Little-endian magnitude comparison, most significant byte first.
    for index in (0..32).rev() {
        if y[index] < CURVE25519_FIELD_MODULUS_LE[index] {
            return true;
        }
        if y[index] > CURVE25519_FIELD_MODULUS_LE[index] {
            return false;
        }
    }
    // y == p exactly: a non-canonical encoding of zero.
    false
}

/// Whether `bytes` is a public key that could ever verify anything.
///
/// Three conditions:
///
/// 1. **Canonical y-coordinate** — see [`is_canonical_y_coordinate`], and note
///    that `VerifyingKey::from_bytes` does *not* enforce this.
/// 2. **Decompresses to a curve point** at all.
/// 3. **Not small-order.** A small-order key — the identity point among them —
///    admits forged signatures for arbitrary messages, which is why strict
///    verification refuses it.
///
/// Exposed to the crate rather than to consumers, and placed here rather than
/// at its call site, because this is the one file that knows how lys decides an
/// Ed25519 key is usable. A second copy elsewhere would be free to drift out of
/// agreement with [`Ed25519Identity::verify`] while both kept passing their own
/// tests.
///
/// Two kinds of caller: artifacts that *name* a key they do not verify with — a
/// key that fails here can never authorise anything, so an artifact carrying
/// one is a signed statement that cannot mean anything — and
/// [`Ed25519Identity::verify`] itself, which admits exactly the keys this
/// predicate admits.
///
/// # This USED to be stricter than [`Ed25519Identity::verify`]
///
/// ⛔ The paragraph replaced here recorded the asymmetry as deliberate and
/// deferred: condition 1 had no counterpart in verification, because
/// `verify_strict` checks the canonical `s` scalar and small-order `R` and `A`
/// but **not** that `A`'s y-coordinate is canonically encoded, and neither does
/// `from_bytes`. It argued that closing the gap "would change shipped, ungated,
/// semver-bound behaviour on the strength of a low-severity finding, which is a
/// decision for a release rather than for this module".
///
/// That was a reasonable thing to defer and a bad thing to *leave written down*
/// as a resting state. Two notions of "a key lys will accept" in one crate is
/// the drift this function was extracted to prevent, reintroduced one level up:
/// the delegation decoder and `verify` disagreed about the same 32 bytes, and
/// nothing anywhere would have failed if they had drifted further. `verify` now
/// calls this predicate, so agreement is structural rather than reviewed.
///
/// **What that narrowed, precisely.** Only encodings with `y >= p` once the sign
/// bit is masked — the 38 strings `y ∈ {p, …, p + 18}` × 2 sign bits. Of those,
/// 14 never decompressed and were already refused by `from_bytes`; 4 (`y = p`
/// and `y = p + 1`, both signs) reduce to the order-4 and identity points and
/// were already refused by `verify_strict`'s small-order check. The remaining
/// **20 were accepted as verifying keys and now are not.** None of the 20 can
/// have had a verifying signature that anyone could produce: each is a second
/// spelling of a point with `y ∈ {3, 4, 5, 6, 9, 10, 14, 15, 16, 18}`, and
/// signing under one means holding its discrete logarithm. So the change
/// narrows the set of accepted *key encodings* and cannot change any
/// constructible `Ok` outcome — which is also why no test can distinguish the
/// two behaviours through `verify`'s return value. See the tests.
pub(crate) fn is_usable_ed25519_public_key(bytes: &[u8; 32]) -> bool {
    if !is_canonical_y_coordinate(bytes) {
        return false;
    }
    match ed25519_dalek::VerifyingKey::from_bytes(bytes) {
        Ok(key) => !key.is_weak(),
        Err(_err) => false,
    }
}

#[cfg(test)]
#[path = "identity_tests.rs"]
mod tests;