Skip to main content

artifactize_core/auth/
remote.rs

1//! Remote review store configuration and its bearer token.
2//!
3//! The remote is configured only by `$STATE/remote.json` and the environment, never by
4//! `index.artf`. Callers must never print or log the token.
5#[cfg(test)]
6#[path = "remote/tests/lookup.rs"]
7mod lookup_tests;
8
9use std::{
10    fs,
11    io::{Read, Write},
12    net::IpAddr,
13    path::Path,
14    sync::OnceLock,
15    time::Duration,
16};
17
18use reqwest::{Method, Response, StatusCode, Url};
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21
22use super::storage::{Storage, Tokens};
23use crate::remote::Record;
24
25pub const CONFIG: &str = "remote.json";
26const TOKEN: &str = "remote-token.json";
27const LOGIN: &str = "run `artifactize remote login URL` or set ARTIFACTIZE_REMOTE_TOKEN";
28/// Bound bearer-header size while allowing token formats larger than this server's
29/// generated tokens; validation is identical for environment and saved tokens.
30const MAX_TOKEN_BYTES: usize = 4096;
31/// A URL/share declaration is small; bound its read so malformed local config
32/// cannot cause unbounded allocation. The existing parser sees one extra byte.
33const MAX_CONFIG_BYTES: u64 = 64 * 1024;
34/// Remote reuse is optional; fail an unreachable connection quickly so local work resumes.
35const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
36/// Bound each review-store request, including response reads, independently of provider work.
37const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
38/// Clip server-supplied client-error explanations before they enter CLI/audit diagnostics.
39const MAX_ERROR_CHARS: usize = 300;
40
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
42#[serde(rename_all = "lowercase")]
43pub enum Share {
44    /// Reduced records without argv, captured output, tool calls or paths.
45    #[default]
46    Summary,
47    /// Also the saved execution as is.
48    Full,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
52#[serde(rename_all = "lowercase")]
53pub enum TokenSource {
54    Env,
55    File,
56    None,
57}
58
59#[derive(Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61struct Config {
62    url: String,
63    #[serde(default)]
64    share: Share,
65}
66
67#[derive(Serialize, Deserialize)]
68#[serde(deny_unknown_fields)]
69struct StoredToken {
70    url: String,
71    token: String,
72}
73
74/// A resolved remote; its token is private and never serialized.
75pub struct Remote {
76    url: Url,
77    pub share: Share,
78    token: Credential,
79    client: OnceLock<reqwest::Client>,
80}
81
82enum Credential {
83    None,
84    Environment(BearerToken),
85    File(BearerToken),
86}
87
88impl Credential {
89    fn as_deref(&self) -> Option<&str> {
90        match self {
91            Self::None => None,
92            Self::Environment(token) | Self::File(token) => Some(&token.0),
93        }
94    }
95
96    fn source(&self) -> TokenSource {
97        match self {
98            Self::None => TokenSource::None,
99            Self::Environment(_) => TokenSource::Env,
100            Self::File(_) => TokenSource::File,
101        }
102    }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct Principal {
107    pub principal: crate::types::TokenName,
108    pub scopes: Vec<Scope>,
109}
110
111/// A permission a remote token grants, as the server names it. A scope this version does
112/// not know is kept by its name, so it is still shown, but it grants nothing here.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(from = "String", into = "String")]
115pub enum Scope {
116    Read,
117    Publish,
118    Human,
119    Other(String),
120}
121
122impl From<String> for Scope {
123    fn from(name: String) -> Self {
124        match name.as_str() {
125            "read" => Self::Read,
126            "publish" => Self::Publish,
127            "human" => Self::Human,
128            _ => Self::Other(name),
129        }
130    }
131}
132
133impl From<Scope> for String {
134    fn from(scope: Scope) -> Self {
135        scope.to_string()
136    }
137}
138
139impl std::fmt::Display for Scope {
140    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        formatter.write_str(match self {
142            Self::Read => "read",
143            Self::Publish => "publish",
144            Self::Human => "human",
145            Self::Other(name) => name,
146        })
147    }
148}
149
150#[derive(Debug)]
151pub enum Failure {
152    Transport(String),
153    HttpRefusal(String),
154    ServerOutage(String),
155    LocalSetup(String),
156}
157
158impl Failure {
159    pub fn message(&self) -> &str {
160        match self {
161            Self::Transport(message)
162            | Self::HttpRefusal(message)
163            | Self::ServerOutage(message)
164            | Self::LocalSetup(message) => message,
165        }
166    }
167}
168
169impl From<Failure> for String {
170    fn from(failure: Failure) -> Self {
171        match failure {
172            Failure::Transport(message)
173            | Failure::HttpRefusal(message)
174            | Failure::ServerOutage(message)
175            | Failure::LocalSetup(message) => message,
176        }
177    }
178}
179
180fn variable(name: &str) -> Option<String> {
181    crate::platform::environment::var_text(name).filter(|value| !value.is_empty())
182}
183
184/// Accept HTTPS, or plain HTTP only on loopback; never credentials, queries or fragments.
185pub fn parse_url(value: &str) -> Result<Url, String> {
186    let mut url = Url::parse(value).map_err(|_| "Invalid remote URL.".to_owned())?;
187    if !url.username().is_empty()
188        || url.password().is_some()
189        || url.query().is_some()
190        || url.fragment().is_some()
191    {
192        return Err("The remote URL must not contain credentials, a query or a fragment.".into());
193    }
194    let loopback = match url.host() {
195        Some(url::Host::Domain(host)) => host == "localhost",
196        Some(url::Host::Ipv4(ip)) => IpAddr::V4(ip).is_loopback(),
197        Some(url::Host::Ipv6(ip)) => IpAddr::V6(ip).is_loopback(),
198        None => false,
199    };
200    if !((url.scheme() == "https" && url.host().is_some()) || (url.scheme() == "http" && loopback))
201    {
202        return Err("The remote URL must use https:// (http:// only on loopback).".into());
203    }
204    if !url.path().ends_with('/') {
205        url.set_path(&format!("{}/", url.path()));
206    }
207    Ok(url)
208}
209
210/// A validated credential; intentionally not printable or serializable.
211pub struct BearerToken(String);
212
213impl TryFrom<String> for BearerToken {
214    type Error = String;
215
216    fn try_from(token: String) -> Result<Self, Self::Error> {
217        if (1..=MAX_TOKEN_BYTES).contains(&token.len())
218            && token.bytes().all(|byte| byte.is_ascii_graphic())
219        {
220            Ok(Self(token))
221        } else {
222            Err(format!(
223                "A remote token is 1–{MAX_TOKEN_BYTES} printable ASCII characters without spaces."
224            ))
225        }
226    }
227}
228
229fn read_config(state: &Path) -> Result<Option<Config>, String> {
230    let file = match crate::platform::open_no_follow(
231        fs::OpenOptions::new().read(true),
232        &state.join(CONFIG),
233    ) {
234        Ok(file) => file,
235        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
236        Err(error) => return Err(format!("Cannot read {CONFIG}: {error}")),
237    };
238    if !file.metadata().map_err(|e| e.to_string())?.is_file() {
239        return Err(format!("{CONFIG} must be a regular file."));
240    }
241    let mut data = Vec::new();
242    file.take(MAX_CONFIG_BYTES + 1)
243        .read_to_end(&mut data)
244        .map_err(|e| e.to_string())?;
245    serde_json::from_slice(&data).map(Some).map_err(|_| {
246        format!("Invalid {CONFIG}; expected {{\"url\":\"https://...\",\"share\":\"summary\"}}.")
247    })
248}
249
250/// Resolve the remote from the environment and `$STATE/remote.json` without network access.
251/// `None` means no remote is configured or `ARTIFACTIZE_REMOTE=off`.
252pub fn remote(state: Option<&Path>, repo: Option<&Path>) -> Result<Option<Remote>, String> {
253    let state_dir = crate::store::state_dir(state)?;
254    let config = read_config(&state_dir)?;
255    let url = match (variable("ARTIFACTIZE_REMOTE"), &config) {
256        (Some(url), _) if url == "off" => return Ok(None),
257        (Some(url), _) => url,
258        (None, Some(config)) => config.url.clone(),
259        (None, None) => return Ok(None),
260    };
261    let url = parse_url(&url)?;
262    let share = match variable("ARTIFACTIZE_REMOTE_SHARE") {
263        Some(share) => serde_json::from_value(serde_json::Value::String(share))
264            .map_err(|_| "ARTIFACTIZE_REMOTE_SHARE must be summary or full.".to_owned())?,
265        None => config.map(|config| config.share).unwrap_or_default(),
266    };
267    let token = if let Some(token) = variable("ARTIFACTIZE_REMOTE_TOKEN") {
268        Credential::Environment(
269            token
270                .try_into()
271                .map_err(|e| format!("ARTIFACTIZE_REMOTE_TOKEN: {e}"))?,
272        )
273    } else {
274        match Storage::inspect(Some(&state_dir), repo, Tokens::Remote)?
275            .read::<StoredToken>(TOKEN)?
276        {
277            Some(stored) if parse_url(&stored.url)?.origin() == url.origin() => {
278                Credential::File(stored.token.try_into()?)
279            }
280            // A token is bound to the origin it was issued for.
281            Some(_) => {
282                return Err(format!(
283                    "The stored remote token was issued for another store; {LOGIN}."
284                ));
285            }
286            None => Credential::None,
287        }
288    };
289    Ok(Some(Remote {
290        url,
291        share,
292        token,
293        client: OnceLock::new(),
294    }))
295}
296
297fn client() -> Result<reqwest::Client, Failure> {
298    reqwest::Client::builder()
299        .connect_timeout(CONNECT_TIMEOUT)
300        .timeout(REQUEST_TIMEOUT)
301        .redirect(reqwest::redirect::Policy::none())
302        .build()
303        .map_err(|error| Failure::LocalSetup(error.to_string()))
304}
305
306/// rustls reports handshake and certificate failures as InvalidData I/O errors, possibly
307/// nested inside other I/O errors whose `source` skips them.
308fn tls(error: &(dyn std::error::Error + 'static)) -> bool {
309    match error.downcast_ref::<std::io::Error>() {
310        Some(io) => {
311            io.kind() == std::io::ErrorKind::InvalidData
312                || io.get_ref().is_some_and(|inner| tls(inner))
313        }
314        None => error.source().is_some_and(tls),
315    }
316}
317
318fn transport(error: reqwest::Error) -> Failure {
319    let tls = tls(&error);
320    let cause = std::iter::successors(Some(&error as &dyn std::error::Error), |error| {
321        error.source()
322    })
323    .last()
324    .map(ToString::to_string)
325    .unwrap_or_default();
326    if tls {
327        Failure::LocalSetup(format!("TLS with the remote store failed: {cause}"))
328    } else {
329        let message = format!("Remote store is unreachable: {cause}");
330        if error.is_connect() || error.is_timeout() {
331            Failure::Transport(message)
332        } else {
333            Failure::LocalSetup(message)
334        }
335    }
336}
337
338/// A store's own text (an error, a record it could not decode), safe to show and save: the
339/// shared rule for server text that may echo the token this request carried.
340fn diagnostic(text: &str, token: Option<&str>) -> String {
341    crate::secret::server_text(text, token.as_slice(), MAX_ERROR_CHARS)
342}
343
344impl Remote {
345    pub fn url(&self) -> &Url {
346        &self.url
347    }
348
349    pub fn token_source(&self) -> TokenSource {
350        self.token.source()
351    }
352
353    fn request(&self, method: Method, route: &str) -> Result<reqwest::RequestBuilder, Failure> {
354        // One client per process reuses connections and the loaded trust store.
355        let client = match self.client.get() {
356            Some(client) => client,
357            None => {
358                let built = client()?;
359                self.client.get_or_init(|| built)
360            }
361        };
362        let url = self
363            .url
364            .join(route)
365            .map_err(|_| Failure::LocalSetup("Invalid route for the remote store.".into()))?;
366        let mut request = client.request(method, url);
367        if let Some(token) = self.token.as_deref() {
368            request = request.bearer_auth(token);
369        }
370        Ok(request)
371    }
372
373    /// 401/403 and other client errors fail closed; 5xx and transport outages are unavailable.
374    async fn send(&self, request: reqwest::RequestBuilder) -> Result<Response, Failure> {
375        let response = request.send().await.map_err(transport)?;
376        let status = response.status();
377        if status.is_success() {
378            return Ok(response);
379        }
380        let failure = if status.is_server_error() {
381            Failure::ServerOutage
382        } else {
383            Failure::HttpRefusal
384        };
385        Err(match status {
386            StatusCode::UNAUTHORIZED if matches!(self.token, Credential::None) => {
387                failure(format!("No remote token; {LOGIN}."))
388            }
389            StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => failure(format!(
390                "The remote store rejected the token (HTTP {}).",
391                status.as_u16()
392            )),
393            _ => {
394                // A client error explains itself, for example a store of another schema.
395                let detail = if status.is_client_error() {
396                    response.json::<Value>().await.ok().and_then(|body| {
397                        body["error"]
398                            .as_str()
399                            .map(|error| diagnostic(error, self.token.as_deref()))
400                    })
401                } else {
402                    None
403                };
404                failure(match detail {
405                    Some(detail) => format!(
406                        "The remote store answered HTTP {}: {detail}",
407                        status.as_u16()
408                    ),
409                    None => format!("The remote store answered HTTP {}.", status.as_u16()),
410                })
411            }
412        })
413    }
414
415    async fn json<T: serde::de::DeserializeOwned>(
416        response: Response,
417        route: &str,
418    ) -> Result<T, Failure> {
419        response
420            .json()
421            .await
422            .map_err(|_| Failure::HttpRefusal(format!("Invalid remote {route} response.")))
423    }
424
425    /// Ask the server who this token is; works without a token to test reachability.
426    pub async fn whoami(&self) -> Result<Principal, Failure> {
427        let response = self.send(self.request(Method::GET, "v1/whoami")?).await?;
428        Self::json(response, "whoami").await
429    }
430
431    /// Decode each record at the HTTP boundary; malformed entries remain individually skippable.
432    pub async fn lookup(
433        &self,
434        keys: &[crate::types::ReuseKey],
435    ) -> Result<Vec<Result<Record, String>>, Failure> {
436        #[derive(Deserialize)]
437        struct Found {
438            entries: Vec<Value>,
439        }
440        let mut entries = Vec::new();
441        for chunk in keys.chunks(crate::server::MAX_LOOKUP_KEYS) {
442            let request = self
443                .request(Method::POST, "v1/lookup")?
444                .json(&json!({ "keys": chunk }));
445            let found: Found = Self::json(self.send(request).await?, "lookup").await?;
446            // A decode error quotes the record's own fields and values: server text.
447            entries.extend(found.entries.into_iter().map(|entry| {
448                serde_json::from_value::<Record>(entry)
449                    .map_err(|error| diagnostic(&error.to_string(), self.token.as_deref()))
450            }));
451        }
452        Ok(entries)
453    }
454
455    /// Append a record to its key's history; `false` when the store already has this execution.
456    pub async fn publish(&self, record: &Record) -> Result<bool, Failure> {
457        #[derive(Deserialize)]
458        struct Published {
459            created: bool,
460        }
461        let route = format!("v1/entries/{}", record.key);
462        let request = self.request(Method::PUT, &route)?.json(record);
463        let published: Published = Self::json(self.send(request).await?, "publish").await?;
464        Ok(published.created)
465    }
466}
467
468/// Verify a token from stdin against the store, then save it and `remote.json`.
469pub async fn login(
470    state: Option<&Path>,
471    repo: Option<&Path>,
472    url: Url,
473    share: Share,
474    token: BearerToken,
475) -> Result<(Remote, Principal), String> {
476    let url = parse_url(url.as_str())?;
477    let remote = Remote {
478        url,
479        share,
480        token: Credential::File(token),
481        client: OnceLock::new(),
482    };
483    let principal = remote.whoami().await.map_err(String::from)?;
484    let storage = Storage::new(state, repo, Tokens::Remote)?;
485    storage.save(
486        TOKEN,
487        &StoredToken {
488            url: remote.url.to_string(),
489            token: remote.token.as_deref().expect("login token").to_owned(),
490        },
491    )?;
492    let state = crate::store::state_dir(state)?;
493    let mut file = tempfile::NamedTempFile::new_in(&state).map_err(|e| e.to_string())?;
494    serde_json::to_writer(
495        &mut file,
496        &Config {
497            url: remote.url.to_string(),
498            share,
499        },
500    )
501    .map_err(|e| e.to_string())?;
502    file.flush().map_err(|e| e.to_string())?;
503    crate::platform::paths::replace_open_file(file, &state.join(CONFIG))
504        .map_err(|error| error.to_string())?;
505    Ok((remote, principal))
506}
507
508/// What `remote status` reports: where the remote is, what it shares, where its token comes
509/// from, and whether the store answers to it. Never the token.
510#[derive(Debug, Clone)]
511pub struct Status {
512    pub url: String,
513    pub share: Share,
514    pub token_source: TokenSource,
515    pub connection: Connection,
516}
517
518/// What asking the store who the token belongs to came to.
519#[derive(Debug, Clone)]
520pub enum Connection {
521    /// The token was accepted.
522    SignedIn {
523        principal: crate::types::TokenName,
524        scopes: Vec<Scope>,
525    },
526    /// The store answered with an HTTP response, but not with an accepted token.
527    Refused { error: String },
528    /// The store sent no HTTP response.
529    Unreachable { error: String },
530}
531
532impl Status {
533    /// The token was accepted.
534    pub fn signed_in(&self) -> bool {
535        matches!(self.connection, Connection::SignedIn { .. })
536    }
537
538    /// The store sent an HTTP response, whether or not it accepted the token.
539    pub fn reachable(&self) -> bool {
540        !matches!(self.connection, Connection::Unreachable { .. })
541    }
542
543    /// Why the token was not accepted.
544    pub fn error(&self) -> Option<&str> {
545        match &self.connection {
546            Connection::SignedIn { .. } => None,
547            Connection::Refused { error } | Connection::Unreachable { error } => Some(error),
548        }
549    }
550}
551
552/// The fields of `remote status --json`, which stay as they were.
553impl Serialize for Status {
554    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
555        #[derive(Serialize)]
556        #[serde(rename_all = "camelCase")]
557        struct Wire<'a> {
558            url: &'a str,
559            share: Share,
560            token_source: TokenSource,
561            reachable: bool,
562            principal: Option<&'a crate::types::TokenName>,
563            scopes: Option<&'a [Scope]>,
564            error: Option<&'a str>,
565        }
566        let (principal, scopes) = match &self.connection {
567            Connection::SignedIn { principal, scopes } => {
568                (Some(principal), Some(scopes.as_slice()))
569            }
570            _ => (None, None),
571        };
572        Wire {
573            url: &self.url,
574            share: self.share,
575            token_source: self.token_source,
576            reachable: self.reachable(),
577            principal,
578            scopes,
579            error: self.error(),
580        }
581        .serialize(serializer)
582    }
583}
584
585/// Resolve the remote and ask the store who its token belongs to; `None` when no remote is
586/// configured (or `ARTIFACTIZE_REMOTE=off`).
587pub async fn status(state: Option<&Path>, repo: Option<&Path>) -> Result<Option<Status>, String> {
588    let Some(remote) = remote(state, repo)? else {
589        return Ok(None);
590    };
591    let connection = match remote.whoami().await {
592        Ok(principal) => Connection::SignedIn {
593            principal: principal.principal,
594            scopes: principal.scopes,
595        },
596        Err(Failure::HttpRefusal(error) | Failure::ServerOutage(error)) => {
597            Connection::Refused { error }
598        }
599        Err(failure) => Connection::Unreachable {
600            error: failure.into(),
601        },
602    };
603    Ok(Some(Status {
604        url: remote.url.to_string(),
605        share: remote.share,
606        token_source: remote.token_source(),
607        connection,
608    }))
609}
610
611/// Forget the stored token and `remote.json`; the server keeps the token until revoked.
612pub fn logout(state: Option<&Path>, repo: Option<&Path>) -> Result<(), String> {
613    Storage::new(state, repo, Tokens::Remote)?.remove(TOKEN)?;
614    // A concurrent status lookup may still have the file open.
615    match crate::platform::paths::remove_open_file(&crate::store::state_dir(state)?.join(CONFIG)) {
616        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),
617        _ => Ok(()),
618    }
619}
620
621#[cfg(test)]
622mod tests;