OXYGENHUB
# a66c05a6a881 oxygenhub / crates / hub / src / web / mod.rs
45.1 KiB · Rust · last changed A mistyped address shows the not-found page (closes #294) 12 days ago source blame history raw
1
//! Pages (hub spec §6): the router, the shell every template extends, the
2
//! error page, viewer-aware lookups and askama filters. Handlers are thin:
3
//! they resolve names, call the view layer under the repository lock, and
4
//! render.
5
6
mod admin;
7
mod artifacts;
8
pub(crate) mod assistants;
9
mod avatar;
10
pub(crate) mod backups;
11
pub mod chain;
12
pub mod charts;
13
pub mod coverage;
14
mod device;
15
mod diffusion;
16
mod drops;
17
pub mod edit;
18
pub mod filters;
19
pub mod flow;
20
mod forks;
21
pub mod help;
22
pub mod history;
23
pub mod home;
24
pub mod icons;
25
mod insights;
26
mod live_stream;
27
mod security_txt;
28
mod transparency;
29
30
/// A state as people read it (oxygenhub#170): `02a6c9d4746a+… (14 heads)`
31
/// for heads joined by `+`, which can run to hundreds of characters; a
32
/// single head, or text that is not heads, unchanged.
33
pub fn state_label(text: &str) -> String {
34
    let parts: Vec<&str> = text.split('+').collect();
35
    let heads = parts.len() > 1 && parts.iter().all(|p| p.len() >= 7 && p.chars().all(|c| c.is_ascii_hexdigit()));
36
    if !heads {
37
        return text.to_string();
38
    }
39
    format!("{}+… ({} heads)", &parts[0][..12.min(parts[0].len())], parts.len())
40
}
41
mod inbox;
42
pub mod issues;
43
mod orgs;
44
pub mod projects;
45
pub mod proposals;
46
mod recovery;
47
mod refs;
48
pub mod release_trust;
49
pub mod releases;
50
mod repo;
51
mod repo_settings;
52
pub mod reports;
53
mod resolve;
54
pub mod runners;
55
mod secrets;
56
mod session;
57
pub(crate) mod settings;
58
mod signin;
59
mod statics;
60
pub mod test_reports;
61
mod variables;
62
mod webhooks;
63
mod wiki;
64
65
use crate::auth::{self, Access, Role, Viewer};
66
use crate::repos::RepoError;
67
use crate::{db, Shared};
68
use askama::Template;
69
use axum::extract::DefaultBodyLimit;
70
use axum::http::{header, StatusCode};
71
use axum::response::{Html, IntoResponse, Redirect, Response};
72
use axum::routing::{any, get, post};
73
use axum::Router;
74
use tower_http::compression::CompressionLayer;
75
use tower_http::trace::TraceLayer;
76
77
pub fn router(app: Shared) -> Router {
78
    let push_limit = app.config.limits.push_body_limit.0 as usize;
79
    Router::new()
80
        .route("/", get(home::index))
81
        .route("/explore", get(home::explore))
82
        .route("/avatar/agent/{name}", get(avatar::agent))
83
        .route("/avatar/{name}", get(avatar::avatar))
84
        .route("/health", get(home::health))
85
        .route("/about", get(home::about))
86
        .route("/.well-known/oxyhub-key", get(home::hub_key))
87
        .route("/metrics", get(crate::metrics::metrics))
88
        .route("/log", get(transparency::page))
89
        .route("/log/checkpoint", get(crate::tlog::checkpoint))
90
        .route("/log/witnesses", get(crate::tlog::witnesses))
91
        .route("/log/tile/{*path}", get(crate::tlog::tile))
92
        .route("/log/witness/add-checkpoint", axum::routing::post(crate::tlog::add_checkpoint))
93
        .route("/.well-known/oxyhub-ca.pem", get(home::hub_ca))
94
        .route("/.well-known/oxyhub-signing.pem", get(flow::signing_key))
95
        .route("/.well-known/openid-configuration", get(crate::oidc::discovery))
96
        .route("/.well-known/jwks.json", get(crate::oidc::jwks))
97
        .route("/live", get(live_stream::stream))
98
        .route("/.well-known/security.txt", get(security_txt::serve))
99
        .route("/security.txt", get(security_txt::serve))
100
        .route("/security-contact", get(security_txt::contact_page))
101
        .route("/style.css", get(statics::style))
102
        .route("/favicon.svg", get(statics::favicon))
103
        .route("/favicon.ico", get(statics::favicon))
104
        .route("/static/{*path}", get(statics::asset))
105
        .route("/login", get(session::login_form).post(session::login))
106
        .route("/device", get(device::form).post(device::answer))
107
        .route(crate::headers::REPORT_PATH, post(crate::headers::csp_report).layer(DefaultBodyLimit::max(16 * 1024)))
108
        .route("/logout", post(session::logout))
109
        .route("/register", get(session::register_form).post(session::register))
110
        .route("/settings", get(settings::profile).post(settings::update_profile))
111
        .route("/settings/password", post(settings::change_password))
112
        .route("/settings/appearance", post(settings::appearance))
113
        .route("/settings/security", get(settings::security))
114
        .route("/settings/security/totp/begin", post(settings::totp_begin))
115
        .route("/settings/security/totp/enable", post(settings::totp_enable))
116
        .route("/settings/security/totp/disable", post(settings::totp_disable))
117
        .route("/settings/security/sessions", post(settings::sessions_reset))
118
        .route("/settings/security/sessions/{id}/end", post(settings::session_end))
119
        .route("/settings/keys", get(settings::keys))
120
        .route("/settings/keys/upload", post(settings::keys_upload))
121
        .route("/settings/keys/verify", post(settings::keys_verify))
122
        .route("/settings/keys/unlink", post(settings::keys_unlink))
123
        .route("/settings/tokens", get(settings::tokens).post(settings::tokens_create))
124
        .route("/sky/arrivals", get(home::arrivals))
125
        .route("/settings/backups", get(backups::user).post(backups::user_save))
126
        .route("/settings/backups/run", post(backups::user_run))
127
        .route("/settings/backups/test", post(backups::user_test))
128
        .route("/orgs/{name}/settings/backups", get(backups::org).post(backups::org_save))
129
        .route("/orgs/{name}/settings/backups/run", post(backups::org_run))
130
        .route("/orgs/{name}/settings/backups/test", post(backups::org_test))
131
        .route("/settings/tokens/{id}/delete", post(settings::tokens_delete))
132
        .route("/settings/tokens/{id}/agent", post(settings::tokens_agent))
133
        .route("/new", get(repo_settings::new_form).post(repo_settings::create))
134
        .route("/orgs/new", get(orgs::new_form).post(orgs::create))
135
        .route("/orgs/{name}/settings", get(orgs::settings).post(orgs::update))
136
        .route("/orgs/{name}/settings/members", post(orgs::member))
137
        .route("/orgs/{name}/settings/teams", post(orgs::team))
138
        .route("/orgs/{name}/settings/hooks", post(orgs::hooks))
139
        .route("/orgs/{name}/settings/assistants", post(orgs::assistants))
140
        .route("/orgs/{name}/settings/assistants/models", post(orgs::assistant_models))
141
        .route("/orgs/{name}/settings/variables", post(orgs::variables))
142
        .route("/orgs/{name}/settings/secrets", post(orgs::secrets))
143
        .route("/orgs/{name}/settings/storage", post(orgs::storage))
144
        .route("/orgs/{name}/settings/runners/token", post(orgs::runner_token))
145
        .route("/orgs/{name}/settings/runners/{id}/remove", post(orgs::runner_remove))
146
        .route("/orgs/{name}/settings/hooks/{id}/deliveries", get(orgs::deliveries))
147
        .route("/orgs/{name}/settings/hooks/{id}/redeliver/{delivery}", post(orgs::redeliver))
148
        .route("/orgs/{name}/settings/avatar", post(orgs::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
149
        .route("/settings/avatar", post(settings::avatar).layer(DefaultBodyLimit::max(avatar::MAX_BYTES + (64 << 10))))
150
        .route("/notifications", get(inbox::inbox))
151
        .route("/notifications/read", post(inbox::mark_read))
152
        .route("/settings/notifications", get(inbox::unsubscribe).post(inbox::prefs))
153
        .route("/search", get(inbox::search))
154
        .route("/admin", get(admin::index))
155
        .route("/admin/accounts", get(admin::section))
156
        .route("/admin/organisations", get(admin::section))
157
        .route("/admin/audit", get(admin::section))
158
        .route("/admin/registration", get(admin::section).post(admin::set_mode))
159
        .route("/admin/invite", post(admin::invite))
160
        .route("/admin/account", post(admin::account))
161
        .route("/admin/storage", get(admin::storage).post(admin::maintain))
162
        .route("/admin/runners", get(runners::list))
163
        .route("/admin/runners/settings", get(runners::settings).post(runners::save_settings))
164
        .route("/admin/runners/priority", post(runners::save_priority))
165
        .route("/admin/runners/images", get(runners::images))
166
        .route("/admin/insights", get(insights::site))
167
        .route("/insights/{owner}", get(insights::owner))
168
        .route("/admin/diffusion", get(diffusion::admin))
169
        .route("/admin/backups", get(backups::admin))
170
        .route("/{owner}/{name}/diffusion", get(diffusion::page))
171
        .route("/admin/runners/token", post(runners::new_token))
172
        .route("/admin/runners/{id}", get(runners::show))
173
        .route("/admin/runners/{id}/state", post(runners::set_state))
174
        .route("/admin/runners/{id}/scope", post(runners::set_scope))
175
        .route("/admin/runners/{id}/limits", post(runners::set_limits))
176
        .route("/admin/mail", get(admin::section).post(admin::set_mail))
177
        .route("/admin/mail/test", post(admin::test_mail))
178
        .route("/admin/assistants", get(admin::section).post(admin::assistants))
179
        .route("/admin/assistants/models", post(admin::assistant_models))
180
        .route("/admin/signin", get(admin::section).post(admin::signin))
181
        .route("/admin/security", get(admin::section).post(security_txt::save))
182
        .route("/login/{provider}", get(signin::start))
183
        .route("/login/{provider}/callback", get(signin::callback))
184
        .route("/settings/security/connect/{provider}", get(signin::connect))
185
        .route("/settings/security/disconnect/{provider}", post(signin::disconnect))
186
        .route("/admin/variables", get(admin::section).post(admin::variables))
187
        .route("/admin/secrets", get(admin::section).post(admin::secrets))
188
        .route("/admin/runners/{id}/remove", post(runners::remove))
189
        .nest("/api/v1", crate::api::router(app.config.limits.asset_limit.0 as usize))
190
        // Drops (#279): `drops` is reserved, as an owner and as a repository name.
191
        .route("/drops", get(drops::mine))
192
        .route("/drops/new", get(drops::new_form).post(drops::create))
193
        .route("/{owner}/drops", get(drops::list))
194
        .route("/{owner}/drops/{id}", get(drops::show))
195
        .route("/{owner}/drops/{id}/tree/{r}", get(drops::show_at))
196
        .route("/{owner}/drops/{id}/edit", get(drops::edit_form).post(drops::save))
197
        .route("/{owner}/drops/{id}/delete", post(drops::delete))
198
        .route("/{owner}/drops/{id}/fork", post(drops::fork))
199
        .route("/{owner}/drops/{id}/star", post(drops::star))
200
        .route("/{owner}/drops/{id}/embed", get(drops::embed))
201
        .route("/{owner}/drops/{id}/comment", post(drops::comment))
202
        .route("/{owner}/drops/{id}/comment/{n}/delete", post(drops::delete_comment))
203
        .route("/{owner}/drops/{id}/changes/{r}", get(drops::changes))
204
        .route("/{owner}/drops/{id}/change/{hash}", get(drops::change))
205
        .route("/{owner}/drops/{id}/raw/{r}/{*path}", get(drops::raw))
206
        .route("/{owner}/drops/{id}/file/{r}/{*path}", get(drops::file))
207
        .route("/{owner}/drops/{id}/oxy/v1/{endpoint}", any(crate::protocol::dispatch_drop).layer(DefaultBodyLimit::max(push_limit)))
208
        .route("/{owner}", get(home::owner))
209
        .route("/{owner}/{name}", get(repo::overview))
210
        .route("/{owner}/{name}/tree/{r}", get(repo::tree_root))
211
        .route("/{owner}/{name}/tree/{r}/{*path}", get(repo::tree))
212
        .route("/{owner}/{name}/file/{r}/{*path}", get(repo::file))
213
        .route("/{owner}/{name}/function/{r}/{*path}", get(history::function))
214
        .route("/{owner}/{name}/lanes/{r}", get(history::lanes))
215
        .route("/{owner}/{name}/lanes/{r}/plan", post(history::plan))
216
        .route("/{owner}/{name}/raw/{r}/{*path}", get(repo::raw_file))
217
        .route("/{owner}/{name}/last/{r}", get(repo::last_changes))
218
        .route("/{owner}/{name}/changes/{r}", get(history::history))
219
        .route("/{owner}/{name}/change/{hash}", get(history::change))
220
        .route("/apt", get(crate::apt::home))
221
        .route("/apt/{file}", get(crate::apt::key))
222
        .route("/apt/dists/{suite}/{*rest}", get(crate::apt::dists))
223
        .route("/apt/pool/{*path}", get(crate::apt::pool))
224
        .route("/help", get(help::help))
225
        .route("/projects/{owner}", get(projects::list).post(projects::create))
226
        .route("/projects/{owner}/{number}", get(projects::show).post(projects::act))
227
        .route("/notifications/thread", post(inbox::thread))
228
        .route("/notifications/open/{id}", get(inbox::open))
229
        .route("/login/reset", get(recovery::request_form).post(recovery::request))
230
        .route("/login/reset/{secret}", get(recovery::new_password_form).post(recovery::set_new_password))
231
        .route("/verify/{secret}", get(recovery::verify))
232
        .route("/settings/email/verify", post(settings::resend_verification))
233
        .route("/{owner}/{name}/compare", get(history::compare_index))
234
        .route("/{owner}/{name}/compare/{spec}", get(history::compare))
235
        .route("/{owner}/{name}/bookmarks", get(refs::bookmarks))
236
        .route("/{owner}/{name}/bookmarks/delete", post(refs::delete_bookmark))
237
        .route("/{owner}/{name}/tags", get(refs::tags))
238
        .route("/{owner}/{name}/artifacts", get(artifacts::artifacts))
239
        .route("/{owner}/{name}/images", get(artifacts::images))
240
        .route("/{owner}/{name}/terraform", get(artifacts::terraform))
241
        .route("/{owner}/{name}/insights", get(insights::repo))
242
        .route("/{owner}/{name}/terraform/{state}/download", get(artifacts::download))
243
        .route("/{owner}/{name}/terraform/{state}/restore", post(artifacts::restore))
244
        .route("/{owner}/{name}/conflicts", get(refs::conflicts))
245
        .route("/{owner}/{name}/trust", get(refs::trust))
246
        .route("/{owner}/{name}/pushes", get(refs::pushes))
247
        .route("/{owner}/{name}/fork", get(forks::form).post(forks::create))
248
        .route("/{owner}/{name}/forks", get(forks::list))
249
        .route("/{owner}/{name}/settings", get(repo_settings::settings).post(repo_settings::update))
250
        // One page per setting (#278); some share their form's path.
251
        .route("/{owner}/{name}/settings/{page}", get(repo_settings::page))
252
        .route("/{owner}/{name}/settings/collaborators", get(repo_settings::page).post(repo_settings::collaborator))
253
        .route("/{owner}/{name}/settings/delete", post(repo_settings::delete))
254
        .route("/{owner}/{name}/settings/transfer", post(repo_settings::transfer))
255
        .route("/{owner}/{name}/settings/archive", post(repo_settings::archive))
256
        .route("/{owner}/{name}/settings/wiki/delete", post(repo_settings::wiki_delete))
257
        .route("/{owner}/{name}/wiki", get(wiki::home))
258
        .route("/{owner}/{name}/wiki/_pages", get(wiki::pages))
259
        .route("/{owner}/{name}/wiki/_new", get(wiki::new_form))
260
        .route("/{owner}/{name}/wiki/_raw/{*path}", get(wiki::raw))
261
        .route("/{owner}/{name}/wiki/{slug}", get(wiki::show))
262
        .route("/{owner}/{name}/wiki/{slug}/edit", get(wiki::edit_form).post(wiki::save))
263
        .route("/{owner}/{name}/wiki/{slug}/history", get(wiki::history))
264
        .route("/{owner}/{name}/wiki/{slug}/delete", post(wiki::delete))
265
        .route("/{owner}/{name}/settings/requirements", post(repo_settings::requirements))
266
        .route("/{owner}/{name}/proposals", get(proposals::list))
267
        .route("/{owner}/{name}/proposals/new", get(proposals::new_form).post(proposals::create))
268
        .route("/{owner}/{name}/proposals/new/draft", post(proposals::new_draft))
269
        .route("/{owner}/{name}/proposals/new/draft/stream", post(proposals::new_draft_stream))
270
        .route("/{owner}/{name}/proposal/{number}", get(proposals::show))
271
        .route("/{owner}/{name}/proposal/{number}/comment", post(proposals::comment))
272
        .route("/{owner}/{name}/proposal/{number}/comment/{id}/resolve", post(proposals::resolve_comment))
273
        .route("/{owner}/{name}/proposal/{number}/review", post(proposals::review))
274
        .route("/{owner}/{name}/proposal/{number}/reviewers", post(proposals::reviewers))
275
        .route("/{owner}/{name}/proposal/{number}/assistant", post(proposals::assistant))
276
        .route("/{owner}/{name}/proposal/{number}/draft", post(proposals::draft))
277
        .route("/{owner}/{name}/proposal/{number}/draft/stream", post(proposals::draft_stream))
278
        .route("/{owner}/{name}/proposal/{number}/edit", post(proposals::edit))
279
        .route("/{owner}/{name}/proposal/{number}/state", post(proposals::state))
280
        .route("/{owner}/{name}/proposal/{number}/land", post(proposals::land))
281
        .route("/{owner}/{name}/proposal/{number}/auto-land", post(proposals::auto_land))
282
        .route("/{owner}/{name}/proposal/{number}/labels", post(proposals::set_labels))
283
        .route("/{owner}/{name}/proposal/{number}/project", post(projects::place_proposal))
284
        .route("/{owner}/{name}/issue/{number}/project", post(projects::place_issue))
285
        .route("/{owner}/{name}/proposal/{number}/events", get(proposals::events))
286
        .route("/{owner}/{name}/settings/hooks", post(repo_settings::hooks))
287
        .route("/{owner}/{name}/settings/assistants", get(repo_settings::page).post(repo_settings::assistants))
288
        .route("/{owner}/{name}/settings/assistants/models", post(repo_settings::assistant_models))
289
        .route("/{owner}/{name}/settings/variables", get(repo_settings::page).post(repo_settings::variables))
290
        .route("/{owner}/{name}/settings/secrets", get(repo_settings::page).post(repo_settings::secrets))
291
        .route("/{owner}/{name}/settings/hooks/{id}/deliveries", get(repo_settings::deliveries))
292
        .route("/{owner}/{name}/settings/hooks/{id}/redeliver/{delivery}", post(repo_settings::redeliver))
293
        .route("/{owner}/{name}/settings/checks", get(repo_settings::page).post(repo_settings::required_checks))
294
        .route("/{owner}/{name}/watch", post(issues::watch))
295
        .route("/{owner}/{name}/star", post(issues::star))
296
        .route("/{owner}/{name}/edit/{r}", post(edit::save))
297
        .route("/{owner}/{name}/edit/{r}/{*path}", get(edit::edit_form))
298
        .route("/{owner}/{name}/resolve/{bookmark}/{*path}", get(resolve::form).post(resolve::save))
299
        .route("/{owner}/{name}/resolve-live/{bookmark}/{*path}", get(resolve::live_events).post(resolve::live_choose))
300
        .route("/{owner}/{name}/newfile/{r}", get(edit::new_form))
301
        .route("/{owner}/{name}/flow", get(flow::runs))
302
        .route("/{owner}/{name}/flow/badge.svg", get(flow::badge))
303
        .route("/{owner}/{name}/tests", get(test_reports::overview))
304
        .route("/{owner}/{name}/tests/case", get(test_reports::case))
305
        .route("/{owner}/{name}/reports", get(reports::overview))
306
        .route("/{owner}/{name}/reports/files/{id}/{mac}/{*path}", get(reports::file))
307
        .route("/{owner}/{name}/reports/{report}", get(reports::show))
308
        .route("/{owner}/{name}/coverage", get(coverage::overview))
309
        .route("/{owner}/{name}/coverage/badge.svg", get(coverage::badge))
310
        .route("/{owner}/{name}/coverage/{id}/file/{*path}", get(coverage::file))
311
        .route("/{owner}/{name}/deployments", get(flow::deployments))
312
        .route("/{owner}/{name}/flow/{id}", get(flow::run))
313
        .route("/{owner}/{name}/flow/{id}/live", get(flow::live))
314
        .route("/{owner}/{name}/flow/start", post(flow::start))
315
        .route("/{owner}/{name}/flow/{id}/rerun", post(flow::rerun))
316
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/rerun", post(flow::rerun_job))
317
        .route("/{owner}/{name}/flow/{id}/jobs/{job}/decide", post(flow::decide))
318
        .route("/{owner}/{name}/flow/{id}/cancel", post(flow::cancel))
319
        .route("/{owner}/{name}/flow/{id}/expedite", post(flow::expedite))
320
        .route("/{owner}/{name}/flow/stamp/{r}", get(flow::stamp))
321
        .route("/{owner}/{name}/flow/at/{r}", get(flow::at))
322
        .route("/{owner}/{name}/receipts/{attest}", get(flow::receipt_file))
323
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}", get(flow::artifact_file))
324
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach", post(flow::attach))
325
        .route("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance", get(flow::provenance))
326
        .route("/{owner}/{name}/releases", get(releases::list))
327
        .route("/{owner}/{name}/releases/new", get(releases::new_form).post(releases::create))
328
        .route("/{owner}/{name}/releases/tag/{*tag}", get(releases::show))
329
        .route("/{owner}/{name}/releases/trust/{*tag}", get(release_trust::page))
330
        .route("/{owner}/{name}/releases/edit/{id}", post(releases::edit))
331
        .route(
332
            "/{owner}/{name}/releases/upload/{id}",
333
            post(releases::upload).layer(DefaultBodyLimit::max(app.config.limits.asset_limit.0 as usize + (1 << 20))),
334
        )
335
        .route("/{owner}/{name}/asset/{id}/{file}", get(releases::download))
336
        .route("/{owner}/{name}/archive", get(releases::source_archive))
337
        .route("/{owner}/{name}/search", get(repo::code_search))
338
        .route("/{owner}/{name}/info/{*rest}", any(git_info))
339
        .route("/{owner}/{name}/HEAD", get(git_head))
340
        .route("/{owner}/{name}/objects/{*rest}", get(git_objects))
341
        .route("/{owner}/{name}/git-upload-pack", post(git_upload_pack))
342
        .route("/{owner}/{name}/git-receive-pack", post(git_receive_pack))
343
        .route("/{owner}/{name}/settings/mirror", post(repo_settings::mirror))
344
        .route("/{owner}/{name}/settings/flow", get(repo_settings::page).post(repo_settings::flow))
345
        .route("/{owner}/{name}/settings/flow-priority", post(repo_settings::flow_priority))
346
        .route("/{owner}/{name}/settings/agent-gates", post(repo_settings::agent_gates))
347
        .route("/{owner}/{name}/settings/push-protection", get(repo_settings::page).post(repo_settings::push_protection))
348
        .route("/{owner}/{name}/settings/secret-bypass", post(repo_settings::secret_bypass))
349
        .route("/{owner}/{name}/settings/secret-bypass/remove", post(repo_settings::secret_bypass_remove))
350
        .route("/{owner}/{name}/settings/secret-resolve", post(repo_settings::secret_resolve))
351
        .route("/{owner}/{name}/settings/secret-scan", post(repo_settings::secret_scan))
352
        .route("/{owner}/{name}/settings/flow-supersede", post(repo_settings::flow_supersede))
353
        .route("/{owner}/{name}/settings/flow-skip", post(repo_settings::flow_skip))
354
        .route("/{owner}/{name}/settings/flow-reuse", post(repo_settings::flow_reuse))
355
        .route("/{owner}/{name}/settings/diffusion", get(repo_settings::page).post(repo_settings::diffusion))
356
        .route("/{owner}/{name}/settings/backup", get(repo_settings::page).post(repo_settings::backup))
357
        .route("/{owner}/{name}/settings/storage", get(repo_settings::page).post(repo_settings::storage))
358
        .route("/{owner}/{name}/settings/coverage", get(repo_settings::page).post(repo_settings::coverage))
359
        .route("/{owner}/{name}/settings/runners/token", post(repo_settings::runner_token))
360
        .route("/{owner}/{name}/settings/runners/{id}/remove", post(repo_settings::runner_remove))
361
        .route("/{owner}/{name}/issues", get(issues::list))
362
        .route("/{owner}/{name}/issues/new", get(issues::new_form).post(issues::create))
363
        .route("/{owner}/{name}/issue/{number}", get(issues::show))
364
        .route("/{owner}/{name}/issue/{number}/comment", post(issues::comment))
365
        .route("/{owner}/{name}/issue/{number}/comment/{id}/delete", post(issues::delete_comment))
366
        .route("/{owner}/{name}/issue/{number}/edit", post(issues::edit))
367
        .route("/{owner}/{name}/issue/{number}/state", post(issues::state))
368
        .route("/{owner}/{name}/issue/{number}/labels", post(issues::set_labels))
369
        .route("/{owner}/{name}/issue/{number}/assign", post(issues::assign))
370
        .route("/{owner}/{name}/issue/{number}/milestone", post(issues::set_milestone))
371
        .route("/{owner}/{name}/issue/{number}/subscribe", post(issues::subscribe))
372
        .route("/{owner}/{name}/labels", get(issues::labels).post(issues::save_label))
373
        .route("/{owner}/{name}/milestones", get(issues::milestones).post(issues::save_milestone))
374
        .route("/{owner}/{name}/oxy/v1/{endpoint}", any(crate::protocol::dispatch).layer(DefaultBodyLimit::max(push_limit)))
375
        .fallback(not_found)
376
        .layer(axum::middleware::from_fn_with_state(app.clone(), rejections_as_pages))
377
        .layer(axum::middleware::from_fn_with_state(app.clone(), same_origin))
378
        .layer(CompressionLayer::new())
379
        .layer(TraceLayer::new_for_http())
380
        .with_state(app)
381
}
382
383
// Git's smart HTTP paths under `/{owner}/{name}.git/`, forwarded to the
384
// mirror (hub spec §14).
385
async fn git_info(
386
    st: axum::extract::State<Shared>,
387
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
388
    m: axum::http::Method,
389
    q: axum::extract::RawQuery,
390
    h: axum::http::HeaderMap,
391
    b: axum::body::Bytes,
392
) -> Response {
393
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("info/{rest}"))), m, q, h, b).await
394
}
395
396
async fn git_head(
397
    st: axum::extract::State<Shared>,
398
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
399
    m: axum::http::Method,
400
    q: axum::extract::RawQuery,
401
    h: axum::http::HeaderMap,
402
    b: axum::body::Bytes,
403
) -> Response {
404
    crate::mirror::serve(st, axum::extract::Path((o, n, "HEAD".into())), m, q, h, b).await
405
}
406
407
async fn git_objects(
408
    st: axum::extract::State<Shared>,
409
    axum::extract::Path((o, n, rest)): axum::extract::Path<(String, String, String)>,
410
    m: axum::http::Method,
411
    q: axum::extract::RawQuery,
412
    h: axum::http::HeaderMap,
413
    b: axum::body::Bytes,
414
) -> Response {
415
    crate::mirror::serve(st, axum::extract::Path((o, n, format!("objects/{rest}"))), m, q, h, b).await
416
}
417
418
async fn git_upload_pack(
419
    st: axum::extract::State<Shared>,
420
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
421
    m: axum::http::Method,
422
    q: axum::extract::RawQuery,
423
    h: axum::http::HeaderMap,
424
    b: axum::body::Bytes,
425
) -> Response {
426
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-upload-pack".into())), m, q, h, b).await
427
}
428
429
async fn git_receive_pack(
430
    st: axum::extract::State<Shared>,
431
    axum::extract::Path((o, n)): axum::extract::Path<(String, String)>,
432
    m: axum::http::Method,
433
    q: axum::extract::RawQuery,
434
    h: axum::http::HeaderMap,
435
    b: axum::body::Bytes,
436
) -> Response {
437
    crate::mirror::serve(st, axum::extract::Path((o, n, "git-receive-pack".into())), m, q, h, b).await
438
}
439
440
/// Cross-site form posts are refused (hub spec §15.2): a browser that
441
/// sends `Origin` or `Sec-Fetch-Site` must name this site. Protocol and
442
/// API clients send neither.
443
async fn same_origin(
444
    axum::extract::State(app): axum::extract::State<Shared>,
445
    req: axum::extract::Request,
446
    next: axum::middleware::Next,
447
) -> Response {
448
    if req.method() != axum::http::Method::GET && req.method() != axum::http::Method::HEAD {
449
        let headers = req.headers();
450
        if headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) == Some("cross-site") {
451
            return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
452
        }
453
        if let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) {
454
            let host_of = |u: &str| u.split("://").nth(1).unwrap_or(u).split('/').next().unwrap_or("").to_ascii_lowercase();
455
            let request_host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).map(|h| h.to_ascii_lowercase());
