acme-proxy 0.6.1

An ACME (RFC 8555) server that issues from a local CA, relays to an upstream CA, or delegates to a script
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! `POST /keyChange` (RFC 8555 §7.3.5, Account Key Rollover): the outer JWS
//! is `kid`-signed by the *old* key and carries, as its payload, a nested
//! inner JWS self-signed by the *new* key. Covers the success path (EC→EC and
//! a cross-algorithm RSA→EC rollover, plus proof the old key stops working
//! while the new one takes over), every RFC-mandated inner-JWS check (shape,
//! signature, `url` match, `account` match, `oldKey` match), the `409
//! Conflict` + `Location` case when the new key already belongs to a
//! different account, a deactivated account being refused, and that the
//! outer JWS's generic checks (`url`, nonce) still apply to this endpoint.

use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::response::Response;
use base64::prelude::*;
use serde_json::{Value, json};
use tower::ServiceExt;

mod common;
use common::{EcSigner, RsaSigner, TestSigner, body_json, fetch_nonce, p, test_app};

const BASE: &str = common::BASE;
const NEW_ACCOUNT_URL: &str = "http://localhost:3000/profile/default/newAccount";
const KEY_CHANGE_URL: &str = "http://localhost:3000/profile/default/keyChange";

async fn post(app: &Router, path: &str, body: String) -> Response {
    app.clone()
        .oneshot(
            Request::post(path)
                .header("content-type", "application/jose+json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap()
}

/// Registers an account and returns its account URL (used as `kid`).
async fn register(app: &Router, signer: &impl TestSigner) -> String {
    let nonce = fetch_nonce(app).await;
    let payload = json!({ "termsOfServiceAgreed": true });
    let res = post(
        app,
        &p("/newAccount"),
        signer.sign(NEW_ACCOUNT_URL, &nonce, &payload),
    )
    .await;
    assert_eq!(res.status(), StatusCode::CREATED);
    res.headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .expect("newAccount must set a Location header")
        .to_string()
}

async fn key_change(app: &Router, body: String) -> Response {
    post(app, &p("/keyChange"), body).await
}

/// Builds the inner keyChange JWS (self-signed by `new_signer`, embedding its
/// own JWK) as a [`Value`], ready to embed as the outer JWS's payload.
fn build_inner_value(new_signer: &impl TestSigner, url: &str, payload: &Value) -> Value {
    let inner_jws = new_signer.sign_inner(url, payload);
    serde_json::from_str(&inner_jws).unwrap()
}

/// Builds a complete, well-formed `keyChange` outer request body: the
/// `{account, oldKey}` inner JWS self-signed by `new_signer`, wrapped in an
/// outer `kid`-signed JWS from `old_signer`.
fn key_change_body(
    old_signer: &impl TestSigner,
    new_signer: &impl TestSigner,
    account_url: &str,
    nonce: &str,
) -> String {
    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(new_signer, KEY_CHANGE_URL, &inner_payload);
    old_signer.sign_kid(account_url, KEY_CHANGE_URL, nonce, &inner_value)
}

/// Asserts a 400 `malformed` problem+json and returns its body.
async fn assert_malformed(res: Response) -> Value {
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:malformed");
    problem
}

#[tokio::test]
async fn key_change_succeeds_ec() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;
    let path = account_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let body = key_change_body(&old_signer, &new_signer, &account_url, &nonce);
    let res = key_change(&app, body).await;
    assert_eq!(res.status(), StatusCode::OK);
    let account = body_json(res).await;
    assert_eq!(account["status"], "valid");

    // The old key no longer authenticates this account...
    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, &account_url, &nonce, &json!({}));
    let res = post(&app, path, body).await;
    assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:unauthorized"
    );

    // ...but the new one does, proving the rollover actually took effect.
    let nonce = fetch_nonce(&app).await;
    let body = new_signer.sign_kid(&account_url, &account_url, &nonce, &json!({}));
    let res = post(&app, path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
}

/// A cross-algorithm rollover: an account registered with an RSA key rolls
/// over to a freshly generated EC key. Exercises the outer `kid` path
/// verifying against a *stored RSA* SPKI (and `spki_to_jwk` reconstructing an
/// RSA `Jwk` for the `oldKey` comparison) while the inner JWS is self-signed
/// with ES256.
#[tokio::test]
async fn key_change_succeeds_cross_algorithm_rsa_to_ec() {
    let app = test_app().await;
    let old_signer = RsaSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;
    let path = account_url.strip_prefix(common::HOST).unwrap();

    let nonce = fetch_nonce(&app).await;
    let body = key_change_body(&old_signer, &new_signer, &account_url, &nonce);
    let res = key_change(&app, body).await;
    assert_eq!(res.status(), StatusCode::OK);

    let nonce = fetch_nonce(&app).await;
    let body = new_signer.sign_kid(&account_url, &account_url, &nonce, &json!({}));
    let res = post(&app, path, body).await;
    assert_eq!(res.status(), StatusCode::OK);
}

