forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

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