OXYGENHUB
# 417184c73f4e oxygenhub / crates / hub / src / main.rs
13.1 KiB · Rust · last changed feat: backups for users and organisations, to a directory, with restore (refs #169) 22 days ago source blame history raw
d23464c0 Andy McCall ↶ 1
//! `oxygenhub`: `init`, `serve`, `admin`, `check` (hub spec §17.3).
2
3
use clap::{Parser, Subcommand};
4
use hub_api::Visibility;
5
use oxygenhub::config::Config;
6
use oxygenhub::repos::RepoName;
7
use oxygenhub::{db, keys};
8
use std::path::PathBuf;
9
10
#[derive(Parser)]
11
#[command(name = "oxygenhub", version, about = "A forge for Oxygen repositories")]
12
struct Cli {
13
    /// The data directory (hub spec §3.2)
14
    #[arg(long, global = true, env = "OXYHUB_DATA", default_value = "data")]
15
    data: PathBuf,
16
    #[command(subcommand)]
17
    cmd: Cmd,
18
}
19
20
#[derive(Subcommand)]
21
enum Cmd {
22
    /// Create the data directory, keys, database and a default hub.toml
23
    Init {
24
        /// What links and clone URLs start with
25
        #[arg(long)]
26
        base_url: Option<String>,
27
        /// Generate a self-signed TLS certificate (developer edition)
28
        #[arg(long)]
29
        self_signed: bool,
30
    },
31
    /// Run the hub
32
    Serve,
33
    /// Offline administration
34
    Admin {
35
        #[command(subcommand)]
36
        cmd: AdminCmd,
37
    },
38
    /// Verify every repository's objects and signatures
39
    Check,
8a3334b7 Andy McCall ↶ 40
    /// Garbage-collect every repository now, as the nightly job does
41
    Gc,
d23464c0 Andy McCall ↶ 42
}
43
44
#[derive(Subcommand)]
45
enum AdminCmd {
46
    /// Repositories
47
    Repo {
48
        #[command(subcommand)]
49
        cmd: RepoCmd,
50
    },
19bb31ff Andy McCall ↶ 51
    /// Accounts
52
    User {
53
        #[command(subcommand)]
54
        cmd: UserCmd,
55
    },
d7d18246 Andy McCall ↶ 56
    /// Backups (docs/backups.md)
57
    Backup {
58
        #[command(subcommand)]
59
        cmd: BackupCmd,
60
    },
61
}
62
63
#[derive(Subcommand)]
64
enum BackupCmd {
65
    /// Back up a user's or organisation's repositories now, as its settings say
66
    Run { owner: String },
67
    /// Restore every repository of a whole run from a backup directory
68
    /// (the one holding LATEST, runs/ and blobs/) into this hub
69
    Restore {
70
        #[arg(long)]
71
        from: std::path::PathBuf,
72
        /// The run (runs/<RUN>); the latest whole one when not given
73
        #[arg(long)]
74
        run: Option<String>,
75
    },
d23464c0 Andy McCall ↶ 76
}
77
78
#[derive(Subcommand)]
19bb31ff Andy McCall ↶ 79
enum UserCmd {
80
    /// Create an account with a generated password, printed once
81
    Create {
82
        username: String,
83
        #[arg(long, default_value = "")]
84
        email: String,
85
        /// Make it a site administrator
86
        #[arg(long)]
87
        admin: bool,
88
    },
89
    /// Reset an account's password to a new generated one, printed once
90
    ResetPassword { username: String },
91
    /// List accounts
92
    List,
93
}
94
95
#[derive(Subcommand)]
d23464c0 Andy McCall ↶ 96
enum RepoCmd {
97
    /// Create an empty repository OWNER/NAME
98
    Create {
99
        slug: String,
100
        #[arg(long, default_value = "")]
101
        description: String,
102
        #[arg(long, default_value = "public")]
103
        visibility: String,
104
        /// Bind to this repository id now (32 hex characters, from `.oxy/id`);
105
        /// otherwise the first push binds it
106
        #[arg(long)]
107
        id: Option<String>,
108
    },
109
    /// List repositories
110
    List,
111
    /// Move a repository to the trash
112
    Delete { slug: String },
113
    /// Change the description, default bookmark or visibility
114
    Set {
115
        slug: String,
116
        #[arg(long)]
117
        description: Option<String>,
118
        #[arg(long)]
119
        default_bookmark: Option<String>,
120
        #[arg(long)]
121
        visibility: Option<String>,
122
    },
123
}
124
125
#[tokio::main]
126
async fn main() -> anyhow::Result<()> {
127
    tracing_subscriber::fmt()
128
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env().add_directive("oxygenhub=info".parse()?))
129
        .init();
130
    let cli = Cli::parse();
131
    match cli.cmd {
132
        Cmd::Init { base_url, self_signed } => init(&cli.data, base_url, self_signed).await,
133
        Cmd::Serve => {
134
            let config = Config::load(&cli.data)?;
135
            let app = oxygenhub::build(config).await?;
136
            oxygenhub::serve(app).await
137
        }
138
        Cmd::Admin { cmd: AdminCmd::Repo { cmd } } => {
139
            let config = Config::load(&cli.data)?;
140
            let app = oxygenhub::build(config).await?;
141
            repo_admin(&app, cmd).await
d7d18246 Andy McCall ↶ 142
        }
143
        Cmd::Admin { cmd: AdminCmd::Backup { cmd } } => {
144
            let config = Config::load(&cli.data)?;
145
            let app = oxygenhub::build(config).await?;
146
            match cmd {
147
                BackupCmd::Run { owner } => {
148
                    let r = oxygenhub::backups::run(&app, &owner, "now").await?;
149
                    println!(
150
                        "{} {}: {} repositories, {} of {} files sent ({} KiB){}",
151
                        r.status,
152
                        r.at,
153
                        r.repos,
154
                        r.sent,
155
                        r.files,
156
                        r.bytes / 1024,
157
                        if r.detail.is_empty() { String::new() } else { format!(": {}", r.detail) }
158
                    );
159
                    if r.status == "failed" {
160
                        std::process::exit(1);
161
                    }
162
                    Ok(())
163
                }
164
                BackupCmd::Restore { from, run } => {
165
                    let dest: std::sync::Arc<dyn oxygenhub::backups::Destination> =
166
                        std::sync::Arc::new(oxygenhub::backups::Directory { root: from });
167
                    for d in oxygenhub::backups::restore_into_hub(&app, dest, run).await? {
168
                        println!("restored {d}");
169
                    }
170
                    Ok(())
171
                }
172
            }
d23464c0 Andy McCall ↶ 173
        }
19bb31ff Andy McCall ↶ 174
        Cmd::Admin { cmd: AdminCmd::User { cmd } } => {
175
            let config = Config::load(&cli.data)?;
176
            let app = oxygenhub::build(config).await?;
177
            user_admin(&app, cmd).await
178
        }
d23464c0 Andy McCall ↶ 179
        Cmd::Check => {
180
            let config = Config::load(&cli.data)?;
181
            let app = oxygenhub::build(config).await?;
182
            check(&app).await
183
        }
8a3334b7 Andy McCall ↶ 184
        Cmd::Gc => {
185
            let config = Config::load(&cli.data)?;
186
            let app = oxygenhub::build(config).await?;
187
            let done = oxygenhub::maintenance::gc_all(&app).await;
188
            for d in &done {
189
                println!("{d}");
190
            }
191
            if done.iter().any(|d| d.failed) {
192
                anyhow::bail!("a repository could not be garbage collected");
193
            }
194
            Ok(())
195
        }
d23464c0 Andy McCall ↶ 196
    }
197
}
198
199
async fn init(data: &PathBuf, base_url: Option<String>, self_signed: bool) -> anyhow::Result<()> {
200
    std::fs::create_dir_all(data)?;
201
    let toml_path = data.join("hub.toml");
202
    if !toml_path.exists() {
203
        let base = base_url.clone().unwrap_or_else(|| "http://127.0.0.1:7300".into());
8d2caf12 Andy McCall ↶ 204
        let mut text = String::from("# OxygenHub configuration (docs/spec.md section 17.1)\n\n[site]\nname = \"OxygenHub\"\n\n[server]\nbind = \"127.0.0.1:7300\"\n");
d23464c0 Andy McCall ↶ 205
        if self_signed {
206
            text.push_str("tls_bind = \"0.0.0.0:7343\"\n");
207
        }
208
        text.push_str(&format!("base_url = \"{base}\"\n\n[tls]\nself_signed = {self_signed}\n\n[auth]\n# Bearer tokens allowed to push until accounts exist.\npush_tokens = []\n"));
209
        std::fs::write(&toml_path, text)?;
210
        println!("wrote {}", toml_path.display());
211
    }
212
    let mut config = Config::load(data)?;
213
    if let Some(b) = base_url {
214
        config.server.base_url = b;
215
    }
216
    let app = oxygenhub::build(config).await?;
217
    println!("hub key {}", app.hub_key.key.to_hex());
218
    if (self_signed || app.config.tls.self_signed)
219
        && keys::ensure_self_signed(&app.config.tls_cert(), &app.config.tls_key(), app.config.base_url())?
220
    {
221
        println!("wrote self-signed certificate {}", app.config.tls_cert().display());
222
    }
223
    println!("data directory {} is ready", data.display());
224
    Ok(())
225
}
226
227
async fn repo_admin(app: &oxygenhub::Shared, cmd: RepoCmd) -> anyhow::Result<()> {
228
    match cmd {
229
        RepoCmd::Create { slug, description, visibility, id } => {
230
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
231
            let visibility = Visibility::parse(&visibility).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?;
232
            let id = match id {
233
                Some(h) => {
234
                    let bytes = hex::decode(h.trim()).ok().and_then(|v| <[u8; 16]>::try_from(v).ok());
235
                    Some(bytes.ok_or_else(|| anyhow::anyhow!("--id takes 32 hex characters"))?)
236
                }
237
                None => None,
238
            };
239
            if db::repos::get(&app.db, &name.owner, &name.name).await?.is_some() {
240
                anyhow::bail!("{name} already exists");
241
            }
242
            app.repos.create(&name, id)?;
243
            db::repos::create(&app.db, &name.owner, &name.name, &description, visibility).await?;
244
            println!("created {name}: oxy clone {}/{name}", app.config.base_url());
245
        }
246
        RepoCmd::List => {
247
            for r in db::repos::list(&app.db).await? {
248
                println!("{:<40} {:<8} {}", r.slug(), r.visibility, r.description);
249
            }
250
        }
251
        RepoCmd::Delete { slug } => {
252
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
253
            let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?;
254
            let dest = app.repos.trash(&name)?;
255
            db::repos::delete(&app.db, row.id).await?;
256
            println!("moved {name} to {}", dest.display());
257
        }
258
        RepoCmd::Set { slug, description, default_bookmark, visibility } => {
259
            let name = RepoName::parse(&slug).ok_or_else(|| anyhow::anyhow!("{slug:?} is not a valid owner/name"))?;
260
            let row = db::repos::get(&app.db, &name.owner, &name.name).await?.ok_or_else(|| anyhow::anyhow!("{name} does not exist"))?;
261
            if let Some(d) = description {
262
                db::repos::set_description(&app.db, row.id, &d).await?;
263
            }
264
            if let Some(b) = default_bookmark {
265
                db::repos::set_default_bookmark(&app.db, row.id, &b).await?;
266
            }
267
            if let Some(v) = visibility {
268
                let v = Visibility::parse(&v).ok_or_else(|| anyhow::anyhow!("visibility is public, internal or private"))?;
269
                db::repos::set_visibility(&app.db, row.id, v).await?;
270
            }
271
            println!("updated {name}");
272
        }
273
    }
274
    Ok(())
275
}
276
19bb31ff Andy McCall ↶ 277
async fn user_admin(app: &oxygenhub::Shared, cmd: UserCmd) -> anyhow::Result<()> {
278
    use oxygenhub::auth;
279
    use oxygenhub::db::accounts;
280
    match cmd {
281
        UserCmd::Create { username, email, admin } => {
282
            if !oxygenhub::repos::names::valid_owner(&username) {
283
                anyhow::bail!("{username:?} is not a valid username");
284
            }
285
            if accounts::account_by_name(&app.db, &username).await?.is_some() || accounts::org_by_name(&app.db, &username).await?.is_some()
286
            {
287
                anyhow::bail!("{username} is taken");
288
            }
289
            let password = auth::random_hex(12);
290
            let hash = auth::hash_password(&password)?;
291
            accounts::create_account(&app.db, &username, &email, &hash, &auth::random_hex(16), admin).await?;
292
            accounts::audit(&app.db, None, "admin.user.create", &username, if admin { "administrator" } else { "" }).await?;
293
            println!("created {username}{}; one-time password: {password}", if admin { " (administrator)" } else { "" });
294
            println!("sign in at {}/login and change it under Settings", app.config.base_url());
295
        }
296
        UserCmd::ResetPassword { username } => {
297
            let account = accounts::account_by_name(&app.db, &username).await?.ok_or_else(|| anyhow::anyhow!("no such account"))?;
298
            let password = auth::random_hex(12);
299
            let hash = auth::hash_password(&password)?;
300
            accounts::set_password(&app.db, account.id, &hash, &auth::random_hex(16)).await?;
301
            accounts::audit(&app.db, None, "admin.user.reset_password", &username, "").await?;
302
            println!("new one-time password for {username}: {password}");
303
        }
304
        UserCmd::List => {
305
            for a in accounts::accounts(&app.db).await? {
306
                println!(
6a178055 Andy McCall ↶ 307
                    "{:<24} {:<32} {}{}{}",
19bb31ff Andy McCall ↶ 308
                    a.username,
309
                    a.email,
310
                    if a.is_admin { "admin " } else { "" },
6a178055 Andy McCall ↶ 311
                    if a.banned { "banned " } else { "" },
312
                    if a.disabled { "disabled" } else { "" }
19bb31ff Andy McCall ↶ 313
                );
314
            }
315
        }
316
    }
317
    Ok(())
318
}
319
d23464c0 Andy McCall ↶ 320
async fn check(app: &oxygenhub::Shared) -> anyhow::Result<()> {
321
    let mut problems = 0;
322
    for r in db::repos::list(&app.db).await? {
323
        let name = RepoName::new(&r.owner, &r.name).unwrap();
9ff27da5 Andy McCall ↶ 324
        let report = app.repos.read(&name, |r, cache| oxygenhub::repos::view::verification(r, cache)).await;
d23464c0 Andy McCall ↶ 325
        match report {
326
            Ok(v) => {
327
                println!(
328
                    "{:<40} {} changes, {} signed, {} sealed, {} unsigned, {} invalid",
329
                    name,
330
                    v.total,
331
                    v.signed,
332
                    v.sealed,
333
                    v.unsigned,
334
                    v.invalid.len()
335
                );
336
                problems += v.invalid.len();
337
            }
338
            Err(e) => {
339
                println!("{name:<40} ERROR {e}");
340
                problems += 1;
341
            }
342
        }
343
    }
344
    if problems > 0 {
345
        anyhow::bail!("{problems} problem(s)");
346
    }
347
    Ok(())
348
}