acme-proxy 0.5.0

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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! `acme-proxy upstream …` — managing this server's own ACME account at the
//! upstream CA, when the `relay` signer backend is in use.
//!
//! ## Why this command exists alongside `signer.relay.eab`
//!
//! An upstream that requires External Account Binding hands the operator a
//! `kid` and an HMAC secret out of band. That credential authorizes exactly
//! one thing — a single `newAccount` call — and is useless afterwards. This
//! command takes the secret on **stdin** (or from a file), uses it once, and
//! never writes it anywhere — no bootstrap secret is left readable on disk
//! for the life of the server, unlike the alternative of setting
//! `signer.relay.eab` in configuration (see
//! [`crate::config::RelayEabConfig`]), which trades that property away
//! for not needing this separate step. The secret is deliberately not
//! accepted as a command-line flag either way: argv is visible to every
//! process on the host via `ps` and is routinely written to shell history.

use std::io::BufRead;
use std::path::PathBuf;
use std::sync::Arc;

use clap::Subcommand;

use crate::admin;
use crate::cli::render;
use crate::cli::style::Palette;
use crate::cli::window::{DEFAULT_LIMIT, Window};
use crate::cli::{CliError, resolve_profile};
use crate::config::Config;
use crate::signer::relay;
use crate::sqlite::db::Database;
use crate::sqlite::status::UpstreamOrderStatus;
use crate::sqlite::upstream_order::{UpstreamOrder, UpstreamOrderQuery};

#[derive(Subcommand)]
pub enum UpstreamCommand {
    /// Register this server's account at the upstream ACME server, writing the
    /// `kid` it returns so `serve` never needs the credential again.
    Register {
        /// The EAB key id the upstream's operator issued. Omit when the
        /// upstream requires no External Account Binding.
        #[arg(long = "eab-kid")]
        eab_kid: Option<String>,
        /// Read the EAB HMAC secret (base64url) from this file instead of
        /// prompting on stdin. The file is read, used, and never copied.
        #[arg(long = "eab-hmac-key-file")]
        eab_hmac_key_file: Option<PathBuf>,
        /// Which profile's upstream to register with. Optional when the
        /// configuration defines exactly one profile.
        #[arg(long)]
        profile: Option<String>,
    },
    /// Show the configured upstream and whether this server is registered.
    Show {
        #[arg(long)]
        json: bool,
        /// Which profile's upstream to describe. Optional when the
        /// configuration defines exactly one profile.
        #[arg(long)]
        profile: Option<String>,
    },
    /// The relay backend's per-order upstream state. Read-only — abandoning an
    /// in-flight relay is done through `acme-proxy jobs cancel` on the
    /// `signer_relay_issue` job, which owns the state machine.
    Order {
        #[command(subcommand)]
        command: UpstreamOrderCommand,
    },
}

#[derive(Subcommand)]
pub enum UpstreamOrderCommand {
    /// List upstream orders, optionally filtered.
    List {
        /// Restrict to one ACME endpoint (the local order's profile).
        #[arg(long)]
        profile: Option<String>,
        #[arg(long)]
        status: Option<String>,
        #[arg(long, default_value_t = DEFAULT_LIMIT)]
        limit: i64,
        #[arg(long, default_value_t = 0)]
        offset: i64,
        #[arg(long)]
        json: bool,
    },
    /// Show one upstream order by its **local** order id, cross-linked to its
    /// relay job.
    Show {
        id: String,
        #[arg(long)]
        json: bool,
    },
}

