OXYGENHUB
# d1727c573f30 oxygenhub / crates / hub / src / web / admin.rs
17.4 KiB · Rust · last changed Secrets for pipelines, mounted as files 1 month ago source blame history raw
19bb31ff Andy McCall ↶ 1
//! Site administration (hub spec §6.3 `/admin/*`): accounts, registration
2
//! mode and invitations, the audit log.
3
4
use super::settings::csrf;
5
use super::{filters, Error, Page, Shell};
6
use crate::auth::{self, Viewer};
7
use crate::db::accounts;
8
use crate::Shared;
9
use askama::Template;
10
use axum::extract::{Form, State};
11
use serde::Deserialize;
12
13
#[derive(Template)]
14
#[template(path = "admin.html")]
15
pub struct AdminPage {
16
    shell: Shell,
17
    accounts: Vec<accounts::Account>,
18
    orgs: Vec<accounts::Organisation>,
19
    mode: String,
20
    invitations: Vec<(String, Option<i64>, i64)>,
21
    audit: Vec<accounts::AuditRow>,
22
    repos: usize,
23
    notice: Option<String>,
3556d08e Andy McCall ↶ 24
    /// Mail settings (#101): the SMTP URL with its password masked, the
25
    /// From address, whether mail is on, and the administrator's own
26
    /// address for a test message.
27
    mail_smtp: String,
28
    mail_from: String,
29
    mail_enabled: bool,
30
    my_email: String,
e71846aa Andy McCall ↶ 31
    /// The site's AI assistants and prompt (#97).
32
    assistants: super::assistants::Panel,
2a83f530 Andy McCall ↶ 33
    /// The site's Flow variables (#102).
34
    variables: super::variables::Panel,
4ac01a73 Andy McCall ↶ 35
    /// The site's Flow secrets (#107).
36
    secrets: super::secrets::Panel,
19bb31ff Andy McCall ↶ 37
}
38
39
fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> {
40
    match viewer.account() {
41
        Some(a) if a.is_admin => Ok(a.clone()),
42
        _ => Err(Error::not_found(shell.clone())),
43
    }
44
}
45
46
async fn admin_page(app: &Shared, shell: Shell, notice: Option<String>) -> Result<Page<AdminPage>, Error> {
47
    let e = |e| Error::from_db(shell.clone(), e);
48
    let accounts_list = accounts::accounts(&app.db).await.map_err(e)?;
49
    let orgs = accounts::orgs(&app.db).await.map_err(e)?;
50
    let mode = super::session::registration_mode(app).await;
51
    let invitations = accounts::invitations(&app.db).await.map_err(e)?;
52
    let audit = accounts::audit_rows(&app.db, 100).await.map_err(e)?;
53
    let repos = crate::db::repos::list(&app.db).await.map_err(e)?.len();
3556d08e Andy McCall ↶ 54
    let mail = crate::mail::settings(app);
55
    let my_email = match shell.user.as_deref() {
56
        Some(u) => accounts::account_by_name(&app.db, u).await.map_err(e)?.map(|a| a.email).unwrap_or_default(),
57
        None => String::new(),
58
    };
e71846aa Andy McCall ↶ 59
    let assistants = super::assistants::panel(app, &site_assistants()).await.map_err(e)?;
2a83f530 Andy McCall ↶ 60
    let variables = super::variables::panel(app, &site_assistants()).await.map_err(e)?;
4ac01a73 Andy McCall ↶ 61
    let secrets = super::secrets::panel(app, &site_assistants()).await.map_err(e)?;
3556d08e Andy McCall ↶ 62
    Ok(Page(AdminPage {
e71846aa Andy McCall ↶ 63
        assistants,
2a83f530 Andy McCall ↶ 64
        variables,
4ac01a73 Andy McCall ↶ 65
        secrets,
3556d08e Andy McCall ↶ 66
        shell,
67
        accounts: accounts_list,
68
        orgs,
69
        mode,
70
        invitations,
71
        audit,
72
        repos,
73
        notice,
74
        mail_smtp: crate::mail::masked(&mail.smtp),
75
        mail_from: mail.from.clone(),
76
        mail_enabled: !mail.smtp.is_empty() && !mail.from.is_empty(),
77
        my_email,
78
    }))
79
}
80
81
#[derive(Deserialize)]
82
pub struct MailForm {
83
    #[serde(rename = "_csrf")]
84
    csrf_token: String,
85
    #[serde(default)]
86
    smtp: String,
87
    #[serde(default)]
88
    from: String,
89
}
90
91
/// `POST /admin/mail`: the SMTP URL and From address (#101). The URL
92
/// comes back masked, so a masked value left as it was keeps the stored
93
/// one; an empty URL turns mail off.
94
pub async fn set_mail(State(app): State<Shared>, viewer: Viewer, Form(f): Form<MailForm>) -> Result<Page<AdminPage>, Error> {
95
    let shell = Shell::new(&app, "/admin", &viewer);
96
    let me = require_admin(&viewer, &shell)?;
97
    csrf(&viewer, &f.csrf_token, &shell)?;
98
    let current = crate::mail::settings(&app);
99
    let smtp = f.smtp.trim();
100
    let smtp = if !current.smtp.is_empty() && smtp == crate::mail::masked(&current.smtp) { current.smtp.clone() } else { smtp.to_string() };
101
    let from = f.from.trim().to_string();
102
    if !smtp.is_empty() && !(smtp.starts_with("smtp://") || smtp.starts_with("smtps://") || smtp.starts_with("file://")) {
103
        return admin_page(
104
            &app,
105
            shell,
106
            Some("The SMTP URL starts with smtp:// or smtps:// (file:///dir writes messages to a directory, for testing).".into()),
107
        )
108
        .await;
109
    }
110
    if !smtp.is_empty() && from.is_empty() {
111
        return admin_page(&app, shell, Some("A From address is needed: OxygenHub <[email protected]>.".into())).await;
112
    }
113
    crate::mail::save(&app, &smtp, &from).await.map_err(|e| Error::from_db(shell.clone(), e))?;
114
    accounts::audit(&app.db, Some(&me), "admin.mail", if smtp.is_empty() { "off" } else { "on" }, &from).await.ok();
115
    admin_page(&app, shell, Some(if smtp.is_empty() { "Mail is off.".into() } else { "Mail settings saved.".into() })).await
116
}
117
118
/// `POST /admin/mail/test`: a message to the administrator's own address.
119
pub async fn test_mail(
120
    State(app): State<Shared>,
121
    viewer: Viewer,
122
    Form(f): Form<super::session::CsrfForm>,
123
) -> Result<Page<AdminPage>, Error> {
124
    let shell = Shell::new(&app, "/admin", &viewer);
125
    let me = require_admin(&viewer, &shell)?;
126
    csrf(&viewer, &f.csrf, &shell)?;
127
    if !crate::mail::enabled(&app) {
128
        return admin_page(&app, shell, Some("Mail is off; save an SMTP URL and a From address first.".into())).await;
129
    }
130
    if me.email.is_empty() {
131
        return admin_page(&app, shell, Some("Your account has no email address to send the test to.".into())).await;
132
    }
133
    let notice = match crate::mail::send(
134
        &app,
135
        me.name(),
136
        &me.email,
137
        "Test message",
138
        "This is a test message from your hub's mail settings. If you can read it, mail works.",
139
    )
140
    .await
141
    {
142
        Ok(()) => format!("Sent a test message to {}.", me.email),
143
        Err(e) => format!("Sending failed: {e}"),
144
    };
145
    admin_page(&app, shell, Some(notice)).await
19bb31ff Andy McCall ↶ 146
}
147
148
pub async fn index(State(app): State<Shared>, viewer: Viewer) -> Result<Page<AdminPage>, Error> {
149
    let shell = Shell::new(&app, "/admin", &viewer);
150
    require_admin(&viewer, &shell)?;
151
    admin_page(&app, shell, None).await
152
}
153
154
#[derive(Deserialize)]
155
pub struct ModeForm {
156
    #[serde(rename = "_csrf")]
157
    csrf_token: String,
158
    mode: String,
159
}
160
161
pub async fn set_mode(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ModeForm>) -> Result<Page<AdminPage>, Error> {
162
    let shell = Shell::new(&app, "/admin", &viewer);
163
    let me = require_admin(&viewer, &shell)?;
164
    csrf(&viewer, &f.csrf_token, &shell)?;
165
    if !matches!(f.mode.as_str(), "open" | "invite" | "closed") {
166
        return Err(Error::bad(shell, "mode is open, invite or closed"));
167
    }
168
    accounts::set_setting(&app.db, "registration_mode", &f.mode).await.map_err(|e| Error::from_db(shell.clone(), e))?;
169
    accounts::audit(&app.db, Some(&me), "admin.registration", &f.mode, "").await.ok();
170
    admin_page(&app, shell, Some(format!("Registration is {}.", f.mode))).await
171
}
172
173
pub async fn invite(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Page<AdminPage>, Error> {
174
    let shell = Shell::new(&app, "/admin", &viewer);
175
    let me = require_admin(&viewer, &shell)?;
176
    csrf(&viewer, &f.csrf, &shell)?;
177
    let code = auth::random_hex(12);
178
    accounts::create_invitation(&app.db, &code, Some(me.id)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
179
    accounts::audit(&app.db, Some(&me), "admin.invite", &code, "").await.ok();
180
    admin_page(&app, shell, Some(format!("Invitation created: {}/register?invite={code}", app.config.base_url()))).await
181
}
182
183
#[derive(Deserialize)]
184
pub struct AccountForm {
185
    #[serde(rename = "_csrf")]
186
    csrf_token: String,
187
    username: String,
188
    action: String,
6a178055 Andy McCall ↶ 189
    /// For delete: the username typed again.
190
    #[serde(default)]
191
    confirm: String,
19bb31ff Andy McCall ↶ 192
}
193
194
pub async fn account(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AccountForm>) -> Result<Page<AdminPage>, Error> {
195
    let shell = Shell::new(&app, "/admin", &viewer);
196
    let me = require_admin(&viewer, &shell)?;
197
    csrf(&viewer, &f.csrf_token, &shell)?;
198
    let Some(target) = accounts::account_by_name(&app.db, f.username.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))? else {
199
        return admin_page(&app, shell, Some("No such account.".into())).await;
200
    };
6a178055 Andy McCall ↶ 201
    if target.id == me.id && matches!(f.action.as_str(), "ban" | "demote" | "disable" | "delete") {
19bb31ff Andy McCall ↶ 202
        return admin_page(&app, shell, Some("Not on yourself.".into())).await;
203
    }
204
    let e = |e| Error::from_db(shell.clone(), e);
6a178055 Andy McCall ↶ 205
    // The hub must keep an admin who can sign in (oxygenhub#81).
206
    if target.is_admin && matches!(f.action.as_str(), "disable" | "delete") {
207
        let others =
208
            accounts::accounts(&app.db).await.map_err(e)?.into_iter().filter(|a| a.is_admin && !a.blocked() && a.id != target.id).count();
209
        if others == 0 {
210
            return admin_page(&app, shell, Some(format!("{} is the last admin who can sign in.", target.username))).await;
211
        }
212
    }
213
    if f.action == "delete" {
214
        if f.confirm.trim() != target.username {
215
            return admin_page(&app, shell, Some(format!("Not deleted: type {} to confirm.", target.username))).await;
216
        }
217
        let repos = crate::db::repos::list_by_owner(&app.db, &target.username).await.map_err(e)?;
218
        let orgs = accounts::orgs_owned_only_by(&app.db, target.id).await.map_err(e)?;
219
        if !repos.is_empty() || !orgs.is_empty() {
220
            let mut held: Vec<String> = repos.iter().map(|r| r.slug()).collect();
221
            held.extend(orgs.iter().map(|o| format!("organisation {o} (sole owner)")));
222
            return admin_page(
223
                &app,
224
                shell,
225
                Some(format!("Not deleted: {} still owns {}. Transfer or delete them first.", target.username, held.join(", "))),
226
            )
227
            .await;
228
        }
229
        accounts::delete_account(&app.db, target.id, &target.username).await.map_err(e)?;
230
        accounts::audit(&app.db, Some(&me), "admin.account.delete", &target.username, "").await.ok();
231
        return admin_page(&app, shell, Some(format!("{} deleted; the name stays retired.", target.username))).await;
232
    }
34beb1a7 Andy McCall ↶ 233
    if f.action == "reset_link" {
6a178055 Andy McCall ↶ 234
        if target.blocked() {
235
            return admin_page(&app, shell, Some("A banned or disabled account cannot be reset.".into())).await;
34beb1a7 Andy McCall ↶ 236
        }
237
        let url = super::recovery::admin_reset_link(&app, &me, &target).await.map_err(e)?;
238
        return admin_page(
239
            &app,
240
            shell,
241
            Some(format!("Reset link for {} (works once, for 24 hours; shown only now): {url}", target.username)),
242
        )
243
        .await;
244
    }
19bb31ff Andy McCall ↶ 245
    match f.action.as_str() {
246
        "ban" => accounts::set_banned(&app.db, target.id, true).await.map_err(e)?,
247
        "unban" => accounts::set_banned(&app.db, target.id, false).await.map_err(e)?,
6a178055 Andy McCall ↶ 248
        "disable" => accounts::set_disabled(&app.db, target.id, true).await.map_err(e)?,
249
        "enable" => accounts::set_disabled(&app.db, target.id, false).await.map_err(e)?,
19bb31ff Andy McCall ↶ 250
        "promote" => accounts::set_admin(&app.db, target.id, true).await.map_err(e)?,
251
        "demote" => accounts::set_admin(&app.db, target.id, false).await.map_err(e)?,
252
        _ => return Err(Error::bad(shell, "unknown action")),
253
    }
254
    accounts::audit(&app.db, Some(&me), &format!("admin.account.{}", f.action), &target.username, "").await.ok();
255
    admin_page(&app, shell, Some(format!("{}: {}.", target.username, f.action))).await
256
}
8fb35df7 Andy McCall ↶ 257
258
// ------------------------------------------------------------------ storage
259
260
/// One repository's footprint on disk.
261
pub struct StorageRow {
262
    pub slug: String,
263
    pub bytes: u64,
264
    /// Objects not yet in a pack.
265
    pub loose: usize,
266
    pub packs: usize,
267
}
268
269
#[derive(Template)]
270
#[template(path = "admin_storage.html")]
271
pub struct StoragePage {
272
    shell: Shell,
273
    rows: Vec<StorageRow>,
274
    total: u64,
275
    notice: Option<String>,
276
    error: Option<String>,
277
}
278
279
/// Size, loose objects and packs under a repository directory.
280
fn footprint(dir: &std::path::Path) -> (u64, usize, usize) {
281
    let (mut bytes, mut loose, mut packs) = (0u64, 0usize, 0usize);
282
    let mut stack = vec![dir.to_path_buf()];
283
    while let Some(d) = stack.pop() {
284
        let Ok(rd) = std::fs::read_dir(&d) else { continue };
285
        for e in rd.flatten() {
286
            let Ok(ft) = e.file_type() else { continue };
287
            if ft.is_dir() {
288
                stack.push(e.path());
289
            } else if ft.is_file() {
290
                bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
291
                let p = e.path();
292
                if p.components().any(|c| c.as_os_str() == "loose") {
293
                    loose += 1;
294
                } else if p.extension().is_some_and(|x| x == "pack") {
295
                    packs += 1;
296
                }
297
            }
298
        }
299
    }
300
    (bytes, loose, packs)
301
}
302
303
async fn storage_page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Result<Page<StoragePage>, Error> {
304
    let repos = crate::db::repos::list(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))?;
305
    let dirs: Vec<(String, std::path::PathBuf)> =
306
        repos.iter().filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name).map(|n| (n.to_string(), app.repos.dir(&n)))).collect();
