steid

@jamesgill /

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