456
            let ok = host_of(origin) == host_of(app.config.base_url()) || request_host.as_deref() == Some(host_of(origin).as_str());
457
            if !ok && origin != "null" {
458
                return (StatusCode::FORBIDDEN, "cross-site request refused").into_response();
459
            }
460
        }
461
    }
462
    next.run(req).await
463
}
464
465
/// What every page's chrome needs.
466
#[derive(Clone, Debug)]
467
pub struct Shell {
468
    pub site: String,
469
    pub base_url: String,
470
    pub path: String,
471
    pub version: &'static str,
472
    /// What was built: `oxy describe` at deploy, a Flow build's heads, or "local build".
473
    pub build: &'static str,
474
    /// The signed-in username, if any.
475
    pub user: Option<String>,
476
    pub is_admin: bool,
477
    pub csrf: String,
478
    pub unread: i64,
479
    /// The signed-in viewer's live topic, `user:<id>` (docs/live.md L4),
480
    /// or empty.
481
    pub live_user: String,
482
}
483
484
impl Shell {
485
    /// The version in the stylesheet and script URLs (`statics::assets_version`).
486
    pub fn assets(&self) -> &'static str {
487
        statics::assets_version()
488
    }
489
490
    pub fn new(app: &Shared, path: &str, viewer: &Viewer) -> Shell {
491
        Shell {
492
            site: app.config.site.name.clone(),
493
            base_url: app.config.base_url().to_string(),
494
            path: path.to_string(),
495
            version: env!("CARGO_PKG_VERSION"),
496
            build: env!("OXY_BUILD_ID"),
497
            user: viewer.account().map(|a| a.username.clone()),
498
            is_admin: viewer.is_admin(),
499
            csrf: viewer.csrf().to_string(),
500
            unread: viewer.0.as_ref().map(|v| v.unread).unwrap_or(0),
501
            live_user: viewer.account().map(|a| format!("user:{}", a.id)).unwrap_or_default(),
502
        }
503
    }