307
    let mut rows = tokio::task::spawn_blocking(move || {
308
        dirs.into_iter()
309
            .map(|(slug, dir)| {
310
                let (bytes, loose, packs) = footprint(&dir);
311
                StorageRow { slug, bytes, loose, packs }
312
            })
313
            .collect::<Vec<_>>()
314
    })
315
    .await
316
    .unwrap_or_default();
317
    rows.sort_by_key(|r| std::cmp::Reverse(r.bytes));
318
    let total = rows.iter().map(|r| r.bytes).sum();
319
    Ok(Page(StoragePage { shell, rows, total, notice, error }))
320
}
321
322
pub async fn storage(State(app): State<Shared>, viewer: Viewer) -> Result<Page<StoragePage>, Error> {
323
    let shell = Shell::new(&app, "/admin/storage", &viewer);
324
    require_admin(&viewer, &shell)?;
325
    storage_page(&app, shell, None, None).await
326
}
327
328
#[derive(Deserialize)]
329
pub struct MaintainForm {
330
    #[serde(rename = "_csrf")]
331
    csrf_token: String,
332
    /// `owner/name`, or `*` for every repository.
333
    repo: String,
334
}
335
336
/// `POST /admin/storage`: `oxy gc` on one repository or all of them, under
337
/// each repository's write lock, with the grace period kept.
338
pub async fn maintain(State(app): State<Shared>, viewer: Viewer, Form(f): Form<MaintainForm>) -> Result<Page<StoragePage>, Error> {
339
    let shell = Shell::new(&app, "/admin/storage", &viewer);
340
    let me = require_admin(&viewer, &shell)?;
341
    csrf(&viewer, &f.csrf_token, &shell)?;
342
    let names: Vec<crate::repos::RepoName> = if f.repo == "*" {
343
        crate::db::repos::list(&app.db)
344
            .await
345
            .map_err(|e| Error::from_db(shell.clone(), e))?
346
            .iter()
347
            .filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name))
