1#[cfg(test)]
6mod lookup_tests;
7
8use std::{
9 fs,
10 io::{Read, Write},
11 net::IpAddr,
12 path::Path,
13 sync::OnceLock,
14 time::Duration,
15};
16
17use reqwest::{Method, Response, StatusCode, Url};
18use serde::{Deserialize, Serialize};
19use serde_json::{Value, json};
20
21use super::storage::{Storage, Tokens};
22use crate::remote::Record;
23
24pub const CONFIG: &str = "remote.json";
25const TOKEN: &str = "remote-token.json";
26const LOGIN: &str = "run `artifactize remote login URL` or set ARTIFACTIZE_REMOTE_TOKEN";
27const MAX_TOKEN_BYTES: usize = 4096;
30const MAX_CONFIG_BYTES: u64 = 64 * 1024;
33const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
35const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
37const MAX_ERROR_CHARS: usize = 300;
39
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
41#[serde(rename_all = "lowercase")]
42pub enum Share {
43 #[default]
45 Summary,
46 Full,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
51#[serde(rename_all = "lowercase")]
52pub enum TokenSource {
53 Env,
54 File,
55 None,
56}
57
58#[derive(Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60struct Config {
61 url: String,
62 #[serde(default)]
63 share: Share,
64}
65
66#[derive(Serialize, Deserialize)]
67#[serde(deny_unknown_fields)]
68struct StoredToken {
69 url: String,
70 token: String,
71}
72
73pub struct Remote {
75 url: Url,
76 pub share: Share,
77 token: Credential,
78 client: OnceLock<reqwest::Client>,
79}
80
81enum Credential {
82 None,
83 Environment(BearerToken),
84 File(BearerToken),
85}
86
87impl Credential {
88 fn as_deref(&self) -> Option<&str> {
89 match self {
90 Self::None => None,
91 Self::Environment(token) | Self::File(token) => Some(&token.0),
92 }
93 }
94
95 fn source(&self) -> TokenSource {
96 match self {
97 Self::None => TokenSource::None,
98 Self::Environment(_) => TokenSource::Env,
99 Self::File(_) => TokenSource::File,
100 }
101 }
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct Principal {
106 pub principal: crate::types::TokenName,
107 pub scopes: Vec<Scope>,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(from = "String", into = "String")]
114pub enum Scope {
115 Read,
116 Publish,
117 Human,
118 Other(String),
119}
120
121impl From<String> for Scope {
122 fn from(name: String) -> Self {
123 match name.as_str() {
124 "read" => Self::Read,
125 "publish" => Self::Publish,
126 "human" => Self::Human,
127 _ => Self::Other(name),
128 }
129 }
130}
131
132impl From<Scope> for String {
133 fn from(scope: Scope) -> Self {
134 scope.to_string()
135 }
136}
137
138impl std::fmt::Display for Scope {
139 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 formatter.write_str(match self {
141 Self::Read => "read",
142 Self::Publish => "publish",
143 Self::Human => "human",
144 Self::Other(name) => name,
145 })
146 }
147}
148
149#[derive(Debug)]
150pub enum Failure {
151 Transport(String),
152 HttpRefusal(String),
153 ServerOutage(String),
154 LocalSetup(String),
155}
156
157impl Failure {
158 pub fn message(&self) -> &str {
159 match self {
160 Self::Transport(message)
161 | Self::HttpRefusal(message)
162 | Self::ServerOutage(message)
163 | Self::LocalSetup(message) => message,
164 }
165 }
166}
167
168impl From<Failure> for String {
169 fn from(failure: Failure) -> Self {
170 match failure {
171 Failure::Transport(message)
172 | Failure::HttpRefusal(message)
173 | Failure::ServerOutage(message)
174 | Failure::LocalSetup(message) => message,
175 }
176 }
177}
178
179fn variable(name: &str) -> Option<String> {
180 crate::platform::environment::var_text(name).filter(|value| !value.is_empty())
181}
182
183pub fn parse_url(value: &str) -> Result<Url, String> {
185 let mut url = Url::parse(value).map_err(|_| "Invalid remote URL.".to_owned())?;
186 if !url.username().is_empty()
187 || url.password().is_some()
188 || url.query().is_some()
189 || url.fragment().is_some()
190 {
191 return Err("The remote URL must not contain credentials, a query or a fragment.".into());
192 }
193 let loopback = match url.host() {
194 Some(url::Host::Domain(host)) => host == "localhost",
195 Some(url::Host::Ipv4(ip)) => IpAddr::V4(ip).is_loopback(),
196 Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).is_loopback(),
197 None => false,
198 };
199 if !((url.scheme() == "https" && url.host().is_some()) || (url.scheme() == "http" && loopback))
200 {
201 return Err("The remote URL must use https:// (http:// only on loopback).".into());
202 }
203 if !url.path().ends_with('/') {
204 url.set_path(&format!("{}/", url.path()));
205 }
206 Ok(url)
207}
208
209pub struct BearerToken(String);
211
212impl TryFrom<String> for BearerToken {
213 type Error = String;
214
215 fn try_from(token: String) -> Result<Self, Self::Error> {
216 if (1..=MAX_TOKEN_BYTES).contains(&token.len())
217 && token.bytes().all(|byte| byte.is_ascii_graphic())
218 {
219 Ok(Self(token))
220 } else {
221 Err(format!(
222 "A remote token is 1–{MAX_TOKEN_BYTES} printable ASCII characters without spaces."
223 ))
224 }
225 }
226}
227
228fn read_config(state: &Path) -> Result<Option<Config>, String> {
229 let file = match crate::platform::open_no_follow(
230 fs::OpenOptions::new().read(true),
231 &state.join(CONFIG),
232 ) {
233 Ok(file) => file,
234 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
235 Err(error) => return Err(format!("Cannot read {CONFIG}: {error}")),
236 };
237 if !file.metadata().map_err(|e| e.to_string())?.is_file() {
238 return Err(format!("{CONFIG} must be a regular file."));
239 }
240 let mut data = Vec::new();
241 file.take(MAX_CONFIG_BYTES + 1)
242 .read_to_end(&mut data)
243 .map_err(|e| e.to_string())?;
244 serde_json::from_slice(&data).map(Some).map_err(|_| {
245 format!("Invalid {CONFIG}; expected {{\"url\":\"https://...\",\"share\":\"summary\"}}.")
246 })
247}
248
249pub fn remote(state: Option<&Path>, repo: Option<&Path>) -> Result<Option<Remote>, String> {
252 let state_dir = crate::store::state_dir(state)?;
253 let config = read_config(&state_dir)?;
254 let url = match (variable("ARTIFACTIZE_REMOTE"), &config) {
255 (Some(url), _) if url == "off" => return Ok(None),
256 (Some(url), _) => url,
257 (None, Some(config)) => config.url.clone(),
258 (None, None) => return Ok(None),
259 };
260 let url = parse_url(&url)?;
261 let share = match variable("ARTIFACTIZE_REMOTE_SHARE") {
262 Some(share) => serde_json::from_value(serde_json::Value::String(share))
263 .map_err(|_| "ARTIFACTIZE_REMOTE_SHARE must be summary or full.".to_owned())?,
264 None => config.map(|config| config.share).unwrap_or_default(),
265 };
266 let token = if let Some(token) = variable("ARTIFACTIZE_REMOTE_TOKEN") {
267 Credential::Environment(
268 token
269 .try_into()
270 .map_err(|e| format!("ARTIFACTIZE_REMOTE_TOKEN: {e}"))?,
271 )
272 } else {
273 match Storage::inspect(Some(&state_dir), repo, Tokens::Remote)?
274 .read::<StoredToken>(TOKEN)?
275 {
276 Some(stored) if parse_url(&stored.url)?.origin() == url.origin() => {
277 Credential::File(stored.token.try_into()?)
278 }
279 Some(_) => {
281 return Err(format!(
282 "The stored remote token was issued for another store; {LOGIN}."
283 ));
284 }
285 None => Credential::None,
286 }
287 };
288 Ok(Some(Remote {
289 url,
290 share,
291 token,
292 client: OnceLock::new(),
293 }))
294}
295
296fn client() -> Result<reqwest::Client, Failure> {
297 reqwest::Client::builder()
298 .connect_timeout(CONNECT_TIMEOUT)
299 .timeout(REQUEST_TIMEOUT)
300 .redirect(reqwest::redirect::Policy::none())
301 .build()
302 .map_err(|error| Failure::LocalSetup(error.to_string()))
303}
304
305fn tls(error: &(dyn std::error::Error + 'static)) -> bool {
308 match error.downcast_ref::<std::io::Error>() {
309 Some(io) => {
310 io.kind() == std::io::ErrorKind::InvalidData
311 || io.get_ref().is_some_and(|inner| tls(inner))
312 }
313 None => error.source().is_some_and(tls),
314 }
315}
316
317fn transport(error: reqwest::Error) -> Failure {
318 let tls = tls(&error);
319 let cause = std::iter::successors(Some(&error as &dyn std::error::Error), |error| {
320 error.source()
321 })
322 .last()
323 .map(ToString::to_string)
324 .unwrap_or_default();
325 if tls {
326 Failure::LocalSetup(format!("TLS with the remote store failed: {cause}"))
327 } else {
328 let message = format!("Remote store is unreachable: {cause}");
329 if error.is_connect() || error.is_timeout() {
330 Failure::Transport(message)
331 } else {
332 Failure::LocalSetup(message)
333 }
334 }
335}
336
337fn diagnostic(text: &str, token: Option<&str>) -> String {
340 crate::secret::server_text(text, token.as_slice(), MAX_ERROR_CHARS)
341}
342
343impl Remote {
344 pub fn url(&self) -> &Url {
345 &self.url
346 }
347
348 pub fn token_source(&self) -> TokenSource {
349 self.token.source()
350 }
351
352 fn request(&self, method: Method, route: &str) -> Result<reqwest::RequestBuilder, Failure> {
353 let client = match self.client.get() {
355 Some(client) => client,
356 None => {
357 let built = client()?;
358 self.client.get_or_init(|| built)
359 }
360 };
361 let url = self
362 .url
363 .join(route)
364 .map_err(|_| Failure::LocalSetup("Invalid route for the remote store.".into()))?;
365 let mut request = client.request(method, url);
366 if let Some(token) = self.token.as_deref() {
367 request = request.bearer_auth(token);
368 }
369 Ok(request)
370 }
371
372 async fn send(&self, request: reqwest::RequestBuilder) -> Result<Response, Failure> {
374 let response = request.send().await.map_err(transport)?;
375 let status = response.status();
376 if status.is_success() {
377 return Ok(response);
378 }
379 let failure = if status.is_server_error() {
380 Failure::ServerOutage
381 } else {
382 Failure::HttpRefusal
383 };
384 Err(match status {
385 StatusCode::UNAUTHORIZED if matches!(self.token, Credential::None) => {
386 failure(format!("No remote token; {LOGIN}."))
387 }
388 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => failure(format!(
389 "The remote store rejected the token (HTTP {}).",
390 status.as_u16()
391 )),
392 _ => {
393 let detail = if status.is_client_error() {
395 response.json::<Value>().await.ok().and_then(|body| {
396 body["error"]
397 .as_str()
398 .map(|error| diagnostic(error, self.token.as_deref()))
399 })
400 } else {
401 None
402 };
403 failure(match detail {
404 Some(detail) => format!(
405 "The remote store answered HTTP {}: {detail}",
406 status.as_u16()
407 ),
408 None => format!("The remote store answered HTTP {}.", status.as_u16()),
409 })
410 }
411 })
412 }
413
414 async fn json<T: serde::de::DeserializeOwned>(
415 response: Response,
416 route: &str,
417 ) -> Result<T, Failure> {
418 response
419 .json()
420 .await
421 .map_err(|_| Failure::HttpRefusal(format!("Invalid remote {route} response.")))
422 }
423
424 pub async fn whoami(&self) -> Result<Principal, Failure> {
426 let response = self.send(self.request(Method::GET, "v1/whoami")?).await?;
427 Self::json(response, "whoami").await
428 }
429
430 pub async fn lookup(
432 &self,
433 keys: &[crate::types::ReuseKey],
434 ) -> Result<Vec<Result<Record, String>>, Failure> {
435 #[derive(Deserialize)]
436 struct Found {
437 entries: Vec<Value>,
438 }
439 let mut entries = Vec::new();
440 for chunk in keys.chunks(crate::server::MAX_LOOKUP_KEYS) {
441 let request = self
442 .request(Method::POST, "v1/lookup")?
443 .json(&json!({ "keys": chunk }));
444 let found: Found = Self::json(self.send(request).await?, "lookup").await?;
445 entries.extend(found.entries.into_iter().map(|entry| {
447 serde_json::from_value::<Record>(entry)
448 .map_err(|error| diagnostic(&error.to_string(), self.token.as_deref()))
449 }));
450 }
451 Ok(entries)
452 }
453
454 pub async fn publish(&self, record: &Record) -> Result<bool, Failure> {
456 #[derive(Deserialize)]
457 struct Published {
458 created: bool,
459 }
460 let route = format!("v1/entries/{}", record.key);
461 let request = self.request(Method::PUT, &route)?.json(record);
462 let published: Published = Self::json(self.send(request).await?, "publish").await?;
463 Ok(published.created)
464 }
465}
466
467pub async fn login(
469 state: Option<&Path>,
470 repo: Option<&Path>,
471 url: Url,
472 share: Share,
473 token: BearerToken,
474) -> Result<(Remote, Principal), String> {
475 let url = parse_url(url.as_str())?;
476 let remote = Remote {
477 url,
478 share,
479 token: Credential::File(token),
480 client: OnceLock::new(),
481 };
482 let principal = remote.whoami().await.map_err(String::from)?;
483 let storage = Storage::new(state, repo, Tokens::Remote)?;
484 storage.save(
485 TOKEN,
486 &StoredToken {
487 url: remote.url.to_string(),
488 token: remote.token.as_deref().expect("login token").to_owned(),
489 },
490 )?;
491 let state = crate::store::state_dir(state)?;
492 let mut file = tempfile::NamedTempFile::new_in(&state).map_err(|e| e.to_string())?;
493 serde_json::to_writer(
494 &mut file,
495 &Config {
496 url: remote.url.to_string(),
497 share,
498 },
499 )
500 .map_err(|e| e.to_string())?;
501 file.flush().map_err(|e| e.to_string())?;
502 crate::platform::paths::replace_open_file(file, &state.join(CONFIG))
503 .map_err(|error| error.to_string())?;
504 Ok((remote, principal))
505}
506
507#[derive(Debug, Clone)]
510pub struct Status {
511 pub url: String,
512 pub share: Share,
513 pub token_source: TokenSource,
514 pub connection: Connection,
515}
516
517#[derive(Debug, Clone)]
519pub enum Connection {
520 SignedIn {
522 principal: crate::types::TokenName,
523 scopes: Vec<Scope>,
524 },
525 Refused { error: String },
527 Unreachable { error: String },
529}
530
531impl Status {
532 pub fn signed_in(&self) -> bool {
534 matches!(self.connection, Connection::SignedIn { .. })
535 }
536
537 pub fn reachable(&self) -> bool {
539 !matches!(self.connection, Connection::Unreachable { .. })
540 }
541
542 pub fn error(&self) -> Option<&str> {
544 match &self.connection {
545 Connection::SignedIn { .. } => None,
546 Connection::Refused { error } | Connection::Unreachable { error } => Some(error),
547 }
548 }
549}
550
551impl Serialize for Status {
553 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
554 #[derive(Serialize)]
555 #[serde(rename_all = "camelCase")]
556 struct Wire<'a> {
557 url: &'a str,
558 share: Share,
559 token_source: TokenSource,
560 reachable: bool,
561 principal: Option<&'a crate::types::TokenName>,
562 scopes: Option<&'a [Scope]>,
563 error: Option<&'a str>,
564 }
565 let (principal, scopes) = match &self.connection {
566 Connection::SignedIn { principal, scopes } => {
567 (Some(principal), Some(scopes.as_slice()))
568 }
569 _ => (None, None),
570 };
571 Wire {
572 url: &self.url,
573 share: self.share,
574 token_source: self.token_source,
575 reachable: self.reachable(),
576 principal,
577 scopes,
578 error: self.error(),
579 }
580 .serialize(serializer)
581 }
582}
583
584pub async fn status(state: Option<&Path>, repo: Option<&Path>) -> Result<Option<Status>, String> {
587 let Some(remote) = remote(state, repo)? else {
588 return Ok(None);
589 };
590 let connection = match remote.whoami().await {
591 Ok(principal) => Connection::SignedIn {
592 principal: principal.principal,
593 scopes: principal.scopes,
594 },
595 Err(Failure::HttpRefusal(error) | Failure::ServerOutage(error)) => {
596 Connection::Refused { error }
597 }
598 Err(failure) => Connection::Unreachable {
599 error: failure.into(),
600 },
601 };
602 Ok(Some(Status {
603 url: remote.url.to_string(),
604 share: remote.share,
605 token_source: remote.token_source(),
606 connection,
607 }))
608}
609
610pub fn logout(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
612 Storage::new(state, repo, Tokens::Remote)?.remove(TOKEN)?;
613 match crate::platform::paths::remove_open_file(&crate::store::state_dir(state)?.join(CONFIG)) {
615 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),
616 _ => Ok(()),
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use super::*;
623
624 #[test]
625 fn nested_invalid_data_is_a_tls_failure() {
626 use std::io::{Error, ErrorKind};
627 let handshake = Error::other(Error::new(ErrorKind::InvalidData, "bad certificate"));
628 assert!(tls(&handshake));
629 assert!(!tls(&Error::from(ErrorKind::ConnectionRefused)));
630 }
631
632 #[test]
633 fn urls_need_https_except_on_loopback() {
634 for url in [
635 "https://reviews.example",
636 "https://reviews.example/team/",
637 "http://127.0.0.1:8417",
638 "http://[::1]:8417/",
639 "http://localhost:8417/",
640 ] {
641 assert!(parse_url(url).unwrap().path().ends_with('/'), "{url}");
642 }
643 for url in [
644 "http://reviews.example/",
645 "http://10.0.0.1/",
646 "https://user:secret@reviews.example/",
647 "https://reviews.example/?token=x",
648 "ftp://reviews.example/",
649 "reviews.example",
650 ] {
651 assert!(parse_url(url).is_err(), "{url}");
652 }
653 }
654}