504
505
    pub fn anonymous(app: &Shared, path: &str) -> Shell {
506
        Shell::new(app, path, &Viewer(None))
507
    }
508
}
509
510
/// The repository chrome: tabs and counts.
511
#[derive(Clone, Debug)]
512
pub struct RepoShell {
513
    /// The repository's row id: its live topics name it (docs/live.md).
514
    pub id: i64,
515
    pub owner: String,
516
    pub name: String,
517
    pub url: String,
518
    pub description: String,
519
    pub default_bookmark: String,
520
    pub visibility: String,
521
    pub tab: &'static str,
522
    pub clone_url: String,
523
    /// The Git mirror's address, when the mirror is on (oxygenhub#215).
524
    pub git_url: Option<String>,
525
    /// The viewer's role, for showing settings and write actions.
526
    pub role: Option<Role>,
527
    /// Open issues and proposals, shown on their tabs.
528
    pub open_issues: i64,
529
    pub open_proposals: i64,
530
    /// Read-only (#108).
531
    pub archived: bool,
532
    /// Whether the repository has a wiki (§6.11).
533
    pub wiki: bool,
534
    /// The bucket its data lives in, when not this hub's disk (#96), as
535
    /// the header's provider icon shows it (#123).
536
    pub stored_in: Option<crate::storage::StoreBadge>,
537
    /// Whether it has coverage reports, for the Coverage tab (#113).
538
    pub coverage: bool,
539
    /// Whether it has test reports, for the Tests tab (#114).
540
    pub tests: bool,
541
    /// Whether it has reports of its own (#127); with coverage or tests,
542
    /// the Reports tab.
543
    pub reports: bool,
544
    /// Whether it pins, or is pinned by, another repository here: the
545
    /// Diffusion tab (#150).
546
    pub diffusion: bool,
547
    /// The backdrop's data, a sky of this repository alone; empty for none
548
    /// (docs/backgrounds.md, oxygenhub#196).
549
    pub backdrop: String,
550
    /// A drop (#279): its pages show the drop's own bar, not the
551
    /// repository's tabs. Its title, for that bar.
552
    pub is_drop: bool,
553
    pub drop_title: String,
554
}
555
556
impl RepoShell {
557
    pub fn new(app: &Shared, row: &db::repos::RepoRow, tab: &'static str) -> RepoShell {
558
        RepoShell {
559
            id: row.id,
560
            owner: row.owner.clone(),
561
            name: row.name.clone(),
562
            url: format!("/{}/{}", row.owner, row.name),
563
            description: row.description.clone(),
564
            default_bookmark: row.default_bookmark.clone(),
565
            visibility: row.visibility.clone(),
566
            tab,
567
            clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name),
568
            git_url: row.git_mirror.then(|| format!("{}/{}/{}.git", app.config.base_url(), row.owner, row.name)),
569
            role: None,
570
            open_issues: row.open_issues,
571
            open_proposals: row.open_proposals,
572
            archived: row.archived,
573
            wiki: crate::repos::RepoName::new(&row.owner, &row.name).is_some_and(|n| app.wikis.exists(&n)),
574
            stored_in: crate::storage::location(app, &row.owner, &row.name).and_then(|u| crate::storage::StoreBadge::of(&u)),
575
            coverage: crate::coverage::has_reports(app, row.id),
576
            tests: crate::junit::has_reports(app, row.id),
577
            reports: crate::reports::has_reports(app, row.id),
578
            diffusion: crate::diffusion::involved(app, row.id),
579
            backdrop: String::new(),
580
            is_drop: row.is_drop(),
581
            drop_title: row.title.clone(),
582
        }
583
    }
