steid

@jamesgill /

Rust18.5 KBCode·Blame·History·Raw
1//! Request-scoped helpers.
2//!
3//! Functions taking `cx: &Cx`, not middleware or extractors — Topcoat's guidance, and
4//! the safer shape: a page that forgets to call `current_actor` gets no actor, whereas
5//! a route added without its middleware silently gets someone else's.
6
7use std::{sync::Arc, time::SystemTime};
8
9use sqlx::SqlitePool;
10use topcoat::{
11 Result,
12 context::{Cx, app_context},
13 router::{
14 HeaderName, HeaderValue,
15 error::{internal_server_error, not_found},
16 header::{HOST, LOCATION},
17 headers,
18 },
19 session,
20};
21
22use crate::{
23 application::{
24 AppConfig, Error, Identity, PublicProfile, RepoView, describe_identity, is_claimed,
25 resolve_actor,
26 },
27 domain::{Actor, DomainError, PrivateTargets, SessionTokenHash},
28 infrastructure::{
29 cat_file::CatFilePool,
30 disk::WalkingDiskUsage,
31 git::{DiskGitArchive, DiskGitMerge, DiskGitStorage, GitFeatures, GitHttpBackend},
32 git_query::DiskGitQuery,
33 highlight::HighlightCache,
34 mail::LettreMailer,
35 merge_cache::MergeCache,
36 repository::{
37 SqliteIssueRepo, SqliteLabelRepo, SqliteMembershipRepo, SqliteOrgRepo,
38 SqlitePasswordResetRepo, SqlitePullRequestRepo, SqlitePushEventRepo, SqliteRepoRepo,
39 SqliteSessionRepo, SqliteTokenRepo, SqliteUserRepo, SqliteWebhookDeliveryRepo,
40 SqliteWebhookRepo,
41 },
42 webhook::UreqWebhookSender,
43 },
44};
45
46/// The one-time token that authorises claiming an unclaimed instance.
47///
48/// Present in app context only while the installation is unclaimed.
49pub struct SetupState(pub crate::domain::SetupToken);
50
51pub fn pool(cx: &Cx) -> &SqlitePool {
52 app_context::<SqlitePool>(cx)
53}
54
55/// Anything below the web layer failing is a 500 — the visitor can't act on it, and
56/// the detail belongs in the log rather than the page.
57pub fn server_error<E>(error: E) -> topcoat::Error
58where
59 E: std::error::Error + Send + Sync + 'static,
60{
61 eprintln!("steid: {error}");
62 internal_server_error(error).into()
63}
64
65/// Whether a use case failed because git was too slow rather than because git broke.
66///
67/// A timeout is the one read failure that is not a fault: the repository is fine and the
68/// request asked more of it than one page's budget allows. A page that can say so
69/// renders a state of its own — in its own words, offering whatever costs less — rather
70/// than a 500 that claims the instance is broken.
71///
72/// Four pages wanted this within one wave (`refs`, `commit`, `blame`, and `search`
73/// before it moved), which is what it took to earn a home here. `search_repo` is the
74/// exception and stays as it is: it answers `Searched::TimedOut` in the application
75/// layer, because there the timeout is one of several results the same form re-renders
76/// rather than an error to be caught.
77pub fn timed_out(error: &Error) -> bool {
78 matches!(error, Error::GitQuery(query) if query.is_timeout())
79}
80
81pub fn orgs(cx: &Cx) -> SqliteOrgRepo {
82 SqliteOrgRepo::new(pool(cx).clone())
83}
84
85pub fn memberships(cx: &Cx) -> SqliteMembershipRepo {
86 SqliteMembershipRepo::new(pool(cx).clone())
87}
88
89pub fn repos(cx: &Cx) -> SqliteRepoRepo {
90 SqliteRepoRepo::new(pool(cx).clone())
91}
92
93/// How much disk the instance is using.
94///
95/// A borrow, not a clone, and the one accessor here that is: it holds the cache, and a
96/// per-request copy would share the `Arc` but there is nothing to be gained by building
97/// the wrapper again. Absent from the context is not a state Steid builds, so this
98/// panics like every other `app_context` reader.
99pub fn disk_usage(cx: &Cx) -> &WalkingDiskUsage {
100 app_context::<WalkingDiskUsage>(cx)
101}
102
103/// Bare repositories on disk, rooted at the configured data directory.
104pub fn storage(cx: &Cx) -> DiskGitStorage {
105 DiskGitStorage::new(app_context::<AppConfig>(cx).data_dir.clone())
106}
107
108pub fn users(cx: &Cx) -> SqliteUserRepo {
109 SqliteUserRepo::new(pool(cx).clone())
110}
111
112pub fn tokens(cx: &Cx) -> SqliteTokenRepo {
113 SqliteTokenRepo::new(pool(cx).clone())
114}
115
116/// Session records, for the pages that end them rather than merely read one.
117///
118/// [`current_actor`] builds its own; this is for the password paths, which sign other
119/// devices out and so need the repository itself rather than the actor behind it.
120pub fn sessions(cx: &Cx) -> SqliteSessionRepo {
121 SqliteSessionRepo::new(pool(cx).clone())
122}
123
124/// One-shot password reset links.
125pub fn resets(cx: &Cx) -> SqlitePasswordResetRepo {
126 SqlitePasswordResetRepo::new(pool(cx).clone())
127}
128
129/// Outgoing mail.
130///
131/// Constructed per request like every repository here. It cannot fail at this point:
132/// `main` builds one at boot from the same configuration and refuses to start if the
133/// configuration is unusable, so anything that gets this far parses — and an
134/// unconfigured instance yields a mailer that says `configured()` is false, which is a
135/// state and not a fault.
136pub fn mailer(cx: &Cx) -> LettreMailer {
137 LettreMailer::from_config(app_context::<AppConfig>(cx)).unwrap_or_else(|error| {
138 // Unreachable in a process that booted. Said out loud rather than silently
139 // becoming an instance that cannot mail, because that is the failure that would
140 // otherwise look like configuration nobody set.
141 eprintln!("steid: the mail configuration stopped being usable: {error}");
142 LettreMailer::unusable()
143 })
144}
145
146pub fn issues(cx: &Cx) -> SqliteIssueRepo {
147 SqliteIssueRepo::new(pool(cx).clone())
148}
149
150/// Labels, and which issues carry them.
151pub fn labels(cx: &Cx) -> SqliteLabelRepo {
152 SqliteLabelRepo::new(pool(cx).clone())
153}
154
155/// Pull requests, and their comments.
156pub fn pulls(cx: &Cx) -> SqlitePullRequestRepo {
157 SqlitePullRequestRepo::new(pool(cx).clone())
158}
159
160/// Writing a merge into a bare repository, rooted at the same data directory as
161/// [`storage`].
162///
163/// Separate from [`storage`] because merging is a different git family — see
164/// [`GitMerge`](crate::application::port::GitMerge).
165pub fn merges(cx: &Cx) -> DiskGitMerge {
166 DiskGitMerge::new(app_context::<AppConfig>(cx).data_dir.clone())
167}
168
169/// What this server's `git` can do, read once at boot.
170///
171/// Out of app context rather than detected per request: it is one `git --version` per
172/// process, and asking on every page that draws a merge box would be a subprocess spent
173/// re-learning something that cannot change while the process runs.
174///
175/// Absent only in a context built without it, which is no context Steid builds — the
176/// default reports no capabilities, so a merge box would say the server cannot merge
177/// rather than offering a button that fails.
178pub fn git_features(cx: &Cx) -> GitFeatures {
179 topcoat::context::try_app_context::<GitFeatures>(cx)
180 .copied()
181 .unwrap_or_default()
182}
183
184/// Push events — one row per ref an authorized push moved.
185pub fn push_events(cx: &Cx) -> SqlitePushEventRepo {
186 SqlitePushEventRepo::new(pool(cx).clone())
187}
188
189pub fn webhooks(cx: &Cx) -> SqliteWebhookRepo {
190 SqliteWebhookRepo::new(pool(cx).clone())
191}
192
193pub fn deliveries(cx: &Cx) -> SqliteWebhookDeliveryRepo {
194 SqliteWebhookDeliveryRepo::new(pool(cx).clone())
195}
196
197/// Outbound webhook delivery.
198///
199/// Stateless apart from the one policy it carries, so it is constructed per request like
200/// every repository here rather than living in app context.
201pub fn webhook_sender(cx: &Cx) -> UreqWebhookSender {
202 UreqWebhookSender::new(private_targets(cx))
203}
204
205/// Whether this instance will deliver to its own network.
206///
207/// Read here rather than in each caller so that the two halves of the SSRF rule — the
208/// check when a hook is saved and the check on the resolved address before it is dialled
209/// — cannot end up reading different configuration. `Refused` unless
210/// `STEID_ALLOW_PRIVATE_WEBHOOKS` says otherwise; see
211/// [`AppConfig::allow_private_webhooks`].
212pub fn private_targets(cx: &Cx) -> PrivateTargets {
213 if app_context::<AppConfig>(cx).allow_private_webhooks {
214 PrivateTargets::Allowed
215 } else {
216 PrivateTargets::Refused
217 }
218}
219
220/// Repository contents, read from the same data directory as [`storage`].
221///
222/// Constructed per request like every adapter here, but handed the process pool out of
223/// app context rather than making one: the pool owns live `git cat-file` processes, and
224/// one built per request would spawn and kill a pair per request. See
225/// [`cat_file`](crate::infrastructure::cat_file).
226pub fn queries(cx: &Cx) -> DiskGitQuery {
227 DiskGitQuery::new(
228 app_context::<AppConfig>(cx).data_dir.clone(),
229 app_context::<Arc<CatFilePool>>(cx).clone(),
230 app_context::<Arc<MergeCache>>(cx).clone(),
231 )
232}
233
234/// Highlighted markup, remembered across requests.
235///
236/// Out of app context rather than constructed here, and the one adapter on this page
237/// that is: a cache built per request remembers nothing, which is the same reason the
238/// `cat-file` pool lives there. See [`highlight`](crate::infrastructure::highlight).
239pub fn highlights(cx: &Cx) -> &Arc<HighlightCache> {
240 app_context::<Arc<HighlightCache>>(cx)
241}
242
243/// `git archive`, rooted at the same data directory as [`storage`].
244pub fn archives(cx: &Cx) -> DiskGitArchive {
245 DiskGitArchive::new(app_context::<AppConfig>(cx).data_dir.clone())
246}
247
248/// The git smart-HTTP protocol, rooted at the same data directory as [`storage`].
249pub fn protocol(cx: &Cx) -> GitHttpBackend {
250 GitHttpBackend::new(app_context::<AppConfig>(cx).data_dir.clone())
251}
252
253/// Who is making this request.
254///
255/// Resolves to [`Actor::Anonymous`] when there is no session, the session is unknown,
256/// or it has expired.
257pub async fn current_actor(cx: &Cx) -> Result<Actor> {
258 let presented = session::token_hash(cx)
259 .await?
260 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
261
262 let sessions = SqliteSessionRepo::new(pool(cx).clone());
263
264 resolve_actor(presented.as_ref(), SystemTime::now(), &sessions)
265 .await
266 .map_err(server_error)
267}
268
269/// Who the current actor actually is, resolved for display.
270///
271/// `None` when anonymous, or when the session outlived the user it names.
272pub async fn identity(cx: &Cx) -> Result<Option<Identity>> {
273 let actor = current_actor(cx).await?;
274 let pool = pool(cx).clone();
275
276 describe_identity(
277 &actor,
278 &SqliteUserRepo::new(pool.clone()),
279 &SqliteOrgRepo::new(pool),
280 )
281 .await
282 .map_err(server_error)
283}
284
285/// Whether this installation has an owner yet.
286pub async fn claimed(cx: &Cx) -> Result<bool> {
287 let users = SqliteUserRepo::new(pool(cx).clone());
288
289 is_claimed(&users).await.map_err(server_error)
290}
291
292/// The setup token, when the instance is still unclaimed.
293pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> {
294 topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0)
295}
296
297/// The `Location` header for a post-redirect-get reply.
298///
299/// Pair it with `StatusCode::SEE_OTHER` inside a `view!` to redirect from a page that
300/// otherwise renders a view:
301///
302/// ```ignore
303/// view! { (StatusCode::SEE_OTHER) (location("/somewhere")?) }
304/// ```
305///
306/// The awkward-looking route to a 303: `redirect()` is a **307**, which preserves the
307/// method, so a browser re-POSTs the form to its target instead of fetching it.
308/// `see_other()` is the right status but is a response type, and `#[page]` handlers
309/// must return a view so the layout can wrap the failure re-render. Setting the status
310/// and header inside `view!` is the documented way to get both from one handler.
311pub fn location(uri: &str) -> Result<(HeaderName, HeaderValue)> {
312 Ok((LOCATION, HeaderValue::try_from(uri).map_err(server_error)?))
313}
314
315/// The origin this instance is being reached on, e.g. `https://steid.example`.
316///
317/// Derived from the request rather than configured, so an instance is deployable
318/// anywhere without being told its own address — behind a proxy, on a platform
319/// subdomain, or on localhost, all with no configuration.
320///
321/// The scheme comes from `X-Forwarded-Proto` when a proxy sets it, since TLS is
322/// terminated in front of us and the request that arrives here is plain HTTP. Falling
323/// back to `http` is right for local development and wrong nowhere that matters: a
324/// deployment without a terminating proxy has no TLS to advertise anyway.
325pub fn public_origin(cx: &Cx) -> String {
326 let headers = headers(cx);
327 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
328
329 let scheme = value("x-forwarded-proto").unwrap_or("http");
330 let host = headers
331 .get(HOST)
332 .and_then(|value| value.to_str().ok())
333 .unwrap_or("localhost");
334
335 format!("{scheme}://{host}")
336}
337
338/// Renders a `TokenHash` as lowercase hex for storage.
339pub fn hex(hash: &session::TokenHash) -> String {
340 hash.iter().map(|byte| format!("{byte:02x}")).collect()
341}
342
343/// The repository in the path, refused for anyone who does not own it.
344///
345/// [`repo_for`](super::repo::repo_for) already 404s a repository the viewer may not
346/// see; this adds the stronger half, and answers **404 rather than 403** — a 403 on a
347/// repository somebody cannot see would confirm it exists, and an owner-only page that
348/// answered differently to a stranger than to a passer-by would leak the same fact by
349/// its status code alone.
350///
351/// The use cases decide this too. The guard only keeps a page from rendering for
352/// someone whose submission would be refused a moment later; it is not the
353/// authorization.
354///
355/// Written out identically in five page modules before it landed here, with three more
356/// inline copies on profiles — see [`owned_profile`].
357pub async fn owned_repo(cx: &Cx) -> Result<RepoView> {
358 let repo = super::repo::repo_for(cx).await?;
359
360 if !repo.viewer_is_owner {
361 return Err(not_found().into());
362 }
363
364 Ok(repo)
365}
366
367/// Whether the viewer owns the **instance**, as opposed to the thing in the path.
368///
369/// [`owned_repo`]'s question two levels up, and the only way a page asks it. The rule
370/// itself is [`application::instance_owner`](crate::application::instance_owner) — what
371/// "the instance's owner" means is a milestone 7 decision, and a page that compared
372/// against the sole user itself would have to be found and changed when it moves.
373///
374/// A `bool` rather than a guard, because the two callers want different things from the
375/// same answer: `/{handle}/settings` draws or omits its Backup section, and
376/// `/{handle}/settings/backup.tar.gz` turns a `false` into a 404. Neither is *the*
377/// authorization — `back_up_for` re-checks before it writes a byte, and it is that
378/// answer which counts. This one keeps a page from offering something whose submission
379/// would be refused a moment later.
380pub async fn instance_owner(cx: &Cx) -> Result<bool> {
381 crate::application::instance_owner(&current_actor(cx).await?, &users(cx))
382 .await
383 .map_err(server_error)
384}
385
386/// The profile in the path, refused for anyone but its owner.
387///
388/// [`owned_repo`]'s rule one level up, for `/{handle}/settings` and the pages under it.
389/// The same 404: whether a handle has settings is not a stranger's business, and the
390/// profile pages used to answer 403 here while every repository page answered 404.
391pub async fn owned_profile(cx: &Cx) -> Result<PublicProfile> {
392 let profile = super::profile::profile_for(cx).await?;
393
394 if !profile.viewer_is_owner {
395 return Err(not_found().into());
396 }
397
398 Ok(profile)
399}
400
401/// Turns a use case failure into either a message to re-render with, or a response.
402///
403/// The shape every form in Steid wants: validation is the visitor's to fix, so it is
404/// shown beside what they typed; anything about authorization is a page they should
405/// not have reached, so it is a status code.
406///
407/// `Forbidden` reaching here means the actor lost ownership between the guard and the
408/// write, and `NotFound` that the thing being edited went away. Both answer **404**,
409/// the same answer [`owned_repo`] gives, because by this point the two are
410/// indistinguishable to whoever is asking and a 403 would confirm the target exists.
411/// Three near-copies of this lived in `issues`, `labels` and `pulls` and disagreed on
412/// exactly that arm; a fourth in `webhook` was spelled `explain`.
413///
414/// A page with more to say layers its own arms *before* calling this — see
415/// `pulls::merge_failure`, which turns an archived repository and a stale merge into
416/// sentences rather than statuses.
417pub fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> {
418 match error {
419 Error::Domain(DomainError::Validation { field, reason }) => {
420 Ok(format!("That {field} is no good: {reason}."))
421 }
422 Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => {
423 Err(not_found().into())
424 }
425 // Ours, so it is logged and answered generically.
426 other => Err(server_error(std::io::Error::other(other.to_string()))),
427 }
428}
429
430#[cfg(test)]
431mod tests {
432 use topcoat::router::error::{InternalServerError, NotFoundError};
433
434 use super::*;
435
436 /// The status a `topcoat::Error` will answer with.
437 ///
438 /// Asserted by downcasting rather than by rendering: `into_response` wants a `Cx`,
439 /// and a request context is not something a unit test has.
440 fn is_not_found(error: topcoat::Error) -> bool {
441 error.downcast::<NotFoundError>().is_ok()
442 }
443
444 #[test]
445 fn a_validation_failure_becomes_a_sentence_the_form_can_show() {
446 let message = write_failure(Error::Domain(DomainError::Validation {
447 field: "title".to_owned(),
448 reason: "it is empty".to_owned(),
449 }));
450
451 assert_eq!(
452 message.expect("a message"),
453 "That title is no good: it is empty."
454 );
455 }
456
457 #[test]
458 fn losing_ownership_mid_write_is_a_404_rather_than_a_403() {
459 // The 403 three of the four copies used to give would confirm that the thing
460 // being written to exists, which the guard's 404 was careful not to.
461 let error = write_failure(Error::Domain(DomainError::Forbidden)).expect_err("a response");
462
463 assert!(is_not_found(error));
464 }
465
466 #[test]
467 fn a_target_that_went_away_is_the_same_404() {
468 let error = write_failure(Error::Domain(DomainError::NotFound { entity: "issue" }))
469 .expect_err("a response");
470
471 assert!(is_not_found(error));
472 }
473
474 #[test]
475 fn anything_else_is_ours_and_is_a_500() {
476 // Archived is a sentence on the pull request pages, which layer that arm before
477 // calling this. Anywhere else it is a case nobody handled, and a 500 says so.
478 let error = write_failure(Error::Domain(DomainError::Archived)).expect_err("a response");
479
480 assert!(error.downcast::<InternalServerError>().is_ok());
481 }
482}