use std::collections::HashMap;
use std::path::{Path, PathBuf};
pub use composer_auth::AuthCredentials;
use eyre::{Result, eyre};
use serde_json::{Map, Value};
fn parse_auth_object(
obj: &Map<String, Value>,
source: &str,
) -> Result<HashMap<String, AuthCredentials>> {
composer_auth::parse_auth_object(obj, source).map_err(|e| eyre!("{e}"))
}
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>> {
composer_auth::parse_auth_json(raw, "COMPOSER_AUTH").map_err(|e| eyre!("{e}"))
}
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>> {
read_all_auth_with::<std::hash::RandomState>(composer_json, project_root, None)
}
pub fn read_all_auth_with<S: std::hash::BuildHasher>(
composer_json: &Value,
project_root: &Path,
machine: Option<&HashMap<String, AuthCredentials, S>>,
) -> Result<HashMap<String, AuthCredentials>> {
Ok(merge_auth_sources(
machine_slot(read_global_auth_json()?, machine),
read_auth_from_composer_json(composer_json)?,
read_auth_json(project_root)?,
read_composer_auth_env()?,
))
}
fn machine_slot<S: std::hash::BuildHasher>(
mut global: HashMap<String, AuthCredentials>,
machine: Option<&HashMap<String, AuthCredentials, S>>,
) -> HashMap<String, AuthCredentials> {
if let Some(machine) = machine {
global.extend(machine.iter().map(|(k, v)| (k.clone(), v.clone())));
}
global
}
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 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:?}"),
}
}
fn bearer(token: &str) -> HashMap<String, AuthCredentials> {
HashMap::from([(
"h".to_string(),
AuthCredentials::Bearer {
token: token.into(),
},
)])
}
fn token_for_h(map: &HashMap<String, AuthCredentials>) -> &str {
match map.get("h") {
Some(AuthCredentials::Bearer { token }) => token,
other => panic!("expected a bearer token, got {other:?}"),
}
}
#[test]
fn machine_store_beats_global_auth_json_but_not_the_project() {
let store = bearer("store");
let slot = machine_slot(bearer("global"), Some(&store));
assert_eq!(token_for_h(&slot), "store");
let merged = merge_auth_sources(slot, bearer("config"), HashMap::new(), HashMap::new());
assert_eq!(token_for_h(&merged), "config");
}
}