348
            .collect()
349
    } else {
350
        match crate::repos::RepoName::parse(&f.repo) {
351
            Some(n) if app.repos.exists(&n) => vec![n],
352
            _ => return storage_page(&app, shell, None, Some(format!("No repository {}.", f.repo))).await,
353
        }
354
    };
355
    let (mut packed, mut pruned, mut freed, mut failed) = (0usize, 0usize, 0u64, Vec::new());
356
    for name in &names {
357
        match app.repos.write(name, |r, _| r.gc(false).map_err(crate::repos::RepoError::Oxy)).await {
358
            Ok(rep) => {
359
                packed += rep.packed.objects;
360
                pruned += rep.pruned.objects;
361
                freed += rep.pruned.bytes + rep.packed.raw_bytes.saturating_sub(rep.packed.packed_bytes);
362
            }
363
            Err(e) => failed.push(format!("{name}: {e}")),
364
        }
365
    }
366
    let summary = format!(
367
        "Maintained {} repositor{}: {packed} loose objects packed, {pruned} unreachable objects pruned, about {} saved.",
368
        names.len(),
369
        if names.len() == 1 { "y" } else { "ies" },
370
        crate::render::bytes(freed)
371
    );
372
    accounts::audit(&app.db, Some(&me), "admin.gc", &f.repo, &summary).await.ok();
