jose-rs 0.14.0

Pure-Rust JOSE library (JWS, JWE, JWK, JWT) with software and HSM key support
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
//! The key-agreement boundary: turning a JWK into something that can perform
//! ECDH, and nothing else (ADR 0016).
//!
//! Key agreement is a different operation from signing or key wrapping, and the
//! difference is not cosmetic:
//!
//! * an agreement **needs a private scalar**, but never sends or verifies
//!   anything — so `use`/`key_ops` must say *derive*, not *sign*;
//! * it is *two-party*: one's own key and a **peer** key, which for
//!   `ECDH-ES` arrives inside the message (`epk`) as attacker-chosen bytes;
//! * the curve is part of the identity of the operation. A P-256 secret
//!   multiplied against a P-384 point is either an error or, in a lax
//!   implementation, a silently different shared secret.
//!
//! So this module hands out two distinct types instead of a `SoftwareKey` and a
//! wish: [`AgreementKey`] (own key, private material enforced) and [`PeerKey`]
//! (public material only, point validated), and [`AgreementKey::agree`] refuses
//! a peer on a different curve.
//!
//! [`AgreementCurve`] is the list of curves that can be agreed on at all:
//! P-256, P-384, P-521 and X25519. Everything else an attacker or a config file
//! can name — Ed25519 and Ed448 (signing curves that share the `OKP` key type
//! with X25519), X448 (a genuine agreement curve this backend cannot do),
//! secp256k1, Brainpool — is refused here, by name, rather than reaching a
//! crypto layer that would report it as a generic failure.
//!
//! ```
//! use jose_rs::jwk::agreement::{agreement_key, peer_key};
//! use jose_rs::jwk::Jwk;
//!
//! let own: Jwk = serde_json::from_value(serde_json::json!({
//!     "kty": "EC", "crv": "P-256",
//!     "x": "weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ",
//!     "y": "e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck",
//!     "d": "VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw",
//!     "key_ops": ["deriveKey"],
//! })).unwrap();
//! let peer: Jwk = serde_json::from_value(serde_json::json!({
//!     "kty": "EC", "crv": "P-256",
//!     "x": "gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0",
//!     "y": "SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps",
//! })).unwrap();
//!
//! let own = agreement_key(&own).unwrap();
//! let peer = peer_key(&peer).unwrap();
//!
//! // The two halves are consumed by `derive_key`, which runs JOSE's Concat KDF
//! // so the shared secret never has to be handled as a key. These are RFC 7518
//! // Appendix C's own keys and expected output.
//! let cek = own
//!     .derive_key(&peer, "A128GCM", Some("QWxpY2U"), Some("Qm9i"), 16)
//!     .unwrap();
//! assert_eq!(jose_rs::base64url::encode(&cek), "VqqN6vgjbSBcIijNcacQGg");
//! ```

use zeroize::Zeroizing;

use crate::error::{JoseError, Result};
use crate::jwk::Jwk;

/// The curves this crate can perform key agreement on.
///
/// The list is deliberately short and it is a *type*, not a string: an
/// unsupported `crv` (X448, Brainpool, secp256k1) is refused here, at the
/// boundary, rather than becoming a downstream crypto error — or worse, being
/// silently reinterpreted as another curve.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AgreementCurve {
    /// NIST P-256 (`crv`: `P-256`).
    P256,
    /// NIST P-384 (`crv`: `P-384`).
    P384,
    /// NIST P-521 (`crv`: `P-521`).
    P521,
    /// Curve25519 in X25519 form (`kty`: `OKP`, `crv`: `X25519`, RFC 8037 §2).
    ///
    /// The only OKP curve here. Ed25519 and Ed448 are signing curves and are
    /// refused; X448 is an agreement curve this backend cannot do.
    X25519,
}