#[tokio::test]
async fn key_change_rejects_inner_missing_jwk() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let protected = json!({ "alg": "ES256", "url": KEY_CHANGE_URL });
    let protected_b64 = BASE64_URL_SAFE_NO_PAD.encode(serde_json::to_vec(&protected).unwrap());
    let payload_b64 = BASE64_URL_SAFE_NO_PAD.encode(
        serde_json::to_vec(&json!({ "account": account_url, "oldKey": old_signer.jwk() })).unwrap(),
    );
    let inner_value = json!({
        "protected": protected_b64,
        "payload": payload_b64,
        "signature": BASE64_URL_SAFE_NO_PAD.encode([0u8; 64]),
    });

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_rejects_inner_malformed_protected_json() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_value = json!({
        "protected": BASE64_URL_SAFE_NO_PAD.encode(b"not json"),
        "payload": BASE64_URL_SAFE_NO_PAD.encode(b"{}"),
        "signature": BASE64_URL_SAFE_NO_PAD.encode([0u8; 64]),
    });

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_rejects_inner_malformed_protected_base64() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_value = json!({
        "protected": "!!!not-base64!!!",
        "payload": BASE64_URL_SAFE_NO_PAD.encode(b"{}"),
        "signature": BASE64_URL_SAFE_NO_PAD.encode([0u8; 64]),
    });

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_rejects_inner_signature_tampered() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let mut inner_value = build_inner_value(&new_signer, KEY_CHANGE_URL, &inner_payload);
    inner_value["signature"] = json!(BASE64_URL_SAFE_NO_PAD.encode([0u8; 64]));

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    let res = key_change(&app, body).await;
    assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:unauthorized"
    );
}

#[tokio::test]
async fn key_change_rejects_inner_url_mismatch() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(&new_signer, &format!("{BASE}/other"), &inner_payload);

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_rejects_account_mismatch() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let other_signer = EcSigner::new();
    let other_account_url = register(&app, &other_signer).await;

    // The inner payload names a different, real account than the one that
    // signed the outer JWS.
    let inner_payload = json!({ "account": other_account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(&new_signer, KEY_CHANGE_URL, &inner_payload);

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_rejects_old_key_mismatch() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    // A third, unrelated key claimed as `oldKey` -- not the key that actually
    // signed the outer JWS.
    let unrelated_signer = EcSigner::new();
    let inner_payload = json!({ "account": account_url, "oldKey": unrelated_signer.jwk() });
    let inner_value = build_inner_value(&new_signer, KEY_CHANGE_URL, &inner_payload);

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

/// RFC 8555 §7.3.5 check #9: the new key must not already belong to a
/// different account. The server responds `409 Conflict` with a `Location`
/// header naming that account -- a genuinely new assertion shape (no other
/// endpoint in this codebase puts a header on an error response).
#[tokio::test]
async fn key_change_rejects_conflicting_new_key() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let other_signer = EcSigner::new();
    let other_account_url = register(&app, &other_signer).await;

    // Ask to roll `old_signer`'s account onto `other_signer`'s already
    // registered key.
    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(&other_signer, KEY_CHANGE_URL, &inner_payload);

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, KEY_CHANGE_URL, &nonce, &inner_value);
    let res = key_change(&app, body).await;

    assert_eq!(res.status(), StatusCode::CONFLICT);
    assert_eq!(
        res.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/problem+json")
    );
    let location = res
        .headers()
        .get("location")
        .and_then(|v| v.to_str().ok())
        .unwrap()
        .to_string();
    assert_eq!(location, other_account_url);

    let problem = body_json(res).await;
    assert_eq!(problem["type"], "urn:ietf:params:acme:error:malformed");
    assert_eq!(problem["status"], 409);
}

#[tokio::test]
async fn key_change_rejects_deactivated_account() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;
    let path = account_url.strip_prefix(common::HOST).unwrap();

    // Deactivate the account (RFC 8555 §7.3.6).
    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(
        &account_url,
        &account_url,
        &nonce,
        &json!({ "status": "deactivated" }),
    );
    let res = post(&app, path, body).await;
    assert_eq!(res.status(), StatusCode::OK);

    // RFC check #1: the account must be "currently active" — a deactivated
    // one cannot roll its key.
    let nonce = fetch_nonce(&app).await;
    let body = key_change_body(&old_signer, &new_signer, &account_url, &nonce);
    let res = key_change(&app, body).await;
    assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:unauthorized"
    );
}

