1use bynk_driver::emsg;
20use std::io::Read;
21use std::path::{Component, Path, PathBuf};
22
23use serde_json::json;
24use sha2::{Digest, Sha256};
25
26use super::commands::{
27 Refusal, admit, read_config, signing_key, write_private, write_replacing, yank_line,
28};
29use super::protocol::Config;
30
31const MAX_UPLOAD: u64 = 64 * 1024 * 1024;
33
34pub const DEFAULT_LISTEN: &str = "127.0.0.1:8730";
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39struct TokenEntry {
40 sha256: String,
41 organisations: Vec<String>,
42 can: Vec<String>,
43}
44
45pub fn serve(
49 dir: &Path,
50 key_file: &Path,
51 tokens_file: &Path,
52 listen: &str,
53 ready: impl FnOnce(&str),
54) -> Result<(), String> {
55 for (what, path) in [("signing key", key_file), ("tokens file", tokens_file)] {
56 if inside(path, dir) {
57 return Err(format!(
58 "the {what} `{}` is inside the registry directory, which is served — keep it elsewhere",
59 path.display()
60 ));
61 }
62 }
63 let mut config = read_config(dir)?;
64 let key = signing_key(key_file)?;
65 super::commands::current_key(&config, &key, key_file)?;
66 if config.api.is_none() {
67 config.api = Some("api".to_string());
68 write_replacing(&dir.join("config.json"), config.render().as_bytes())
69 .map_err(|e| format!("could not record the API in `config.json`: {e}"))?;
70 }
71 let tokens = read_tokens(tokens_file)?;
72 let server = tiny_http::Server::http(listen)
73 .map_err(|e| format!("could not listen on `{listen}`: {e}"))?;
74 let bound = server
75 .server_addr()
76 .to_ip()
77 .ok_or("the server isn't on an IP address")?;
78 if !bound.ip().is_loopback() {
79 emsg!(
80 "bynk: warning: serving on {bound}, beyond this machine, over plain HTTP — tokens travel in clear unless a TLS-terminating proxy is in front"
81 );
82 }
83 ready(&format!("http://{bound}"));
84 for mut request in server.incoming_requests() {
85 let (status, body, kind) = handle(dir, &config, &key, &tokens, &mut request);
86 let response = tiny_http::Response::from_data(body)
87 .with_status_code(status)
88 .with_header(
89 tiny_http::Header::from_bytes(&b"Content-Type"[..], kind.as_bytes())
90 .expect("a valid header"),
91 );
92 let _ = request.respond(response);
93 }
94 Ok(())
95}
96
97fn handle(
99 dir: &Path,
100 config: &Config,
101 key: &super::protocol::SigningKey,
102 tokens: &[TokenEntry],
103 request: &mut tiny_http::Request,
104) -> (u16, Vec<u8>, &'static str) {
105 let url = request
106 .url()
107 .split(['?', '#'])
108 .next()
109 .unwrap_or("/")
110 .to_string();
111 let method = request.method().clone();
112 if let Some(rest) = url.strip_prefix("/api/") {
113 let parts: Vec<&str> = rest.split('/').collect();
114 let error = |status: u16, code: &str, message: String| {
115 (
116 status,
117 json!({ "error": code, "message": message })
118 .to_string()
119 .into_bytes(),
120 "application/json",
121 )
122 };
123 let token = request
124 .headers()
125 .iter()
126 .find(|h| h.field.equiv("Authorization"))
127 .and_then(|h| h.value.as_str().strip_prefix("Bearer ").map(str::to_owned));
128 let authorise = |org: &str, cap: &str| -> Result<(), (u16, Vec<u8>, &'static str)> {
129 let Some(token) = &token else {
130 return Err(error(
131 401,
132 "unauthorised",
133 "this registry needs a publish token".into(),
134 ));
135 };
136 let digest = hex(&Sha256::digest(token.as_bytes()));
137 let Some(entry) = tokens
138 .iter()
139 .find(|t| constant_time_eq(t.sha256.as_bytes(), digest.as_bytes()))
140 else {
141 return Err(error(
142 401,
143 "unauthorised",
144 "the token isn't known to this registry".into(),
145 ));
146 };
147 if !entry.organisations.iter().any(|o| o == org) {
148 return Err(error(
149 403,
150 "forbidden",
151 format!("the token can't act for the organisation `{org}`"),
152 ));
153 }
154 if !entry.can.iter().any(|c| c == cap) {
155 return Err(error(403, "forbidden", format!("the token can't `{cap}`")));
156 }
157 Ok(())
158 };
159 return match (method, parts.as_slice()) {
160 (tiny_http::Method::Put, [org, package, version]) => {
161 if let Err(e) = authorise(org, "publish") {
162 return e;
163 }
164 if request.body_length().is_some_and(|n| n as u64 > MAX_UPLOAD) {
165 return error(
166 413,
167 "too_large",
168 format!("an upload is limited to {MAX_UPLOAD} bytes"),
169 );
170 }
171 let mut upload = Vec::new();
172 if request
173 .as_reader()
174 .take(MAX_UPLOAD + 1)
175 .read_to_end(&mut upload)
176 .is_err()
177 {
178 return error(400, "invalid_package", "the upload couldn't be read".into());
179 }
180 if upload.len() as u64 > MAX_UPLOAD {
181 return error(
182 413,
183 "too_large",
184 format!("an upload is limited to {MAX_UPLOAD} bytes"),
185 );
186 }
187 let name = format!("{org}/{package}");
188 match admit(dir, config, key, &upload, Some((&name, version))) {
189 Ok(a) => (
192 if a.fresh { 201 } else { 200 },
193 a.line.render().into_bytes(),
194 "application/json",
195 ),
196 Err(r) => refusal(r),
197 }
198 }
199 (tiny_http::Method::Post, [org, package, version, verb @ ("yank" | "unyank")]) => {
200 if let Err(e) = authorise(org, "yank") {
201 return e;
202 }
203 match yank_line(dir, &format!("{org}/{package}"), version, *verb == "unyank") {
204 Ok(()) => (
205 200,
206 json!({ "ok": true }).to_string().into_bytes(),
207 "application/json",
208 ),
209 Err(r) if r.code == "withdrawn" => {
212 let (_, body, kind) = refusal(r);
213 (409, body, kind)
214 }
215 Err(r) => refusal(r),
216 }
217 }
218 _ => error(404, "not_found", format!("no API endpoint at `{url}`")),
219 };
220 }
221 if method != tiny_http::Method::Get {
222 return (405, Vec::new(), "text/plain");
223 }
224 match served_path(dir, &url).and_then(|p| std::fs::read(p).ok()) {
225 Some(bytes) => (200, bytes, "application/octet-stream"),
226 None => (404, Vec::new(), "text/plain"),
227 }
228}
229
230fn refusal(r: Refusal) -> (u16, Vec<u8>, &'static str) {
232 let status = match r.code {
233 "invalid_package" => 400,
234 "version_exists" => 409,
235 "withdrawn" => 410,
236 "not_found" => 404,
237 "too_large" => 413,
238 _ => 500,
239 };
240 (
241 status,
242 json!({ "error": r.code, "message": r.message })
243 .to_string()
244 .into_bytes(),
245 "application/json",
246 )
247}
248
249fn served_path(dir: &Path, url: &str) -> Option<PathBuf> {
251 let rel = url.trim_start_matches('/');
252 if rel.is_empty() || rel.contains('\\') {
253 return None;
254 }
255 let path = Path::new(rel);
256 if !path.components().all(|c| matches!(c, Component::Normal(_))) {
257 return None;
258 }
259 let full = dir.join(path);
260 full.is_file().then_some(full)
261}
262
263pub fn mint(
267 tokens_file: &Path,
268 organisations: &[String],
269 can: &[String],
270) -> Result<String, String> {
271 if organisations.is_empty() {
272 return Err("name at least one organisation with `--org`".to_string());
273 }
274 for org in organisations {
275 if let Some(problem) = bynk_project::manifest::org_problem(org) {
276 return Err(format!("`{org}` isn't an organisation: {problem}"));
277 }
278 }
279 for c in can {
280 if c != "publish" && c != "yank" {
281 return Err(format!("`{c}` isn't a capability: use `publish` or `yank`"));
282 }
283 }
284 let mut raw = [0u8; 32];
285 ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw)
286 .map_err(|_| "could not generate a token".to_string())?;
287 let token = format!("bynk_{}", hex(&raw));
288 let mut text = std::fs::read_to_string(tokens_file).unwrap_or_default();
289 if !text.is_empty() && !text.ends_with('\n') {
290 text.push('\n');
291 }
292 let list = |xs: &[String]| {
293 xs.iter()
294 .map(|x| format!("\"{x}\""))
295 .collect::<Vec<_>>()
296 .join(", ")
297 };
298 text.push_str(&format!(
299 "\n[[token]]\nsha256 = \"{}\"\norganisations = [{}]\ncan = [{}]\n",
300 hex(&Sha256::digest(token.as_bytes())),
301 list(organisations),
302 list(can),
303 ));
304 write_private(tokens_file, text.as_bytes())?;
305 Ok(token)
306}
307
308fn read_tokens(path: &Path) -> Result<Vec<TokenEntry>, String> {
309 let text = std::fs::read_to_string(path)
310 .map_err(|e| format!("could not read the tokens file `{}`: {e}", path.display()))?;
311 let doc: toml::Table = text
312 .parse()
313 .map_err(|e| format!("the tokens file `{}` isn't TOML: {e}", path.display()))?;
314 let list = |v: Option<&toml::Value>| -> Vec<String> {
315 v.and_then(|v| v.as_array())
316 .map(|a| {
317 a.iter()
318 .filter_map(|x| x.as_str().map(str::to_owned))
319 .collect()
320 })
321 .unwrap_or_default()
322 };
323 let entries = doc
324 .get("token")
325 .and_then(|v| v.as_array())
326 .map(|a| {
327 a.iter()
328 .filter_map(|t| {
329 Some(TokenEntry {
330 sha256: t.get("sha256")?.as_str()?.to_ascii_lowercase(),
331 organisations: list(t.get("organisations")),
332 can: list(t.get("can")),
333 })
334 })
335 .collect()
336 })
337 .unwrap_or_default();
338 Ok(entries)
339}
340
341fn inside(path: &Path, dir: &Path) -> bool {
342 let abs = |p: &Path| {
343 p.canonicalize()
344 .unwrap_or_else(|_| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()))
345 };
346 abs(path).starts_with(abs(dir))
347}
348
349fn hex(bytes: &[u8]) -> String {
350 bytes.iter().map(|b| format!("{b:02x}")).collect()
351}
352
353fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
355 a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
356}