OXYGENHUB

Coverage / crates/hub/src/web/admin.rs 88.2%

447 of 507 lines run, 53 of 146 functions · run #531 on main · run missed

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
/// A page of the admin area (oxygenhub#288): grouped in a sidebar, one
14
/// page per section, as a repository's settings are (#278).
15
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16
pub enum AdminSection {
17
    Overview,
18
    Accounts,
19
    Registration,
20
    Organisations,
21
    SignIn,
22
    SecurityContact,
23
    Mail,
24
    Runners,
25
    Images,
26
    RunnerSettings,
27
    RunnerUpdates,
28
    Insights,
29
    Variables,
30
    Secrets,
31
    Assistants,
32
    Diffusion,
33
    Storage,
34
    Backups,
35
    Audit,
36
}
37
38
/// The sidebar: each group's heading and its pages, in order.
39
const ADMIN_GROUPS: &[(&str, &[AdminSection])] = &[
40
    ("Overview", &[AdminSection::Overview]),
41
    ("People", &[AdminSection::Accounts, AdminSection::Registration, AdminSection::Organisations]),
42
    ("Sign-in", &[AdminSection::SignIn, AdminSection::SecurityContact]),
43
    ("Mail", &[AdminSection::Mail]),
44
    (
45
        "Flow",
46
        &[
47
            AdminSection::Runners,
48
            AdminSection::Images,
49
            AdminSection::RunnerSettings,
50
            AdminSection::RunnerUpdates,
51
            AdminSection::Insights,
52
            AdminSection::Variables,
53
            AdminSection::Secrets,
54
        ],
55
    ),
56
    ("Integrations", &[AdminSection::Assistants, AdminSection::Diffusion]),
57
    ("Data", &[AdminSection::Storage, AdminSection::Backups]),
58
    ("Audit", &[AdminSection::Audit]),
59
];
60
61
/// The admin sidebar's groups, for templates.
62178×
pub fn admin_groups() -> &'static [(&'static str, &'static [AdminSection])] {
63178×
    ADMIN_GROUPS
64178×
}
65
66
impl AdminSection {
67
    /// Its page's address.
683550×
    pub fn href(self) -> &'static str {
693550×
        match self {
70176×
            AdminSection::Overview => "/admin",
71197×
            AdminSection::Accounts => "/admin/accounts",
72195×
            AdminSection::Registration => "/admin/registration",
73194×
            AdminSection::Organisations => "/admin/organisations",
74193×
            AdminSection::SignIn => "/admin/signin",
75191×
            AdminSection::SecurityContact => "/admin/security",
76189×
            AdminSection::Mail => "/admin/mail",
77187×
            AdminSection::Runners => "/admin/runners",
78187×
            AdminSection::Images => "/admin/runners/images",
79187×
            AdminSection::RunnerSettings => "/admin/runners/settings",
80187×
            AdminSection::RunnerUpdates => "/admin/runners/updates",
81187×
            AdminSection::Insights => "/admin/insights",
82187×
            AdminSection::Variables => "/admin/variables",
83185×
            AdminSection::Secrets => "/admin/secrets",
84184×
            AdminSection::Assistants => "/admin/assistants",
85181×
            AdminSection::Diffusion => "/admin/diffusion",
86181×
            AdminSection::Storage => "/admin/storage",
87181×
            AdminSection::Backups => "/admin/backups",
88181×
            AdminSection::Audit => "/admin/audit",
89
        }
903550×
    }
91
92
    /// The anchor it had on the one-page admin, so a kept `/admin#mail`
93
    /// link opens its page (hub.js).
942983×
    pub fn slug(self) -> &'static str {
952983×
        match self {
96157×
            AdminSection::Overview => "overview",
97157×
            AdminSection::Accounts => "accounts",
98157×
            AdminSection::Registration => "registration",
99157×
            AdminSection::Organisations => "organisations",
100157×
            AdminSection::SignIn => "signin",
101157×
            AdminSection::SecurityContact => "security",
102157×
            AdminSection::Mail => "mail",
103157×
            AdminSection::Runners => "runners",
104157×
            AdminSection::Images => "images",
105157×
            AdminSection::RunnerSettings => "runner-settings",
106157×
            AdminSection::RunnerUpdates => "runner-updates",
107157×
            AdminSection::Insights => "insights",
108157×
            AdminSection::Variables => "variables",
109157×
            AdminSection::Secrets => "secrets",
110157×
            AdminSection::Assistants => "assistants",
111157×
            AdminSection::Diffusion => "diffusion",
112157×
            AdminSection::Storage => "storage",
113157×
            AdminSection::Backups => "backups",
114157×
            AdminSection::Audit => "audit",
115
        }
