OXYGENHUB
# c4bffee5b0d4 oxygenhub / crates / hub / src / web / refs.rs
11.6 KiB · Rust · last changed Create and withdraw tags on the website (closes #295, closes #301) 12 days ago source blame history raw
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
26
async fn bookmarks_page(
27
    app: &Shared,
28
    shell: Shell,
29
    repo: crate::repos::RepoName,
30
    row: db::repos::RepoRow,
31
    role: Role,
32
    notice: Option<String>,
33
    error: Option<String>,
34
) -> Result<Page<BookmarksPage>, Error> {
35
    let default = row.default_bookmark.clone();
36
    let bookmarks =
37
        app.repos.read(&repo, move |r, cache| view::bookmarks(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
38
    let can_delete = shell.user.is_some() && role >= Role::Write;
39
    let can_run = super::flow::why_not_run(crate::flow::enabled(app, &row), shell.user.is_some(), role).is_none();
40
    Ok(Page(BookmarksPage {
41
        shell,
42
        repo: RepoShell::new(app, &row, "bookmarks").with_role(role),
43
        bookmarks,
44
        can_delete,
45
        can_run,
46
        notice,
47
        error,
48
    }))
49
}
50
51
pub async fn bookmarks(
52
    State(app): State<Shared>,
53
    viewer: Viewer,
54
    Path((owner, name)): Path<(String, String)>,
55
) -> Result<Page<BookmarksPage>, Error> {
56
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
57
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
58
    bookmarks_page(&app, shell, repo, row, role, None, None).await
59
}
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.
71
pub async fn delete_bookmark(
72
    State(app): State<Shared>,
73
    viewer: Viewer,
74
    Path((owner, name)): Path<(String, String)>,
75
    Form(f): Form<DeleteBookmarkForm>,
76
) -> Result<Page<BookmarksPage>, Error> {
77
    let shell = Shell::new(&app, &format!("/{owner}/{name}/bookmarks"), &viewer);
78
    let me = require(&viewer, &shell)?;
79
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
80
    csrf(&viewer, &f.csrf_token, &shell)?;
81
    let bookmark = f.bookmark.trim().to_string();
82
    if bookmark == row.default_bookmark {
83
        let msg = format!("{bookmark} is the default bookmark; choose another default in Settings first.");
84
        return bookmarks_page(&app, shell, repo, row, role, None, Some(msg)).await;
85
    }
86
    let target = bookmark.clone();
87
    let outcome = app
88
        .repos
89
        .write(&repo, move |r, _| {
90
            let Some(state) = r.view()?.bookmarks.get(&target).copied() else {
91
                return Ok(Err(format!("There is no bookmark {target}.")));
92
            };
93
            let update = oxy_core::protocol::RefUpdate {
94
                name: target.clone(),
95
                old_state: state,
96
                new_state: oxy_core::hash::ObjectRef::ZERO,
97
                force: true,
98
                attestation: None,
99
            };
100
            let report = r.receive_push_report(Default::default(), vec![update], None, vec![])?;
101
            Ok(match report.results.first() {
102
                Some(res) if res.ok => Ok(state.to_hex()),
103
                Some(res) => Err(res.reason.clone()),
104
                None => Err("nothing happened".into()),
105
            })
106
        })
107
        .await
108
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
109
    let old_state = match outcome {
110
        Ok(s) => s,
111
        Err(msg) => return bookmarks_page(&app, shell, repo, row, role, None, Some(format!("Could not delete {bookmark}: {msg}"))).await,
112
    };
113
    let result = db::repos::PushOutcome {
114
        reference: bookmark.clone(),
115
        ok: true,
116
        reason: "deleted on the web".into(),
117
        old_state: old_state.clone(),
118
        new_state: oxy_core::hash::ObjectRef::ZERO.to_hex(),
119
        heads: 0,
120
        changes: 0,
121
    };
122
    db::repos::record_push(&app.db, row.id, Some((me.account.id, &me.account.username)), &[result]).await.ok();
123
    crate::hooks::emit(
124
        &app,
125
        &row,
126
        "push",
127
        &me.account.username,
128
        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" }),
129
    )
130
    .await;
131
    db::accounts::audit(&app.db, Some(&me.account), "bookmark.deleted", &format!("{owner}/{name}"), &bookmark).await.ok();
132
    bookmarks_page(
133
        &app,
134
        shell,
135
        repo,
136
        row,
137
        role,
138
        Some(format!("Deleted {bookmark}. Its changes stay while anything else reaches them.")),
139
        None,
140
    )
141
    .await
142
}
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 {
160
    fn released(&self, tag: &str) -> bool {
161
        self.released.iter().any(|t| t == tag)
162
    }
163
}
164
165
async fn tags_page(
166
    app: &Shared,
167
    shell: Shell,
168
    repo: crate::repos::RepoName,
169
    row: db::repos::RepoRow,
170
    role: Role,
171
    notice: Option<String>,
172
    error: Option<String>,
173
) -> Result<Page<TagsPage>, Error> {
174
    let (tags, withdrawn) = app
175
        .repos
176
        .read(&repo, |r, _| Ok((view::tags(r)?, view::withdrawn_tags(r)?)))
177
        .await
178
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
179
    let released = db::releases::list(&app.db, row.id).await.unwrap_or_default().into_iter().map(|r| r.tag).collect();
180
    let signed_in = shell.user.is_some();
181
    Ok(Page(TagsPage {
182
        shell,
183
        repo: RepoShell::new(app, &row, "tags").with_role(role),
184
        tags,
185
        withdrawn,
186
        released,
187
        can_create: signed_in && role >= Role::Write,
188
        can_withdraw: signed_in && role >= Role::Maintain,
189
        notice,
190
        error,
191
    }))
192
}
193
194
pub async fn tags(State(app): State<Shared>, viewer: Viewer, Path((owner, name)): Path<(String, String)>) -> Result<Page<TagsPage>, Error> {
195
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
196
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
197
    tags_page(&app, shell, repo, row, role, None, None).await
198
}
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.
213
pub async fn create_tag(
214
    State(app): State<Shared>,
215
    viewer: Viewer,
216
    Path((owner, name)): Path<(String, String)>,
217
    Form(f): Form<CreateTagForm>,
218
) -> Result<Page<TagsPage>, Error> {
219
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
220
    let me = require(&viewer, &shell)?;
221
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
222
    csrf(&viewer, &f.csrf_token, &shell)?;
223
    match crate::tags::create(&app, &row, &repo, &me.account, &f.name, &f.target, &f.message).await {
224
        Ok(t) => {
225
            let notice = format!(
226
                "Tagged {} ({} head{}). Start a release from it under Releases.",
227
                t.name,
228
                t.heads.len(),
229
                if t.heads.len() == 1 { "" } else { "s" }
230
            );
231
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
232
        }
233
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not create the tag: {e}"))).await,
234
    }
235
}
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.
249
pub async fn withdraw_tag(
250
    State(app): State<Shared>,
251
    viewer: Viewer,
252
    Path((owner, name)): Path<(String, String)>,
253
    Form(f): Form<WithdrawTagForm>,
254
) -> Result<Page<TagsPage>, Error> {
255
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tags"), &viewer);
256
    let me = require(&viewer, &shell)?;
257
    let (repo, row, role) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?;
258
    csrf(&viewer, &f.csrf_token, &shell)?;
259
    match crate::tags::withdraw(&app, &row, &repo, &me.account, &f.tag, &f.reason).await {
260
        Ok(t) => {
261
            let notice = format!("Withdrew {}. Clones drop it on their next fetch; the name is not used again.", t.name);
262
            tags_page(&app, shell, repo, row, role, Some(notice), None).await
263
        }
264
        Err(e) => tags_page(&app, shell, repo, row, role, None, Some(format!("Could not withdraw {}: {e}", f.tag.trim()))).await,
265
    }
266
}
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
276
pub async fn conflicts(
277
    State(app): State<Shared>,
278
    viewer: Viewer,
279
    Path((owner, name)): Path<(String, String)>,
280
) -> Result<Page<ConflictsPage>, Error> {
281
    let shell = Shell::new(&app, &format!("/{owner}/{name}/conflicts"), &viewer);
282
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
283
    let conflicts = app.repos.read(&repo, view::conflicts).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
284
    Ok(Page(ConflictsPage { shell, repo: RepoShell::new(&app, &row, "conflicts").with_role(role).with_sky(&app, &row).await, conflicts }))
285
}
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
295
pub async fn trust(
296
    State(app): State<Shared>,
297
    viewer: Viewer,
298
    Path((owner, name)): Path<(String, String)>,
299
) -> Result<Page<TrustPage>, Error> {
300
    let shell = Shell::new(&app, &format!("/{owner}/{name}/trust"), &viewer);
301
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
302
    let key = app.hub_key.key;
303
    let t = app.repos.read(&repo, move |r, cache| view::trust(r, cache, &key)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
304
    Ok(Page(TrustPage { shell, repo: RepoShell::new(&app, &row, "trust").with_role(role), t }))
305
}
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
315
pub async fn pushes(
316
    State(app): State<Shared>,
317
    viewer: Viewer,
318
    Path((owner, name)): Path<(String, String)>,
319
) -> Result<Page<PushesPage>, Error> {
320
    let shell = Shell::new(&app, &format!("/{owner}/{name}/pushes"), &viewer);
321
    let (_, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
322
    let pushes = db::repos::pushes(&app.db, row.id, 200).await.map_err(|e| Error::from_db(shell.clone(), e))?;
323
    Ok(Page(PushesPage { shell, repo: RepoShell::new(&app, &row, "pushes").with_role(role), pushes }))
324
}