forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiB51b2bbfTahinli1 month ago19 commits

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