/// Resolves which profile's `[signer.relay]` a command should act on.
///
/// `signer` is a **per-profile** section, but this command read
/// `config.signer.relay` — the global base every profile overlays, which
/// nothing serves from. An operator who configured the upstream only under
/// `[profiles.le].signer.relay` was told "directory_url is not set", which
/// was simply false; and if a *different* upstream happened to be configured
/// globally, `register` would write the account key and `.kid` sidecar for the
pub async fn run_upstream_command(
    command: UpstreamCommand,
    reader: &mut impl BufRead,
    palette: Palette,
    config: &Config,
    database: Arc<Database>,
) -> Result<(), CliError> {
    match command {
        UpstreamCommand::Register {
            eab_kid,
            eab_hmac_key_file,
            profile,
        } => {
            let resolved = resolve_profile(config, profile.as_deref())?;
            let cfg = &resolved.sections.signer.relay;
            if cfg.directory_url.is_empty() {
                return Err(CliError::failed(
                    "signer.relay.directory_url is not set: there is no upstream to register \
                     with"
                        .to_string(),
                ));
            }

            // Only read a secret when a kid names one; an upstream that needs
            // no EAB must not prompt for something the operator does not have.
            let secret = eab_kid
                .as_ref()
                .map(|_| read_secret(eab_hmac_key_file.as_deref(), reader))
                .transpose()?;
            let eab = eab_kid.as_deref().zip(secret.as_deref());

            // A throwaway resolver, for the same reason `order revoke` builds
            // one: a one-shot command has no server around it to share the
            // process-wide one.
            let resolver = crate::dns::resolver_addr(&config.dns)
                .and_then(crate::challenge::build_resolver)
                .map_err(|error| CliError::failed(format!("configuration error: {error}")))?;
            let proxies = crate::proxy::from_config(&config.proxy)
                .map_err(|error| CliError::failed(format!("configuration error: {error}")))?;
            let outbound = crate::http_client::Outbound::new(resolver, proxies);
            match relay::register_upstream_account(cfg, outbound, eab).await {
                Ok(kid) => println!("Registered. kid = {kid}"),
                Err(error) => {
                    return Err(CliError::failed(format!(
                        "upstream registration failed: {error}"
                    )));
                }
            }
        }

        UpstreamCommand::Show { json, profile } => {
            let resolved = resolve_profile(config, profile.as_deref())?;
            let cfg = &resolved.sections.signer.relay;
            let kid = relay::stored_kid(cfg);
            let key_present = std::path::Path::new(&cfg.account_key_path).exists();

            if json {
                println!(
                    "{}",
                    serde_json::json!({
                        "directoryUrl": cfg.directory_url,
                        "accountKeyPath": cfg.account_key_path,
                        "accountKeyPresent": key_present,
                        "kid": kid,
                        "registered": kid.is_some(),
                    })
                );
            } else {
                println!("directory:   {}", none_if_empty(&cfg.directory_url));
                println!(
                    "account key: {} ({})",
                    cfg.account_key_path,
                    if key_present { "present" } else { "absent" }
                );
                match kid {
                    Some(kid) => println!("kid:         {kid}"),
                    None => println!("kid:         (not registered)"),
                }
            }
        }

        UpstreamCommand::Order { command } => match command {
            UpstreamOrderCommand::List {
                profile,
                status,
                limit,
                offset,
                json,
            } => {
                let status = status
                    .map(|value| value.parse::<UpstreamOrderStatus>())
                    .transpose()
                    .map_err(|error| CliError::bad_request(format!("--status: {error}")))?;
                let window = Window::resolve(limit, offset);
                let query = UpstreamOrderQuery {
                    profile,
                    status,
                    limit: window.limit,
                    offset: window.offset,
                };
                let (rows, total) = UpstreamOrder::search(&query, &database).await?;
                render::print_page(
                    &rows,
                    total,
                    window,
                    json,
                    admin::render_upstream_order_json,
                    |row| render::render_upstream_order_line(row, palette),
                );
            }
            UpstreamOrderCommand::Show { id, json } => {
                let Some(detail) = admin::load_upstream_order_detail(&id, database).await? else {
                    return Err(CliError::bad_request(format!(
                        "no upstream order for local order {id}"
                    )));
                };
                if json {
                    println!("{}", admin::render_upstream_order_detail_json(&detail));
                } else {
                    print!(
                        "{}",
                        render::render_upstream_order_detail_text(&detail, palette)
                    );
                }
            }
        },
    }
    Ok(())
}