1162983×
    }
117
1183436×
    pub fn title(self) -> &'static str {
1193436×
        match self {
120157×
            AdminSection::Overview => "Overview",
121188×
            AdminSection::Accounts => "Accounts",
122189×
            AdminSection::Registration => "Registration & invitations",
123179×
            AdminSection::Organisations => "Organisations",
124186×
            AdminSection::SignIn => "Sign in with",
125184×
            AdminSection::SecurityContact => "Security contact",
126191×
            AdminSection::Mail => "Mail",
127178×
            AdminSection::Runners => "Runners",
128178×
            AdminSection::Images => "Images",
129178×
            AdminSection::RunnerSettings => "Runner settings",
130178×
            AdminSection::RunnerUpdates => "Runner updates",
131178×
            AdminSection::Insights => "Insights",
132181×
            AdminSection::Variables => "Variables",
133181×
            AdminSection::Secrets => "Secrets",
134195×
            AdminSection::Assistants => "AI assistants",
135178×
            AdminSection::Diffusion => "Diffusion",
136178×
            AdminSection::Storage => "Storage & maintenance",
137178×
            AdminSection::Backups => "Backups",
138181×
            AdminSection::Audit => "Audit log",
139
        }
1403436×
    }
141
142
    /// The section a page of admin.html shows, by its address.
14319×
    fn of_path(path: &str) -> Option<AdminSection> {
144189×
        ADMIN_GROUPS.iter().flat_map(|(_, pages)| pages.iter().copied()).find(|s| s.href() == path)
14519×
    }
