verctl-core 0.9.3

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! The registry token `release` hands to each publisher.
//!
//! The release workflow sets the token in one of two variables and runs the
//! bare verb.
//! verctl reads it once, here.
//! It gives the token to each publisher under the variable
//! `--registry-token-env` names.
//! The publisher's registry `query` gets it too, because a private registry
//! needs the same credential for that query.
//!
//! No other child process sees it.
//! [`crate::process`] removes both source variables, and the owner's token in
//! [`OWNER`], from every command it starts, and only the publisher and its
//! query get the registry token back under the named variable.
//!
//! `release --new` may carry both tokens. A crate crates.io lacks is
//! created with [`SECRET`], and every other upload takes [`TRUSTED`] when it
//! is set. [`RegistryToken::env_for`] makes that choice.

use std::{env, fmt};

use anyhow::{Result, bail};

/// The variable the release workflow sets from its `registry-token` secret.
pub const SECRET: &str = "VERCTL_REGISTRY_TOKEN";

/// The variable the release workflow sets from a crates.io trusted-publishing
/// token.
pub const TRUSTED: &str = "VERCTL_TRUSTED_PUBLISHING_TOKEN";

/// The variables a token arrives in, which no child process inherits.
pub const SOURCES: [&str; 2] = [SECRET, TRUSTED];

/// The variable an owner's crates.io token with the `trusted-publishing`
/// scope arrives in, for `check trust` and the release proof to read the
/// trusted publisher entries. It is not the token `release` publishes with:
/// that scope can also create and delete entries, so no publisher gets it,
/// and no child process inherits it.
pub const OWNER: &str = "VERCTL_OWNER_TOKEN";

/// The owner's token in [`OWNER`], or `None` when it is unset or empty.
#[must_use]
pub fn owner_token() -> Option<String> {
    env::var(OWNER).ok().filter(|token| !token.is_empty())
}

/// Which crates a `release` run may create with the registry token, when
/// crates.io lacks them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum NewCrates {
    /// None: a crate crates.io lacks fails the release proof.
    #[default]
    Off,
    /// Every crate crates.io lacks, as `release --new` creates them.
    Every,
    /// Only these crates, as `release bootstrap <crate>...` names them.
    Only(Vec<String>),
}

impl NewCrates {
    /// Whether a run may create the crate `name`.
    #[must_use]
    pub fn allows(&self, name: &str) -> bool {
        match self {
            Self::Off => false,
            Self::Every => true,
            Self::Only(names) => names.iter().any(|only| only == name),
        }
    }

    /// Whether a run may create some crate, so it needs the registry token.
    #[must_use]
    pub const fn is_on(&self) -> bool {
        !matches!(self, Self::Off)
    }
}

/// A registry token and the variable its publisher reads it from.
///
/// Its `Debug` output names the variable and hides the token, so an error or a
/// log line that prints it shows no secret.
#[derive(Clone, PartialEq, Eq)]
pub struct RegistryToken {
    variable: String,
    value: String,
    /// The token that creates a crate, when `value` is another: the
    /// registry-token secret next to a trusted-publishing token.
    creation: Option<String>,
}

impl fmt::Debug for RegistryToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RegistryToken")
            .field("variable", &self.variable)
            .finish_non_exhaustive()
    }
}

impl RegistryToken {
    /// The token in [`SECRET`] or [`TRUSTED`], for the publisher to read
    /// from `variable`. `None` when neither is set; an empty variable is
    /// unset.
    ///
    /// # Errors
    ///
    /// Returns an error when both are set, because one release takes one
    /// credential and picking either would hide a mistake in the caller.
    pub fn from_env(variable: &str) -> Result<Option<Self>> {
        let read = |key| {
            env::var(key)
                .ok()
                .filter(|value: &String| !value.is_empty())
        };
        Self::resolve(read(SECRET), read(TRUSTED), variable)
    }

    /// [`Self::from_env`] over values already read.
    ///
    /// # Errors
    ///
    /// Returns an error when both `secret` and `trusted` contain a token.
    pub fn resolve(
        secret: Option<String>,
        trusted: Option<String>,
        variable: &str,
    ) -> Result<Option<Self>> {
        let value = match (secret, trusted) {
            (Some(_), Some(_)) => bail!(
                "{SECRET} and {TRUSTED} are both set: pass either the registry-token secret or crates-io-trusted-publishing"
            ),
            (Some(value), None) | (None, Some(value)) => value,
            (None, None) => return Ok(None),
        };
        Ok(Some(Self {
            variable: variable.to_owned(),
            value,
            creation: None,
        }))
    }

    /// The tokens of a run under `--new`, for the publisher to read
    /// from `variable`: the one in [`SECRET`], which creates a crate, and the
    /// one in [`TRUSTED`] when it is set, which every other upload uses.
    ///
    /// # Errors
    ///
    /// Returns an error when [`SECRET`] is unset or empty, naming it and the
    /// workflow secret `registry-token` that sets it.
    pub fn from_env_new(variable: &str) -> Result<Self> {
        let read = |key| {
            env::var(key)
                .ok()
                .filter(|value: &String| !value.is_empty())
        };
        Self::resolve_new(read(SECRET), read(TRUSTED), variable)
    }