fn none_if_empty(value: &str) -> &str {
    if value.is_empty() { "(not set)" } else { value }
}

/// Reads the EAB HMAC secret from `path`, or prompts for it on stdin.
///
/// Accepts the base64url form `acme-proxy eab create` prints, and falls back
/// to standard base64 so a credential from another CA's console pastes in
/// unchanged. A value that decodes as neither is an error rather than being
/// silently used as raw bytes — that would produce a valid-looking binding the
/// upstream rejects for no visible reason.
fn read_secret(
    path: Option<&std::path::Path>,
    reader: &mut impl BufRead,
) -> Result<Vec<u8>, CliError> {
    let raw = match path {
        Some(path) => std::fs::read_to_string(path).map_err(|error| {
            CliError::failed(format!("cannot read {}: {error}", path.display()))
        })?,
        None => {
            eprintln!("Enter the upstream EAB HMAC key (base64), then press Enter:");
            let mut line = String::new();
            // `bad_request` for the same reason the unparseable-key refusal two
            // lines below is one: nothing usable was supplied, and re-running
            // the identical command will not change that. A read failure is the
            // host's problem and stays `failed`.
            match reader.read_line(&mut line) {
                Ok(0) => return Err(CliError::bad_request("no EAB key supplied".to_string())),
                Ok(_) => {}
                Err(error) => {
                    return Err(CliError::failed(format!(
                        "cannot read the EAB key from stdin: {error}"
                    )));
                }
            }
            line
        }
    };

    relay::decode_secret(raw.trim())
        .ok_or_else(|| CliError::bad_request("the EAB key is not valid base64".to_string()))
}

#[cfg(test)]
mod tests {
    use crate::config::ENV_LOCK;

    /// Loads a `Config` from TOML the way the server does, so `resolve_profiles`
    /// has the raw sources it needs for per-key inheritance.
    fn config_from(body: &str) -> Config {
        let _lock = ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let dir = crate::testutil::TempDir::new("upstream");
        std::fs::write(dir.join("config.toml"), body).unwrap();
        // SAFETY: single-threaded test holding ENV_LOCK; removed before return.
        unsafe {
            std::env::set_var("ACME_PROXY_CONFIG", dir.join("config").to_str().unwrap());
        }
        let config = Config::load().expect("the configuration must load");
        unsafe {
            std::env::remove_var("ACME_PROXY_CONFIG");
        }
        config
    }

    /// The bug this resolution fixes: `[signer.relay]` written *inside* a
    /// profile was invisible, because the command read the global base section
    /// that nothing ever serves from. An operator saw "directory_url is not
    /// set" for a configuration where it plainly was.
    #[test]
    fn a_profiles_own_upstream_is_what_gets_resolved() {
        let config = config_from(
            r#"
            [profiles.le]
            signer.backend = "relay"
            signer.relay.directory_url = "https://upstream.example/directory"
            signer.relay.account_key_path = "/tmp/le-upstream.key"
            "#,
        );

        let resolved = resolve_profile(&config, None).unwrap();
        assert_eq!(resolved.name, "le");
        assert_eq!(
            resolved.sections.signer.relay.directory_url,
            "https://upstream.example/directory"
        );
        assert_eq!(
            resolved.sections.signer.relay.account_key_path,
            "/tmp/le-upstream.key"
        );
    }