146
}
147
148
#[derive(Template)]
149
#[template(path = "admin.html")]
150
pub struct AdminPage {
151
    shell: Shell,
152
    /// The page shown (oxygenhub#288).
153
    section: AdminSection,
154
    accounts: Vec<accounts::Account>,
155
    orgs: Vec<accounts::Organisation>,
156
    mode: String,
157
    invitations: Vec<(String, Option<i64>, i64)>,
158
    audit: Vec<accounts::AuditRow>,
159
    repos: usize,
160
    notice: Option<String>,
161
    /// Mail settings (#101): the SMTP URL with its password masked, the
162
    /// From address, whether mail is on, and the administrator's own
163
    /// address for a test message.
164
    mail_smtp: String,
165
    mail_from: String,
166
    mail_enabled: bool,
167
    /// The saved mail settings as the panel shows them (oxygenhub#181).
168
    mail: crate::mail::Choice,
169
    my_email: String,
170
    /// The audit log's next page: rows older than this id (#110).
171
    audit_older: Option<i64>,
172
    /// The site's AI assistants and prompt (#97).
173
    assistants: super::assistants::Panel,
174
    /// The site's Flow variables (#102).
175
    variables: super::variables::Panel,
176
    /// The site's Flow secrets (#107).
177
    secrets: super::secrets::Panel,
178
    /// Sign-in providers (#106).
179
    providers: Vec<super::signin::ProviderView>,
180
    /// The security.txt contact and policy (oxygenhub#224).
181
    security_contact: String,
182
    security_policy: String,
183
    /// The /security-contact page's address and text (oxygenhub#230).
184
    security_email: String,
185
    security_page: String,
186
    security_default: &'static str,
187
}
188
189112×
pub(super) fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> {
190112×
    match viewer.account() {
191106×
        Some(a) if a.is_admin => Ok(a.clone()),
1926×
        _ => Err(Error::not_found(shell.clone())),
193
    }
194112×
}
195
19656×
pub(super) async fn admin_page(
19756×
    app: &Shared,
19856×
    shell: Shell,
19956×
    section: AdminSection,
20056×
    notice: Option<String>,
20156×
) -> Result<Page<AdminPage>, Error> {
20256×
    admin_page_at(app, shell, section, notice, None).await
20356×
}
204
205
/// The audit log shows this many rows a page.
206
const AUDIT_PAGE: i64 = 50;
207
20896×
async fn admin_page_at(
20996×
    app: &Shared,
21096×
    shell: Shell,
21196×
    section: AdminSection,
21296×
    notice: Option<String>,
21396×
    audit_before: Option<i64>,
21496×
) -> Result<Page<AdminPage>, Error> {
21596×
    let e = |e| Error::from_db(shell.clone(), e);
21696×
    let accounts_list = accounts::accounts(&app.db).await.map_err(e)?;
21796×
    let orgs = accounts::orgs(&app.db).await.map_err(e)?;
21896×
    let mode = super::session::registration_mode(app).await;
21996×
    let invitations = accounts::invitations(&app.db).await.map_err(e)?;
22096×
    let mut audit = accounts::audit_page(&app.db, audit_before, AUDIT_PAGE + 1).await.map_err(e)?;
22196×
    let audit_older = if audit.len() as i64 > AUDIT_PAGE {
22212×
        audit.truncate(AUDIT_PAGE as usize);
22312×
        audit.last().map(|r| r.id)
224
    } else {
22584×
        None
226
    };
22796×
    let repos = crate::db::repos::list(&app.db).await.map_err(e)?.len();
22896×
    let mail = crate::mail::settings(app);
22996×
    let my_email = match shell.user.as_deref() {
23096×
        Some(u) => accounts::account_by_name(&app.db, u).await.map_err(e)?.map(|a| a.email).unwrap_or_default(),
2310×
        None => String::new(),
232
    };
23396×
    let assistants = super::assistants::panel(app, &site_assistants()).await.map_err(e)?;
23496×
    let variables = super::variables::panel(app, &site_assistants()).await.map_err(e)?;
23596×
    let secrets = super::secrets::panel(app, &site_assistants()).await.map_err(e)?;
23696×
    let providers = super::signin::provider_views(app).await.map_err(e)?;
23796×
    let (security_contact, security_policy) = super::security_txt::settings(app).await;
23896×
    let (security_email, security_page) = super::security_txt::page_settings(app).await;
239
    Ok(Page(AdminPage {
24096×
        section,
24196×
        providers,
24296×
        security_contact,
24396×
        security_policy,
24496×
        security_email,
24596×
        security_page,
246
        security_default: super::security_txt::DEFAULT_PAGE,
24796×
        assistants,
24896×
        variables,
24996×
        secrets,
25096×
        shell,
25196×
        accounts: accounts_list,
25296×
        orgs,
25396×
        mode,
25496×
        invitations,
25596×
        audit,
25696×
        repos,
25796×
        notice,
25896×
        mail: crate::mail::describe(&mail.smtp),
25996×
        mail_smtp: crate::mail::masked(&mail.smtp),
26096×
        mail_from: mail.from.clone(),
26196×
        mail_enabled: !mail.smtp.is_empty() && !mail.from.is_empty(),
26296×
        my_email,
26396×
        audit_older,
264
    }))
26596×
}
266
267
impl AdminPage {
26813×
    fn mail_services(&self) -> &'static [(&'static str, &'static str)] {
26913×
        crate::mail::SERVICES
27013×
    }