584
585
    /// Give the page a backdrop: this repository's sky, its activity of the
586
    /// last 30 days from the database (#196).
587
    pub async fn with_sky(mut self, app: &Shared, row: &db::repos::RepoRow) -> RepoShell {
588
        self.backdrop = home::repo_sky(app, row).await;
589
        self
590
    }
591
592
    /// The repository's live topic (docs/live.md).
593
    pub fn live_topic(&self) -> String {
594
        crate::events::topic::repo(self.id)
595
    }
596
597
    /// Its Diffusion topic: bumps and pills.
598
    pub fn diffusion_topic(&self) -> String {
599
        crate::events::topic::diffusion(self.id)
600
    }
601
602
    pub fn with_role(mut self, role: Role) -> RepoShell {
603
        self.role = Some(role);
604
        self
605
    }
606
607
    pub fn can(&self, access: Access) -> bool {
608
        auth::roles::allows(self.role, access)
609
    }
610
611
    pub fn can_maintain(&self) -> bool {
612
        self.can(Access::Maintain)
613
    }
614
}
615
616
/// Render a template as an HTML response.
617
/// One page of a long list: which page, how many, and links that keep
618
/// the rest of the query.
619
#[derive(Clone, Debug)]
620
pub struct Pager {
621
    pub page: usize,
622
    pub pages: usize,
623
    pub total: usize,
624
    /// The query without `page`, each pair encoded, joined with `&`.
625
    query: String,
626
}
627
628
impl Pager {
629
    pub const PER_PAGE: usize = 25;
630
631
    /// `page` counts from 1; out-of-range pages clamp to the last.
632
    pub fn new(total: usize, page: Option<usize>, query: &[(&str, &str)]) -> Pager {
633
        let pages = total.div_ceil(Self::PER_PAGE).max(1);
634
        let page = page.unwrap_or(1).clamp(1, pages);
635
        let query = query
636
            .iter()
637
            .filter(|(_, v)| !v.is_empty())
638
            .map(|(k, v)| format!("{k}={}", settings::urlencode(v).replace('/', "%2F")))
639
            .collect::<Vec<_>>()
640
            .join("&");
641
        Pager { page, pages, total, query }
642
    }
643
644
    /// This page's items.
645
    pub fn slice<T>(&self, all: Vec<T>) -> Vec<T> {
646
        all.into_iter().skip((self.page - 1) * Self::PER_PAGE).take(Self::PER_PAGE).collect()
647
    }
648
649
    pub fn url(&self, page: usize) -> String {
650
        if self.query.is_empty() {
651
            format!("?page={page}")
652
        } else {
653
            format!("?{}&page={page}", self.query)
654
        }
655
    }
656
657
    /// The same query with another sort, back on page one.
658
    pub fn sorted(&self, sort: &str) -> String {
659
        let rest: Vec<&str> = self.query.split('&').filter(|p| !p.is_empty() && !p.starts_with("sort=")).collect();
660
        let mut q = rest.join("&");
661
        if !q.is_empty() {
662
            q.push('&');
663
        }
664
        format!("?{q}sort={sort}")
665
    }
666
}
667
668
pub struct Page<T: Template>(pub T);
669
670
impl<T: Template> IntoResponse for Page<T> {
671
    fn into_response(self) -> Response {
672
        match self.0.render() {
673
            Ok(s) => Html(s).into_response(),
674
            Err(e) => {
675
                tracing::error!("template: {e}");
676
                (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
677
            }
678
        }
679
    }
680
}
681
682
#[derive(Template)]
683
#[template(path = "error.html")]
684
struct ErrorPage {
685
    shell: Shell,
686
    status: u16,
687
    title: String,
688
    detail: String,
689
}
690
691
/// A page-level failure, rendered inside the shell, or a redirect.
692
#[derive(Debug)]
693
pub struct Error {
694
    pub status: StatusCode,
695
    pub detail: String,
696
    shell: Option<Box<Shell>>,
697
    redirect: Option<String>,
698
}
699
700
impl Error {
701
    pub fn redirect(to: String) -> Error {
702
        Error { status: StatusCode::SEE_OTHER, detail: String::new(), shell: None, redirect: Some(to) }
703
    }
704
705
    pub fn not_found(shell: Shell) -> Error {
706
        Error {
707
            status: StatusCode::NOT_FOUND,
708
            detail: "There is nothing at this address.".into(),
709
            shell: Some(Box::new(shell)),
710
            redirect: None,
711
        }
712
    }
713
714
    pub fn bad(shell: Shell, detail: impl Into<String>) -> Error {
715
        Error { status: StatusCode::BAD_REQUEST, detail: detail.into(), shell: Some(Box::new(shell)), redirect: None }
716
    }
717
718
    pub fn from_repo(shell: Shell, e: RepoError) -> Error {
719
        match e {
720
            RepoError::NotFound => Error::not_found(shell),
721
            RepoError::Oxy(oxy_core::repo::RepoError::Msg(m)) => {
722
                Error { status: StatusCode::NOT_FOUND, detail: m, shell: Some(Box::new(shell)), redirect: None }
723
            }
724
            other => {
725
                Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: other.to_string(), shell: Some(Box::new(shell)), redirect: None }
726
            }
727
        }
728
    }
729
730
    pub fn from_db(shell: Shell, e: sqlx::Error) -> Error {
731
        Error { status: StatusCode::INTERNAL_SERVER_ERROR, detail: e.to_string(), shell: Some(Box::new(shell)), redirect: None }
732
    }
733
}
734
735
impl IntoResponse for Error {
736
    fn into_response(self) -> Response {
737
        if let Some(to) = self.redirect {
738
            return Redirect::to(&to).into_response();
739
        }
740
        let title = match self.status {
741
            StatusCode::NOT_FOUND => "Not found",
742
            StatusCode::BAD_REQUEST => "Bad request",
743
            _ => "Something went wrong",
744
        };
745
        if self.status.is_server_error() {
746
            tracing::error!("{}", self.detail);
747
        }
748
        let shell = self.shell.map(|b| *b).unwrap_or(Shell {
749
            site: "OxygenHub".into(),
750
            base_url: String::new(),
751
            path: String::new(),
752
            version: "",
753
            build: "",
754
            user: None,
755
            is_admin: false,
756
            csrf: String::new(),
757
            unread: 0,
758
            live_user: String::new(),
759
        });
760
        let page = ErrorPage { shell, status: self.status.as_u16(), title: title.into(), detail: self.detail };
761
        match page.render() {
762
            Ok(s) => (self.status, Html(s)).into_response(),
763
            Err(_) => (self.status, title).into_response(),
764
        }
765
    }
766
}
767
768
/// A page address the router matched but could not read (a number that is
769
/// not one, a malformed query): axum answers that in plain text before any
770
/// handler runs. For pages, that is the site's not-found page instead
771
/// (#294); the oxy protocol and anything not asked for with GET or HEAD keep
772
/// the plain answer.
773
async fn rejections_as_pages(
774
    axum::extract::State(app): axum::extract::State<Shared>,
775
    req: axum::extract::Request,
776
    next: axum::middleware::Next,
777
) -> Response {
778
    let page = matches!(*req.method(), axum::http::Method::GET | axum::http::Method::HEAD) && !req.uri().path().contains("/oxy/v1/");
779
    if !page {
780
        return next.run(req).await;
781
    }
782
    let (uri, headers) = (req.uri().clone(), req.headers().clone());
783
    let res = next.run(req).await;
784
    let plain = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|t| t.starts_with("text/plain"));
