verctl-core 0.9.6

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,
    token: String,
    /// The token that creates a crate, when `token` is another: the
    /// registry-token secret next to a trusted-publishing token.
    creation: Option<String>,
    /// Whether `token` came from [`TRUSTED`] (an OIDC trusted-publishing token)
    /// rather than [`SECRET`] (a static API token).
    has_trusted_publishing: bool,
}

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 (token, has_trusted_publishing) = match (secret, trusted) {
            (Some(_), Some(_)) => bail!(
                "{SECRET} and {TRUSTED} are both set: pass either the registry-token secret or crates-io-trusted-publishing"
            ),
            (Some(token), None) => (token, false),
            (None, Some(token)) => (token, true),
            (None, None) => return Ok(None),
        };
        Ok(Some(Self {
            variable: variable.to_owned(),
            token,
            creation: None,
            has_trusted_publishing,
        }))
    }

    /// 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(token) => Self {
                variable: variable.to_owned(),
                token,
                creation: Some(secret),
                has_trusted_publishing: true,
            },
            None => Self {
                variable: variable.to_owned(),
                token: secret,
                creation: None,
                has_trusted_publishing: false,
            },
        })
    }

    /// Whether regular (non-creation) uploads use a crates.io
    /// trusted-publishing token from [`TRUSTED`] rather than a static API token
    /// from [`SECRET`].
    #[must_use]
    pub const fn has_trusted_publishing(&self) -> bool {
        self.has_trusted_publishing
    }

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

    /// [`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;