    /// With several profiles there is no right answer to guess — and guessing
    /// wrong means `register` writing an account key and `.kid` for the wrong
    /// CA at the wrong paths.
    #[test]
    fn several_profiles_require_saying_which() {
        let config = config_from(
            r#"
            [profiles.le]
            [profiles.internal]
            "#,
        );

        let error = resolve_profile(&config, None).unwrap_err().to_string();
        assert!(error.contains("--profile"), "{error}");
        assert!(
            error.contains("le") && error.contains("internal"),
            "{error}"
        );

        // Named explicitly, it resolves.
        assert_eq!(resolve_profile(&config, Some("le")).unwrap().name, "le");
        // And an unknown name is refused rather than falling back.
        let error = resolve_profile(&config, Some("nope"))
            .unwrap_err()
            .to_string();
        assert!(error.contains("nope"), "{error}");
    }

    use super::*;
    use base64::prelude::*;

    use crate::cli::CliErrorKind;

    // `decode_secret`'s own decoding tests (base64url, standard base64, a
    // refused non-base64 value) live in `signer::relay::eab`, which now
    // owns the one implementation both this module and `provision()` call.

    #[test]
    fn an_empty_directory_url_renders_as_unset() {
        assert_eq!(none_if_empty(""), "(not set)");
        assert_eq!(none_if_empty("https://x/dir"), "https://x/dir");
    }

    /// The secret must be readable from stdin, so it never reaches argv.
    #[test]
    fn the_secret_can_come_from_stdin() {
        let secret = b"01234567890123456789012345678901";
        let encoded = BASE64_URL_SAFE_NO_PAD.encode(secret);
        let mut reader = std::io::Cursor::new(format!("{encoded}\n").into_bytes());
        assert_eq!(read_secret(None, &mut reader).unwrap(), secret.to_vec());
    }

    #[test]
    fn the_secret_can_come_from_a_file() {
        let secret = b"01234567890123456789012345678901";
        let dir = crate::testutil::TempDir::new("eab");
        let path = dir.join("key.b64");
        // Trailing newline is what an editor or `echo` leaves behind.
        std::fs::write(
            &path,
            format!("{}\n", BASE64_URL_SAFE_NO_PAD.encode(secret)),
        )
        .unwrap();

        let mut empty = std::io::Cursor::new(Vec::new());
        assert_eq!(
            read_secret(Some(&path), &mut empty).unwrap(),
            secret.to_vec()
        );
    }

    #[test]
    fn a_missing_secret_file_is_reported() {
        let mut empty = std::io::Cursor::new(Vec::new());
        let error = read_secret(
            Some(std::path::Path::new("/nonexistent/eab.b64")),
            &mut empty,
        )
        .expect_err("a missing file must be reported");
        assert!(error.to_string().starts_with("cannot read "), "{error}");
    }

    /// Closed stdin means the operator has nothing to give; prompting forever
    /// or reading an empty secret would both be worse than saying so.
    #[test]
    fn an_empty_stdin_is_reported() {
        // `bad_request` (exit 3), not `failed` (exit 1): nothing usable was
        // supplied, and re-running the identical command cannot change that --
        // the same class as the unparseable key below.
        let mut empty = std::io::Cursor::new(Vec::new());
        assert_eq!(
            read_secret(None, &mut empty),
            Err(CliError::bad_request("no EAB key supplied".to_string()))
        );
    }

    #[test]
    fn a_secret_that_is_not_base64_is_reported() {
        let mut reader = std::io::Cursor::new(b"not base64!!!\n".to_vec());
        assert_eq!(
            read_secret(None, &mut reader),
            Err(CliError::bad_request(
                "the EAB key is not valid base64".to_string()
            ))
        );
    }

    /// Without `signer.relay.directory_url` there is no upstream at all,
    /// so registration stops before it can prompt for a credential.
    #[tokio::test]
    async fn registering_without_an_upstream_is_refused() {
        // A real profile, but one whose signer is the default `local_ca` — so
        // there genuinely is no upstream, which is what the message must say.
        // (`Config::default()` would now fail earlier, on having no profiles at
        // all, and would not exercise this branch.)
        let config = config_from("[profiles.default]\n");
        let mut reader: &[u8] = &[];
        let error = run_upstream_command(
            UpstreamCommand::Register {
                eab_kid: None,
                eab_hmac_key_file: None,
                profile: None,
            },
            &mut reader,
            Palette::plain(),
            &config,
            test_db().await,
        )
        .await
        .expect_err("there is no upstream to register with");
        assert!(error.to_string().contains("directory_url"), "{error}");
    }