785
    if !(plain && matches!(res.status(), StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY)) {
786
        return res;
787
    }
788
    // Only axum's own rejections: a handler's plain 400 (the live stream's
789
    // "unknown topic") is the handler's answer and stays.
790
    let (head, body) = res.into_parts();
791
    let Ok(bytes) = axum::body::to_bytes(body, 4096).await else { return StatusCode::BAD_REQUEST.into_response() };
792
    let rejected = [&b"Invalid URL"[..], b"Failed to deserialize query string", b"Failed to deserialize the query string"]
793
        .iter()
794
        .any(|p| bytes.starts_with(p));
795
    if !rejected {
796
        return Response::from_parts(head, axum::body::Body::from(bytes));
797
    }
798
    let mut probe = axum::http::Request::builder().uri(uri.clone()).body(()).expect("a request");
799
    *probe.headers_mut() = headers;
800
    let (mut parts, ()) = probe.into_parts();
801
    let viewer = match <Viewer as axum::extract::FromRequestParts<Shared>>::from_request_parts(&mut parts, &app).await {
802
        Ok(v) => v,
803
        Err(never) => match never {},
804
    };
805
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
806
}
807
808
async fn not_found(axum::extract::State(app): axum::extract::State<Shared>, viewer: Viewer, uri: axum::http::Uri) -> Response {
809
    Error::not_found(Shell::new(&app, uri.path(), &viewer)).into_response()
810
}
811
812
/// A raw file response with a safe content type (hub spec §15.2).
813
pub fn raw(bytes: Vec<u8>, name: &str, inline_image: bool) -> Response {
814
    let mime = mime_of(name);
815
    let disposition = if inline_image && mime.starts_with("image/") { "inline" } else { "attachment" };
816
    (
817
        [
818
            (header::CONTENT_TYPE, mime.to_string()),
819
            (header::CONTENT_DISPOSITION, format!("{disposition}; filename=\"{}\"", name.replace('"', ""))),
820
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
821
        ],
822
        bytes,
823
    )
824
        .into_response()
825
}
826
827
pub fn mime_of(name: &str) -> &'static str {
828
    match name.rsplit('.').next().map(|e| e.to_ascii_lowercase()).as_deref() {
829
        Some("png") => "image/png",
830
        Some("jpg" | "jpeg") => "image/jpeg",
831
        Some("gif") => "image/gif",
832
        Some("webp") => "image/webp",
833
        Some("svg") => "image/svg+xml",
834
        Some("pdf") => "application/pdf",
835
        Some(
836
            "txt" | "md" | "rs" | "toml" | "json" | "yml" | "yaml" | "c" | "h" | "cpp" | "hpp" | "py" | "js" | "ts" | "html" | "css" | "sh",
837
        ) => "text/plain; charset=utf-8",
838
        _ => "application/octet-stream",
839
    }