/// The outer JWS's own generic checks (RFC 8555 §6.4/§6.5) still apply here,
/// the same way `update_account.rs` re-asserts them for `POST /acct/{id}`.
#[tokio::test]
async fn key_change_wrong_outer_url_is_malformed() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(&new_signer, KEY_CHANGE_URL, &inner_payload);

    let nonce = fetch_nonce(&app).await;
    let body = old_signer.sign_kid(&account_url, &format!("{BASE}/other"), &nonce, &inner_value);
    assert_malformed(key_change(&app, body).await).await;
}

#[tokio::test]
async fn key_change_unknown_nonce_is_bad_nonce() {
    let app = test_app().await;
    let old_signer = EcSigner::new();
    let new_signer = EcSigner::new();
    let account_url = register(&app, &old_signer).await;

    let inner_payload = json!({ "account": account_url, "oldKey": old_signer.jwk() });
    let inner_value = build_inner_value(&new_signer, KEY_CHANGE_URL, &inner_payload);

    let body = old_signer.sign_kid(
        &account_url,
        KEY_CHANGE_URL,
        "00000000-0000-0000-0000-000000000000",
        &inner_value,
    );
    let res = key_change(&app, body).await;
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    assert_eq!(
        body_json(res).await["type"],
        "urn:ietf:params:acme:error:badNonce"
    );
}

/// Two accounts rolling onto the *same* new key at the same time. One must win
/// with a `200`; the loser owes RFC 8555 §7.3.5's `409` + `Location`, never a
/// `500`.
///
/// `key_change_rejects_conflicting_new_key` above covers the sequential case,
/// where the conflict check sees the other account and refuses. This is the
/// interleaving it cannot reach: both requests run that check before either
/// `UPDATE` lands, both are told the key is free, and the loser then trips
/// `UNIQUE (profile, pubkey)` inside `update_pubkey`. Until the handler learned
/// to recognise that violation it became `serverInternal` — the same answer the
/// server gives when it has no idea what happened, for a case the RFC gives a
/// status *and* a `Location` for.
///
/// A file-backed database, because `connect_in_memory` pins the pool to one
/// connection and serializes the two requests out of the race entirely. Rounds,
/// because the window is a few statements wide and one attempt is not reliably
/// inside it; the assertions hold whichever way a round interleaves, so a round
/// that misses the window still passes rather than flaking.
#[tokio::test]
async fn concurrent_key_changes_onto_one_key_leave_a_winner_and_a_conflict() {
    const ROUNDS: usize = 12;
    let (app, _db, _disk) = common::test_app_on_disk().await;

    for round in 0..ROUNDS {
        let signer_a = EcSigner::new();
        let signer_b = EcSigner::new();
        let account_a = register(&app, &signer_a).await;
        let account_b = register(&app, &signer_b).await;

        // One new key, wanted by both.
        let new_key = EcSigner::new();
        let nonce_a = fetch_nonce(&app).await;
        let nonce_b = fetch_nonce(&app).await;
        let body_a = key_change_body(&signer_a, &new_key, &account_a, &nonce_a);
        let body_b = key_change_body(&signer_b, &new_key, &account_b, &nonce_b);

        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
        let mut tasks = Vec::with_capacity(2);
        for body in [body_a, body_b] {
            let app = app.clone();
            let barrier = barrier.clone();
            tasks.push(tokio::spawn(async move {
                barrier.wait().await;
                key_change(&app, body).await
            }));
        }

        let mut statuses = Vec::with_capacity(2);
        for task in tasks {
            let res = task.await.unwrap();
            let status = res.status();
            assert_ne!(
                status,
                StatusCode::INTERNAL_SERVER_ERROR,
                "round {round}: a lost rollover race is a 409, not a server error"
            );
            if status == StatusCode::CONFLICT {
                // The loser is told where the key actually lives, which is the
                // half of §7.3.5 that lets a client recover on its own.
                let location = res
                    .headers()
                    .get("location")
                    .and_then(|value| value.to_str().ok())
                    .unwrap_or_default()
                    .to_string();
                assert!(
                    location == account_a || location == account_b,
                    "round {round}: 409 must name the account holding the key, got {location:?}"
                );
                let problem = body_json(res).await;
                assert_eq!(problem["status"], 409, "round {round}");
            }
            statuses.push(status);
        }

        assert_eq!(
            statuses.iter().filter(|s| **s == StatusCode::OK).count(),
            1,
            "round {round}: exactly one rollover may take the key, got {statuses:?}"
        );
        assert_eq!(
            statuses
                .iter()
                .filter(|s| **s == StatusCode::CONFLICT)
                .count(),
            1,
            "round {round}: the other must be refused with 409, got {statuses:?}"
        );
    }
}