    /// An upstream that cannot be reached is reported, not retried forever:
    /// `register` is a one-shot operator command.
    #[tokio::test]
    async fn an_unreachable_upstream_is_reported() {
        let dir = crate::testutil::TempDir::new("upstream");

        // Port 1 on loopback: nothing listens, so the directory fetch fails
        // fast rather than hanging on a routable-but-silent address.
        let config = config_from(&format!(
            r#"
            [profiles.default]
            signer.backend = "relay"
            signer.relay.directory_url = "http://127.0.0.1:1/directory"
            signer.relay.account_key_path = "{}"
            "#,
            dir.join("upstream.key").display()
        ));

        // A kid means a secret is read first — the path that proves the
        // credential comes off stdin and never from argv.
        let secret = BASE64_URL_SAFE_NO_PAD.encode(b"01234567890123456789012345678901");
        let mut reader = std::io::Cursor::new(format!("{secret}\n").into_bytes());
        let error = run_upstream_command(
            UpstreamCommand::Register {
                eab_kid: Some("kid-1".to_string()),
                eab_hmac_key_file: None,
                profile: None,
            },
            &mut reader,
            Palette::plain(),
            &config,
            test_db().await,
        )
        .await
        .expect_err("nothing is listening on that port");
        assert!(
            error
                .to_string()
                .starts_with("upstream registration failed: "),
            "{error}"
        );
    }

    /// `show` reports an unconfigured, unregistered upstream in both forms
    /// rather than failing — "nothing is set up" is a valid answer.
    #[tokio::test]
    async fn show_renders_an_unregistered_upstream() {
        let config = config_from("[profiles.default]\n");
        for json in [true, false] {
            let mut reader: &[u8] = &[];
            run_upstream_command(
                UpstreamCommand::Show {
                    json,
                    profile: None,
                },
                &mut reader,
                Palette::plain(),
                &config,
                test_db().await,
            )
            .await
            .unwrap();
        }
    }

    async fn test_db() -> Arc<Database> {
        Arc::new(Database::connect_in_memory().await.unwrap())
    }

    /// `upstream order list` renders both ways, and `--status` is refused by
    /// name.
    #[tokio::test]
    async fn upstream_order_list_and_show() {
        let config = config_from("[profiles.default]\n");
        let db = test_db().await;
        for json in [true, false] {
            run_upstream_command(
                UpstreamCommand::Order {
                    command: UpstreamOrderCommand::List {
                        profile: None,
                        status: None,
                        limit: 50,
                        offset: 0,
                        json,
                    },
                },
                &mut &b""[..],
                Palette::plain(),
                &config,
                db.clone(),
            )
            .await
            .unwrap();
        }

        let err = run_upstream_command(
            UpstreamCommand::Order {
                command: UpstreamOrderCommand::List {
                    profile: None,
                    status: Some("bogus".to_string()),
                    limit: 50,
                    offset: 0,
                    json: false,
                },
            },
            &mut &b""[..],
            Palette::plain(),
            &config,
            db.clone(),
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("--status"), "{err}");
        assert_eq!(err.kind(), CliErrorKind::BadRequest);

        let err = run_upstream_command(
            UpstreamCommand::Order {
                command: UpstreamOrderCommand::Show {
                    id: "nope".to_string(),
                    json: false,
                },
            },
            &mut &b""[..],
            Palette::plain(),
            &config,
            db,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("no upstream order"), "{err}");
        assert_eq!(err.kind(), CliErrorKind::BadRequest);
    }
}