271
}
272
273
#[derive(Deserialize)]
274
pub struct MailForm {
275
    #[serde(rename = "_csrf")]
276
    csrf_token: String,
277
    #[serde(default)]
278
    smtp: String,
279
    #[serde(default)]
280
    from: String,
281
    /// The panel's service (oxygenhub#181); absent, `smtp` is the URL as
282
    /// before.
283
    #[serde(default)]
284
    service: String,
285
    #[serde(default)]
286
    region: String,
287
    #[serde(default)]
288
    user: String,
289
    #[serde(default)]
290
    secret: String,
291
    #[serde(default)]
292
    host: String,
293
    #[serde(default)]
294
    port: String,
295
    #[serde(default)]
296
    security: String,
297
}
298
299
/// `POST /admin/mail`: the SMTP URL and From address (#101). The URL
300
/// comes back masked, so a masked value left as it was keeps the stored
301
/// one; an empty URL turns mail off.
30211×
pub async fn set_mail(State(app): State<Shared>, viewer: Viewer, Form(f): Form<MailForm>) -> Result<Page<AdminPage>, Error> {
30311×
    let shell = Shell::new(&app, "/admin", &viewer);
30411×
    let me = require_admin(&viewer, &shell)?;
30510×
    csrf(&viewer, &f.csrf_token, &shell)?;
30610×
    let current = crate::mail::settings(&app);
307
    // A service the panel knows: it makes the SMTP URL (oxygenhub#181).
30810×
    let smtp = match f.service.as_str() {
30910×
        "off" => String::new(),
3109×
        "" | "url" => {
3115×
            let smtp = f.smtp.trim();
3125×
            if !current.smtp.is_empty() && smtp == crate::mail::masked(&current.smtp) {
3131×
                current.smtp.clone()
314
            } else {
3154×
                smtp.to_string()
316
            }
317
        }
318
        _ => {
3194×
            let asked = crate::mail::Asked {
3204×
                service: f.service.clone(),
3214×
                region: f.region.clone(),
3224×
                user: f.user.clone(),
3234×
                secret: f.secret.trim().to_string(),
3244×
                host: f.host.clone(),
3254×
                port: f.port.clone(),
3264×
                security: f.security.clone(),
3274×
            };
3284×
            match crate::mail::compose(&asked, &current.smtp) {
3293×
                Ok(url) => url,
3301×
                Err(why) => return admin_page(&app, shell, AdminSection::Mail, Some(why)).await,
331
            }
332
        }
333
    };
3349×
    let from = f.from.trim().to_string();
3359×
    if !smtp.is_empty() && !(smtp.starts_with("smtp://") || smtp.starts_with("smtps://") || smtp.starts_with("file://")) {
3361×
        return admin_page(
3371×
            &app,
3381×
            shell,
3391×
            AdminSection::Mail,
3401×
            Some("The SMTP URL starts with smtp:// or smtps:// (file:///dir writes messages to a directory, for testing).".into()),
3411×
        )
3421×
        .await;
3438×
    }
3448×
    if !smtp.is_empty() && from.is_empty() {
3450×
        return admin_page(&app, shell, AdminSection::Mail, Some("A From address is needed: OxygenHub <[email protected]>.".into()))
3460×
            .await;
3478×
    }
3488×
    crate::mail::save(&app, &smtp, &from).await.map_err(|e| Error::from_db(shell.clone(), e))?;
3498×
    accounts::audit(&app.db, Some(&me), "admin.mail", if smtp.is_empty() { "off" } else { "on" }, &from).await.ok();
3508×
    admin_page(&app, shell, AdminSection::Mail, Some(if smtp.is_empty() { "Mail is off.".into() } else { "Mail settings saved.".into() }))
3518×
        .await
35211×
}
353
354
/// `POST /admin/mail/test`: a message to the administrator's own address.
3551×
pub async fn test_mail(
3561×
    State(app): State<Shared>,
3571×
    viewer: Viewer,
3581×
    Form(f): Form<super::session::CsrfForm>,
3591×
) -> Result<Page<AdminPage>, Error> {
3601×
    let shell = Shell::new(&app, "/admin", &viewer);
3611×
    let me = require_admin(&viewer, &shell)?;
3621×
    csrf(&viewer, &f.csrf, &shell)?;
3631×
    if !crate::mail::enabled(&app) {
3640×
        return admin_page(&app, shell, AdminSection::Mail, Some("Mail is off; save an SMTP URL and a From address first.".into())).await;
3651×
    }
3661×
    if me.email.is_empty() {
3670×
        return admin_page(&app, shell, AdminSection::Mail, Some("Your account has no email address to send the test to.".into())).await;
3681×
    }
3691×
    let base = app.config.base_url().to_string();
3701×
    let notice = match crate::mail::send_letter(
3711×
        &app,
3721×
        me.name(),
3731×
        &me.email,
3741×
        "🧪 Test message",
3751×
        "This is a test message from your hub's mail settings. If you can read it, mail works: verification links, password resets and notifications will reach people.",
3761×
        Some(crate::mail::Action { label: "Open the hub", url: &base }),
3771×
        None,
378
    )
3791×
    .await
380
    {
3811×
        Ok(()) => format!("Sent a test message to {}.", me.email),
3820×
        Err(e) => format!("Sending failed: {e}"),
383
    };
3841×
    admin_page(&app, shell, AdminSection::Mail, Some(notice)).await
3851×
}
386
387
#[derive(Deserialize)]
388
pub struct IndexQuery {
389
    audit_before: Option<i64>,
390
}
391
39221×
pub async fn index(
39321×
    State(app): State<Shared>,
39421×
    viewer: Viewer,
39521×
    axum::extract::Query(q): axum::extract::Query<IndexQuery>,
39621×
) -> Result<Page<AdminPage>, Error> {
39721×
    let shell = Shell::new(&app, "/admin", &viewer);
39821×
    require_admin(&viewer, &shell)?;
39921×
    admin_page_at(&app, shell, AdminSection::Overview, None, q.audit_before).await
40021×
}
401
402
/// `GET /admin/{page}` for the sections admin.html shows (oxygenhub#288):
403
/// accounts, registration, organisations, sign-in, the security contact,
404
/// mail, variables, secrets, AI assistants and the audit log.
40521×
pub async fn section(
40621×
    State(app): State<Shared>,
40721×
    viewer: Viewer,
40821×
    uri: axum::http::Uri,
40921×
    axum::extract::Query(q): axum::extract::Query<IndexQuery>,
41021×
) -> Result<Page<AdminPage>, Error> {
41121×
    let shell = Shell::new(&app, uri.path(), &viewer);
41221×
    require_admin(&viewer, &shell)?;
41319×
    let section = AdminSection::of_path(uri.path()).ok_or_else(|| Error::not_found(shell.clone()))?;
41419×
    admin_page_at(&app, shell, section, None, q.audit_before).await
41521×
}
416
417
#[derive(Deserialize)]
418
pub struct ModeForm {
419
    #[serde(rename = "_csrf")]
420
    csrf_token: String,
421
    mode: String,
422
}
423
4240×
pub async fn set_mode(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ModeForm>) -> Result<Page<AdminPage>, Error> {
4250×
    let shell = Shell::new(&app, "/admin", &viewer);
4260×
    let me = require_admin(&viewer, &shell)?;
4270×
    csrf(&viewer, &f.csrf_token, &shell)?;
4280×
    if !matches!(f.mode.as_str(), "open" | "invite" | "closed") {
4290×
        return Err(Error::bad(shell, "mode is open, invite or closed"));
4300×
    }
4310×
    accounts::set_setting(&app.db, "registration_mode", &f.mode).await.map_err(|e| Error::from_db(shell.clone(), e))?;
4320×
    accounts::audit(&app.db, Some(&me), "admin.registration", &f.mode, "").await.ok();
4330×
    admin_page(&app, shell, AdminSection::Registration, Some(format!("Registration is {}.", f.mode))).await
4340×
}
435
43610×
pub async fn invite(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Page<AdminPage>, Error> {
43710×
    let shell = Shell::new(&app, "/admin", &viewer);
43810×
    let me = require_admin(&viewer, &shell)?;
43910×
    csrf(&viewer, &f.csrf, &shell)?;
44010×
    let code = auth::random_hex(12);
44110×
    accounts::create_invitation(&app.db, &code, Some(me.id)).await.map_err(|e| Error::from_db(shell.clone(), e))?;
44210×
    accounts::audit(&app.db, Some(&me), "admin.invite", &code, "").await.ok();
44310×
    admin_page(
44410×
        &app,
44510×
        shell,
44610×
        AdminSection::Registration,
44710×
        Some(format!("Invitation created: {}/register?invite={code}", app.config.base_url())),
44810×
    )
44910×
    .await
45010×
}
451
452
#[derive(Deserialize)]
453
pub struct AccountForm {
454
    #[serde(rename = "_csrf")]
455
    csrf_token: String,
456
    username: String,
457
    action: String,
458
    /// For delete: the username typed again.
459
    #[serde(default)]
460
    confirm: String,
461
}
462
4638×
pub async fn account(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AccountForm>) -> Result<Page<AdminPage>, Error> {
4648×
    let shell = Shell::new(&app, "/admin", &viewer);
4658×
    let me = require_admin(&viewer, &shell)?;
4668×
    csrf(&viewer, &f.csrf_token, &shell)?;
4678×
    let Some(target) = accounts::account_by_name(&app.db, f.username.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))? else {
4680×
        return admin_page(&app, shell, AdminSection::Accounts, Some("No such account.".into())).await;
469
    };
4708×
    if target.id == me.id && matches!(f.action.as_str(), "ban" | "demote" | "disable" | "delete") {
4712×
        return admin_page(&app, shell, AdminSection::Accounts, Some("Not on yourself.".into())).await;
4726×
    }
4736×
    let e = |e| Error::from_db(shell.clone(), e);
474
    // The hub must keep an admin who can sign in (oxygenhub#81).
4756×
    if target.is_admin && matches!(f.action.as_str(), "disable" | "delete") {
4760×
        let others =
4770×
            accounts::accounts(&app.db).await.map_err(e)?.into_iter().filter(|a| a.is_admin && !a.blocked() && a.id != target.id).count();
4780×
        if others == 0 {
4790×
            return admin_page(
4800×
                &app,
4810×
                shell,
4820×
                AdminSection::Accounts,
4830×
                Some(format!("{} is the last admin who can sign in.", target.username)),
4840×
            )
4850×
            .await;
4860×
        }
4876×
    }
4886×
    if f.action == "delete" {
4893×
        if f.confirm.trim() != target.username {
4901×
            return admin_page(&app, shell, AdminSection::Accounts, Some(format!("Not deleted: type {} to confirm.", target.username)))
4911×
                .await;
4922×
        }
4932×
        let repos = crate::db::repos::list_by_owner(&app.db, &target.username).await.map_err(e)?;
4942×
        let orgs = accounts::orgs_owned_only_by(&app.db, target.id).await.map_err(e)?;
4952×
        if !repos.is_empty() || !orgs.is_empty() {
4961×
            let mut held: Vec<String> = repos.iter().map(|r| r.slug()).collect();
4971×
            held.extend(orgs.iter().map(|o| format!("organisation {o} (sole owner)")));
4981×
            return admin_page(
4991×
                &app,
5001×
                shell,
5011×
                AdminSection::Accounts,
5021×
                Some(format!("Not deleted: {} still owns {}. Transfer or delete them first.", target.username, held.join(", "))),
5031×
            )
5041×
            .await;
5051×
        }
5061×
        accounts::delete_account(&app.db, target.id, &target.username).await.map_err(e)?;
5071×
        accounts::audit(&app.db, Some(&me), "admin.account.delete", &target.username, "").await.ok();
5081×
        return admin_page(&app, shell, AdminSection::Accounts, Some(format!("{} deleted; the name stays retired.", target.username)))
5091×
            .await;
5103×
    }
5113×
    if f.action == "reset_link" {
5121×
        if target.blocked() {
5130×
            return admin_page(&app, shell, AdminSection::Accounts, Some("A banned or disabled account cannot be reset.".into())).await;
5141×
        }
5151×
        let url = super::recovery::admin_reset_link(&app, &me, &target).await.map_err(e)?;
5161×
        return admin_page(
5171×
            &app,
5181×
            shell,
5191×
            AdminSection::Accounts,
5201×
            Some(format!("Reset link for {} (works once, for 24 hours; shown only now): {url}", target.username)),
5211×
        )
5221×
        .await;
5232×
    }
5242×
    match f.action.as_str() {
5252×
        "ban" => accounts::set_banned(&app.db, target.id, true).await.map_err(e)?,
5262×
        "unban" => accounts::set_banned(&app.db, target.id, false).await.map_err(e)?,
5272×
        "disable" => accounts::set_disabled(&app.db, target.id, true).await.map_err(e)?,
5281×
        "enable" => accounts::set_disabled(&app.db, target.id, false).await.map_err(e)?,
5290×
        "promote" => accounts::set_admin(&app.db, target.id, true).await.map_err(e)?,
5300×
        "demote" => accounts::set_admin(&app.db, target.id, false).await.map_err(e)?,
5310×
        _ => return Err(Error::bad(shell, "unknown action")),
532
    }
5332×
    accounts::audit(&app.db, Some(&me), &format!("admin.account.{}", f.action), &target.username, "").await.ok();
5342×
    admin_page(&app, shell, AdminSection::Accounts, Some(format!("{}: {}.", target.username, f.action))).await
5358×
}
536
537
// ------------------------------------------------------------------ storage
538
539
/// One repository's footprint on disk.
540
pub struct StorageRow {
541
    pub slug: String,
542
    /// A drop (#279), labelled as one.
543
    pub drop: bool,
544
    pub bytes: u64,
545
    /// Objects not yet in a pack.
546
    pub loose: usize,
547
    pub packs: usize,
548
}
549
550
#[derive(Template)]
551
#[template(path = "admin_storage.html")]
552
pub struct StoragePage {
553
    shell: Shell,
554
    rows: Vec<StorageRow>,
555
    total: u64,
556
    notice: Option<String>,
557
    error: Option<String>,
558
}
559
560
/// Size, loose objects and packs under a repository directory.
56112×
fn footprint(dir: &std::path::Path) -> (u64, usize, usize) {
56212×
    let (mut bytes, mut loose, mut packs) = (0u64, 0usize, 0usize);
56312×
    let mut stack = vec![dir.to_path_buf()];
56451×
    while let Some(d) = stack.pop() {
56539×
        let Ok(rd) = std::fs::read_dir(&d) else { continue };
56666×
        for e in rd.flatten() {
56766×
            let Ok(ft) = e.file_type() else { continue };
56866×
            if ft.is_dir() {
56927×
                stack.push(e.path());
57039×
            } else if ft.is_file() {
57139×
                bytes += e.metadata().map(|m| m.len()).unwrap_or(0);
57239×
                let p = e.path();
573339×
                if p.components().any(|c| c.as_os_str() == "loose") {
57415×
                    loose += 1;
57524×
                } else if p.extension().is_some_and(|x| x == "pack") {
5762×
                    packs += 1;
57722×
                }
5780×
            }
579
        }
580
    }
58112×
    (bytes, loose, packs)
58212×
}
583
5844×
async fn storage_page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Result<Page<StoragePage>, Error> {
585
    // Drops too, labelled as such (#279).
5864×
    let repos = crate::db::repos::list_with_drops(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))?;
