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