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