forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

mod.rs292 lines, 10.3 KiBHistoryRawDownload
1//! Our own small JSON API under `/api/v1`. Authentication is by personal access token only:
2//! `Authorization: Bearer forge_...` or `Authorization: token forge_...`, or, for Gitea clients, Basic auth
3//! with the token as the password or `?access_token=` on the Gitea routes. Session cookies are never
4//! read here, so a browser cannot drive these routes and CSRF protection does not apply. Errors are
5//! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot
6//! use a repo, the same as git, so missing and hidden repos look identical to them.
7
8pub mod gitea;
9#[cfg(test)]
10mod gitea_tests;
11pub mod packages;
12pub mod releases;
13pub mod statuses;
14
15use std::net::IpAddr;
16use std::path::PathBuf;
17use std::time::Instant;
18
19use forge_core::{Action, Denied, Repo, User, authorize, token::hash_token};
20use forge_git::browse;
21use http::HeaderMap;
22use http::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue, RETRY_AFTER, WWW_AUTHENTICATE};
23use serde_json::{Value, json};
24use topcoat::router::StatusCode;
25use topcoat::router::response::Response;
26
27use crate::state::AppState;
28use crate::throttle::{self, GIT_IP_LIMIT};
29
30/// The scope a token needs to use this API. It is the only scope the token form offers.
31pub const REPO_SCOPE: &str = "repo";
32
33/// A failed step. The response is boxed, as in git_http, to keep `Result` small.
34pub type Refusal = Box<Response>;
35
36/// Builds a JSON response with the given status.
37pub fn json(status: StatusCode, value: &Value) -> Response {
38 let mut res = Response::new(topcoat::router::Body::from(value.to_string()));
39 *res.status_mut() = status;
40 res.headers_mut().insert(
41 CONTENT_TYPE,
42 HeaderValue::from_static("application/json; charset=utf-8"),
43 );
44 res
45}
46
47/// A JSON error: `{"error": message}`.
48pub fn error(status: StatusCode, message: &str) -> Response {
49 json(status, &json!({ "error": message }))
50}
51
52/// 401 with a Bearer challenge.
53pub fn unauthorized() -> Response {
54 let mut res = error(StatusCode::UNAUTHORIZED, "authentication required");
55 res.headers_mut().insert(
56 WWW_AUTHENTICATE,
57 HeaderValue::from_static("Bearer realm=\"forge\""),
58 );
59 res
60}
61
62/// A 500 that does not reveal the cause; the cause is logged.
63pub fn internal(message: impl std::fmt::Display) -> Refusal {
64 tracing::error!(error = %message, "api request failed");
65 Box::new(error(
66 StatusCode::INTERNAL_SERVER_ERROR,
67 "internal server error",
68 ))
69}
70
71/// Pulls the token out of `Bearer <token>`, `token <token>` or `Basic base64(user:<token>)`. The
72/// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone
73/// names the user. Returns `None` for a missing header and `Some(None)` for any other shape.
74pub(crate) fn presented_token(headers: &HeaderMap) -> Option<Option<String>> {
75 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
76 let Some((scheme, rest)) = value.split_once(' ') else {
77 return Some(None);
78 };
79 let token = if scheme.eq_ignore_ascii_case("basic") {
80 crate::git_auth::parse_basic_auth(headers).map(|(_, password)| password)
81 } else if scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token") {
82 Some(rest.trim().to_owned())
83 } else {
84 None
85 };
86 match token {
87 Some(token) if token.starts_with("forge_") => Some(Some(token)),
88 _ => Some(None),
89 }
90}
91
92/// Resolves the caller from the `Authorization` header.
93///
94/// - No header: `Ok(None)`, an anonymous caller.
95/// - A header that is not a forge token, an unknown or expired token, or a token whose user is
96/// gone: 401, and the failure counts against the client IP. The budget is the git one, so
97/// guesses cannot be split between git and the API.
98/// - A token without the `repo` scope: 403, which does not count as a failed login.
99/// - Otherwise the token's `last_used_at` is touched and the user is returned.
100pub async fn authenticate(
101 state: &AppState,
102 ip: IpAddr,
103 headers: &HeaderMap,
104) -> Result<Option<User>, Refusal> {
105 let Some((user, token_id, scopes)) = authenticate_token(state, ip, headers).await? else {
106 return Ok(None);
107 };
108 if !scopes.iter().any(|scope| scope == REPO_SCOPE) {
109 return Err(Box::new(error(
110 StatusCode::FORBIDDEN,
111 "the token lacks the repo scope",
112 )));
113 }
114 if let Err(e) = state.store.touch_token(&token_id).await {
115 return Err(internal(e));
116 }
117 crate::pages::settings_live::bump_account(state, &user.id);
118 Ok(Some(user))
119}
120
121/// The user a token names, with the token's id and scopes. `None` when the request carries no
122/// Authorization header. The scope is not checked and the token is not touched: the caller does both.
123pub(crate) async fn authenticate_token(
124 state: &AppState,
125 ip: IpAddr,
126 headers: &HeaderMap,
127) -> Result<Option<(User, String, Vec<String>)>, Refusal> {
128 if !headers.contains_key(AUTHORIZATION) {
129 return Ok(None);
130 }
131 let key = throttle::ip_key("git-ip", ip);
132 let now = Instant::now();
133 if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) {
134 tracing::warn!(ip = %ip, retry_after_secs = retry.as_secs(), "api authentication throttled");
135 let mut res = error(
136 StatusCode::TOO_MANY_REQUESTS,
137 "too many failed attempts, try again later",
138 );
139 res.headers_mut()
140 .insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1)));
141 return Err(Box::new(res));
142 }
143
144 let Some(Some(token)) = presented_token(headers) else {
145 state.throttle.record_failure(&key, now);
146 return Err(Box::new(unauthorized()));
147 };
148 let access = match state.store.token_by_hash(&hash_token(&token)).await {
149 Ok(Some(access)) => access,
150 Ok(None) => {
151 state.throttle.record_failure(&key, now);
152 return Err(Box::new(unauthorized()));
153 }
154 Err(e) => return Err(internal(e)),
155 };
156 let user = match state.store.user_by_id(&access.user_id).await {
157 Ok(Some(user)) if !user.is_org() => user,
158 Ok(_) => {
159 state.throttle.record_failure(&key, now);
160 return Err(Box::new(unauthorized()));
161 }
162 Err(e) => return Err(internal(e)),
163 };
164 Ok(Some((user, access.id, access.scopes)))
165}
166
167/// Maps a refused action. Anonymous callers always get 401, whether the repo is hidden, missing,
168/// or merely read-only to them. Signed-in callers get 404 for hidden repos and 403 otherwise.
169fn refused(actor: Option<&User>, denied: Denied) -> Refusal {
170 Box::new(match (actor, denied) {
171 (None, _) => unauthorized(),
172 (Some(_), Denied::NotFound) => error(StatusCode::NOT_FOUND, "repository not found"),
173 (Some(_), Denied::Forbidden) => error(StatusCode::FORBIDDEN, "forbidden"),
174 })
175}
176
177/// Loads `owner/name` and checks that `actor` may perform `action` on it.
178pub async fn load_repo(
179 state: &AppState,
180 actor: Option<&User>,
181 owner: &str,
182 name: &str,
183 action: Action,
184) -> Result<Repo, Refusal> {
185 let repo = match state.store.repo_by_owner_and_name(owner, name).await {
186 Ok(Some(repo)) => repo,
187 Ok(None) => return Err(refused(actor, Denied::NotFound)),
188 Err(e) => return Err(internal(e)),
189 };
190 let (role, org_role) = match actor {
191 Some(user) => (
192 state
193 .store
194 .collaborator_role(&repo.id, &user.id)
195 .await
196 .map_err(internal)?,
197 state
198 .store
199 .org_repo_role(&repo.owner_id, &user.id, &repo.id)
200 .await
201 .map_err(internal)?,
202 ),
203 None => (None, None),
204 };
205 authorize(actor, &repo, role, org_role, action).map_err(|denied| refused(actor, denied))?;
206 Ok(repo)
207}
208
209/// On-disk path of a repo's bare directory.
210pub fn repo_dir(state: &AppState, repo: &Repo) -> Result<PathBuf, Refusal> {
211 forge_git::repo::repo_path(&state.config.data_dir, &repo.id).map_err(internal)
212}
213
214/// True when `sha` names a commit in the repo. Runs the git read off the async runtime.
215pub async fn commit_exists(path: PathBuf, sha: String) -> Result<bool, Refusal> {
216 let found = tokio::task::spawn_blocking(move || browse::read_commit(&path, &sha))
217 .await
218 .map_err(internal)?
219 .map_err(internal)?;
220 Ok(found.is_some())
221}
222
223/// Lowercases a full commit id. `None` unless it is 40 or 64 hex characters.
224pub fn normalize_sha(raw: &str) -> Option<String> {
225 let lower = raw.to_ascii_lowercase();
226 forge_core::store::commit_status::is_full_sha(&lower).then_some(lower)
227}
228
229/// Reads the request body, refusing anything over `limit` bytes.
230pub async fn read_body(body: topcoat::router::Body, limit: usize) -> Result<Vec<u8>, Refusal> {
231 topcoat::router::to_bytes(body, limit)
232 .await
233 .map(|bytes| bytes.to_vec())
234 .map_err(|_| {
235 Box::new(error(
236 StatusCode::PAYLOAD_TOO_LARGE,
237 "request body is too large",
238 ))
239 })
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245 use http::HeaderValue;
246
247 fn headers_with(value: &str) -> HeaderMap {
248 let mut headers = HeaderMap::new();
249 headers.insert(
250 AUTHORIZATION,
251 HeaderValue::from_str(value).expect("valid header"),
252 );
253 headers
254 }
255
256 #[test]
257 fn accepts_bearer_and_token_schemes() {
258 assert_eq!(
259 presented_token(&headers_with("Bearer forge_abc")),
260 Some(Some("forge_abc".into()))
261 );
262 assert_eq!(
263 presented_token(&headers_with("token forge_abc")),
264 Some(Some("forge_abc".into()))
265 );
266 assert_eq!(
267 presented_token(&headers_with("BEARER forge_abc")),
268 Some(Some("forge_abc".into()))
269 );
270 }
271
272 #[test]
273 fn rejects_other_shapes() {
274 assert_eq!(
275 presented_token(&headers_with("Basic Zm9vOmJhcg==")),
276 Some(None)
277 );
278 assert_eq!(
279 presented_token(&headers_with("Bearer notforge")),
280 Some(None)
281 );
282 assert_eq!(presented_token(&headers_with("Bearer ")), Some(None));
283 assert_eq!(presented_token(&HeaderMap::new()), None);
284 }
285
286 #[test]
287 fn sha_is_lowercased_and_must_be_full() {
288 assert_eq!(normalize_sha(&"AB".repeat(20)), Some("ab".repeat(20)));
289 assert_eq!(normalize_sha("abc123"), None);
290 assert_eq!(normalize_sha(&"z".repeat(40)), None);
291 }
292}