use std::collections::HashMap;
use std::path::{Path, PathBuf};
use base64::Engine;
use eyre::{Result, eyre};
use serde_json::{Map, Value};
#[derive(Clone)]
pub enum AuthCredentials {
Basic { username: String, password: String },
Bearer { token: String },
GitHubToken { token: String },
GitLabToken { token: String },
}
impl std::fmt::Debug for AuthCredentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Basic { username, .. } => f
.debug_struct("Basic")
.field("username", username)
.field("password", &"<redacted>")
.finish(),
Self::Bearer { .. } => f
.debug_struct("Bearer")
.field("token", &"<redacted>")
.finish(),
Self::GitHubToken { .. } => f
.debug_struct("GitHubToken")
.field("token", &"<redacted>")
.finish(),
Self::GitLabToken { .. } => f
.debug_struct("GitLabToken")
.field("token", &"<redacted>")
.finish(),
}
}
}
impl AuthCredentials {
pub fn header_value(&self) -> String {
match self {
Self::Basic { username, password } => {
let raw = format!("{username}:{password}");
let encoded = base64::engine::general_purpose::STANDARD.encode(raw);
format!("Basic {encoded}")
}
Self::Bearer { token } => format!("Bearer {token}"),
Self::GitHubToken { token } => format!("token {token}"),
Self::GitLabToken { token } => token.clone(),
}
}
pub fn header_name(&self) -> &'static str {
match self {
Self::Basic { .. } | Self::Bearer { .. } | Self::GitHubToken { .. } => "authorization",
Self::GitLabToken { .. } => "private-token",
}
}
}
fn parse_auth_object(
obj: &Map<String, Value>,
source: &str,
) -> Result<HashMap<String, AuthCredentials>> {
let mut out: HashMap<String, AuthCredentials> = HashMap::new();
if let Some(bearer) = obj.get("bearer").and_then(Value::as_object) {
for (host, val) in bearer {
let token = val
.as_str()
.ok_or_else(|| eyre!("{source}: bearer.{host} must be a string token"))?;
out.insert(
host.clone(),
AuthCredentials::Bearer {
token: token.to_owned(),
},
);
}
}
if let Some(github) = obj.get("github-oauth").and_then(Value::as_object) {
for (host, val) in github {
let token = val
.as_str()
.ok_or_else(|| eyre!("{source}: github-oauth.{host} must be a string token"))?;
out.insert(
host.clone(),
AuthCredentials::GitHubToken {
token: token.to_owned(),
},
);
}
}
if let Some(gitlab) = obj.get("gitlab-oauth").and_then(Value::as_object) {
for (host, val) in gitlab {
let token = val
.as_str()
.ok_or_else(|| eyre!("{source}: gitlab-oauth.{host} must be a string token"))?;
out.insert(
host.clone(),
AuthCredentials::Bearer {
token: token.to_owned(),
},
);
}
}
if let Some(gitlab) = obj.get("gitlab-token").and_then(Value::as_object) {
for (host, val) in gitlab {
let token = if let Some(s) = val.as_str() {
s.to_owned()
} else if let Some(obj) = val.as_object() {
obj.get("token")
.and_then(Value::as_str)
.ok_or_else(|| {
eyre!("{source}: gitlab-token.{host}.token is missing or not a string")
})?
.to_owned()
} else {
return Err(eyre!(
"{source}: gitlab-token.{host} must be a string or object with `token`"
));
};
out.insert(host.clone(), AuthCredentials::GitLabToken { token });
}
}
if let Some(http_basic) = obj.get("http-basic").and_then(Value::as_object) {
for (host, val) in http_basic {
let entry = val.as_object().ok_or_else(|| {
eyre!(
"{source}: http-basic.{host} must be an object with `username` and `password`"
)
})?;
let username = entry
.get("username")
.and_then(Value::as_str)
.ok_or_else(|| {
eyre!("{source}: http-basic.{host}.username is missing or not a string")
})?;
let password = entry
.get("password")
.and_then(Value::as_str)
.ok_or_else(|| {
eyre!("{source}: http-basic.{host}.password is missing or not a string")
})?;
out.insert(
host.clone(),
AuthCredentials::Basic {
username: username.to_owned(),
password: password.to_owned(),
},
);
}
}
Ok(out)
}
pub fn read_auth_from_composer_json(
composer_json: &Value,
) -> Result<HashMap<String, AuthCredentials>> {
let Some(obj) = composer_json.as_object() else {
return Ok(HashMap::new());
};
let Some(config) = obj.get("config").and_then(Value::as_object) else {
return Ok(HashMap::new());
};
parse_auth_object(config, "composer.json config")
}
pub fn read_auth_json(project_root: &Path) -> Result<HashMap<String, AuthCredentials>> {
read_auth_json_at(&project_root.join("auth.json"))
}
fn read_auth_json_at(path: &Path) -> Result<HashMap<String, AuthCredentials>> {
if !path.is_file() {
return Ok(HashMap::new());
}
let bytes = std::fs::read(path).map_err(|e| eyre!("reading {}: {e}", path.display()))?;
let value: Value =
serde_json::from_slice(&bytes).map_err(|e| eyre!("parsing {}: {e}", path.display()))?;
let Some(obj) = value.as_object() else {
return Ok(HashMap::new());
};
parse_auth_object(obj, &path.display().to_string())
}
fn global_auth_json_candidates(env: impl Fn(&str) -> Option<String>) -> Vec<PathBuf> {
let mut out = Vec::new();
if let Some(h) = env("COMPOSER_HOME") {
out.push(PathBuf::from(h).join("auth.json"));
}
if let Some(h) = env("XDG_CONFIG_HOME") {
out.push(PathBuf::from(h).join("composer").join("auth.json"));
}
if let Some(h) = env("HOME") {
out.push(
PathBuf::from(&h)
.join(".config")
.join("composer")
.join("auth.json"),
);
out.push(PathBuf::from(&h).join(".composer").join("auth.json"));
}
out
}
pub fn read_global_auth_json() -> Result<HashMap<String, AuthCredentials>> {
for candidate in global_auth_json_candidates(|k| std::env::var(k).ok()) {
if candidate.is_file() {
return read_auth_json_at(&candidate);
}
}
Ok(HashMap::new())
}
pub fn parse_composer_auth_env(raw: &str) -> Result<HashMap<String, AuthCredentials>> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Ok(HashMap::new());
}
let value: Value =
serde_json::from_str(trimmed).map_err(|e| eyre!("COMPOSER_AUTH is not valid JSON: {e}"))?;
let Some(obj) = value.as_object() else {
return Err(eyre!("COMPOSER_AUTH must decode to a JSON object"));
};
parse_auth_object(obj, "COMPOSER_AUTH")
}
pub fn read_composer_auth_env() -> Result<HashMap<String, AuthCredentials>> {
match std::env::var("COMPOSER_AUTH") {
Ok(s) => parse_composer_auth_env(&s),
Err(_) => Ok(HashMap::new()),
}
}
pub fn read_all_auth(
composer_json: &Value,
project_root: &Path,
) -> Result<HashMap<String, AuthCredentials>> {
Ok(merge_auth_sources(
read_global_auth_json()?,
read_auth_from_composer_json(composer_json)?,
read_auth_json(project_root)?,
read_composer_auth_env()?,
))
}
fn merge_auth_sources(
global: HashMap<String, AuthCredentials>,
composer_json_config: HashMap<String, AuthCredentials>,
project_auth_json: HashMap<String, AuthCredentials>,
composer_auth_env: HashMap<String, AuthCredentials>,
) -> HashMap<String, AuthCredentials> {
let mut out = global;
out.extend(composer_json_config);
out.extend(project_auth_json);
out.extend(composer_auth_env);
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn basic_header_is_base64_userpass() {
let creds = AuthCredentials::Basic {
username: "user".into(),
password: "pass".into(),
};
assert_eq!(creds.header_value(), "Basic dXNlcjpwYXNz");
assert_eq!(creds.header_name(), "authorization");
}
#[test]
fn gitlab_token_uses_private_token_header() {
let creds = AuthCredentials::GitLabToken {
token: "abc".into(),
};
assert_eq!(creds.header_value(), "abc");
assert_eq!(creds.header_name(), "private-token");
}
#[test]
fn parses_http_basic_and_bearer() {
let obj = json!({
"http-basic": { "repo.example.com": { "username": "u", "password": "p" } },
"bearer": { "api.example.com": "tok" }
});
let map = parse_auth_object(obj.as_object().unwrap(), "test").unwrap();
assert!(matches!(
map.get("repo.example.com"),
Some(AuthCredentials::Basic { .. })
));
assert!(matches!(
map.get("api.example.com"),
Some(AuthCredentials::Bearer { .. })
));
}
#[test]
fn later_source_wins_per_host() {
let mut global = HashMap::new();
global.insert(
"h".to_string(),
AuthCredentials::Bearer {
token: "old".into(),
},
);
let mut env = HashMap::new();
env.insert(
"h".to_string(),
AuthCredentials::Bearer {
token: "new".into(),
},
);
let merged = merge_auth_sources(global, HashMap::new(), HashMap::new(), env);
match merged.get("h") {
Some(AuthCredentials::Bearer { token }) => assert_eq!(token, "new"),
other => panic!("expected the env token to win, got {other:?}"),
}
}
#[test]
fn debug_redacts_secrets() {
let creds = AuthCredentials::Basic {
username: "user".into(),
password: "s3cret".into(),
};
let rendered = format!("{creds:?}");
assert!(rendered.contains("user"));
assert!(!rendered.contains("s3cret"), "{rendered}");
}
}