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
//! `acme-proxy jobs` — inspect and manage the background queue
//! (`src/jobs/` + `src/sqlite/job.rs`), the subsystem whose whole purpose is
//! surviving the failures an operator gets paged about.
//!
//! `list` and `show` are the read half; `cancel` and `run-now` are the two
//! mutations. Cancelling a `signer_relay_issue` job also abandons the ACME
//! order it was driving — that coupling lives in [`crate::admin::ops::cancel_job`],
//! shared with the runner's own `RelayJob::abandon`.

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

use clap::Subcommand;

use crate::admin::{self, CancelJobOutcome, RunJobNowOutcome};
use crate::audit::{Actor, ClientContext};
use crate::cli::CliError;
use crate::cli::render;
use crate::cli::style::Palette;
use crate::cli::window::{DEFAULT_LIMIT, Window};
use crate::sqlite::db::Database;
use crate::sqlite::job::{Job, JobQuery};
use crate::sqlite::status::JobStatus;

#[derive(Subcommand)]
pub enum JobsCommand {
    /// List background jobs, optionally filtered.
    List {
        /// A job kind (`signer_relay_issue`, `nonce_sweep`, …). Passed through
        /// as-is: kinds are an open set, so an unknown one simply matches
        /// nothing rather than being an error — unlike `--status`.
        #[arg(long)]
        kind: 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 job, plus the upstream order it drives if it is a relay job.
    Show {
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Retire a job. On an in-flight relay issuance this also marks the ACME
    /// order invalid and abandons the upstream mapping.
    Cancel { id: String },
    /// Make a job eligible to run at the next queue poll. On a failed job this
    /// grants exactly one more attempt.
    RunNow { id: String },
}

pub async fn run_jobs_command(
    command: JobsCommand,
    yes: bool,
    palette: Palette,
    reader: &mut impl BufRead,
    database: Arc<Database>,
) -> Result<(), CliError> {
    match command {
        JobsCommand::List {
            kind,
            status,
            limit,
            offset,
            json,
        } => {
            // Refused by name rather than passed through: an unknown status
            // would match no rows, which reads exactly like "nothing is in
            // that state" (the `order list --status` rule).
            let status = status
                .map(|value| value.parse::<JobStatus>())
                .transpose()
                .map_err(|error| CliError::bad_request(format!("--status: {error}")))?;
            let window = Window::resolve(limit, offset);
            let query = JobQuery {
                kind,
                status,
                limit: window.limit,
                offset: window.offset,
            };
            let (jobs, total) = Job::search(&query, &database).await?;
            render::print_page(&jobs, total, window, json, admin::render_job_json, |job| {
                render::render_job_line(job, palette)
            });
        }
        JobsCommand::Show { id, json } => {
            let Some(detail) = admin::load_job_detail(&id, database).await? else {
                return Err(not_found(&id));
            };
            if json {
                println!("{}", admin::render_job_detail_json(&detail));
            } else {
                print!("{}", render::render_job_detail_text(&detail, palette));
            }
        }
        JobsCommand::Cancel { id } => {
            match admin::confirm_cancel_job(
                &id,
                yes,
                reader,
                Actor::cli(),
                ClientContext::default(),
                database,
            )
            .await
            .map_err(|error| CliError::failed(error.to_string()))?
            {
                // Not "Cancelled." — on a command named `cancel` that reads
                // as "the job was cancelled", which is the opposite of what a
                // declined prompt means. Every other confirm-gated command can
                // use the idiom; this one cannot.
                None => println!("Left the job alone."),
                Some(CancelJobOutcome::NotFound) => return Err(not_found(&id)),
                Some(CancelJobOutcome::NotCancellable(status)) => {
                    return Err(CliError::bad_request(format!(
                        "job {id} is {status}: only ready or failed jobs can be cancelled"
                    )));
                }
                Some(CancelJobOutcome::Cancelled(job)) => {
                    println!("Cancelled job {id} ({}).", job.kind);
                }
                Some(CancelJobOutcome::CancelledAndOrderAbandoned { order_id, .. }) => {
                    println!(
                        "Cancelled relay job {id}. Order {order_id} was marked invalid and the \
                         upstream mapping abandoned; the client will stop polling."
                    );
                }
            }
        }
        JobsCommand::RunNow { id } => match admin::run_job_now(
            &id,
            Actor::cli(),
            ClientContext::default(),
            database.clone(),
        )
        .await?
        {
            RunJobNowOutcome::NotFound => return Err(not_found(&id)),
            RunJobNowOutcome::Refused(status) => {
                return Err(CliError::bad_request(format!(
                    "job {id} is {status}: run-now applies to ready or failed jobs"
                )));
            }
            RunJobNowOutcome::Nudged(_) => {
                println!("Job {id} will run at the next queue poll (run_at set to now).");
            }
            RunJobNowOutcome::Revived(job) => {
                println!(
                    "Job {id} revived: status ready, attempts {}/{} (one more attempt).",
                    job.attempts, job.max_attempts
                );
            }
        },
    }
    Ok(())
}

fn not_found(id: &str) -> CliError {
    CliError::bad_request(format!("no such job: {id}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::CliErrorKind;
    use crate::sqlite::job::NewJob;
    use crate::sqlite::nonce::now_secs;
    use serde_json::json;

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

    async fn seed(kind: &str, key: &str, run_at: i64, db: &Database) -> uuid::Uuid {
        let id = crate::sqlite::id::mint();
        Job::enqueue(
            NewJob {
                id,
                kind,
                dedup_key: key,
                payload: &json!({}),
                run_at,
                deadline: None,
                max_attempts: 5,
            },
            db,
        )
        .await
        .unwrap();
        id
    }

    fn palette() -> Palette {
        Palette::plain()
    }

    #[tokio::test]
    async fn every_arm_refuses_an_unknown_job() {
        let db = db().await;
        for cmd in [
            JobsCommand::Show {
                id: "nope".into(),
                json: false,
            },
            JobsCommand::Cancel { id: "nope".into() },
            JobsCommand::RunNow { id: "nope".into() },
        ] {
            let err = run_jobs_command(cmd, true, palette(), &mut &b""[..], db.clone())
                .await
                .unwrap_err();
            assert!(err.message.contains("no such job"), "{}", err.message);
            assert_eq!(err.kind(), CliErrorKind::BadRequest);
        }
    }

    #[tokio::test]
    async fn list_renders_both_ways() {
        let db = db().await;
        seed("nonce_sweep", "a", now_secs(), &db).await;
        seed("signer_relay_issue", "b", now_secs(), &db).await;
        for json in [true, false] {
            run_jobs_command(
                JobsCommand::List {
                    kind: None,
                    status: None,
                    limit: 50,
                    offset: 0,
                    json,
                },
                true,
                palette(),
                &mut &b""[..],
                db.clone(),
            )
            .await
            .unwrap();
        }
    }

    #[tokio::test]
    async fn an_unknown_status_is_refused_by_name() {
        let db = db().await;
        let err = run_jobs_command(
            JobsCommand::List {
                kind: None,
                status: Some("halfway".into()),
                limit: 50,
                offset: 0,
                json: false,
            },
            true,
            palette(),
            &mut &b""[..],
            db,
        )
        .await
        .unwrap_err();
        assert!(err.message.contains("--status"), "{}", err.message);
        assert!(err.message.contains("halfway"), "{}", err.message);
        assert!(
            err.message
                .contains("ready, running, done, failed, cancelled"),
            "{}",
            err.message
        );
        assert_eq!(err.kind(), CliErrorKind::BadRequest);
    }

    #[tokio::test]
    async fn every_job_status_is_accepted_as_a_filter() {
        let db = db().await;
        for status in JobStatus::ALL {
            run_jobs_command(
                JobsCommand::List {
                    kind: None,
                    status: Some(status.as_str().to_string()),
                    limit: 50,
                    offset: 0,
                    json: false,
                },
                true,
                palette(),
                &mut &b""[..],
                db.clone(),
            )
            .await
            .unwrap();
        }
    }

    #[tokio::test]
    async fn cancel_is_confirm_gated() {
        let db = db().await;
        let id = seed("nonce_sweep", "a", now_secs(), &db).await;
        run_jobs_command(
            JobsCommand::Cancel { id: id.to_string() },
            false,
            palette(),
            &mut b"n\n".as_slice(),
            db.clone(),
        )
        .await
        .unwrap();
        assert_eq!(
            Job::find_by_id(id, &db).await.unwrap().unwrap().status,
            "ready"
        );
    }

    #[tokio::test]
    async fn cancel_a_ready_job_and_refuse_a_running_one() {
        let db = db().await;
        let id = seed("nonce_sweep", "a", now_secs(), &db).await;
        run_jobs_command(
            JobsCommand::Cancel { id: id.to_string() },
            true,
            palette(),
            &mut &b""[..],
            db.clone(),
        )
        .await
        .unwrap();
        assert_eq!(
            Job::find_by_id(id, &db).await.unwrap().unwrap().status,
            "cancelled"
        );

        let running = seed("nonce_sweep", "b", now_secs(), &db).await;
        sqlx::query("UPDATE jobs SET status = 'running' WHERE id = ?;")
            .bind(running)
            .execute(&db.pool)
            .await
            .unwrap();
        let err = run_jobs_command(
            JobsCommand::Cancel {
                id: running.to_string(),
            },
            true,
            palette(),
            &mut &b""[..],
            db,
        )
        .await
        .unwrap_err();
        assert!(err.message.contains("running"), "{}", err.message);
        assert_eq!(err.kind(), CliErrorKind::BadRequest);
    }

    #[tokio::test]
    async fn run_now_nudges_and_revives() {
        let db = db().await;
        let ready = seed("nonce_sweep", "a", now_secs() + 3_600, &db).await;
        run_jobs_command(
            JobsCommand::RunNow {
                id: ready.to_string(),
            },
            true,
            palette(),
            &mut &b""[..],
            db.clone(),
        )
        .await
        .unwrap();
        assert!(Job::find_by_id(ready, &db).await.unwrap().unwrap().run_at <= now_secs() + 1);

        let failed = seed("nonce_sweep", "b", now_secs(), &db).await;
        sqlx::query("UPDATE jobs SET status = 'failed', attempts = 5 WHERE id = ?;")
            .bind(failed)
            .execute(&db.pool)
            .await
            .unwrap();
        run_jobs_command(
            JobsCommand::RunNow {
                id: failed.to_string(),
            },
            true,
            palette(),
            &mut &b""[..],
            db.clone(),
        )
        .await
        .unwrap();
        let job = Job::find_by_id(failed, &db).await.unwrap().unwrap();
        assert_eq!(job.status, "ready");
        assert_eq!(job.attempts, 4);
    }

    #[tokio::test]
    async fn run_now_on_a_done_job_is_refused() {
        let db = db().await;
        let id = seed("nonce_sweep", "a", now_secs(), &db).await;
        sqlx::query("UPDATE jobs SET status = 'done' WHERE id = ?;")
            .bind(id)
            .execute(&db.pool)
            .await
            .unwrap();
        let err = run_jobs_command(
            JobsCommand::RunNow { id: id.to_string() },
            true,
            palette(),
            &mut &b""[..],
            db,
        )
        .await
        .unwrap_err();
        assert!(err.message.contains("done"), "{}", err.message);
    }

    #[tokio::test]
    async fn the_window_clamps_a_nonsense_one() {
        let db = db().await;
        seed("nonce_sweep", "a", now_secs(), &db).await;
        run_jobs_command(
            JobsCommand::List {
                kind: None,
                status: None,
                limit: 0,
                offset: -5,
                json: false,
            },
            true,
            palette(),
            &mut &b""[..],
            db,
        )
        .await
        .unwrap();
    }
}