5874×
    let dirs: Vec<(String, bool, std::path::PathBuf)> = repos
5884×
        .iter()
58912×
        .filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name).map(|n| (n.to_string(), r.is_drop(), app.repos.dir(&n))))
5904×
        .collect();
5914×
    let mut rows = tokio::task::spawn_blocking(move || {
5924×
        dirs.into_iter()
59312×
            .map(|(slug, drop, dir)| {
59412×
                let (bytes, loose, packs) = footprint(&dir);
59512×
                StorageRow { slug, drop, bytes, loose, packs }
59612×
            })
5974×
            .collect::<Vec<_>>()
5984×
    })
5994×
    .await
6004×
    .unwrap_or_default();
60118×
    rows.sort_by_key(|r| std::cmp::Reverse(r.bytes));
6024×
    let total = rows.iter().map(|r| r.bytes).sum();
6034×
    Ok(Page(StoragePage { shell, rows, total, notice, error }))
6044×
}
605
6062×
pub async fn storage(State(app): State<Shared>, viewer: Viewer) -> Result<Page<StoragePage>, Error> {
6072×
    let shell = Shell::new(&app, "/admin/storage", &viewer);
6082×
    require_admin(&viewer, &shell)?;
6092×
    storage_page(&app, shell, None, None).await
6102×
}
611
612
#[derive(Deserialize)]
613
pub struct MaintainForm {
614
    #[serde(rename = "_csrf")]
615
    csrf_token: String,
616
    /// `owner/name`, or `*` for every repository.
617
    repo: String,
618
}
619
620
/// `POST /admin/storage`: `oxy gc` on one repository or all of them, under
621
/// each repository's write lock, with the grace period kept.
6222×
pub async fn maintain(State(app): State<Shared>, viewer: Viewer, Form(f): Form<MaintainForm>) -> Result<Page<StoragePage>, Error> {
6232×
    let shell = Shell::new(&app, "/admin/storage", &viewer);
6242×
    let me = require_admin(&viewer, &shell)?;
6252×
    csrf(&viewer, &f.csrf_token, &shell)?;
6262×
    let names: Vec<crate::repos::RepoName> = if f.repo == "*" {
6270×
        crate::db::repos::list_with_drops(&app.db)
6280×
            .await
6290×
            .map_err(|e| Error::from_db(shell.clone(), e))?
6300×
            .iter()
6310×
            .filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name))