840
}
841
842
/// Resolve `{owner}/{name}` for the viewer with at least `access`, or 404:
843
/// a repository the viewer may not see does not exist for them (hub spec
844
/// §4.4). Returns the viewer's role too.
845
pub async fn lookup_role(
846
    app: &Shared,
847
    shell: &Shell,
848
    viewer: &Viewer,
849
    owner: &str,
850
    name: &str,
851
    access: Access,
852
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
853
    let repo = crate::repos::RepoName::new(owner, name).ok_or_else(|| Error::not_found(shell.clone()))?;
854
    let row = match db::repos::get(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))? {
855
        Some(row) => row,
856
        None => {
857
            // A transferred repository: the old URL goes to the new one (#108),
858
            // the rest of the path kept, when the viewer may see it.
859
            let moved = db::repos::moved_to(&app.db, owner, name).await.map_err(|e| Error::from_db(shell.clone(), e))?;
860
            let Some(moved) = moved else { return Err(Error::not_found(shell.clone())) };
861
            let role = auth::roles::role_for(&app.db, viewer.account(), &moved).await.map_err(|e| Error::from_db(shell.clone(), e))?;
862
            if !auth::roles::allows(role, Access::Read) {
863
                return Err(Error::not_found(shell.clone()));
864
            }
865
            let old = format!("/{owner}/{name}");
866
            let rest = shell.path.strip_prefix(&old).unwrap_or("");
867
            return Err(Error::redirect(format!("/{}/{}{rest}", moved.owner, moved.name)));
868
        }
869
    };