373
    let error = (!failed.is_empty()).then(|| failed.join("; "));
374
    storage_page(&app, shell, Some(summary), error).await
375
}
e71846aa Andy McCall ↶ 376
2a83f530 Andy McCall ↶ 377
fn site_assistants() -> crate::levels::At {
378
    crate::levels::At::site()
e71846aa Andy McCall ↶ 379
}
380
381
/// `POST /admin/assistants`: the site's assistants and prompt (#97).
382
pub async fn assistants(
383
    State(app): State<Shared>,
384
    viewer: Viewer,
385
    Form(f): Form<super::assistants::AssistantForm>,
386
) -> Result<Page<AdminPage>, Error> {
387
    let shell = Shell::new(&app, "/admin", &viewer);
388
    require_admin(&viewer, &shell)?;
389
    csrf(&viewer, &f.csrf_token, &shell)?;
390
    let outcome = super::assistants::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
391
    admin_page(&app, shell, Some(outcome.unwrap_or_else(|e| e))).await
392
}
2a83f530 Andy McCall ↶ 393
394
/// `POST /admin/variables`: the site's Flow variables (#102).
395
pub async fn variables(
396
    State(app): State<Shared>,
397
    viewer: Viewer,
398
    Form(f): Form<super::variables::VariableForm>,
399
) -> Result<Page<AdminPage>, Error> {
400
    let shell = Shell::new(&app, "/admin", &viewer);
401
    require_admin(&viewer, &shell)?;
402
    csrf(&viewer, &f.csrf_token, &shell)?;
403
    let outcome = super::variables::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
404
    admin_page(&app, shell, Some(outcome.unwrap_or_else(|e| e))).await
405
}
4ac01a73 Andy McCall ↶ 406
407
/// `POST /admin/secrets`: the site's Flow secrets (#107).
408
pub async fn secrets(
409
    State(app): State<Shared>,
410
    viewer: Viewer,
411
    Form(f): Form<super::secrets::SecretForm>,
412
) -> Result<Page<AdminPage>, Error> {
413
    let shell = Shell::new(&app, "/admin", &viewer);
414
    require_admin(&viewer, &shell)?;
415
    csrf(&viewer, &f.csrf_token, &shell)?;
416
    let outcome = super::secrets::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
417
    admin_page(&app, shell, Some(outcome.unwrap_or_else(|e| e))).await
418
}