6320×
            .collect()
633
    } else {
6342×
        match crate::repos::RepoName::parse(&f.repo) {
6352×
            Some(n) if app.repos.exists(&n) => vec![n],
6361×
            _ => return storage_page(&app, shell, None, Some(format!("No repository {}.", f.repo))).await,
637
        }
638
    };
6391×
    let (mut packed, mut pruned, mut freed, mut failed) = (0usize, 0usize, 0u64, Vec::new());
6401×
    for name in &names {
6411×
        match app.repos.write(name, |r, _| r.gc(false).map_err(crate::repos::RepoError::Oxy)).await {
6421×
            Ok(rep) => {
6431×
                packed += rep.packed.objects;
6441×
                pruned += rep.pruned.objects;
6451×
                freed += rep.pruned.bytes + rep.packed.raw_bytes.saturating_sub(rep.packed.packed_bytes);
6461×
            }
6470×
            Err(e) => failed.push(format!("{name}: {e}")),
648
        }
649
    }
6501×
    let summary = format!(
651
        "Maintained {} repositor{}: {packed} loose objects packed, {pruned} unreachable objects pruned, about {} saved.",
6521×
        names.len(),
6531×
        if names.len() == 1 { "y" } else { "ies" },
6541×
        crate::render::bytes(freed)
655
    );