870
    let role = auth::roles::role_for(&app.db, viewer.account(), &row).await.map_err(|e| Error::from_db(shell.clone(), e))?;
871
    if !auth::roles::allows(role, access) {
872
        return Err(Error::not_found(shell.clone()));
873
    }
874
    // A drop's repository pages are read-only (its history, changes and
875
    // raw files, #279): it is changed from the drop's own page.
876
    if row.is_drop() && access != Access::Read {
877
        return Err(Error::not_found(shell.clone()));
878
    }
879
    if row.archived && matches!(access, Access::Write | Access::Maintain) {
880
        return Err(archived(shell));
881
    }
882
    Ok((repo, row, role.unwrap_or(Role::Read)))
883
}
884
885
/// The error for a write to an archived repository (#108).
886
pub fn archived(shell: &Shell) -> Error {
887
    Error::bad(shell.clone(), "This repository is archived and read-only. Its admins can bring it back under Settings › Advanced.")
888
}
889
890
/// Refuse a change to an archived repository, for handlers that open it
891
/// for reading and then write.
892
pub fn writable(row: &db::repos::RepoRow, shell: &Shell) -> Result<(), Error> {
893
    if row.archived {
894
        Err(archived(shell))
895
    } else {
896
        Ok(())
897
    }
898
}
899
900
/// `lookup_role` for reading.
901
pub async fn lookup(
902
    app: &Shared,
903
    shell: &Shell,
904
    viewer: &Viewer,
905
    owner: &str,
906
    name: &str,
907
) -> Result<(crate::repos::RepoName, db::repos::RepoRow, Role), Error> {
908
    lookup_role(app, shell, viewer, owner, name, Access::Read).await
909
}
910
911
/// Fill `account` on change authors whose key is linked to an account.
912
pub async fn attribute(app: &Shared, changes: &mut [&mut crate::repos::view::ChangeView]) {
913
    if changes.is_empty() {
914
        return;
915
    }
916
    let Ok(links) = db::accounts::identity_accounts(&app.db).await else { return };
917
    let map: std::collections::HashMap<String, String> = links.into_iter().collect();
918
    for c in changes.iter_mut() {
919
        if let Some(u) = map.get(&c.author.key) {
920
            c.author.account = Some(u.clone());
921
        }
922
    }
923
}
924
925
/// The part of a rendered page between `<!--frag:NAME-->` and
926
/// `<!--/frag:NAME-->` (live pages, docs/live.md): what a page fetches again
927
/// when its topic changes. `None` when the page has no such part.
928
pub fn fragment(html: &str, name: &str) -> Option<String> {
929
    if !name.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') || name.is_empty() {
930
        return None;
931
    }
932
    let open = format!("<!--frag:{name}-->");
933
    let close = format!("<!--/frag:{name}-->");
934
    let start = html.find(&open)? + open.len();
935
    let end = start + html[start..].find(&close)?;
936
    Some(html[start..end].to_string())
937
}
938
939
#[cfg(test)]
940
mod fragment_tests {
941
    #[test]
942
    fn a_fragment_is_cut_from_the_page_by_its_markers() {
943
        let page = "<p>a</p><div data-fragment=\"x\"><!--frag:x--><b>inside</b><!--/frag:x--></div>";
944
        assert_eq!(super::fragment(page, "x").as_deref(), Some("<b>inside</b>"));
945
        assert_eq!(super::fragment(page, "y"), None);
946
        assert_eq!(super::fragment(page, "x--><b"), None, "names are plain");
947
    }
948
}