Skip to content

Commit d6ca4cb

Browse files
committed
docs: generate the CLI and configuration references from the code, so they can't fall behind it
The configuration table and the CLI examples were written by hand. Now `piquel_common::variables!` declares each environment variable with the doc comment and default the reference shows, and tests render auth-service's and piquel-web's variables, and auth-service's clap commands, into docs/dev/operations. `just test` fails while a page is stale, and `just docs reference` rewrites them.
1 parent 14b1cd5 commit d6ca4cb

22 files changed

Lines changed: 1971 additions & 116 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,6 @@ it to `None`) only with a documented reason next to its arm, as `PurgeUser` and
3030
`PruneAuditChain` have.
3131

3232
Generated files are committed; regenerate them with `just db prepare` (SQLx
33-
cache), `just sdk-vectors` and `just sdk-types`. `just validate` is the local
33+
cache), `just sdk-vectors`, `just sdk-types` and `just docs reference` (the CLI
34+
and configuration references). `just validate` is the local
3435
check, and `just docs` checks the documentation.

‎apps/auth-service/src/cli/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ mod serve;
3131
mod session;
3232
/// Finding, showing, disabling and reactivating accounts.
3333
mod user;
34+
/// The generated command reference.
35+
#[cfg(test)]
36+
mod reference;
3437

