OXYGENHUB

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

214 of 222 lines run, 26 of 64 functions · run #505 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 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
2611×
async fn bookmarks_page(
2711×
    app: &Shared,
2811×
    shell: Shell,
2911×
    repo: crate::repos::RepoName,
3011×
    row: db::repos::RepoRow,
3111×
    role: Role,
3211×
    notice: Option<String>,
3311×
    error: Option<String>,
3411×
) -> Result<Page<BookmarksPage>, Error> {
3511×
    let default = row.default_bookmark.clone();
3611×
    let bookmarks =
3711×
        app.repos.read(&repo, move |r, cache| view::bookmarks(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
3811×
    let can_delete = shell.user.is_some() && role >= Role::Write;
3911×
    let can_run = super::flow::why_not_run(crate::flow::enabled(app, &row), shell.user.is_some(), role).is_none();
4011×
    Ok(Page(BookmarksPage {
4111×
        shell,
4211×
        repo: RepoShell::new(app, &row, "bookmarks").with_role(role),
4311×
        bookmarks,
4411×
        can_delete,
4511×
        can_run,
4611×
        notice,
4711×
        error,
4811×
    }))
4911×
}
50
517×
pub async fn bookmarks(
527×
    State(app): State<Shared>,
537×
    viewer: Viewer,
547×
    Path((owner, name)): Path<(String, String)>,
557×
) -> Result<Page<BookmarksPage>, Error> {
567×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
577×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
587×
    bookmarks_page(&app, shell, repo, row, role, None, None).await
597×
}
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(Template)]
145
#[template(path = "tags.html")]
146
pub struct TagsPage {
147
    shell: Shell,
148
    repo: RepoShell,
149
    tags: Vec<view::TagView>,
150
    withdrawn: Vec<view::WithdrawnView>,
151
    /// Tags a release uses (not withdrawn while it does).
152
    released: Vec<String>,
153
    can_create: bool,
154
    can_withdraw: bool,
155
    notice: Option<String>,
156
    error: Option<String>,
157
}
158
159
impl TagsPage {
16025×
    fn released(&self, tag: &str) -> bool {
16125×
        self.released.iter().any(|t| t == tag)
16225×
    }
163
}
164
1659×
async fn tags_page(
1669×
    app: &Shared,
1679×
    shell: Shell,
1689×
    repo: crate::repos::RepoName,
1699×
    row: db::repos::RepoRow,
1709×
    role: Role,
1719×
    notice: Option<String>,
1729×
    error: Option<String>,
1739×
) -> Result<Page<TagsPage>, Error> {
1749×
    let (tags, withdrawn) = app
1759×
        .repos
1769×
        .read(&repo, |r, _| Ok((view::tags(r)?, view::withdrawn_tags(r)?)))
1779×
        .await
1789×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
1799×
    let released = db::releases::list(&app.db, row.id).await.unwrap_or_default().into_iter().map(|r| r.tag).collect();
1809×
    let signed_in = shell.user.is_some();
181
    Ok(Page(TagsPage {
1829×
        shell,
1839×
        repo: RepoShell::new(app, &row, "tags").with_role(role),
1849×
        tags,
1859×
        withdrawn,
1869×
        released,
1879×
        can_create: signed_in && role >= Role::Write,
1889×
        can_withdraw: signed_in && role >= Role::Maintain,
1899×
        notice,
1909×
        error,
191
    }))
1929×
}
193
1943×
pub async fn tags(State(app): State<Shared>, viewer: Viewer, Path((owner, name)): Path<(String, String)>) -> Result<Page<TagsPage>, Error> {
1953×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
1963×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1973×
    tags_page(&app, shell, repo, row, role, None, None).await
1983×
}
199
200
#[derive(Deserialize)]
201
pub struct CreateTagForm {
202
    #[serde(rename = "_csrf")]
203
    csrf_token: String,
204
    name: String,
205
    #[serde(default)]
206
    target: String,
207
    #[serde(default)]
208
    message: String,
209
}
210
211
/// Create a tag from the web (#295): signed by the hub key as the user's
212
/// delegate, under the policy, as `oxy tag create` and a push would be.
2134×
pub async fn create_tag(
2144×
    State(app): State<Shared>,
2154×
    viewer: Viewer,
2164×
    Path((owner, name)): Path<(String, String)>,
2174×
    Form(f): Form<CreateTagForm>,
2184×
) -> Result<Page<TagsPage>, Error> {
2194×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
2204×
    let me = require(&viewer, &shell)?;
2214×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
2224×
    csrf(&viewer, &f.csrf_token, &shell)?;
2234×
    match crate::tags::create(&app, &row, &repo, &me.account, &f.name, &f.target, &f.message).await {
2242×
        Ok(t) => {
2252×
            let notice = format!(
226
                "Tagged {} ({} head{}). Start a release from it under Releases.",
227
                t.name,
2282×
                t.heads.len(),
2292×
                if t.heads.len() == 1 { "" } else { "s" }
230
            );
2312×
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
232
        }
2332×
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not create the tag: {e}"))).await,
234
    }
2354×
}
236
237
#[derive(Deserialize)]
238
pub struct WithdrawTagForm {
239
    #[serde(rename = "_csrf")]
240
    csrf_token: String,
241
    tag: String,
242
    #[serde(default)]
243
    reason: String,
244
}
245
246
/// Withdraw a tag from the web (#301), as `oxy push --delete tags/NAME`
247
/// does: a signed withdrawal, kept and logged. Maintainers only; never
248
/// while a release uses the tag.
2492×
pub async fn withdraw_tag(
2502×
    State(app): State<Shared>,
2512×
    viewer: Viewer,
2522×
    Path((owner, name)): Path<(String, String)>,
2532×
    Form(f): Form<WithdrawTagForm>,
2542×
) -> Result<Page<TagsPage>, Error> {
2552×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
2562×
    let me = require(&viewer, &shell)?;
2572×
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?;
2582×
    csrf(&viewer, &f.csrf_token, &shell)?;
2592×
    match crate::tags::withdraw(&app, &row, &repo, &me.account, &f.tag, &f.reason).await {
2601×
        Ok(t) => {
2611×
            let notice = format!("Withdrew {}. Clones drop it on their next fetch; the name is not used again.", t.name);
2621×
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
263
        }
2641×
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not withdraw {}: {e}", f.tag.trim()))).await,
265
    }
2662×
}
267
268
#[derive(Template)]
269
#[template(path = "conflicts.html")]
270
pub struct ConflictsPage {
271
    shell: Shell,
272
    repo: RepoShell,
273
    conflicts: Vec<view::ConflictView>,
274
}
275
2768×
pub async fn conflicts(
2778×
    State(app): State<Shared>,
2788×
    viewer: Viewer,
2798×
    Path((owner, name)): Path<(String, String)>,
2808×
) -> Result<Page<ConflictsPage>, Error> {
2818×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/conflicts"), &viewer);
2828×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
2838×
    let conflicts = app.repos.read(&repo, view::conflicts).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
2848×
    Ok(Page(ConflictsPage { shell, repo: RepoShell::new(&app, &row, "conflicts").with_role(role).with_sky(&app, &row).await, conflicts }))
2858×
}
286
287
#[derive(Template)]
288
#[template(path = "trust.html")]
289
pub struct TrustPage {
290
    shell: Shell,
291
    repo: RepoShell,
292
    t: view::Trust,
293
}
294
2952×
pub async fn trust(
2962×
    State(app): State<Shared>,
2972×
    viewer: Viewer,
2982×
    Path((owner, name)): Path<(String, String)>,
2992×
) -> Result<Page<TrustPage>, Error> {
3002×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/trust"), &viewer);
3012×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
3022×
    let key = app.hub_key.key;
3032×
    let t = app.repos.read(&repo, move |r, cache| view::trust(r, cache, &key)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
3042×
    Ok(Page(TrustPage { shell, repo: RepoShell::new(&app, &row, "trust").with_role(role), t }))
3052×
}
306
307
#[derive(Template)]
308
#[template(path = "pushes.html")]
309
pub struct PushesPage {
310
    shell: Shell,
311
    repo: RepoShell,
312
    pushes: Vec<db::repos::PushRow>,
313
}
314
3156×
pub async fn pushes(
3166×
    State(app): State<Shared>,
3176×
    viewer: Viewer,
3186×
    Path((owner, name)): Path<(String, String)>,
3196×
) -> Result<Page<PushesPage>, Error> {
3206×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/pushes"), &viewer);
3216×
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
3226×
    let pushes = db::repos::pushes(&app.db, row.id, 200).await.map_err(|e| Error::from_db(shell.clone(), e))?;
3236×
    Ok(Page(PushesPage { shell, repo: RepoShell::new(&app, &row, "pushes").with_role(role), pushes }))
3246×
}