impl AgreementCurve {
    /// The `crv` member naming this curve on the wire.
    ///
    /// Needed to build an `epk` JWK for a freshly generated ephemeral key, and
    /// to generate that key on the recipient's curve in the first place.
    #[must_use]
    pub fn as_crv_str(self) -> &'static str {
        match self {
            Self::P256 => "P-256",
            Self::P384 => "P-384",
            Self::P521 => "P-521",
            Self::X25519 => "X25519",
        }
    }

    /// Coordinate length in bytes.
    #[must_use]
    pub fn coord_len(self) -> usize {
        match self {
            Self::P256 => 32,
            Self::P384 => 48,
            Self::P521 => 66,
            // A single 32-octet field element: an X25519 public value *is* its
            // u-coordinate, with no second coordinate and no encoding byte.
            Self::X25519 => 32,
        }
    }

    /// The backend curve, or `None` for X25519.
    ///
    /// X25519 is a different primitive in the backend (`agree_x25519`, not the
    /// `EcCurve`-dispatched ECDH), so `None` here means "take the X25519 path"
    /// rather than "unsupported".
    fn kryptering_curve(self) -> Option<kryptering::EcCurve> {
        match self {
            Self::P256 => Some(kryptering::EcCurve::P256),
            Self::P384 => Some(kryptering::EcCurve::P384),
            Self::P521 => Some(kryptering::EcCurve::P521),
            Self::X25519 => None,
        }
    }

    /// Read `kty`/`crv` and reject every curve this crate cannot agree on.
    ///
    /// Curves are named explicitly rather than lumped into one message: an OKP
    /// key is not automatically an agreement key, and a signing curve arriving
    /// at this boundary is a mistake worth a specific error.
    fn from_jwk(jwk: &Jwk) -> Result<Self> {
        match (jwk.kty.as_str(), jwk.crv.as_deref()) {
            ("EC", Some("P-256")) => Ok(Self::P256),
            ("EC", Some("P-384")) => Ok(Self::P384),
            ("EC", Some("P-521")) => Ok(Self::P521),
            ("OKP", Some("X25519")) => Ok(Self::X25519),
            // X448 is an agreement curve, so saying "signing curve" about it
            // would be false; Ed25519 and Ed448 genuinely are signing curves, and
            // both messages are specific because the remedies differ (a different
            // backend for one, a different key for the other).
            ("OKP", Some("X448")) => Err(JoseError::Key(
                "X448 is a key-agreement curve but cannot perform key agreement with this \
                 backend; X25519 and the P-curves can"
                    .into(),
            )),
            ("OKP", Some(other)) => Err(JoseError::Key(format!(
                "OKP curve {other} is a signing curve, not a key-agreement curve"
            ))),
            ("EC", Some(other)) => Err(JoseError::Key(format!(
                "EC curve {other} is not supported for key agreement by this backend"
            ))),
            ("EC", None) => Err(JoseError::Key("missing crv for EC key".into())),
            (kty, _) => Err(JoseError::Key(format!(
                "kty {kty} cannot perform key agreement; expected EC or OKP"
            ))),
        }
    }
}

/// Key-management algorithms that use an agreement key, by `alg` value.
const AGREEMENT_ALGS: &[&str] = &[
    "ECDH-ES",
    "ECDH-ES+A128KW",
    "ECDH-ES+A192KW",
    "ECDH-ES+A256KW",
];

/// Own half of a key-agreement operation: a private scalar on a known curve.
#[derive(Debug, Clone)]
pub struct AgreementKey {
    key: kryptering::SoftwareKey,
    curve: AgreementCurve,
    /// This key's own public value in the encoding agreement expects:
    /// uncompressed SEC1 (`0x04 || X || Y`). Carried because a sender has to
    /// publish it as the `epk` member.
    public: Vec<u8>,
}

impl AgreementKey {
    /// The curve this key is on.
    #[must_use]
    pub fn curve(&self) -> AgreementCurve {
        self.curve
    }

    /// This key's public value, in the agreement encoding (needed to publish an
    /// ephemeral key as `epk`).
    #[must_use]
    pub fn public_bytes(&self) -> &[u8] {
        &self.public
    }

    /// Agree with `peer` and derive a key of `key_len` octets, in one step.
    ///
    /// This is the entry point everything should use: the raw shared secret
    /// never becomes a value the caller can hold, mis-handle, or use as a key.
    /// The derivation is JOSE's Concat KDF (RFC 7518 §4.6.2) with SHA-256 and
    /// the RFC's length-prefixed `OtherInfo`, so the result matches what every
    /// conformant implementation computes for the same inputs — including the
    /// RFC's own Appendix C vector, which the tests assert.
    ///
    /// `alg_id` is the ASCII `enc` value for direct key agreement and the ASCII
    /// `alg` value for key agreement with key wrapping; `apu` / `apv` are the
    /// base64url header values, if present.
    ///
    /// # Errors
    ///
    /// [`JoseError::Key`] for a curve mismatch or a rejected peer point,
    /// [`JoseError::InvalidHeader`] for a non-canonical or duplicated
    /// `apu`/`apv`, [`JoseError::Crypto`] if a primitive fails.
    pub fn derive_key(
        &self,
        peer: &PeerKey,
        alg_id: &str,
        apu: Option<&str>,
        apv: Option<&str>,
        key_len: usize,
    ) -> Result<Zeroizing<Vec<u8>>> {
        let z = self.agree(peer)?;
        crate::jwe::internal::concat_kdf(z.as_slice(), key_len, alg_id, apu, apv)
    }