3538
use crate::{
3639
AuthConfig, SERVICE_NAME, TELEMETRY_FILTER, account::AccountOperation, admin::AdminOperation,
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
//! Renders `docs/dev/operations/cli-commands.md` from the command line's clap
2+
//! model, so it says what `--help` says, and checks the committed page is
3+
//! current. `just docs reference` rewrites it.
4+
5+
use super::Cli;
6+
use clap::{Arg, ArgAction, Command, CommandFactory};
7+
use piquel_common::config::GeneratedFile;
8+
use std::fmt::Write as _;
9+
10+
/// The page's title and introduction, after the generated-file comment.
11+
const INTRO: &str = "\
12+
# auth-service commands
13+
14+
This page lists every `auth-service` command with its arguments and options. It
15+
is generated from the same definitions as `auth-service --help`, so `--help` on
16+
any command prints the same text. [Administration](administration.md) shows the
17+
commands at work, and [deploying](deploying.md#running-auth-service-commands)
18+
how to run them in an environment.
19+
20+
Every command also accepts `-h` and `--help`.
21+
";
22+
23+
/// The page, built one command at a time, depth first.
24+
struct Reference {
25+
/// The Markdown written so far.
26+
page: String,
27+
}
28+
29+
impl Reference {
30+
/// Renders the page from the whole command tree.
31+
fn render() -> String {
32+
let mut command = Cli::command().bin_name("auth-service");
33+
// Building fills in each subcommand's full name and its usage.
34+
command.build();
35+
let mut reference = Self {
36+
page: format!(
37+
"<!-- Generated by `just docs reference` from the clap definitions in \
38+
`apps/auth-service/src/cli`. Do not edit it by hand. -->\n\n{INTRO}"
39+
),
40+
};
41+
reference.command(&command);
42+
reference.page
43+
}
44+
45+
/// Adds `command`'s section: what it does, its usage, its arguments and
46+
/// options, and links to its subcommands, whose sections follow.
47+
fn command(&mut self, command: &Command) {
48+
let path = command.get_bin_name().unwrap_or(command.get_name());
49+
let _ = writeln!(self.page, "\n## `{path}`\n");
50+
if let Some(about) = command.get_long_about().or(command.get_about()) {
51+
let _ = writeln!(self.page, "{}\n", Self::sentence(&about.to_string()));
52+
}
53+
let usage = command.clone().render_usage().to_string();
54+
let _ = writeln!(
55+
self.page,
56+
"```text\n{}\n```",
57+
usage.trim_start_matches("Usage: ")
58+
);
59+
60+
let (positionals, options): (Vec<&Arg>, Vec<&Arg>) = command
61+
.get_arguments()
62+
.filter(|argument| Self::documented(argument))
63+
.partition(|argument| argument.is_positional());
64+
for (title, arguments) in [("Arguments", positionals), ("Options", options)] {
65+
if !arguments.is_empty() {
66+
let _ = writeln!(self.page, "\n{title}:\n");
67+
for argument in arguments {
68+
self.argument(argument);
69+
}
70+
}
71+
}
72+
73+
let subcommands: Vec<&Command> = command
74+
.get_subcommands()
75+
// clap's own `help` command is the `--help` the introduction covers.
76+
.filter(|subcommand| !subcommand.is_hide_set() && subcommand.get_name() != "help")
77+
.collect();
78+
if !subcommands.is_empty() {
79+
let _ = writeln!(self.page, "\nCommands:\n");
80+
for subcommand in &subcommands {
81+
let name = format!("{path} {}", subcommand.get_name());
82+
let about = subcommand
83+
.get_about()
84+
.map(|about| Self::sentence(&about.to_string()))
85+
.unwrap_or_default();
86+
let _ = writeln!(
87+
self.page,
88+
"- [`{name}`](#{}): {about}",
89+
name.replace(' ', "-")
90+
);
91+
}
92+
}
93+
for subcommand in subcommands {
94+
self.command(subcommand);
95+
}
96+
}
97+
98+
/// Adds one argument or option: how to write it, what it does, and its
99+
/// default and accepted values.
100+
fn argument(&mut self, argument: &Arg) {
101+
let syntax = match (argument.get_short(), argument.get_long()) {
102+
(Some(short), Some(_)) => format!("-{short}, {argument}"),
103+
_ => argument.to_string(),
104+
};
105+
let help = argument
106+
.get_long_help()
107+
.or(argument.get_help())
108+
.map(|help| Self::sentence(&help.to_string()))
109+
.unwrap_or_default();
110+
let mut text = format!("`{syntax}`: {help}");
111+
if argument.is_required_set() && !argument.is_positional() {
112+
text.push_str(" Required.");
113+
}
114+
let takes_values = argument.get_action().takes_values();
115+
let defaults: Vec<String> = argument
116+
.get_default_values()
117+
.iter()
118+
.map(|value| format!("`{}`", value.to_string_lossy()))
119+
.filter(|value| value != "``")
120+
.collect();
121+
if takes_values && !defaults.is_empty() {
122+
let _ = write!(text, " Default: {}.", defaults.join(", "));
123+
}
124+
let values: Vec<String> = argument
125+
.get_possible_values()
126+
.iter()
127+
.filter(|value| !value.is_hide_set())
128+
.map(|value| match value.get_help() {
129+
Some(help) => format!("`{}` ({})", value.get_name(), help),
130+
None => format!("`{}`", value.get_name()),
131+
})
132+
.collect();
133+
if takes_values && !values.is_empty() {
134+
let _ = write!(text, " Values: {}.", values.join(", "));
135+
}
136+
let _ = writeln!(self.page, "- {}", text.trim_end());
137+
}
138+
139+
/// Whether `argument` belongs on the page: not hidden, and not clap's own
140+
/// `--help` and `--version`, which the introduction covers.
141+
fn documented(argument: &Arg) -> bool {
142+
!argument.is_hide_set()
143+
&& !matches!(
144+
argument.get_action(),
145+
ArgAction::Help | ArgAction::HelpShort | ArgAction::HelpLong | ArgAction::Version
146+
)
147+
}
148+
149+
/// `text` as prose: clap's help drops a summary's final full stop, so it
150+
/// gets one back, and its paragraphs keep their blank lines.
151+
fn sentence(text: &str) -> String {
152+
let text = text.trim();
153+
if text.is_empty() || text.ends_with(['.', ':', '!', '?']) {
154+
text.to_owned()
155+
} else {
156+
format!("{text}.")
157+
}
158+
}
159+
}
160+
161+
/// The committed page says what the command line's definitions say.
162+
#[test]
163+
fn cli_reference_is_current() {
164+
GeneratedFile {
165+
path: concat!(
166+
env!("CARGO_MANIFEST_DIR"),
167+
"/../../docs/dev/operations/cli-commands.md"
168+
)
169+
.into(),
170+
text: Reference::render(),
171+
}
172+
.write_or_compare()
173+
.expect("current reference");
174+
}

‎apps/auth-service/src/config/database.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,30 @@ const DATABASE_POOL_SIZE: u32 = 10;
1111
/// Maximum startup wait for a pooled database connection.
1212
const DATABASE_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
1313

14-
/// `PostgreSQL` transport and database.
15-
const DATABASE_URL: Variable = Variable::new("AUTH_DATABASE_URL");
16-
/// Optional separately mounted database password.
17-
const DATABASE_PASSWORD: Variable = Variable::new("AUTH_DATABASE_PASSWORD");
18-
/// Optional schema owner `migrate` connects as, to provision the runtime role.
19-
const DATABASE_OWNER_URL: Variable = Variable::new("AUTH_DATABASE_OWNER_URL");
20-
/// Optional separately mounted schema owner password.
21-
const DATABASE_OWNER_PASSWORD: Variable = Variable::new("AUTH_DATABASE_OWNER_PASSWORD");
14+
piquel_common::variables! {
15+
/// The database's variables, in the configuration reference's order.
16+
#[cfg(test)]
17+
pub(crate) const VARIABLES;
18+
19+
/// The PostgreSQL URL every command connects with. Over TCP it requires
20+
/// `sslmode=verify-full`, or an explicit `sslmode=disable` on a trusted
21+
/// private network. For a local Unix socket, use `localhost` as the host and
22+
/// the socket's absolute directory as the `host` parameter, such as
23+
/// `postgres://USER:PASSWORD@localhost/piquel?host=/run/postgresql&sslmode=disable`.
24+
/// Required.
25+
const DATABASE_URL = "AUTH_DATABASE_URL";
26+
/// Where to read the database password, through `env://NAME` or
27+
/// `file:///path`, when the URL leaves it out.
28+
const DATABASE_PASSWORD = "AUTH_DATABASE_PASSWORD";
29+
/// The schema owner `migrate` connects as instead, in the same format as
30+
/// `AUTH_DATABASE_URL`, which `audit prune` uses too. `migrate` then creates
31+
/// or resets the role `AUTH_DATABASE_URL` names, with the
32+
/// `AUTH_DATABASE_PASSWORD` password and only row access to auth's tables. The
33+
/// owner must be a superuser.
34+
const DATABASE_OWNER_URL = "AUTH_DATABASE_OWNER_URL";
35+
/// Where to read the schema owner's password, as for `AUTH_DATABASE_PASSWORD`.
36+
const DATABASE_OWNER_PASSWORD = "AUTH_DATABASE_OWNER_PASSWORD";
37+
}
2238
/// The connection every command uses.
2339
const RUNTIME_DATABASE: DatabaseVariables = DatabaseVariables {
2440
url: DATABASE_URL,

‎apps/auth-service/src/config/email.rs‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,27 @@ use lettre::{
1010
message::Mailbox,
1111
transport::smtp::{authentication::Credentials, extension::ClientId},
1212
};
13-
use piquel_common::config::{ConfigurationError, Origin, SecretReference, Variable};
13+
use piquel_common::config::{ConfigurationError, Origin, SecretReference};
1414
use std::{net::IpAddr, time::Duration};
1515

16-
/// SMTP relay: `smtps://user@host:465`, or `smtp://user@host:587` with STARTTLS.
17-
/// Unset, email is disabled.
18-
pub(super) const SMTP_URL: Variable = Variable::new("AUTH_SMTP_URL");
19-
/// Reference to the SMTP password of the URL's user.
20-
const SMTP_PASSWORD: Variable = Variable::new("AUTH_SMTP_PASSWORD");
21-
/// The sender of every message.
22-
const EMAIL_FROM: Variable = Variable::new("AUTH_EMAIL_FROM");
23-
/// The sender when none is configured.
16+
piquel_common::variables! {
17+
/// Email's variables, in the configuration reference's order.
18+
#[cfg(test)]
19+
pub(crate) const VARIABLES;
20+
21+
/// The SMTP relay auth sends through: `smtps://USER@HOST:465`, with implicit
22+
/// TLS, or `smtp://USER@HOST:587`, which requires STARTTLS. Only a loopback
23+
/// host, such as a local Mailpit, may be reached without TLS. Unset, email is
24+
/// off: adding an address is refused and queued messages are dropped.
25+
pub(super) const SMTP_URL = "AUTH_SMTP_URL";
26+
/// Where to read the password of the URL's user, through `env://NAME` or
27+
/// `file:///path`. Required when the URL names a user; never put it in the
28+
/// URL.
29+
const SMTP_PASSWORD = "AUTH_SMTP_PASSWORD";
30+
/// The sender of every message.
31+
const EMAIL_FROM = "AUTH_EMAIL_FROM", default DEFAULT_EMAIL_FROM;
32+
}
33+
/// [`EMAIL_FROM`] when none is configured.
2434
const DEFAULT_EMAIL_FROM: &str = "Piquel <security@piquel.fr>";
2535
/// Port of `smtps://` URLs without one: SMTP submission over implicit TLS.
2636
const SMTPS_PORT: u16 = 465;

‎apps/auth-service/src/config/federation.rs‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,26 @@ use std::collections::BTreeMap;
1010
/// Maximum provider-assigned client ID length.
1111
const MAX_PROVIDER_CLIENT_ID_LENGTH: usize = 512;
1212

13-
/// GitHub-assigned client identifier.
14-
const GITHUB_CLIENT_ID: Variable = Variable::new("AUTH_GITHUB_CLIENT_ID");
15-
/// Reference to the GitHub client secret.
16-
const GITHUB_CLIENT_SECRET: Variable = Variable::new("AUTH_GITHUB_CLIENT_SECRET");
17-
/// Google-assigned client identifier.
18-
const GOOGLE_CLIENT_ID: Variable = Variable::new("AUTH_GOOGLE_CLIENT_ID");
19-
/// Reference to the Google client secret.
20-
const GOOGLE_CLIENT_SECRET: Variable = Variable::new("AUTH_GOOGLE_CLIENT_SECRET");
13+
piquel_common::variables! {
14+
/// The sign-in providers' variables, in the configuration reference's order.
15+
#[cfg(test)]
16+
pub(crate) const VARIABLES;
17+
18+
/// The client ID of auth's GitHub OAuth app. Set, it turns GitHub sign-in on
19+
/// and requires `AUTH_GITHUB_CLIENT_SECRET`; unset or empty, GitHub is off and
20+
/// its secret isn't read.
21+
const GITHUB_CLIENT_ID = "AUTH_GITHUB_CLIENT_ID";
22+
/// Where to read the GitHub OAuth app's client secret, through `env://NAME` or
23+
/// `file:///path`. It is read and checked at startup: restart auth after
24+
/// changing it.
25+
const GITHUB_CLIENT_SECRET = "AUTH_GITHUB_CLIENT_SECRET";
26+
/// The client ID of auth's Google OAuth client, as `AUTH_GITHUB_CLIENT_ID` is
27+
/// GitHub's.
28+
const GOOGLE_CLIENT_ID = "AUTH_GOOGLE_CLIENT_ID";
29+
/// Where to read the Google OAuth client's secret, as for
30+
/// `AUTH_GITHUB_CLIENT_SECRET`.
31+
const GOOGLE_CLIENT_SECRET = "AUTH_GOOGLE_CLIENT_SECRET";
32+
}
2133

2234
/// OAuth credentials validated before application construction.
2335
#[derive(Clone, Debug)]

‎apps/auth-service/src/config/keys.rs‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
//! The keys auth reads from the environment besides the key-encryption key: the
2-
//! token digest keys, the link keys derived from them, and the audit checkpoint
3-
//! key.
1+
//! The keys auth reads from the environment: the key-encryption key, which
2+
//! `AuthConfig` opens, the token digest keys, the link keys derived from them, and
3+
//! the audit checkpoint key.
44
55
use crate::{emails::VerificationKeys, recovery::RecoveryLinks};
66
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
@@ -22,13 +22,29 @@ const MIN_TOKEN_DIGEST_KEY_BYTES: usize = 32;
2222
/// Bytes of a token digest key's digest kept as its fingerprint.
2323
const DIGEST_KEY_FINGERPRINT_BYTES: usize = 8;
2424

25-
/// Required reference to the key that signs audit checkpoints.
26-
const AUDIT_KEY_PROVIDER: Variable = Variable::new("AUTH_AUDIT_KEY_PROVIDER");
27-
/// Reference to the key under which opaque token secrets are digested.
28-
const TOKEN_DIGEST_KEY: Variable = Variable::new("AUTH_TOKEN_DIGEST_KEY");
29-
/// Optional reference to another token digest key, accepted but never used for
30-
/// new digests: the next key before it is current, or the old one after.
31-
const TOKEN_DIGEST_KEY_ACCEPTED: Variable = Variable::new("AUTH_TOKEN_DIGEST_KEY_ACCEPTED");
25+
piquel_common::variables! {
26+
/// The keys' variables, in the configuration reference's order.
27+
#[cfg(test)]
28+
pub(crate) const VARIABLES;
29+
30+
/// Where to read the key that seals signing keys in the database: 32 bytes as
31+
/// unpadded base64url text, through `env://NAME` or `file:///path`. A trailing
32+
/// newline is ignored. Required. It can't be changed yet: the stored signing
33+
/// keys would no longer open.
34+
pub(super) const KEY_ENCRYPTION_KEY = "AUTH_KEY_ENCRYPTION_KEY";
35+
/// Where to read the key under which refresh tokens, authorization codes and
36+
/// pending logins are stored as HMAC digests. Its raw bytes are the key, at
37+
/// least 32 of them. Email verification and recovery links derive from it too.
38+
/// Required. Replacing it at once ends every refresh token and every login in
39+
/// progress, so change it in two deploys.
40+
const TOKEN_DIGEST_KEY = "AUTH_TOKEN_DIGEST_KEY";
41+
/// Where to read another token digest key, accepted but never used for new
42+
/// digests: the next key before it becomes current, or the old one after.
43+
const TOKEN_DIGEST_KEY_ACCEPTED = "AUTH_TOKEN_DIGEST_KEY_ACCEPTED";
44+
/// Where to read the key that signs audit checkpoints: a 32-byte Ed25519 seed
45+
/// as 64 hex characters. Required.
46+
const AUDIT_KEY_PROVIDER = "AUTH_AUDIT_KEY_PROVIDER";
47+
}
3248

3349
/// One key under which opaque token secrets are stored as HMAC digests.
3450
pub(crate) struct TokenDigestKey {

0 commit comments

Comments
 (0)