use std::path::Path;
use std::process::Stdio;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use tokio::process::Command;
use crate::error::{Error, Result};
use crate::parse::{parse_keys, parse_ownertrust, parse_signatures, parse_verify_status};
use crate::process::{self, Operation};
use crate::types::{
InitializationStatus, Key, OperationOptions, OwnerTrust, RefreshProgress, Signature,
VerifyResult,
};
use crate::validation::{validate_keyid, validate_keyring_name, validate_path};
const DEFAULT_GPG_HOMEDIR: &str = "/etc/pacman.d/gnupg";
pub struct ReadOnlyKeyring {
gpg_homedir: String,
}
impl ReadOnlyKeyring {
fn gpg(&self) -> Command {
let mut command = Command::new("gpg");
command.arg(format!("--homedir={}", self.gpg_homedir));
command
}
async fn run_checked(&self, command: &mut Command, operation: &Operation) -> Result<Vec<u8>> {
let output = process::output(command, operation).await?;
if !output.status.success() {
return Err(check_gpg_error(
&self.gpg_homedir,
output.status,
&output.stderr,
));
}
Ok(output.stdout)
}
async fn run_gpg<I, S>(&self, args: I) -> Result<Vec<u8>>
where
I: IntoIterator<Item = S>,
S: AsRef<std::ffi::OsStr>,
{
self.run_checked(self.gpg().args(args), &Operation::default())
.await
}
pub async fn list_keys(&self) -> Result<Vec<Key>> {
let stdout = self.run_gpg(["--list-keys", "--with-colons"]).await?;
parse_keys(&String::from_utf8_lossy(&stdout))
}
pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
self.run_list_sigs("--list-sigs", keyid).await
}
pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
self.run_list_sigs("--check-sigs", keyid).await
}
async fn run_list_sigs(&self, op: &str, keyid: Option<&str>) -> Result<Vec<Signature>> {
let mut args = vec![op.to_string(), "--with-colons".to_string()];
if let Some(id) = keyid {
args.push(validate_keyid(id)?);
}
let stdout = self.run_gpg(args).await?;
parse_signatures(&String::from_utf8_lossy(&stdout))
}
pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
let mut args = vec!["--armor".to_string(), "--export".to_string()];
for id in keyids {
args.push(validate_keyid(id)?);
}
let stdout = self.run_gpg(args).await?;
Ok(String::from_utf8_lossy(&stdout).into_owned())
}
pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
let mut args = vec!["--with-colons".to_string(), "--fingerprint".to_string()];
for id in keyids {
args.push(validate_keyid(id)?);
}
let stdout = self.run_gpg(args).await?;
let keys = parse_keys(&String::from_utf8_lossy(&stdout))?;
Ok(keys.into_iter().map(|k| k.fingerprint).collect())
}
pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
let bytes = std::fs::read(sig).map_err(Error::Command)?;
if bytes
.windows(b"BEGIN PGP SIGNATURE".len())
.any(|w| w == b"BEGIN PGP SIGNATURE")
{
return Err(Error::InvalidPath {
path: sig.display().to_string(),
reason: "armored signatures are not supported (use a binary signature)".to_string(),
});
}
let mut args = vec![
"--status-fd".to_string(),
"1".to_string(),
"--verify".to_string(),
validate_path(sig)?,
];
if let Some(f) = file {
args.push(validate_path(f)?);
}
let output = process::output(self.gpg().args(&args), &Operation::default()).await?;
Ok(parse_verify_status(&String::from_utf8_lossy(
&output.stdout,
)))
}
pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
let stdout = self.run_gpg(["--export-ownertrust"]).await?;
Ok(parse_ownertrust(&String::from_utf8_lossy(&stdout)))
}
pub fn is_initialized(&self) -> Result<InitializationStatus> {
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
let dir = Path::new(&self.gpg_homedir);
let metadata = match fs::metadata(dir) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(InitializationStatus::DirectoryMissing);
}
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
return Err(Error::PermissionDenied);
}
Err(e) => return Err(Error::Command(e)),
};
if metadata.is_file() {
return Ok(InitializationStatus::PathIsFile);
}
if !metadata.is_dir() {
return Ok(InitializationStatus::DirectoryMissing);
}
let mode = metadata.permissions().mode() & 0o7777;
if mode != 0o755 {
return Ok(InitializationStatus::IncorrectPermissions { actual: mode });
}
let has_pubring = Self::file_exists_and_nonempty(&dir.join("pubring.kbx"))?
|| Self::file_exists_and_nonempty(&dir.join("pubring.gpg"))?;
if !has_pubring {
return Ok(InitializationStatus::NoKeyringFiles);
}
if !Self::file_exists_and_nonempty(&dir.join("trustdb.gpg"))? {
return Ok(InitializationStatus::NoTrustDb);
}
Ok(InitializationStatus::Ready)
}
fn file_exists_and_nonempty(path: &std::path::Path) -> Result<bool> {
use std::fs;
match fs::metadata(path) {
Ok(m) => Ok(m.is_file() && m.len() > 0),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
Err(Error::PermissionDenied)
}
Err(e) => Err(Error::Command(e)),
}
}
}
fn check_gpg_error(homedir: &str, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
let msg = String::from_utf8_lossy(stderr);
if msg.contains("Permission denied") || msg.contains("permission denied") {
return Error::PermissionDenied;
}
if msg.contains("No such file or directory") && msg.contains(homedir) {
return Error::KeyringNotInitialized;
}
Error::PacmanKey {
status: status.code().unwrap_or(-1),
stderr: msg.to_string(),
}
}
fn paths_to_args(flag: &str, paths: &[&Path]) -> Result<Vec<String>> {
let mut args = vec![flag.to_string()];
for p in paths {
args.push(validate_path(p)?);
}
Ok(args)
}
pub struct Keyring {
reader: ReadOnlyKeyring,
keyserver: Option<String>,
}
impl Default for Keyring {
fn default() -> Self {
Self::new()
}
}
impl Keyring {
#[must_use]
pub fn new() -> Self {
Self {
reader: ReadOnlyKeyring {
gpg_homedir: DEFAULT_GPG_HOMEDIR.to_string(),
},
keyserver: None,
}
}
#[must_use]
pub fn with_keyserver(mut self, url: impl Into<String>) -> Self {
self.keyserver = Some(url.into());
self
}
#[must_use]
pub fn with_homedir(path: impl Into<String>) -> ReadOnlyKeyring {
ReadOnlyKeyring {
gpg_homedir: path.into(),
}
}
pub fn get_homedir(&self) -> &str {
&self.reader.gpg_homedir
}
async fn run_pacman_key<I, S>(&self, args: I) -> Result<()>
where
I: IntoIterator<Item = S>,
S: AsRef<std::ffi::OsStr>,
{
self.run_pacman_key_with_options(args, OperationOptions::default())
.await
}
async fn run_pacman_key_with_options<I, S>(
&self,
args: I,
options: OperationOptions,
) -> Result<()>
where
I: IntoIterator<Item = S>,
S: AsRef<std::ffi::OsStr>,
{
let (status, stderr) = process::stderr_only(
Command::new("pacman-key").args(args),
&Operation::new(options),
)
.await?;
if !status.success() {
return Err(self.check_error(status, &stderr));
}
Ok(())
}
pub async fn list_keys(&self) -> Result<Vec<Key>> {
self.reader.list_keys().await
}
pub async fn list_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
self.reader.list_signatures(keyid).await
}
pub async fn check_signatures(&self, keyid: Option<&str>) -> Result<Vec<Signature>> {
self.reader.check_signatures(keyid).await
}
pub async fn export_keys(&self, keyids: &[&str]) -> Result<String> {
self.reader.export_keys(keyids).await
}
pub async fn fingerprints(&self, keyids: &[&str]) -> Result<Vec<String>> {
self.reader.fingerprints(keyids).await
}
pub async fn verify_signature(&self, sig: &Path, file: Option<&Path>) -> Result<VerifyResult> {
self.reader.verify_signature(sig, file).await
}
pub async fn get_ownertrust(&self) -> Result<Vec<(String, OwnerTrust)>> {
self.reader.get_ownertrust().await
}
pub fn is_initialized(&self) -> Result<InitializationStatus> {
self.reader.is_initialized()
}
pub async fn init_keyring(&self) -> Result<()> {
self.init_keyring_with_options(OperationOptions::default())
.await
}
pub async fn init_keyring_with_options(&self, options: OperationOptions) -> Result<()> {
self.run_pacman_key_with_options(&["--init"], options).await
}
pub async fn populate(&self, keyrings: &[&str]) -> Result<()> {
self.populate_with_options(keyrings, OperationOptions::default())
.await
}
pub async fn populate_with_options(
&self,
keyrings: &[&str],
options: OperationOptions,
) -> Result<()> {
for name in keyrings {
validate_keyring_name(name)?;
}
let keyring_args: Vec<&str> = if keyrings.is_empty() {
vec!["archlinux"]
} else {
keyrings.to_vec()
};
let args: Vec<&str> = std::iter::once("--populate").chain(keyring_args).collect();
self.run_pacman_key_with_options(&args, options).await
}
pub async fn receive_keys(&self, keyids: &[&str]) -> Result<()> {
self.receive_keys_with_options(keyids, OperationOptions::default())
.await
}
pub async fn receive_keys_with_options(
&self,
keyids: &[&str],
options: OperationOptions,
) -> Result<()> {
if keyids.is_empty() {
return Ok(());
}
let validated: Vec<String> = keyids
.iter()
.map(|k| validate_keyid(k))
.collect::<Result<_>>()?;
let mut args: Vec<String> = Vec::new();
if let Some(ks) = &self.keyserver {
args.push("--keyserver".to_string());
args.push(ks.clone());
}
args.push("--recv-keys".to_string());
args.extend(validated);
self.run_pacman_key_with_options(args, options).await
}
pub async fn locally_sign_key(&self, keyid: &str) -> Result<()> {
let validated = validate_keyid(keyid)?;
self.run_pacman_key(&["--lsign-key", &validated]).await
}
pub async fn delete_key(&self, keyid: &str) -> Result<()> {
let validated = validate_keyid(keyid)?;
self.run_pacman_key(&["--delete", &validated]).await
}
pub async fn add_keys(&self, files: &[&Path]) -> Result<()> {
self.add_keys_with_options(files, OperationOptions::default())
.await
}
pub async fn add_keys_with_options(
&self,
files: &[&Path],
options: OperationOptions,
) -> Result<()> {
if files.is_empty() {
return Ok(());
}
let args = paths_to_args("--add", files)?;
self.run_pacman_key_with_options(args, options).await
}
pub async fn update_trustdb(&self) -> Result<()> {
self.update_trustdb_with_options(OperationOptions::default())
.await
}
pub async fn update_trustdb_with_options(&self, options: OperationOptions) -> Result<()> {
self.run_pacman_key_with_options(&["--updatedb"], options)
.await
}
pub async fn import_keyrings(&self, dirs: &[&Path]) -> Result<()> {
if dirs.is_empty() {
return Ok(());
}
self.run_pacman_key(paths_to_args("--import", dirs)?).await
}
pub async fn import_trustdb(&self, dirs: &[&Path]) -> Result<()> {
if dirs.is_empty() {
return Ok(());
}
self.run_pacman_key(paths_to_args("--import-trustdb", dirs)?)
.await
}
pub async fn set_ownertrust(&self, entries: &[(&str, OwnerTrust)]) -> Result<()> {
if entries.is_empty() {
return Ok(());
}
let mut input = String::new();
for (keyid, trust) in entries {
let fpr = validate_keyid(keyid)?;
input.push_str(&format!("{}:{}:\n", fpr, trust.to_gpg_level()));
}
self.run_gpg_stdin(&["--import-ownertrust"], input.as_bytes())
.await
}
async fn run_gpg_stdin(&self, args: &[&str], input: &[u8]) -> Result<()> {
use tokio::io::AsyncWriteExt;
let mut command = self.reader.gpg();
command
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped());
let (status, stderr) = process::run(&mut command, &Operation::default(), async |child| {
let mut stdin = child.stdin.take().expect("stdin is piped");
let stderr = child.stderr.take().expect("stderr is piped");
let ((), stderr) = tokio::try_join!(
async move { stdin.write_all(input).await },
process::collect(stderr, process::STDERR_LIMIT)
)?;
Ok(stderr)
})
.await?;
if !status.success() {
return Err(self.check_error(status, &stderr));
}
Ok(())
}
pub async fn refresh_keys<F>(&self, callback: F, options: OperationOptions) -> Result<()>
where
F: Fn(RefreshProgress),
{
let (list, refresh) = self.refresh_commands();
self.refresh_with_commands(callback, options, list, refresh)
.await
}
fn refresh_commands(&self) -> (Command, Command) {
let mut list = self.reader.gpg();
list.args(["--list-keys", "--with-colons"]);
let mut refresh = Command::new("pacman-key");
if let Some(ks) = &self.keyserver {
refresh.arg("--keyserver").arg(ks);
}
refresh.arg("--refresh-keys");
(list, refresh)
}
async fn refresh_with_commands<F>(
&self,
callback: F,
options: OperationOptions,
mut list: Command,
mut refresh: Command,
) -> Result<()>
where
F: Fn(RefreshProgress),
{
let operation = Operation::new(options);
let listed = self.reader.run_checked(&mut list, &operation).await?;
let total = parse_keys(&String::from_utf8_lossy(&listed))?.len();
callback(RefreshProgress::Starting { total_keys: total });
refresh.stdout(Stdio::null()).stderr(Stdio::piped());
let (status, ()) = process::run(&mut refresh, &operation, async |child| {
let stderr = child.stderr.take().expect("stderr is piped");
Self::read_refresh_output(BufReader::new(stderr), &callback, total).await
})
.await?;
if !status.success() {
return Err(Error::PacmanKey {
status: status.code().unwrap_or(-1),
stderr: "refresh failed".to_string(),
});
}
callback(RefreshProgress::Completed);
Ok(())
}
async fn read_refresh_output<F>(
mut reader: BufReader<tokio::process::ChildStderr>,
callback: &F,
total: usize,
) -> Result<()>
where
F: Fn(RefreshProgress),
{
let mut current = 0;
let mut buf = Vec::new();
loop {
buf.clear();
let mut limited = (&mut reader).take(process::STDERR_LIMIT);
if limited.read_until(b'\n', &mut buf).await? == 0 {
break;
}
if buf.ends_with(b"\n") {
buf.pop();
}
let line = String::from_utf8_lossy(&buf).into_owned();
if line.contains("refreshing") || line.contains("requesting") {
current += 1;
let keyid = extract_keyid_from_line(&line);
callback(RefreshProgress::Refreshing {
current,
total,
keyid,
});
} else if line.contains("error")
|| line.contains("failed")
|| line.contains("not found")
{
let keyid = extract_keyid_from_line(&line);
callback(RefreshProgress::Error {
keyid,
message: line.clone(),
});
}
}
Ok(())
}
fn check_error(&self, status: std::process::ExitStatus, stderr: &[u8]) -> Error {
check_gpg_error(self.get_homedir(), status, stderr)
}
}
fn extract_keyid_from_line(line: &str) -> String {
for word in line.split_whitespace().rev() {
let trimmed = word.trim_end_matches([':', ',', '.']);
let normalized = trimmed
.strip_prefix("0x")
.or_else(|| trimmed.strip_prefix("0X"))
.unwrap_or(trimmed);
if !normalized.is_empty()
&& normalized.chars().all(|c| c.is_ascii_hexdigit())
&& matches!(normalized.len(), 8 | 16 | 40)
{
return trimmed.to_uppercase();
}
}
String::new()
}
#[cfg(test)]
mod subprocess_tests {
use super::*;
use crate::CancellationToken;
use crate::process::tests::{Fixture, HUNG_GROUP};
use std::cell::RefCell;
use std::time::Duration;
fn options() -> OperationOptions {
OperationOptions {
timeout_secs: Some(1),
cancel_token: None,
}
}
#[tokio::test]
async fn refresh_deadline_covers_listing_keys() {
let fixture = Fixture::new();
let keyring = Keyring::new();
let list = fixture.command("echo $$ > \"$1/parent\"; exec sleep 60");
let refresh = fixture.command("touch \"$1/refreshed\"");
let result = tokio::time::timeout(
Duration::from_secs(5),
keyring.refresh_with_commands(|_| {}, options(), list, refresh),
)
.await
.unwrap();
assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
assert!(!fixture.path("refreshed").exists());
fixture.stopped().await;
}
#[tokio::test]
async fn refresh_deadline_covers_waiting_after_stderr_closes() {
let fixture = Fixture::new();
let keyring = Keyring::new();
let refresh = fixture.command("echo $$ > \"$1/parent\"; exec 2>&-; exec sleep 60");
let result = tokio::time::timeout(
Duration::from_secs(5),
keyring.refresh_with_commands(|_| {}, options(), Command::new("true"), refresh),
)
.await
.unwrap();
assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
fixture.stopped().await;
}
#[tokio::test]
async fn refresh_cancellation_covers_waiting_after_stderr_closes() {
let fixture = Fixture::new();
let cancel = CancellationToken::new();
let options = OperationOptions {
timeout_secs: None,
cancel_token: Some(cancel.clone()),
};
let refresh = fixture
.command("echo $$ > \"$1/parent\"; exec 2>&-; touch \"$1/ready\"; exec sleep 60");
let task = tokio::spawn(async move {
Keyring::new()
.refresh_with_commands(|_| {}, options, Command::new("true"), refresh)
.await
});
fixture.ready().await;
cancel.cancel();
let result = tokio::time::timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
assert!(matches!(result, Err(Error::Cancelled)), "{result:?}");
fixture.stopped().await;
}
#[tokio::test]
async fn aborting_refresh_kills_its_process_group() {
let fixture = Fixture::new();
let refresh = fixture.command(HUNG_GROUP);
let task = tokio::spawn(async move {
Keyring::new()
.refresh_with_commands(
|_| {},
OperationOptions::default(),
Command::new("true"),
refresh,
)
.await
});
fixture.ready().await;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
fixture.stopped().await;
}
#[tokio::test]
async fn refresh_does_not_start_after_the_deadline() {
let fixture = Fixture::new();
let result = Keyring::new()
.refresh_with_commands(
|_| std::thread::sleep(Duration::from_secs(1)),
options(),
Command::new("true"),
Command::new(fixture.path("missing")),
)
.await;
assert!(matches!(result, Err(Error::Timeout(1))), "{result:?}");
}
#[tokio::test]
async fn refresh_reports_progress_from_stderr() {
let fixture = Fixture::new();
let mut list = Command::new("echo");
list.arg(crate::parse::tests::SAMPLE_KEY_OUTPUT);
let refresh = fixture.command(
"echo 'gpg: requesting key DEADBEEF from hkps://keys.example' >&2; \
echo 'gpg: key 786C63F330D7CB92: not found on keyserver' >&2",
);
let events = RefCell::new(Vec::new());
let result = Keyring::new()
.refresh_with_commands(|p| events.borrow_mut().push(p), options(), list, refresh)
.await;
assert!(result.is_ok(), "{result:?}");
let events = events.into_inner();
assert!(
matches!(
&events[..],
[
RefreshProgress::Starting { total_keys: 2 },
RefreshProgress::Refreshing { current: 1, total: 2, keyid: refreshed },
RefreshProgress::Error { keyid: failed, .. },
RefreshProgress::Completed,
] if refreshed == "DEADBEEF" && failed == "786C63F330D7CB92"
),
"{events:?}"
);
}
#[tokio::test]
async fn refresh_stops_when_listing_fails() {
let fixture = Fixture::new();
let result = Keyring::new()
.refresh_with_commands(
|p| panic!("{p:?}"),
options(),
fixture.command("echo 'gpg: Permission denied' >&2; exit 2"),
Command::new(fixture.path("missing")),
)
.await;
assert!(matches!(result, Err(Error::PermissionDenied)), "{result:?}");
}
#[tokio::test]
async fn refresh_reports_a_failed_exit() {
let fixture = Fixture::new();
let result = Keyring::new()
.refresh_with_commands(
|p| assert_ne!(p, RefreshProgress::Completed),
options(),
Command::new("true"),
fixture.command("exit 3"),
)
.await;
assert!(
matches!(result, Err(Error::PacmanKey { status: 3, .. })),
"{result:?}"
);
}
#[tokio::test]
async fn set_ownertrust_round_trips_through_gpg() {
let dir = tempfile::tempdir().unwrap();
let keyring = Keyring {
reader: Keyring::with_homedir(dir.path().to_string_lossy()),
keyserver: None,
};
let fingerprint = "ABAF11C65A2970B130ABE3C479BE3E4300411886";
tokio::time::timeout(
Duration::from_secs(10),
keyring.set_ownertrust(&[(fingerprint, OwnerTrust::Full)]),
)
.await
.unwrap()
.unwrap();
assert_eq!(
keyring.get_ownertrust().await.unwrap(),
vec![(fingerprint.to_string(), OwnerTrust::Full)]
);
}
#[tokio::test]
async fn zero_timeout_disables_refresh_deadline() {
let options = OperationOptions {
timeout_secs: Some(0),
cancel_token: None,
};
let result = Keyring::new()
.refresh_with_commands(|_| {}, options, Command::new("true"), Command::new("true"))
.await;
assert!(result.is_ok(), "{result:?}");
}
#[tokio::test]
async fn refresh_reads_an_overlong_line_in_bounded_chunks() {
let fixture = Fixture::new();
let script = format!(
"yes requesting 2>/dev/null | tr -d '\\n' | head -c {} >&2",
3 * process::STDERR_LIMIT
);
let refreshing = std::cell::Cell::new(0);
let result = Keyring::new()
.refresh_with_commands(
|p| {
if matches!(p, RefreshProgress::Refreshing { .. }) {
refreshing.set(refreshing.get() + 1);
}
},
OperationOptions::default(),
Command::new("true"),
fixture.command(&script),
)
.await;
assert!(result.is_ok(), "{result:?}");
assert_eq!(refreshing.get(), 3);
}
#[test]
fn refresh_lists_with_gpg_then_runs_pacman_key() {
let argv = |command: &Command| {
let command = command.as_std();
std::iter::once(command.get_program())
.chain(command.get_args())
.map(|arg| arg.to_string_lossy().into_owned())
.collect::<Vec<_>>()
};
let (list, refresh) = Keyring::new()
.with_keyserver("hkps://keys.example")
.refresh_commands();
assert_eq!(
argv(&list),
[
"gpg",
"--homedir=/etc/pacman.d/gnupg",
"--list-keys",
"--with-colons"
]
);
assert_eq!(
argv(&refresh),
[
"pacman-key",
"--keyserver",
"hkps://keys.example",
"--refresh-keys"
]
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_keyid_from_refresh_line() {
assert_eq!(
extract_keyid_from_line("gpg: refreshing 1 key from hkps://keyserver.ubuntu.com"),
""
);
assert_eq!(
extract_keyid_from_line(
"gpg: requesting key DEADBEEF from hkps://keyserver.ubuntu.com"
),
"DEADBEEF"
);
assert_eq!(
extract_keyid_from_line("gpg: key 786C63F330D7CB92: public key imported"),
"786C63F330D7CB92"
);
}
#[test]
fn test_extract_keyid_lowercase_normalized() {
assert_eq!(
extract_keyid_from_line("gpg: key deadbeef: something"),
"DEADBEEF"
);
}
#[test]
fn test_extract_keyid_no_match() {
assert_eq!(extract_keyid_from_line("gpg: some other message"), "");
assert_eq!(extract_keyid_from_line(""), "");
}
#[test]
fn test_check_error_permission_denied() {
let keyring = Keyring::new();
let stderr = b"gpg: Permission denied";
let status = std::process::Command::new("false").status().unwrap();
let err = keyring.check_error(status, stderr);
assert!(matches!(err, Error::PermissionDenied));
}
#[test]
fn test_check_error_permission_denied_lowercase() {
let keyring = Keyring::new();
let stderr = b"gpg: permission denied (are you root?)";
let status = std::process::Command::new("false").status().unwrap();
let err = keyring.check_error(status, stderr);
assert!(matches!(err, Error::PermissionDenied));
}
#[test]
fn test_check_error_keyring_not_initialized() {
let keyring = Keyring::new();
let stderr = b"gpg: keybox '/etc/pacman.d/gnupg/pubring.kbx': No such file or directory";
let status = std::process::Command::new("false").status().unwrap();
let err = keyring.check_error(status, stderr);
assert!(matches!(err, Error::KeyringNotInitialized));
}
#[test]
fn test_check_error_generic() {
let keyring = Keyring::new();
let stderr = b"gpg: some unknown error";
let status = std::process::Command::new("false").status().unwrap();
let err = keyring.check_error(status, stderr);
match err {
Error::PacmanKey { status: _, stderr } => {
assert!(stderr.contains("some unknown error"));
}
_ => panic!("expected PacmanKey error"),
}
}
#[test]
fn test_is_initialized_directory_missing() {
let reader = ReadOnlyKeyring {
gpg_homedir: "/nonexistent/path/that/does/not/exist".to_string(),
};
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::DirectoryMissing);
}
fn keyring_dir(files: &[(&str, &[u8])]) -> (tempfile::TempDir, ReadOnlyKeyring) {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let homedir = dir.path().join("gnupg");
std::fs::create_dir(&homedir).unwrap();
std::fs::set_permissions(&homedir, std::fs::Permissions::from_mode(0o755)).unwrap();
for (name, data) in files {
std::fs::write(homedir.join(name), data).unwrap();
}
(dir, Keyring::with_homedir(homedir.to_string_lossy()))
}
#[test]
fn test_is_initialized_no_keyring_files() {
let (_dir, reader) = keyring_dir(&[]);
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::NoKeyringFiles);
}
#[test]
fn test_is_initialized_no_trustdb() {
let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data")]);
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::NoTrustDb);
}
#[test]
fn test_is_initialized_incorrect_permissions() {
use std::os::unix::fs::PermissionsExt;
let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
for mode in [0o700, 0o777, 0o2755] {
std::fs::set_permissions(&reader.gpg_homedir, std::fs::Permissions::from_mode(mode))
.unwrap();
let status = reader.is_initialized().unwrap();
assert_eq!(
status,
InitializationStatus::IncorrectPermissions { actual: mode }
);
}
}
#[test]
fn test_is_initialized_ready() {
let (_dir, reader) = keyring_dir(&[("pubring.kbx", b"data"), ("trustdb.gpg", b"data")]);
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::Ready);
}
#[test]
fn test_is_initialized_with_legacy_pubring() {
let (_dir, reader) = keyring_dir(&[("pubring.gpg", b"data"), ("trustdb.gpg", b"data")]);
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::Ready);
}
#[test]
fn test_is_initialized_path_is_file() {
use std::fs;
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let tmp = dir.path().join("gnupg");
fs::File::create(&tmp).unwrap().write_all(b"data").unwrap();
let reader = ReadOnlyKeyring {
gpg_homedir: tmp.to_string_lossy().to_string(),
};
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::PathIsFile);
}
#[test]
fn test_is_initialized_dangling_symlink() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("gnupg");
symlink("/nonexistent/pacman_key_target", &link).unwrap();
let reader = ReadOnlyKeyring {
gpg_homedir: link.to_string_lossy().to_string(),
};
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::DirectoryMissing);
}
#[test]
fn test_is_initialized_follows_symlink() {
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("target");
let link = dir.path().join("gnupg");
fs::create_dir(&target).unwrap();
fs::set_permissions(&target, fs::Permissions::from_mode(0o755)).unwrap();
fs::File::create(target.join("pubring.kbx"))
.unwrap()
.write_all(b"data")
.unwrap();
fs::File::create(target.join("trustdb.gpg"))
.unwrap()
.write_all(b"data")
.unwrap();
symlink(&target, &link).unwrap();
let reader = ReadOnlyKeyring {
gpg_homedir: link.to_string_lossy().to_string(),
};
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::Ready);
}
#[test]
fn test_is_initialized_empty_files_treated_as_missing() {
let (_dir, reader) = keyring_dir(&[("pubring.kbx", b""), ("trustdb.gpg", b"")]);
let status = reader.is_initialized().unwrap();
assert_eq!(status, InitializationStatus::NoKeyringFiles);
}
}