    /// Perform agreement against `peer`, returning the raw shared secret `Z`.
    ///
    /// **`Z` is never a key.** It is the direct output of the scalar
    /// multiplication: biased, related to the peer's public value, and used
    /// directly by no JOSE algorithm — every JOSE key-management mode passes it
    /// through the Concat KDF first. Derive; do not consume this directly.
    ///
    /// # Errors
    ///
    /// [`JoseError::Key`] when the peer is on a different curve, or when the
    /// backend rejects the peer point or the agreement itself fails.
    pub fn agree(&self, peer: &PeerKey) -> Result<Zeroizing<Vec<u8>>> {
        if self.curve != peer.curve() {
            return Err(JoseError::Key(format!(
                "key agreement curve mismatch: own key is {:?}, peer is {:?}",
                self.curve,
                peer.curve()
            )));
        }
        // One dispatch, two primitives: the backend does X25519 through its own
        // function rather than an `EcCurve`, and the peer encoding differs
        // accordingly (raw u-coordinate vs SEC1 point). Both refuse a
        // low-order/identity peer value; both return `coord_len()` octets, which
        // is checked below rather than trusted.
        let z = match self.curve.kryptering_curve() {
            Some(ec_curve) => {
                kryptering::software::keyagreement::agree(ec_curve, &peer.encoded, &self.key)
            }
            None => kryptering::software::keyagreement::agree_x25519(&peer.encoded, &self.key),
        }
        .map_err(JoseError::Crypto)?;
        if z.len() != self.curve.coord_len() {
            return Err(JoseError::Key(format!(
                "key agreement returned {} bytes, expected {} for {:?}",
                z.len(),
                self.curve.coord_len(),
                self.curve
            )));
        }
        Ok(Zeroizing::new(z))
    }
}

/// Peer half of a key-agreement operation: public material only, on a known
/// curve, with the point validated.
#[derive(Debug, Clone)]
pub struct PeerKey {
    curve: AgreementCurve,
    /// Uncompressed SEC1 point, `0x04 || X || Y`.
    encoded: Vec<u8>,
}

impl PeerKey {
    /// The curve the peer claims.
    #[must_use]
    pub fn curve(&self) -> AgreementCurve {
        self.curve
    }

    /// The peer's encoded public value.
    #[must_use]
    pub fn public_bytes(&self) -> &[u8] {
        &self.encoded
    }
}

/// Generate a fresh agreement key pair on `curve`.
///
/// One function because the choice is a property of the curve, not of the caller:
/// X25519 keys are OKP and the P-curves are EC, and a sender that got that wrong
/// would publish an `epk` its own recipient cannot parse. Used for the per-message
/// ephemeral key (RFC 7518 §4.6), which is why no caller ever supplies one.
pub(crate) fn generate_ephemeral(curve: AgreementCurve) -> Result<Jwk> {
    match curve {
        AgreementCurve::X25519 => crate::jwk::generate_x25519(),
        other => crate::jwk::generate_ec(other.as_crv_str()),
    }
}

/// Prepare a JWK as one's own key for key agreement.
///
/// Checks, in order: the key type and curve are agreement-capable; `use` and
/// `key_ops` permit `deriveKey` (RFC 7517 §4.3 — a key pinned to `sign` is not
/// an agreement key); an `alg` present on the key names a key-agreement
/// algorithm; and private material is present. Material validity (point on
/// curve, `d` consistent with `(x, y)`) is enforced by
/// [`crate::jwk::jwk_to_software_key`], which is also what stops a JWK from
/// publishing one identity while agreeing with another.
///
/// # Errors
///
/// [`JoseError::Key`] for any of the rejections above.
pub fn agreement_key(jwk: &Jwk) -> Result<AgreementKey> {
    let curve = AgreementCurve::from_jwk(jwk)?;
    // RFC 7517 §4.3: `deriveKey` is the operation an agreement key performs.
    // `use: "sig"` fails the category check, and a `key_ops` list that omits
    // `deriveKey` fails independently, so a key marked for signing cannot reach
    // the crypto layer by this route.
    jwk.check_op(crate::jwk::JwkOp::DeriveKey)?;
    if let Some(alg) = jwk.alg.as_deref() {
        if !AGREEMENT_ALGS.contains(&alg) {
            return Err(JoseError::Key(format!(
                "JWK alg {alg} is not a key-agreement algorithm; this key cannot be used for \
                 ECDH-ES (supported: {})",
                AGREEMENT_ALGS.join(", ")
            )));
        }
    }
    let key = crate::jwk::jwk_to_software_key(jwk)?;
    if !key.has_private_key() {
        return Err(JoseError::Key(
            "key agreement requires the private scalar; a public-only JWK is a peer key, not \
             an agreement key"
                .into(),
        ));
    }
    let public = encode_public(curve, jwk)?;
    Ok(AgreementKey { key, curve, public })
}

