steid

@jamesgill /

steid/src/cli/mod.rs
Rust9.5 KBCode·Blame·History·Raw
1//! The command line: `steid` serves; `steid <command>` does one operator task and
2//! exits.
3//!
4//! Subcommands exist so a machine with no browser — a control plane, a cron job, an
5//! owner locked out of their own instance — can drive Steid headlessly. Each command is
6//! a thin wrapper over an application use case; nothing here decides anything.
7//!
8//! No argument-parsing crate: three commands and a path do not justify one, and the
9//! usage text is the whole contract.
10//!
11//! The commands themselves live here too, one module each, rather than in `main.rs`
12//! where they were until 2026-09-10. They are the operator's recovery path — the least
13//! testable code in the tree while it sat in a binary with no tests — and each is now
14//! reachable from a test that runs it against a temp database and a temp data
15//! directory.
16
17mod backup;
18mod reset_password;
19mod restore;
20
21pub use backup::run_backup;
22pub use reset_password::print_reset_link;
23pub use restore::run_restore;
24
25use std::path::PathBuf;
26
27use crate::application::RestoreMode;
28
29/// Where a backup builds itself: a scratch directory inside the data directory.
30///
31/// Inside it rather than in `/tmp` so the snapshot — a full copy of the database — lands
32/// on the volume that is already sized for the database, under the directory the service
33/// unit already grants write access to. The leading dot is what keeps it out of the
34/// archive being built in it: a handle is `[a-z0-9-]` and can never start with one, so
35/// nothing under a dot-directory is a repository and `pack` skips the lot.
36pub(crate) const BACKUP_WORKSPACE: &str = ".backup";
37
38/// What `steid` was asked to do.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Command {
41 /// Run the server. The default, and what a bare `steid` means.
42 Serve,
43 /// Write one consistent archive of the database and the data directory.
44 Backup { destination: PathBuf },
45 /// Restore an archive into an empty database and data directory — or, with
46 /// `--replace`, over whatever is already there.
47 Restore { archive: PathBuf, mode: RestoreMode },
48 /// Print a one-time password reset link for a user, for an owner who cannot
49 /// receive email.
50 ResetPassword { handle: String },
51}
52
53pub const USAGE: &str = "usage:
54 steid serve
55 steid backup <destination> write one archive of the database and data directory
56 steid restore <archive> restore an archive into an empty instance
57 steid restore --replace <a> replace everything this instance holds with the archive
58 steid reset-password <handle> print a one-time password reset link
59";
60
61impl Command {
62 /// Parses `args` as the process received them, program name first.
63 pub fn parse<I, S>(args: I) -> Result<Self, String>
64 where
65 I: IntoIterator<Item = S>,
66 S: Into<String>,
67 {
68 let args: Vec<String> = args.into_iter().map(Into::into).skip(1).collect();
69 match args
70 .iter()
71 .map(String::as_str)
72 .collect::<Vec<_>>()
73 .as_slice()
74 {
75 [] => Ok(Self::Serve),
76 ["backup", destination] => Ok(Self::Backup {
77 destination: PathBuf::from(destination),
78 }),
79 // Either side of the path. The control plane renders `restore --replace
80 // "$ARCHIVE"`; a person typing it will put the flag wherever it falls.
81 ["restore", "--replace", archive] | ["restore", archive, "--replace"] => {
82 Ok(Self::Restore {
83 archive: PathBuf::from(archive),
84 mode: RestoreMode::Replace,
85 })
86 }
87 // Guarded, so a mistyped flag is a usage error rather than a restore of a
88 // file called `--replac`.
89 ["restore", archive] if !archive.starts_with('-') => Ok(Self::Restore {
90 archive: PathBuf::from(archive),
91 mode: RestoreMode::OnlyIfEmpty,
92 }),
93 ["reset-password", handle] => Ok(Self::ResetPassword {
94 handle: (*handle).to_owned(),
95 }),
96 ["-h" | "--help" | "help", ..] => Err(USAGE.to_owned()),
97 other => Err(format!("steid: unrecognised arguments {other:?}\n{USAGE}")),
98 }
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn a_bare_invocation_serves() {
108 assert_eq!(Command::parse(["steid"]), Ok(Command::Serve));
109 }
110
111 #[test]
112 fn each_command_takes_exactly_one_argument() {
113 assert_eq!(
114 Command::parse(["steid", "backup", "/tmp/out"]),
115 Ok(Command::Backup {
116 destination: PathBuf::from("/tmp/out")
117 })
118 );
119 assert_eq!(
120 Command::parse(["steid", "restore", "a.tar.gz"]),
121 Ok(Command::Restore {
122 archive: PathBuf::from("a.tar.gz"),
123 mode: RestoreMode::OnlyIfEmpty,
124 })
125 );
126 assert_eq!(
127 Command::parse(["steid", "reset-password", "ada"]),
128 Ok(Command::ResetPassword {
129 handle: "ada".to_owned()
130 })
131 );
132 assert!(Command::parse(["steid", "backup"]).is_err());
133 assert!(Command::parse(["steid", "frobnicate"]).is_err());
134 }
135
136 #[test]
137 fn replace_is_opt_in_and_reads_from_either_side_of_the_path() {
138 // The flag is the consent, so the *absence* of it is the property worth pinning:
139 // a restore that quietly replaced would be the one bug this whole feature is
140 // built to avoid.
141 for args in [
142 ["steid", "restore", "--replace", "a.tar.gz"],
143 ["steid", "restore", "a.tar.gz", "--replace"],
144 ] {
145 assert_eq!(
146 Command::parse(args),
147 Ok(Command::Restore {
148 archive: PathBuf::from("a.tar.gz"),
149 mode: RestoreMode::Replace,
150 }),
151 "{args:?}"
152 );
153 }
154
155 assert!(Command::parse(["steid", "restore", "--replace"]).is_err());
156 assert!(Command::parse(["steid", "restore", "--force", "a.tar.gz"]).is_err());
157 }
158
159 #[test]
160 fn the_usage_says_what_replace_does() {
161 let text = Command::parse(["steid", "--help"]).unwrap_err();
162
163 assert!(
164 text.contains("replace everything this instance holds with the archive"),
165 "{text}"
166 );
167 }
168
169 #[test]
170 fn help_is_an_error_carrying_the_usage() {
171 let text = Command::parse(["steid", "--help"]).unwrap_err();
172 assert!(text.contains("steid backup <destination>"));
173 }
174}
175
176/// A whole instance in a temporary directory, for the command tests.
177///
178/// Real SQLite and a real data directory rather than the in-memory repositories the use
179/// cases are tested against: what these tests are for is the wiring between a command
180/// and its adapters — the path resolution, the workspace, the pool — and an in-memory
181/// store would test none of it.
182#[cfg(test)]
183pub(crate) mod fixture {
184 use sqlx::SqlitePool;
185 use tempfile::TempDir;
186
187 use crate::{
188 application::{AppConfig, OwnerSpec, claim_instance},
189 domain::SetupToken,
190 infrastructure::{
191 database,
192 password::Argon2Hasher,
193 repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteUserRepo},
194 },
195 };
196
197 /// A temporary instance: the directory it lives in, its configuration and its pool.
198 ///
199 /// The `TempDir` is held rather than returned separately because dropping it deletes
200 /// everything the other two point at.
201 pub(crate) struct Instance {
202 pub(crate) dir: TempDir,
203 pub(crate) config: AppConfig,
204 pub(crate) pool: SqlitePool,
205 }
206
207 /// A migrated database and an empty data directory, with nobody in it.
208 pub(crate) async fn empty() -> Instance {
209 let dir = tempfile::tempdir().expect("a temp dir");
210 let data_dir = dir.path().join("data");
211 std::fs::create_dir_all(&data_dir).expect("mkdir");
212
213 let database_url = format!("sqlite:{}?mode=rwc", dir.path().join("steid.db").display());
214 let pool = database::connect(&database_url)
215 .await
216 .expect("the database opens");
217
218 Instance {
219 config: AppConfig {
220 database_url,
221 data_dir,
222 insecure_cookies: false,
223 allow_private_webhooks: false,
224 trusted_proxy: false,
225 operator_token: None,
226 setup_token: None,
227 backup_marker: None,
228 smtp_url: None,
229 mail_from: None,
230 owner_email: None,
231 owner_handle: None,
232 public_url: None,
233 },
234 pool,
235 dir,
236 }
237 }
238
239 /// [`empty`], then claimed by `handle` — so it has a user, an organisation and a
240 /// membership, which is what makes it a non-empty instance.
241 pub(crate) async fn claimed(handle: &str) -> Instance {
242 let instance = empty().await;
243 let token = SetupToken::generate();
244 let revealed = token.reveal().to_owned();
245
246 claim_instance(
247 &revealed,
248 &token,
249 &OwnerSpec {
250 handle: handle.to_owned(),
251 email: format!("{handle}@example.com"),
252 password: "a-long-enough-password".to_owned(),
253 },
254 &SqliteUserRepo::new(instance.pool.clone()),
255 &SqliteOrgRepo::new(instance.pool.clone()),
256 &SqliteMembershipRepo::new(instance.pool.clone()),
257 &Argon2Hasher::new(),
258 )
259 .await
260 .expect("the claim succeeds");
261
262 instance
263 }
264}