use std::{env, fmt};
use anyhow::{Result, bail};
pub const SECRET: &str = "VERCTL_REGISTRY_TOKEN";
pub const TRUSTED: &str = "VERCTL_TRUSTED_PUBLISHING_TOKEN";
pub const SOURCES: [&str; 2] = [SECRET, TRUSTED];
pub const OWNER: &str = "VERCTL_OWNER_TOKEN";
#[must_use]
pub fn owner_token() -> Option<String> {
env::var(OWNER).ok().filter(|token| !token.is_empty())
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum NewCrates {
#[default]
Off,
Every,
Only(Vec<String>),
}
impl NewCrates {
#[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),
}
}
#[must_use]
pub const fn is_on(&self) -> bool {
!matches!(self, Self::Off)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct RegistryToken {
variable: String,
value: String,
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 {
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)
}
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,
}))
}
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)
}
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,
},
})
}
#[must_use]
pub fn env(&self) -> (&str, &str) {
(&self.variable, &self.value)
}
#[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
);
}
#[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"));
}
#[test]
fn both_tokens_still_fail_without_new() {
RegistryToken::resolve(Some("secr3t".into()), Some("trust3d".into()), "X").unwrap_err();
}
#[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}");
}
}