/// Prepare a JWK as the **peer** half of a key agreement.
///
/// The peer's key is data, not an identity: for `ECDH-ES` it is the `epk`
/// member of a message somebody chose. So no `use`/`key_ops`/`alg` check is
/// applied — the peer's own policy is nobody's business but its own — while two
/// things *are* enforced:
///
/// * **no private material**: an `epk` carrying `d` is a protocol error, and
///   accepting it would let a producer hand over a "public" key that something
///   else already knows the secret of;
/// * **a valid point on the named curve**, obtained by building the backend key
///   (which validates the point and the coordinate sizes) rather than by
///   trusting the coordinates' byte lengths.
///
/// Agreeing with an arbitrary, unauthenticated ephemeral key is exactly what
/// direct key agreement means, and it is why `ECDH-ES` authenticates *nothing*
/// about the sender (ADR 0016). The result of that agreement is only ever
/// consumable through the KDF, and the message still has to authenticate its
/// own content.
///
/// # Errors
///
/// [`JoseError::Key`] when the key type or curve is not agreement-capable, when
/// private material is present, or when the public value is not a valid point.
pub fn peer_key(jwk: &Jwk) -> Result<PeerKey> {
    let curve = AgreementCurve::from_jwk(jwk)?;
    if jwk.d.is_some() {
        return Err(JoseError::Key(
            "a peer key must carry public material only; the JWK has a private component `d`"
                .into(),
        ));
    }
    // Building the backend key is the point validation: `jwk_to_software_key`
    // rejects an off-curve or mismatched-length point before it produces
    // anything usable.
    crate::jwk::jwk_to_software_key(jwk)?;
    let encoded = encode_public(curve, jwk)?;
    Ok(PeerKey { curve, encoded })
}

/// Encode a JWK's public value as an uncompressed SEC1 point, `0x04 || X || Y`,
/// which is what the backend's agreement functions take.
///
/// Left-padding is applied to the coordinates (a JWK may omit leading zero
/// octets); [`crate::jwk::jwk_to_software_key`] has already rejected anything
/// longer than the field.
fn encode_public(curve: AgreementCurve, jwk: &Jwk) -> Result<Vec<u8>> {
    if curve == AgreementCurve::X25519 {
        // No 0x04 prefix and no `y`: the public value *is* the 32-octet
        // u-coordinate (RFC 7748 §5 / RFC 8037 §2). Prefixing it would be
        // rejected by the primitive as a wrong-length value, but the failure
        // would look like a malformed key rather than a wrong encoding.
        return coordinate(jwk, "x", curve.coord_len());
    }
    let coord_len = curve.coord_len();
    let x = coordinate(jwk, "x", coord_len)?;
    let y = coordinate(jwk, "y", coord_len)?;
    let mut point = Vec::with_capacity(1 + 2 * coord_len);
    point.push(0x04);
    point.extend_from_slice(&x);
    point.extend_from_slice(&y);
    Ok(point)
}

/// One base64url coordinate (`x` or `y`), left-padded to `coord_len`.
///
/// A JWK may legitimately omit leading zero octets, so short is fine and padded;
/// longer than the field is not. Coordinate *validity* (on-curve, consistent
/// with `d`) is enforced by the backend key import, not here.
fn coordinate(jwk: &Jwk, name: &str, coord_len: usize) -> Result<Vec<u8>> {
    let value = match name {
        "x" => jwk.x.as_deref(),
        "y" => jwk.y.as_deref(),
        _ => None,
    }
    .ok_or_else(|| JoseError::Key(format!("missing {name} for an agreement key")))?;
    let bytes = crate::base64url::decode(value)?;
    if bytes.len() > coord_len {
        return Err(JoseError::Key(format!(
            "{name} is {} octets, longer than the {coord_len}-octet field",
            bytes.len()
        )));
    }
    let mut padded = vec![0u8; coord_len - bytes.len()];
    padded.extend_from_slice(&bytes);
    Ok(padded)
}