forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

auth.rs223 lines, 7.7 KiBHistoryRawDownload
1//! Who may use the container registry, and the challenge that asks a client for credentials.
2//!
3//! A request may carry no credentials (anonymous), a personal access token as HTTP Basic or as a
4//! Bearer token (the `packages` scope is needed for anything but public reads), or a short-lived
5//! bearer token that `GET /v2/token` issued. Permissions are checked on every request against the
6//! identity, so a bearer token only names who is calling and expires quickly.
7
8use forge_core::User;
9use forge_core::oci as rules;
10use forge_core::packages::{KIND_OCI, Package};
11use http::header::{AUTHORIZATION, HeaderValue, WWW_AUTHENTICATE};
12use topcoat::context::{Cx, context};
13use topcoat::router::StatusCode;
14use topcoat::router::request::headers;
15use topcoat::router::response::Response;
16
17use super::oci_error;
18use crate::api::{self, Refusal};
19use crate::client_ip::client_ip;
20use crate::package_ops::{self, PackageError};
21use crate::state::AppState;
22
23/// Lifetime of a bearer token from `GET /v2/token`, in seconds.
24pub const TOKEN_TTL_SECS: i64 = 300;
25
26/// The scope the challenge names for a repository.
27const ACTIONS: &str = "pull,push";
28
29/// The caller of a registry request. `user` is `None` for anonymous callers.
30pub struct Caller {
31 pub user: Option<User>,
32}
33
34/// The repository a request names, as its owner and package stand now.
35pub struct Target {
36 pub owner: User,
37 pub image: String,
38 pub package: Option<Package>,
39}
40
41/// Resolves the caller from the `Authorization` header. A bearer token this forge issued is
42/// verified here; anything else goes to the personal access token check the API uses. A bad
43/// credential is a 401 with the challenge, so the client can ask again.
44pub async fn caller(cx: &Cx) -> Result<Caller, Refusal> {
45 let state = context::<AppState>(cx);
46 let headers = headers(cx);
47 let Some(value) = headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()) else {
48 return Ok(Caller { user: None });
49 };
50 if let Some(bearer) = value.strip_prefix("Bearer ").map(str::trim)
51 && !bearer.starts_with("forge_")
52 {
53 let now = unix_now();
54 return match rules::verify_token(&state.key, bearer, now) {
55 Some(Some(user_id)) => match state.store.user_by_id(&user_id).await {
56 Ok(Some(user)) if !user.is_org() => Ok(Caller { user: Some(user) }),
57 Ok(_) => Err(Box::new(challenge(state, None))),
58 Err(e) => Err(Box::new(internal(e))),
59 },
60 Some(None) => Ok(Caller { user: None }),
61 None => Err(Box::new(challenge(state, None))),
62 };
63 }
64 match api::authenticate_token(state, client_ip(cx), headers).await {
65 Ok(Some((user, token_id, scopes))) => {
66 if !scopes
67 .iter()
68 .any(|s| s == crate::api::packages::PACKAGES_SCOPE)
69 {
70 return Ok(Caller { user: None });
71 }
72 if let Err(e) = state.store.touch_token(&token_id).await {
73 return Err(Box::new(internal(e)));
74 }
75 Ok(Caller { user: Some(user) })
76 }
77 Ok(None) => Ok(Caller { user: None }),
78 Err(_) => Err(Box::new(challenge(state, None))),
79 }
80}
81
82/// Resolves the repository `name` for `caller`. A write needs the owner, an org owner, or the
83/// instance admin, and a signed-in caller. A read of a missing or private image is refused
84/// without saying which: anonymous callers get the challenge, signed-in ones 404 or 403.
85pub async fn authorize(
86 state: &AppState,
87 caller: &Caller,
88 name: &str,
89 write: bool,
90) -> Result<Target, Refusal> {
91 let Some((owner_name, image)) = rules::split_repo_name(name) else {
92 return Err(Box::new(oci_error(
93 StatusCode::BAD_REQUEST,
94 "NAME_INVALID",
95 "invalid repository name",
96 )));
97 };
98 let anonymous = caller.user.is_none();
99 if write && anonymous {
100 return Err(Box::new(challenge(state, Some(name))));
101 }
102 let owner = state
103 .store
104 .user_by_username(owner_name)
105 .await
106 .map_err(internal)?;
107 let Some(owner) = owner else {
108 return Err(Box::new(if anonymous {
109 challenge(state, Some(name))
110 } else {
111 oci_error(
112 StatusCode::NOT_FOUND,
113 "NAME_UNKNOWN",
114 "repository name not known to registry",
115 )
116 }));
117 };
118 let package = state
119 .store
120 .package_by_name(&owner.id, KIND_OCI, image)
121 .await
122 .map_err(internal)?;
123 let target = Target {
124 owner: owner.clone(),
125 image: image.to_owned(),
126 package: package.clone(),
127 };
128 if write {
129 let user = caller.user.as_ref().expect("checked above");
130 if !package_ops::may_publish(state, user, &owner)
131 .await
132 .map_err(package_failure)?
133 {
134 return Err(Box::new(denied()));
135 }
136 return Ok(target);
137 }
138 match package {
139 Some(package) => {
140 let readable = package_ops::may_read(state, caller.user.as_ref(), &owner, &package)
141 .await
142 .map_err(package_failure)?;
143 if readable {
144 Ok(target)
145 } else if anonymous {
146 Err(Box::new(challenge(state, Some(name))))
147 } else {
148 // The same answer as a missing image, so a signed-in stranger cannot learn which
149 // private image names exist.
150 Err(Box::new(name_unknown()))
151 }
152 }
153 None if anonymous => Err(Box::new(challenge(state, Some(name)))),
154 None => Err(Box::new(name_unknown())),
155 }
156}
157
158fn name_unknown() -> Response {
159 oci_error(
160 StatusCode::NOT_FOUND,
161 "NAME_UNKNOWN",
162 "repository name not known to registry",
163 )
164}
165
166/// The 401 that asks for credentials. It names the token endpoint, and the repository's scope when
167/// the request names one.
168pub fn challenge(state: &AppState, name: Option<&str>) -> Response {
169 let base = state.config.base_url.trim_end_matches('/');
170 let host = base.split_once("://").map_or(base, |(_, rest)| rest);
171 let mut value = format!("Bearer realm=\"{base}/v2/token\",service=\"{host}\"");
172 if let Some(name) = name {
173 value.push_str(&format!(",scope=\"repository:{name}:{ACTIONS}\""));
174 }
175 let mut res = oci_error(
176 StatusCode::UNAUTHORIZED,
177 "UNAUTHORIZED",
178 "authentication required",
179 );
180 if let Ok(header) = HeaderValue::from_str(&value) {
181 res.headers_mut().insert(WWW_AUTHENTICATE, header);
182 }
183 res
184}
185
186/// The 403 for a signed-in caller who may not do the thing.
187pub fn denied() -> Response {
188 oci_error(
189 StatusCode::FORBIDDEN,
190 "DENIED",
191 "requested access to the resource is denied",
192 )
193}
194
195/// Logs an internal failure and answers 500 in the registry's error body.
196pub fn internal(error: impl std::fmt::Display) -> Response {
197 tracing::error!(error = %error, "oci request failed");
198 oci_error(
199 StatusCode::INTERNAL_SERVER_ERROR,
200 "UNKNOWN",
201 "internal server error",
202 )
203}
204
205/// Maps a package permission failure to a refusal.
206pub fn package_failure(error: PackageError) -> Refusal {
207 match error {
208 PackageError::Internal(cause) => Box::new(internal(cause)),
209 _ => Box::new(denied()),
210 }
211}
212
213/// Logs an internal failure and boxes the 500 as a refusal.
214pub fn internal_refusal(error: impl std::fmt::Display) -> Refusal {
215 Box::new(internal(error))
216}
217
218/// The current time in seconds since the epoch.
219pub fn unix_now() -> i64 {
220 std::time::SystemTime::now()
221 .duration_since(std::time::UNIX_EPOCH)
222 .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
223}