    /// [`Self::from_env_new`] over values already read.
    ///
    /// # Errors
    ///
    /// Returns an error when `secret` contains no token.
    pub fn resolve_new(
        secret: Option<String>,
        trusted: Option<String>,
        variable: &str,
    ) -> Result<Self> {
        let Some(secret) = secret else {
            bail!(
                "--new needs {SECRET}, which the release workflow sets from its `registry-token` secret: set it to the crates.io token that creates new crates"
            );
        };
        Ok(match trusted {
            Some(value) => Self {
                variable: variable.to_owned(),
                value,
                creation: Some(secret),
            },
            None => Self {
                variable: variable.to_owned(),
                value: secret,
                creation: None,
            },
        })
    }

    /// The one variable the publisher runs with: its name and the token.
    #[must_use]
    pub fn env(&self) -> (&str, &str) {
        (&self.variable, &self.value)
    }

    /// [`Self::env`] for an upload that creates its crate: the registry token,
    /// where a trusted-publishing token would otherwise be used.
    #[must_use]
    pub fn creation_env(&self) -> (&str, &str) {
        self.creation
            .as_ref()
            .map_or_else(|| self.env(), |creation| (&self.variable, creation))
    }
}

#[cfg(test)]
mod tests {
    use super::{RegistryToken, SECRET, TRUSTED};

    #[test]
    fn both_tokens_fail_and_name_both_variables() {
        let error = RegistryToken::resolve(
            Some("from-secret".into()),
            Some("from-trusted".into()),
            "CARGO_REGISTRY_TOKEN",
        )
        .expect_err("both set");
        let message = format!("{error:#}");
        assert!(message.contains(SECRET), "{message}");
        assert!(message.contains(TRUSTED), "{message}");
        assert!(!message.contains("from-"), "{message}");
    }

    #[test]
    fn either_token_goes_under_the_named_variable() {
        for (secret, trusted) in [(Some("t0ken".into()), None), (None, Some("t0ken".into()))] {
            let token = RegistryToken::resolve(secret, trusted, "CARGO_REGISTRIES_DEMO_TOKEN")
                .expect("one token")
                .expect("set");
            assert_eq!(token.env(), ("CARGO_REGISTRIES_DEMO_TOKEN", "t0ken"));
        }
    }

    #[test]
    fn no_token_is_none() {
        assert_eq!(
            RegistryToken::resolve(None, None, "CARGO_REGISTRY_TOKEN").expect("none"),
            None
        );
    }

    /// Under `--new` both tokens resolve: a crate that is created gets the
    /// registry token, and every other upload the trusted one.
    #[test]
    fn new_gives_each_upload_its_token() {
        let token = RegistryToken::resolve_new(
            Some("secr3t".into()),
            Some("trust3d".into()),
            "CARGO_REGISTRY_TOKEN",
        )
        .expect("both");
        assert_eq!(token.creation_env(), ("CARGO_REGISTRY_TOKEN", "secr3t"));
        assert_eq!(token.env(), ("CARGO_REGISTRY_TOKEN", "trust3d"));
        let alone = RegistryToken::resolve_new(Some("secr3t".into()), None, "NODE_AUTH_TOKEN")
            .expect("registry token alone");
        assert_eq!(alone.creation_env(), ("NODE_AUTH_TOKEN", "secr3t"));
        assert_eq!(alone.env(), ("NODE_AUTH_TOKEN", "secr3t"));
    }

    /// Without `--new`, both tokens still fail.
    #[test]
    fn both_tokens_still_fail_without_new() {
        RegistryToken::resolve(Some("secr3t".into()), Some("trust3d".into()), "X").unwrap_err();
    }

    /// `--new` without the registry token fails naming the variable and the
    /// workflow secret, whether or not a trusted token is set, and never
    /// names a token's value.
    #[test]
    fn new_needs_the_registry_token() {
        for trusted in [None, Some("trust3d".to_owned())] {
            let error = RegistryToken::resolve_new(None, trusted, "CARGO_REGISTRY_TOKEN")
                .expect_err("no registry token");
            let message = format!("{error:#}");
            assert!(message.contains(SECRET), "{message}");
            assert!(message.contains("`registry-token`"), "{message}");
            assert!(!message.contains("trust3d"), "{message}");
        }
    }

    #[test]
    fn new_debug_hides_both_tokens() {
        let token = RegistryToken::resolve_new(
            Some("secr3t".into()),
            Some("trust3d".into()),
            "CARGO_REGISTRY_TOKEN",
        )
        .expect("both");
        let shown = format!("{token:?}");
        assert!(!shown.contains("secr3t"), "{shown}");
        assert!(!shown.contains("trust3d"), "{shown}");
    }

    #[test]
    fn debug_hides_the_token() {
        let token = RegistryToken::resolve(Some("t0ken".into()), None, "CARGO_REGISTRY_TOKEN")
            .expect("one token")
            .expect("set");
        let shown = format!("{token:?}");
        assert!(shown.contains("CARGO_REGISTRY_TOKEN"), "{shown}");
        assert!(!shown.contains("t0ken"), "{shown}");
    }
}