Skip to main content

cargo_credential/
lib.rs

1//! Helper library for writing Cargo credential providers.
2//!
3//! A credential process should have a `struct` that implements the `Credential` trait.
4//! The `main` function should be called with an instance of that struct, such as:
5//!
6//! ```rust,ignore
7//! fn main() {
8//!     cargo_credential::main(MyCredential);
9//! }
10//! ```
11//!
12//! While in the `perform` function, stdin and stdout will be re-attached to the
13//! active console. This allows credential providers to be interactive if necessary.
14//!
15//! > This crate is maintained by the Cargo team for use by the wider
16//! > ecosystem. This crate follows semver compatibility for its APIs.
17//!
18//! ## Error handling
19//! ### [`Error::UrlNotSupported`]
20//! A credential provider may only support some registry URLs. If this is the case
21//! and an unsupported index URL is passed to the provider, it should respond with
22//! [`Error::UrlNotSupported`]. Other credential providers may be attempted by Cargo.
23//!
24//! ### [`Error::NotFound`]
25//! When attempting an [`Action::Get`] or [`Action::Logout`], if a credential can not
26//! be found, the provider should respond with [`Error::NotFound`]. Other credential
27//! providers may be attempted by Cargo.
28//!
29//! ### [`Error::OperationNotSupported`]
30//! A credential provider might not support all operations. For example if the provider
31//! only supports [`Action::Get`], [`Error::OperationNotSupported`] should be returned
32//! for all other requests.
33//!
34//! ### [`Error::Other`]
35//! All other errors go here. The error will be shown to the user in Cargo, including
36//! the full error chain using [`std::error::Error::source`].
37//!
38//! ## Example
39//! ```rust,ignore
40#![doc = include_str!("../examples/file-provider.rs")]
41//! ```
42
43#![allow(clippy::print_stderr)]
44#![allow(clippy::print_stdout)]
45
46use jiff::Timestamp;
47use serde::{Deserialize, Serialize};
48use std::{fmt::Display, io};
49
50mod error;
51mod secret;
52mod stdio;
53
54pub use error::Error;
55pub use secret::Secret;
56use stdio::stdin_stdout_to_console;
57
58/// Message sent by the credential helper on startup
59#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
60pub struct CredentialHello {
61    // Protocol versions supported by the credential process.
62    pub v: Vec<u32>,
63}
64
65/// Credential provider that doesn't support any registries.
66pub struct UnsupportedCredential;
67impl Credential for UnsupportedCredential {
68    fn perform(
69        &self,
70        _registry: &RegistryInfo<'_>,
71        _action: &Action<'_>,
72        _args: &[&str],
73    ) -> Result<CredentialResponse, Error> {
74        Err(Error::UrlNotSupported)
75    }
76}
77
78/// Message sent by Cargo to the credential helper after the hello
79#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
80#[serde(rename_all = "kebab-case")]
81pub struct CredentialRequest<'a> {
82    // Cargo will respond with the highest common protocol supported by both.
83    pub v: u32,
84    #[serde(borrow)]
85    pub registry: RegistryInfo<'a>,
86    #[serde(borrow, flatten)]
87    pub action: Action<'a>,
88    /// Additional command-line arguments passed to the credential provider.
89    #[serde(skip_serializing_if = "Vec::is_empty", default)]
90    pub args: Vec<&'a str>,
91}
92
93#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
94#[serde(rename_all = "kebab-case")]
95pub struct RegistryInfo<'a> {
96    /// Registry index url
97    pub index_url: &'a str,
98    /// Name of the registry in configuration. May not be available.
99    /// The crates.io registry will be `crates-io` (`CRATES_IO_REGISTRY`).
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub name: Option<&'a str>,
102    /// Headers from attempting to access a registry that resulted in a HTTP 401.
103    #[serde(skip_serializing_if = "Vec::is_empty", default)]
104    pub headers: Vec<String>,
105}
106
107#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
108#[non_exhaustive]
109#[serde(tag = "kind", rename_all = "kebab-case")]
110pub enum Action<'a> {
111    #[serde(borrow)]
112    Get(Operation<'a>),
113    Login(LoginOptions<'a>),
114    Logout,
115    #[serde(other)]
116    Unknown,
117}
118
119impl<'a> Display for Action<'a> {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        match self {
122            Action::Get(_) => f.write_str("get"),
123            Action::Login(_) => f.write_str("login"),
124            Action::Logout => f.write_str("logout"),
125            Action::Unknown => f.write_str("<unknown>"),
126        }
127    }
128}
129
130#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
131#[serde(rename_all = "kebab-case")]
132pub struct LoginOptions<'a> {
133    /// Token passed on the command line via --token or from stdin
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub token: Option<Secret<&'a str>>,
136    /// Optional URL that the user can visit to log in to the registry
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub login_url: Option<&'a str>,
139}
140
141/// A record of what kind of operation is happening that we should generate a token for.
142#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
143#[non_exhaustive]
144#[serde(tag = "operation", rename_all = "kebab-case")]
145pub enum Operation<'a> {
146    /// The user is attempting to fetch a crate.
147    Read,
148    /// The user is attempting to publish a crate.
149    Publish {
150        /// The name of the crate
151        name: &'a str,
152        /// The version of the crate
153        vers: &'a str,
154        /// The checksum of the crate file being uploaded
155        cksum: &'a str,
156    },
157    /// The user is attempting to yank a crate.
158    Yank {
159        /// The name of the crate
160        name: &'a str,
161        /// The version of the crate
162        vers: &'a str,
163    },
164    /// The user is attempting to unyank a crate.
165    Unyank {
166        /// The name of the crate
167        name: &'a str,
168        /// The version of the crate
169        vers: &'a str,
170    },
171    /// The user is attempting to modify the owners of a crate.
172    Owners {
173        /// The name of the crate
174        name: &'a str,
175    },
176    #[serde(other)]
177    Unknown,
178}
179
180/// Message sent by the credential helper
181#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
182#[serde(tag = "kind", rename_all = "kebab-case")]
183#[non_exhaustive]
184pub enum CredentialResponse {
185    Get {
186        token: Secret<String>,
187        #[serde(flatten)]
188        cache: CacheControl,
189        operation_independent: bool,
190    },
191    Login,
192    Logout,
193    #[serde(other)]
194    Unknown,
195}
196
197#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
198#[serde(tag = "cache", rename_all = "kebab-case")]
199#[non_exhaustive]
200pub enum CacheControl {
201    /// Do not cache this result.
202    Never,
203    /// Cache this result and use it for subsequent requests in the current Cargo invocation until the specified time.
204    Expires {
205        /// Serialized as integer Unix seconds.
206        #[serde(with = "jiff::fmt::serde::timestamp::second::required")]
207        expiration: Timestamp,
208    },
209    /// Cache this result and use it for all subsequent requests in the current Cargo invocation.
210    Session,
211    #[serde(other)]
212    Unknown,
213}
214
215/// Credential process JSON protocol version.
216///
217/// If the protocol needs to make
218/// a breaking change, a new protocol version should be defined (`PROTOCOL_VERSION_2`).
219/// This library should offer support for both protocols if possible, by signaling
220/// in the `CredentialHello` message. Cargo will then choose which protocol to use,
221/// or it will error if there are no common protocol versions available.
222pub const PROTOCOL_VERSION_1: u32 = 1;
223pub trait Credential {
224    /// Retrieves a token for the given registry.
225    fn perform(
226        &self,
227        registry: &RegistryInfo<'_>,
228        action: &Action<'_>,
229        args: &[&str],
230    ) -> Result<CredentialResponse, Error>;
231}
232
233/// Runs the credential interaction
234pub fn main(credential: impl Credential) {
235    let result = doit(credential).map_err(|e| Error::Other(e));
236    if result.is_err() {
237        serde_json::to_writer(std::io::stdout(), &result)
238            .expect("failed to serialize credential provider error");
239        println!();
240    }
241}
242
243fn doit(
244    credential: impl Credential,
245) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
246    let hello = CredentialHello {
247        v: vec![PROTOCOL_VERSION_1],
248    };
249    serde_json::to_writer(std::io::stdout(), &hello)?;
250    println!();
251
252    loop {
253        let mut buffer = String::new();
254        let len = std::io::stdin().read_line(&mut buffer)?;
255        if len == 0 {
256            return Ok(());
257        }
258        let request = deserialize_request(&buffer)?;
259        let response = stdin_stdout_to_console(|| {
260            credential.perform(&request.registry, &request.action, &request.args)
261        })?;
262
263        serde_json::to_writer(std::io::stdout(), &response)?;
264        println!();
265    }
266}
267
268/// Deserialize a request from Cargo.
269fn deserialize_request(
270    value: &str,
271) -> Result<CredentialRequest<'_>, Box<dyn std::error::Error + Send + Sync>> {
272    let request: CredentialRequest<'_> = serde_json::from_str(&value)?;
273    if request.v != PROTOCOL_VERSION_1 {
274        return Err(format!("unsupported protocol version {}", request.v).into());
275    }
276    Ok(request)
277}
278
279/// Read a line of text from stdin.
280pub fn read_line() -> Result<String, io::Error> {
281    let mut buf = String::new();
282    io::stdin().read_line(&mut buf)?;
283    Ok(buf.trim().to_string())
284}
285
286/// Prompt the user for a token.
287pub fn read_token(
288    login_options: &LoginOptions<'_>,
289    registry: &RegistryInfo<'_>,
290) -> Result<Secret<String>, Error> {
291    if let Some(token) = &login_options.token {
292        return Ok(token.to_owned());
293    }
294
295    if let Some(url) = login_options.login_url {
296        eprintln!("please paste the token found on {url} below");
297    } else if let Some(name) = registry.name {
298        eprintln!("please paste the token for {name} below");
299    } else {
300        eprintln!("please paste the token for {} below", registry.index_url);
301    }
302
303    Ok(Secret::from(read_line().map_err(Box::new)?))
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn unsupported_version() {
312        // This shouldn't ever happen in practice, since the credential provider signals to Cargo which
313        // protocol versions it supports, and Cargo should only attempt to use one of those.
314        let msg = r#"{"v":999, "registry": {"index-url":""}, "args":[], "kind": "unexpected"}"#;
315        assert_eq!(
316            "unsupported protocol version 999",
317            deserialize_request(msg).unwrap_err().to_string()
318        );
319    }
320
321    #[test]
322    fn cache_control() {
323        let cc = CacheControl::Expires {
324            expiration: Timestamp::from_second(1693928537).unwrap(),
325        };
326        let json = serde_json::to_string(&cc).unwrap();
327        assert_eq!(json, r#"{"cache":"expires","expiration":1693928537}"#);
328
329        let cc = CacheControl::Session;
330        let json = serde_json::to_string(&cc).unwrap();
331        assert_eq!(json, r#"{"cache":"session"}"#);
332
333        let cc: CacheControl = serde_json::from_str(r#"{"cache":"unknown-kind"}"#).unwrap();
334        assert_eq!(cc, CacheControl::Unknown);
335
336        assert_eq!(
337            "missing field `expiration`",
338            serde_json::from_str::<CacheControl>(r#"{"cache":"expires"}"#)
339                .unwrap_err()
340                .to_string()
341        );
342    }
343
344    #[test]
345    fn credential_response() {
346        let cr = CredentialResponse::Get {
347            cache: CacheControl::Never,
348            operation_independent: true,
349            token: Secret::from("value".to_string()),
350        };
351        let json = serde_json::to_string(&cr).unwrap();
352        assert_eq!(
353            json,
354            r#"{"kind":"get","token":"value","cache":"never","operation_independent":true}"#
355        );
356
357        let cr = CredentialResponse::Login;
358        let json = serde_json::to_string(&cr).unwrap();
359        assert_eq!(json, r#"{"kind":"login"}"#);
360
361        let cr: CredentialResponse =
362            serde_json::from_str(r#"{"kind":"unknown-kind","extra-data":true}"#).unwrap();
363        assert_eq!(cr, CredentialResponse::Unknown);
364
365        let cr: CredentialResponse =
366            serde_json::from_str(r#"{"kind":"login","extra-data":true}"#).unwrap();
367        assert_eq!(cr, CredentialResponse::Login);
368
369        let cr: CredentialResponse = serde_json::from_str(r#"{"kind":"get","token":"value","cache":"never","operation_independent":true,"extra-field-ignored":123}"#).unwrap();
370        assert_eq!(
371            cr,
372            CredentialResponse::Get {
373                cache: CacheControl::Never,
374                operation_independent: true,
375                token: Secret::from("value".to_string())
376            }
377        );
378    }
379
380    #[test]
381    fn credential_request() {
382        let get_oweners = CredentialRequest {
383            v: PROTOCOL_VERSION_1,
384            args: vec![],
385            registry: RegistryInfo {
386                index_url: "url",
387                name: None,
388                headers: vec![],
389            },
390            action: Action::Get(Operation::Owners { name: "pkg" }),
391        };
392
393        let json = serde_json::to_string(&get_oweners).unwrap();
394        assert_eq!(
395            json,
396            r#"{"v":1,"registry":{"index-url":"url"},"kind":"get","operation":"owners","name":"pkg"}"#
397        );
398
399        let cr: CredentialRequest<'_> =
400            serde_json::from_str(r#"{"extra-1":true,"v":1,"registry":{"index-url":"url","extra-2":true},"kind":"get","operation":"owners","name":"pkg","args":[]}"#).unwrap();
401        assert_eq!(cr, get_oweners);
402    }
403
404    #[test]
405    fn credential_request_logout() {
406        let unknown = CredentialRequest {
407            v: PROTOCOL_VERSION_1,
408            args: vec![],
409            registry: RegistryInfo {
410                index_url: "url",
411                name: None,
412                headers: vec![],
413            },
414            action: Action::Logout,
415        };
416
417        let cr: CredentialRequest<'_> = serde_json::from_str(
418            r#"{"v":1,"registry":{"index-url":"url"},"kind":"logout","extra-1":true,"args":[]}"#,
419        )
420        .unwrap();
421        assert_eq!(cr, unknown);
422    }
423
424    #[test]
425    fn credential_request_unknown() {
426        let unknown = CredentialRequest {
427            v: PROTOCOL_VERSION_1,
428            args: vec![],
429            registry: RegistryInfo {
430                index_url: "",
431                name: None,
432                headers: vec![],
433            },
434            action: Action::Unknown,
435        };
436
437        let cr: CredentialRequest<'_> = serde_json::from_str(
438            r#"{"v":1,"registry":{"index-url":""},"kind":"unexpected-1","extra-1":true,"args":[]}"#,
439        )
440        .unwrap();
441        assert_eq!(cr, unknown);
442    }
443}