steid

@jamesgill /

Rust10.7 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,
16 header::{HOST, LOCATION},
17 headers,
18 },
19 session,
20};
21
22use crate::{
23 application::{AppConfig, Error, Identity, describe_identity, is_claimed, resolve_actor},
24 domain::{Actor, PrivateTargets, SessionTokenHash},
25 infrastructure::{
26 cat_file::CatFilePool,
27 git::{DiskGitArchive, DiskGitMerge, DiskGitStorage, GitFeatures, GitHttpBackend},
28 git_query::DiskGitQuery,
29 highlight::HighlightCache,
30 merge_cache::MergeCache,
31 repository::{
32 SqliteIssueRepo, SqliteLabelRepo, SqliteMembershipRepo, SqliteOrgRepo,
33 SqlitePullRequestRepo, SqlitePushEventRepo, SqliteRepoRepo, SqliteSessionRepo,
34 SqliteTokenRepo, SqliteUserRepo, SqliteWebhookDeliveryRepo, SqliteWebhookRepo,
35 },
36 webhook::UreqWebhookSender,
37 },
38};
39
40/// The one-time token that authorises claiming an unclaimed instance.
41///
42/// Present in app context only while the installation is unclaimed.
43pub struct SetupState(pub crate::domain::SetupToken);
44
45pub fn pool(cx: &Cx) -> &SqlitePool {
46 app_context::<SqlitePool>(cx)
47}
48
49/// Anything below the web layer failing is a 500 — the visitor can't act on it, and
50/// the detail belongs in the log rather than the page.
51pub fn server_error<E>(error: E) -> topcoat::Error
52where
53 E: std::error::Error + Send + Sync + 'static,
54{
55 eprintln!("steid: {error}");
56 internal_server_error(error).into()
57}
58
59/// Whether a use case failed because git was too slow rather than because git broke.
60///
61/// A timeout is the one read failure that is not a fault: the repository is fine and the
62/// request asked more of it than one page's budget allows. A page that can say so
63/// renders a state of its own — in its own words, offering whatever costs less — rather
64/// than a 500 that claims the instance is broken.
65///
66/// Four pages wanted this within one wave (`refs`, `commit`, `blame`, and `search`
67/// before it moved), which is what it took to earn a home here. `search_repo` is the
68/// exception and stays as it is: it answers `Searched::TimedOut` in the application
69/// layer, because there the timeout is one of several results the same form re-renders
70/// rather than an error to be caught.
71pub fn timed_out(error: &Error) -> bool {
72 matches!(error, Error::GitQuery(query) if query.is_timeout())
73}
74
75pub fn orgs(cx: &Cx) -> SqliteOrgRepo {
76 SqliteOrgRepo::new(pool(cx).clone())
77}
78
79pub fn memberships(cx: &Cx) -> SqliteMembershipRepo {
80 SqliteMembershipRepo::new(pool(cx).clone())
81}
82
83pub fn repos(cx: &Cx) -> SqliteRepoRepo {
84 SqliteRepoRepo::new(pool(cx).clone())
85}
86
87/// Bare repositories on disk, rooted at the configured data directory.
88pub fn storage(cx: &Cx) -> DiskGitStorage {
89 DiskGitStorage::new(app_context::<AppConfig>(cx).data_dir.clone())
90}
91
92pub fn users(cx: &Cx) -> SqliteUserRepo {
93 SqliteUserRepo::new(pool(cx).clone())
94}
95
96pub fn tokens(cx: &Cx) -> SqliteTokenRepo {
97 SqliteTokenRepo::new(pool(cx).clone())
98}
99
100pub fn issues(cx: &Cx) -> SqliteIssueRepo {
101 SqliteIssueRepo::new(pool(cx).clone())
102}
103
104/// Labels, and which issues carry them.
105pub fn labels(cx: &Cx) -> SqliteLabelRepo {
106 SqliteLabelRepo::new(pool(cx).clone())
107}
108
109/// Pull requests, and their comments.
110pub fn pulls(cx: &Cx) -> SqlitePullRequestRepo {
111 SqlitePullRequestRepo::new(pool(cx).clone())
112}
113
114/// Writing a merge into a bare repository, rooted at the same data directory as
115/// [`storage`].
116///
117/// Separate from [`storage`] because merging is a different git family — see
118/// [`GitMerge`](crate::application::port::GitMerge).
119pub fn merges(cx: &Cx) -> DiskGitMerge {
120 DiskGitMerge::new(app_context::<AppConfig>(cx).data_dir.clone())
121}
122
123/// What this server's `git` can do, read once at boot.
124///
125/// Out of app context rather than detected per request: it is one `git --version` per
126/// process, and asking on every page that draws a merge box would be a subprocess spent
127/// re-learning something that cannot change while the process runs.
128///
129/// Absent only in a context built without it, which is no context Steid builds — the
130/// default reports no capabilities, so a merge box would say the server cannot merge
131/// rather than offering a button that fails.
132pub fn git_features(cx: &Cx) -> GitFeatures {
133 topcoat::context::try_app_context::<GitFeatures>(cx)
134 .copied()
135 .unwrap_or_default()
136}
137
138/// Push events — one row per ref an authorized push moved.
139pub fn push_events(cx: &Cx) -> SqlitePushEventRepo {
140 SqlitePushEventRepo::new(pool(cx).clone())
141}
142
143pub fn webhooks(cx: &Cx) -> SqliteWebhookRepo {
144 SqliteWebhookRepo::new(pool(cx).clone())
145}
146
147pub fn deliveries(cx: &Cx) -> SqliteWebhookDeliveryRepo {
148 SqliteWebhookDeliveryRepo::new(pool(cx).clone())
149}
150
151/// Outbound webhook delivery.
152///
153/// Stateless apart from the one policy it carries, so it is constructed per request like
154/// every repository here rather than living in app context.
155pub fn webhook_sender(cx: &Cx) -> UreqWebhookSender {
156 UreqWebhookSender::new(private_targets(cx))
157}
158
159/// Whether this instance will deliver to its own network.
160///
161/// Read here rather than in each caller so that the two halves of the SSRF rule — the
162/// check when a hook is saved and the check on the resolved address before it is dialled
163/// — cannot end up reading different configuration. `Refused` unless
164/// `STEID_ALLOW_PRIVATE_WEBHOOKS` says otherwise; see
165/// [`AppConfig::allow_private_webhooks`].
166pub fn private_targets(cx: &Cx) -> PrivateTargets {
167 if app_context::<AppConfig>(cx).allow_private_webhooks {
168 PrivateTargets::Allowed
169 } else {
170 PrivateTargets::Refused
171 }
172}
173
174/// Repository contents, read from the same data directory as [`storage`].
175///
176/// Constructed per request like every adapter here, but handed the process pool out of
177/// app context rather than making one: the pool owns live `git cat-file` processes, and
178/// one built per request would spawn and kill a pair per request. See
179/// [`cat_file`](crate::infrastructure::cat_file).
180pub fn queries(cx: &Cx) -> DiskGitQuery {
181 DiskGitQuery::new(
182 app_context::<AppConfig>(cx).data_dir.clone(),
183 app_context::<Arc<CatFilePool>>(cx).clone(),
184 app_context::<Arc<MergeCache>>(cx).clone(),
185 )
186}
187
188/// Highlighted markup, remembered across requests.
189///
190/// Out of app context rather than constructed here, and the one adapter on this page
191/// that is: a cache built per request remembers nothing, which is the same reason the
192/// `cat-file` pool lives there. See [`highlight`](crate::infrastructure::highlight).
193pub fn highlights(cx: &Cx) -> &Arc<HighlightCache> {
194 app_context::<Arc<HighlightCache>>(cx)
195}
196
197/// `git archive`, rooted at the same data directory as [`storage`].
198pub fn archives(cx: &Cx) -> DiskGitArchive {
199 DiskGitArchive::new(app_context::<AppConfig>(cx).data_dir.clone())
200}
201
202/// The git smart-HTTP protocol, rooted at the same data directory as [`storage`].
203pub fn protocol(cx: &Cx) -> GitHttpBackend {
204 GitHttpBackend::new(app_context::<AppConfig>(cx).data_dir.clone())
205}
206
207/// Who is making this request.
208///
209/// Resolves to [`Actor::Anonymous`] when there is no session, the session is unknown,
210/// or it has expired.
211pub async fn current_actor(cx: &Cx) -> Result<Actor> {
212 let presented = session::token_hash(cx)
213 .await?
214 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
215
216 let sessions = SqliteSessionRepo::new(pool(cx).clone());
217
218 resolve_actor(presented.as_ref(), SystemTime::now(), &sessions)
219 .await
220 .map_err(server_error)
221}
222
223/// Who the current actor actually is, resolved for display.
224///
225/// `None` when anonymous, or when the session outlived the user it names.
226pub async fn identity(cx: &Cx) -> Result<Option<Identity>> {
227 let actor = current_actor(cx).await?;
228 let pool = pool(cx).clone();
229
230 describe_identity(
231 &actor,
232 &SqliteUserRepo::new(pool.clone()),
233 &SqliteOrgRepo::new(pool),
234 )
235 .await
236 .map_err(server_error)
237}
238
239/// Whether this installation has an owner yet.
240pub async fn claimed(cx: &Cx) -> Result<bool> {
241 let users = SqliteUserRepo::new(pool(cx).clone());
242
243 is_claimed(&users).await.map_err(server_error)
244}
245
246/// The setup token, when the instance is still unclaimed.
247pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> {
248 topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0)
249}
250
251/// The `Location` header for a post-redirect-get reply.
252///
253/// Pair it with `StatusCode::SEE_OTHER` inside a `view!` to redirect from a page that
254/// otherwise renders a view:
255///
256/// ```ignore
257/// view! { (StatusCode::SEE_OTHER) (location("/somewhere")?) }
258/// ```
259///
260/// The awkward-looking route to a 303: `redirect()` is a **307**, which preserves the
261/// method, so a browser re-POSTs the form to its target instead of fetching it.
262/// `see_other()` is the right status but is a response type, and `#[page]` handlers
263/// must return a view so the layout can wrap the failure re-render. Setting the status
264/// and header inside `view!` is the documented way to get both from one handler.
265pub fn location(uri: &str) -> Result<(HeaderName, HeaderValue)> {
266 Ok((LOCATION, HeaderValue::try_from(uri).map_err(server_error)?))
267}
268
269/// The origin this instance is being reached on, e.g. `https://steid.example`.
270///
271/// Derived from the request rather than configured, so an instance is deployable
272/// anywhere without being told its own address — behind a proxy, on a platform
273/// subdomain, or on localhost, all with no configuration.
274///
275/// The scheme comes from `X-Forwarded-Proto` when a proxy sets it, since TLS is
276/// terminated in front of us and the request that arrives here is plain HTTP. Falling
277/// back to `http` is right for local development and wrong nowhere that matters: a
278/// deployment without a terminating proxy has no TLS to advertise anyway.
279pub fn public_origin(cx: &Cx) -> String {
280 let headers = headers(cx);
281 let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
282
283 let scheme = value("x-forwarded-proto").unwrap_or("http");
284 let host = headers
285 .get(HOST)
286 .and_then(|value| value.to_str().ok())
287 .unwrap_or("localhost");
288
289 format!("{scheme}://{host}")
290}
291
292/// Renders a `TokenHash` as lowercase hex for storage.
293pub fn hex(hash: &session::TokenHash) -> String {
294 hash.iter().map(|byte| format!("{byte:02x}")).collect()
295}