6561×
    accounts::audit(&app.db, Some(&me), "admin.gc", &f.repo, &summary).await.ok();
6571×
    let error = (!failed.is_empty()).then(|| failed.join("; "));
6581×
    storage_page(&app, shell, Some(summary), error).await
6592×
}
660
661307×
fn site_assistants() -> crate::levels::At {
662307×
    crate::levels::At::site()
663307×
}
664
665
/// `POST /admin/assistants`: the site's assistants and prompt (#97).
66615×
pub async fn assistants(
66715×
    State(app): State<Shared>,
66815×
    viewer: Viewer,
66915×
    Form(f): Form<super::assistants::AssistantForm>,
67015×
) -> Result<Page<AdminPage>, Error> {
67115×
    let shell = Shell::new(&app, "/admin", &viewer);
67215×
    require_admin(&viewer, &shell)?;
67314×
    csrf(&viewer, &f.csrf_token, &shell)?;
67414×
    let outcome = super::assistants::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
67514×
    admin_page(&app, shell, AdminSection::Assistants, Some(outcome.unwrap_or_else(|e| e))).await
67615×
}
677
678
/// `POST /admin/variables`: the site's Flow variables (#102).
6791×
pub async fn variables(
6801×
    State(app): State<Shared>,
6811×
    viewer: Viewer,
6821×
    Form(f): Form<super::variables::VariableForm>,
6831×
) -> Result<Page<AdminPage>, Error> {
6841×
    let shell = Shell::new(&app, "/admin", &viewer);
6851×
    require_admin(&viewer, &shell)?;
6861×
    csrf(&viewer, &f.csrf_token, &shell)?;
6871×
    let outcome = super::variables::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
6881×
    admin_page(&app, shell, AdminSection::Variables, Some(outcome.unwrap_or_else(|e| e))).await
6891×
}
690
691
/// `POST /admin/secrets`: the site's Flow secrets (#107).
6922×
pub async fn secrets(
6932×
    State(app): State<Shared>,
6942×
    viewer: Viewer,
6952×
    Form(f): Form<super::secrets::SecretForm>,
6962×
) -> Result<Page<AdminPage>, Error> {
6972×
    let shell = Shell::new(&app, "/admin", &viewer);
6982×
    require_admin(&viewer, &shell)?;
6992×
    csrf(&viewer, &f.csrf_token, &shell)?;
7002×
    let outcome = super::secrets::apply(&app, &viewer, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7012×
    admin_page(&app, shell, AdminSection::Secrets, Some(outcome.unwrap_or_else(|e| e))).await
7022×
}
703
704
/// `POST /admin/signin`: a sign-in provider's client id, secret and switch (#106).
7056×
pub async fn signin(
7066×
    State(app): State<Shared>,
7076×
    viewer: Viewer,
7086×
    Form(f): Form<super::signin::ProviderForm>,
7096×
) -> Result<Page<AdminPage>, Error> {
7106×
    let shell = Shell::new(&app, "/admin", &viewer);
7116×
    require_admin(&viewer, &shell)?;
7126×
    csrf(&viewer, &f.csrf_token, &shell)?;
7136×
    let outcome = super::signin::apply(&app, &viewer, f).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7146×
    admin_page(&app, shell, AdminSection::SignIn, Some(outcome.unwrap_or_else(|e| e))).await
7156×
}
716
717
/// `POST /admin/assistants/models`: what a provider offers, as JSON (#109).
7182×
pub async fn assistant_models(
7192×
    State(app): State<Shared>,
7202×
    viewer: Viewer,
7212×
    Form(f): Form<super::assistants::ModelsForm>,
7222×
) -> Result<axum::Json<serde_json::Value>, Error> {
7232×
    let shell = Shell::new(&app, "/admin", &viewer);
7242×
    require_admin(&viewer, &shell)?;
7252×
    csrf(&viewer, &f.csrf_token, &shell)?;
7262×
    Ok(axum::Json(super::assistants::models(&app, &site_assistants(), f).await.map_err(|e| Error::from_db(shell.clone(), e))?))
7272×
}