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