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