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