forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB5bed83dTahinli1 month ago79 commits

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