OXYGENHUB

Coverage / crates/hub/src/web/refs.rs 93.7%

298 of 318 lines run, 33 of 86 functions · run #507 on main · run missed

1
//! Bookmarks, tags, conflicts, trust and pushes pages.
2
3
use super::settings::{csrf, require};
4
use super::{filters, lookup, lookup_role, Error, Page, RepoShell, Shell};
5
use crate::auth::{Access, Role, Viewer};
6
use crate::repos::view;
7
use crate::{db, Shared};
8
use askama::Template;
9
use axum::extract::{Form, Path, State};
10
use serde::Deserialize;
11
12
#[derive(Template)]
13
#[template(path = "bookmarks.html")]
14
pub struct BookmarksPage {
15
    shell: Shell,
16
    repo: RepoShell,
17
    bookmarks: Vec<view::BookmarkView>,
18
    /// Whether the viewer may create and delete bookmarks (write access).
19
    can_delete: bool,
20
    /// Whether the viewer may run the pipeline of a bookmark.
21
    can_run: bool,
22
    notice: Option<String>,
23
    error: Option<String>,
24
}
25
2616×
async fn bookmarks_page(
2716×
    app: &Shared,
2816×
    shell: Shell,
2916×
    repo: crate::repos::RepoName,
3016×
    row: db::repos::RepoRow,
3116×
    role: Role,
3216×
    notice: Option<String>,
3316×
    error: Option<String>,
3416×
) -> Result<Page<BookmarksPage>, Error> {
3516×
    let default = row.default_bookmark.clone();
3616×
    let bookmarks =
3716×
        app.repos.read(&repo, move |r, cache| view::bookmarks(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
3816×
    let can_delete = shell.user.is_some() && role >= Role::Write;
3916×
    let can_run = super::flow::why_not_run(crate::flow::enabled(app, &row), shell.user.is_some(), role).is_none();
4016×
    Ok(Page(BookmarksPage {
4116×
        shell,
4216×
        repo: RepoShell::new(app, &row, "bookmarks").with_role(role),
4316×
        bookmarks,
4416×
        can_delete,
4516×
        can_run,
4616×
        notice,
4716×
        error,
4816×
    }))
4916×
}
50
518×
pub async fn bookmarks(
528×
    State(app): State<Shared>,
538×
    viewer: Viewer,
548×
    Path((owner, name)): Path<(String, String)>,
558×
) -> Result<Page<BookmarksPage>, Error> {
568×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
578×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
588×
    bookmarks_page(&app, shell, repo, row, role, None, None).await
598×
}
60
61
#[derive(Deserialize)]
62
pub struct DeleteBookmarkForm {
63
    #[serde(rename = "_csrf")]
64
    csrf_token: String,
65
    bookmark: String,
66
}
67
68
/// Delete a bookmark from the web (hub spec §6.4): what `oxy push --delete`
69
/// does, through the same checks. Never the default bookmark; refused under
70
/// a trust policy, which needs a signed attestation only a client can make.
715×
pub async fn delete_bookmark(
725×
    State(app): State<Shared>,
735×
    viewer: Viewer,
745×
    Path((owner, name)): Path<(String, String)>,
755×
    Form(f): Form<DeleteBookmarkForm>,
765×
) -> Result<Page<BookmarksPage>, Error> {
775×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
785×
    let me = require(&viewer, &shell)?;
794×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
804×
    csrf(&viewer, &f.csrf_token, &shell)?;
814×
    let bookmark = f.bookmark.trim().to_string();
824×
    if bookmark == row.default_bookmark {
831×
        let msg = format!("{bookmark} is the default bookmark; choose another default in Settings first.");
841×
        return bookmarks_page(&app, shell, repo, row, role, None, Some(msg)).await;
853×
    }
863×
    let target = bookmark.clone();
873×
    let outcome = app
883×
        .repos
893×
        .write(&repo, move |r, _| {
903×
            let Some(state) = r.view()?.bookmarks.get(&target).copied() else {
911×
                return Ok(Err(format!("There is no bookmark {target}.")));
92
            };
932×
            let update = oxy_core::protocol::RefUpdate {
942×
                name: target.clone(),
952×
                old_state: state,
962×
                new_state: oxy_core::hash::ObjectRef::ZERO,
972×
                force: true,
982×
                attestation: None,
992×
            };
1002×
            let report = r.receive_push_report(Default::default(), vec![update], None, vec![])?;
1012×
            Ok(match report.results.first() {
1022×
                Some(res) if res.ok => Ok(state.to_hex()),
1030×
                Some(res) => Err(res.reason.clone()),
1040×
                None => Err("nothing happened".into()),
105
            })
1063×
        })
1073×
        .await
1083×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
1093×
    let old_state = match outcome {
1102×
        Ok(s) => s,
1111×
        Err(msg) => return bookmarks_page(&app, shell, repo, row, role, None, Some(format!("Could not delete {bookmark}: {msg}"))).await,
112
    };
1132×
    let result = db::repos::PushOutcome {
1142×
        reference: bookmark.clone(),
1152×
        ok: true,
1162×
        reason: "deleted on the web".into(),
1172×
        old_state: old_state.clone(),
1182×
        new_state: oxy_core::hash::ObjectRef::ZERO.to_hex(),
1192×
        heads: 0,
1202×
        changes: 0,
1212×
    };
1222×
    db::repos::record_push(&app.db, row.id, Some((me.account.id, &me.account.username)), &[result]).await.ok();
1232×
    crate::hooks::emit(
1242×
        &app,
1252×
        &row,
1262×
        "push",
1272×
        &me.account.username,
1282×
        serde_json::json!({ "updates": [{ "reference": bookmark, "old_state": old_state, "new_state": oxy_core::hash::ObjectRef::ZERO.to_hex(), "heads": 0, "changes": 0, "deleted": true }], "via": "web" }),
1292×
    )
1302×
    .await;
1312×
    db::accounts::audit(&app.db, Some(&me.account), "bookmark.deleted", &format!("{owner}/{name}"), &bookmark).await.ok();
1322×
    bookmarks_page(
1332×
        &app,
1342×
        shell,
1352×
        repo,
1362×
        row,
1372×
        role,
1382×
        Some(format!("Deleted {bookmark}. Its changes stay while anything else reaches them.")),
1392×
        None,
1402×
    )
1412×
    .await
1425×
}
143
144
#[derive(Deserialize)]
145
pub struct CreateBookmarkForm {
146
    #[serde(rename = "_csrf")]
147
    csrf_token: String,
148
    name: String,
149
    /// A bookmark, tag or change; the default bookmark when empty.
150
    #[serde(default)]
151
    from: String,
152
}
153
154
/// Create a bookmark from the web at the heads of a bookmark, tag or change:
155
/// what pushing a new bookmark does, signed by the hub key as the user's
156
/// delegate, as the web's other changes to bookmarks are.
1574×
pub async fn create_bookmark(
1584×
    State(app): State<Shared>,
1594×
    viewer: Viewer,
1604×
    Path((owner, name)): Path<(String, String)>,
1614×
    Form(f): Form<CreateBookmarkForm>,
1624×
) -> Result<Page<BookmarksPage>, Error> {
1634×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
1644×
    let me = require(&viewer, &shell)?;
1654×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
1664×
    csrf(&viewer, &f.csrf_token, &shell)?;
1674×
    let bookmark = f.name.trim().to_string();
1684×
    let from = match f.from.trim() {
1694×
        "" => row.default_bookmark.clone(),
1703×
        s => s.to_string(),
171
    };
1724×
    if bookmark.is_empty() || bookmark.chars().any(char::is_whitespace) {
1731×
        return bookmarks_page(&app, shell, repo, row, role, None, Some("A bookmark's name has no spaces.".into())).await;
1743×
    }
1753×
    let (wanted, spec) = (bookmark.clone(), from.clone());
1763×
    let found = app
1773×
        .repos
1783×
        .read(&repo, move |r, cache| {
1793×
            if r.view()?.bookmarks.contains_key(&wanted) {
1801×
                return Ok(Err(format!("{wanted} is a bookmark already.")));
1812×
            }
1822×
            Ok(view::resolve(r, cache, &spec).map(|t| t.heads).map_err(|e| e.to_string()))
1833×
        })
1843×
        .await
1853×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
1861×
    let heads = match found {
1871×
        Ok(heads) if !heads.is_empty() => heads,
1880×
        Ok(_) => return bookmarks_page(&app, shell, repo, row, role, None, Some(format!("{from} holds no changes to start from."))).await,
1892×
        Err(msg) => return bookmarks_page(&app, shell, repo, row, role, None, Some(msg)).await,
190
    };
191
    // As the user's delegate when they have one; otherwise unsigned, which
192
    // a repository without a trust policy takes, as a push without one.
1931×
    let made = match super::edit::signer_for(&app, me.account.id).await {
1940×
        Ok(signer) => crate::repos::edits::move_bookmark(&app.repos, &repo, bookmark.clone(), heads.clone(), signer)
1950×
            .await
1960×
            .map(|_| ())
1970×
            .map_err(|e| e.to_string()),
1981×
        Err(why) => {
1991×
            let (target, at) = (bookmark.clone(), heads.clone());
2001×
            let unsigned = app
2011×
                .repos
2021×
                .write(&repo, move |r, _| {
2031×
                    let update = r.host_ref_update(&target, &at, None)?;
2041×
                    let report = r.receive_push_report(Default::default(), vec![update], None, vec![])?;
2051×
                    Ok(match report.results.first() {
2061×
                        Some(res) if res.ok => Ok(()),
2070×
                        Some(res) => Err(res.reason.clone()),
2080×
                        None => Err("nothing happened".to_string()),
209
                    })
2101×
                })
2111×
                .await
2121×
                .map_err(|e| e.to_string())
2131×
                .and_then(|r| r);
2141×
            unsigned.map_err(|refused| format!("{refused}. {why}"))
215
        }
216
    };
2171×
    if let Err(e) = made {
2180×
        return bookmarks_page(&app, shell, repo, row, role, None, Some(format!("Could not create {bookmark}: {e}"))).await;
2191×
    }
2201×
    let made = bookmark.clone();
2211×
    let new_state = app
2221×
        .repos
2231×
        .read(&repo, move |r, _| Ok(r.view()?.bookmarks.get(&made).map(|s| s.to_hex()).unwrap_or_default()))
2241×
        .await
2251×
        .unwrap_or_default();
2261×
    let result = db::repos::PushOutcome {
2271×
        reference: bookmark.clone(),
2281×
        ok: true,
2291×
        reason: format!("created on the web from {from}"),
2301×
        old_state: oxy_core::hash::ObjectRef::ZERO.to_hex(),
2311×
        new_state: new_state.clone(),
2321×
        heads: heads.len() as i64,
2331×
        changes: 0,
2341×
    };
2351×
    db::repos::record_push(&app.db, row.id, Some((me.account.id, &me.account.username)), &[result]).await.ok();
2361×
    crate::hooks::emit(
2371×
        &app,
2381×
        &row,
2391×
        "push",
2401×
        &me.account.username,
2411×
        serde_json::json!({ "updates": [{ "reference": bookmark, "old_state": oxy_core::hash::ObjectRef::ZERO.to_hex(), "new_state": new_state, "heads": heads.len(), "changes": 0, "created": true }], "via": "web" }),
2421×
    )
2431×
    .await;
2441×
    db::accounts::audit(&app.db, Some(&me.account), "bookmark.created", &format!("{owner}/{name}"), &format!("{bookmark} from {from}"))
2451×
        .await
2461×
        .ok();
2471×
    let notice = format!("Created {bookmark} from {from}. Propose changes into it, or make it the default in Settings.");
2481×
    bookmarks_page(&app, shell, repo, row, role, Some(notice), None).await
2494×
}
250
251
#[derive(Template)]
252
#[template(path = "tags.html")]
253
pub struct TagsPage {
254
    shell: Shell,
255
    repo: RepoShell,
256
    tags: Vec<view::TagView>,
257
    withdrawn: Vec<view::WithdrawnView>,
258
    /// Tags a release uses (not withdrawn while it does).
259
    released: Vec<String>,
260
    can_create: bool,
261
    can_withdraw: bool,
262
    notice: Option<String>,
263
    error: Option<String>,
264
}
265
266
impl TagsPage {
26725×
    fn released(&self, tag: &str) -> bool {
26825×
        self.released.iter().any(|t| t == tag)
26925×
    }
270
}
271
2729×
async fn tags_page(
2739×
    app: &Shared,
2749×
    shell: Shell,
2759×
    repo: crate::repos::RepoName,
2769×
    row: db::repos::RepoRow,
2779×
    role: Role,
2789×
    notice: Option<String>,
2799×
    error: Option<String>,
2809×
) -> Result<Page<TagsPage>, Error> {
2819×
    let (tags, withdrawn) = app
2829×
        .repos
2839×
        .read(&repo, |r, _| Ok((view::tags(r)?, view::withdrawn_tags(r)?)))
2849×
        .await
2859×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
2869×
    let released = db::releases::list(&app.db, row.id).await.unwrap_or_default().into_iter().map(|r| r.tag).collect();
2879×
    let signed_in = shell.user.is_some();
288
    Ok(Page(TagsPage {
2899×
        shell,
2909×
        repo: RepoShell::new(app, &row, "tags").with_role(role),
2919×
        tags,
2929×
        withdrawn,
2939×
        released,
2949×
        can_create: signed_in && role >= Role::Write,
2959×
        can_withdraw: signed_in && role >= Role::Maintain,
2969×
        notice,
2979×
        error,
298
    }))
2999×
}
300
3013×
pub async fn tags(State(app): State<Shared>, viewer: Viewer, Path((owner, name)): Path<(String, String)>) -> Result<Page<TagsPage>, Error> {
3023×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
3033×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
3043×
    tags_page(&app, shell, repo, row, role, None, None).await
3053×
}
306
307
#[derive(Deserialize)]
308
pub struct CreateTagForm {
309
    #[serde(rename = "_csrf")]
310
    csrf_token: String,
311
    name: String,
312
    #[serde(default)]
313
    target: String,
314
    #[serde(default)]
315
    message: String,
316
}
317
318
/// Create a tag from the web (#295): signed by the hub key as the user's
319
/// delegate, under the policy, as `oxy tag create` and a push would be.
3204×
pub async fn create_tag(
3214×
    State(app): State<Shared>,
3224×
    viewer: Viewer,
3234×
    Path((owner, name)): Path<(String, String)>,
3244×
    Form(f): Form<CreateTagForm>,
3254×
) -> Result<Page<TagsPage>, Error> {
3264×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
3274×
    let me = require(&viewer, &shell)?;
3284×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
3294×
    csrf(&viewer, &f.csrf_token, &shell)?;
3304×
    match crate::tags::create(&app, &row, &repo, &me.account, &f.name, &f.target, &f.message).await {
3312×
        Ok(t) => {
3322×
            let notice = format!(
333
                "Tagged {} ({} head{}). Start a release from it under Releases.",
334
                t.name,
3352×
                t.heads.len(),
3362×
                if t.heads.len() == 1 { "" } else { "s" }
337
            );
3382×
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
339
        }
3402×
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not create the tag: {e}"))).await,
341
    }
3424×
}
343
344
#[derive(Deserialize)]
345
pub struct WithdrawTagForm {
346
    #[serde(rename = "_csrf")]
347
    csrf_token: String,
348
    tag: String,
349
    #[serde(default)]
350
    reason: String,
351
}
352
353
/// Withdraw a tag from the web (#301), as `oxy push --delete tags/NAME`
354
/// does: a signed withdrawal, kept and logged. Maintainers only; never
355
/// while a release uses the tag.
3562×
pub async fn withdraw_tag(
3572×
    State(app): State<Shared>,
3582×
    viewer: Viewer,
3592×
    Path((owner, name)): Path<(String, String)>,
3602×
    Form(f): Form<WithdrawTagForm>,
3612×
) -> Result<Page<TagsPage>, Error> {
3622×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
3632×
    let me = require(&viewer, &shell)?;
3642×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?;
3652×
    csrf(&viewer, &f.csrf_token, &shell)?;
3662×
    match crate::tags::withdraw(&app, &row, &repo, &me.account, &f.tag, &f.reason).await {
3671×
        Ok(t) => {
3681×
            let notice = format!("Withdrew {}. Clones drop it on their next fetch; the name is not used again.", t.name);
3691×
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
370
        }
3711×
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not withdraw {}: {e}", f.tag.trim()))).await,
372
    }
3732×
}
374
375
#[derive(Template)]
376
#[template(path = "conflicts.html")]
377
pub struct ConflictsPage {
378
    shell: Shell,
379
    repo: RepoShell,
380
    conflicts: Vec<view::ConflictView>,
381
}
382
3838×
pub async fn conflicts(
3848×
    State(app): State<Shared>,
3858×
    viewer: Viewer,
3868×
    Path((owner, name)): Path<(String, String)>,
3878×
) -> Result<Page<ConflictsPage>, Error> {
3888×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/conflicts"), &viewer);
3898×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
3908×
    let conflicts = app.repos.read(&repo, view::conflicts).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
3918×
    Ok(Page(ConflictsPage { shell, repo: RepoShell::new(&app, &row, "conflicts").with_role(role).with_sky(&app, &row).await, conflicts }))
3928×
}
393
394
#[derive(Template)]
395
#[template(path = "trust.html")]
396
pub struct TrustPage {
397
    shell: Shell,
398
    repo: RepoShell,
399
    t: view::Trust,
400
}
401
4022×
pub async fn trust(
4032×
    State(app): State<Shared>,
4042×
    viewer: Viewer,
4052×
    Path((owner, name)): Path<(String, String)>,
4062×
) -> Result<Page<TrustPage>, Error> {
4072×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/trust"), &viewer);
4082×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
4092×
    let key = app.hub_key.key;
4102×
    let t = app.repos.read(&repo, move |r, cache| view::trust(r, cache, &key)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
4112×
    Ok(Page(TrustPage { shell, repo: RepoShell::new(&app, &row, "trust").with_role(role), t }))
4122×
}
413
414
#[derive(Template)]
415
#[template(path = "pushes.html")]
416
pub struct PushesPage {
417
    shell: Shell,
418
    repo: RepoShell,
419
    pushes: Vec<db::repos::PushRow>,
420
}
421
4226×
pub async fn pushes(
4236×
    State(app): State<Shared>,
4246×
    viewer: Viewer,
4256×
    Path((owner, name)): Path<(String, String)>,
4266×
) -> Result<Page<PushesPage>, Error> {
4276×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/pushes"), &viewer);
4286×
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
4296×
    let pushes = db::repos::pushes(&app.db, row.id, 200).await.map_err(|e| Error::from_db(shell.clone(), e))?;
4306×
    Ok(Page(PushesPage { shell, repo: RepoShell::new(&app, &row, "pushes").with_role(role), pushes }))
4316×
}