use clap::{Arg, ArgMatches, Command};
use colored::Colorize;
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
use std::fs::File;
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
use std::io::{self, IsTerminal, Read, Write};
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
use std::path::PathBuf;
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
use zeroize::Zeroize;
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
))]
use cryptex::{KeyRing, KeyRingSecret};
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
))]
use std::collections::BTreeMap;
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring};
#[cfg(all(target_os = "macos", feature = "macos-keychain"))]
use cryptex::macos::MacOsKeyRing as OsKeyRing;
#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
use cryptex::linux::LinuxOsKeyRing as OsKeyRing;
#[cfg(all(target_os = "windows", feature = "windows-credentials"))]
use cryptex::windows::WindowsOsKeyRing as OsKeyRing;
#[cfg(any(
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey"
))]
use cryptex::NewKeyRing;
#[cfg(any(
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey"
))]
use cryptex::kms::{KmsBackend, KmsKeyRing};
#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
use cryptex::yubihsm::YubiHsmBackend;
#[cfg(feature = "nitrokey")]
use cryptex::nitrokey::{NitrokeyBackend, NitrokeyKeyRing};
pub(crate) fn main() {
let matches = Command::new("cryptex")
.version(env!("CARGO_PKG_VERSION"))
.author("Michael Lodder")
.about("Platform-independent CLI for storing and retrieving secrets from secure keyrings")
.arg(
Arg::new("keyring")
.long("keyring")
.short('k')
.value_name("TYPE")
.global(true)
.help(
"Keyring backend to use: 'os' (default), 'yubihsm', 'nitrokey', or a file keyring: \
'sqlcipher', 'evfs', 'turso', 'turso-io'. File keyrings take their \
directory as SERVICE ('default' for ~/.cryptex) and read the connection \
string from CRYPTEX_CONNECTION, or prompt for the password.",
),
)
.subcommand(
Command::new("get")
.about("Retrieve a secret by ID")
.arg(
Arg::new("SERVICE")
.help("Service name (os), keyring directory (file keyrings) or connection string (yubihsm, nitrokey)")
.required(true)
.index(1),
)
.arg(
Arg::new("ID")
.help("The secret ID. If omitted, read from STDIN")
.required(false)
.index(2),
),
)
.subcommand(
Command::new("set")
.about("Save a secret by ID")
.arg(
Arg::new("SERVICE")
.help("Service name (os), keyring directory (file keyrings) or connection string (yubihsm, nitrokey)")
.required(true)
.index(1),
)
.arg(
Arg::new("ID")
.help("The secret ID")
.required(true)
.index(2),
)
.arg(
Arg::new("SECRET")
.help("The secret value. If omitted, read from STDIN")
.required(false)
.index(3),
),
)
.subcommand(
Command::new("delete")
.about("Delete a secret by ID")
.arg(
Arg::new("SERVICE")
.help("Service name (os), keyring directory (file keyrings) or connection string (yubihsm, nitrokey)")
.required(true)
.index(1),
)
.arg(
Arg::new("ID")
.help("The secret ID. If omitted, read from STDIN")
.required(false)
.index(2),
),
)
.subcommand(
Command::new("peek")
.about("Inspect OS keyring entries without full retrieval (OS backends only)")
.arg(
Arg::new("ID")
.help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)")
.required(false)
.index(1),
),
)
.subcommand(
Command::new("setup")
.about(
"Create the FIDO2 credential a 'nitrokey' keyring uses and print its ID \
for the credential= parameter. Needs a touch.",
)
.arg(
Arg::new("SERVICE")
.help("Optional connection string with pin= and rp_id=")
.required(false)
.index(1),
),
)
.subcommand(
Command::new("migrate")
.about(
"Copy the secrets from a cryptex 2.x 'evfs' or 'turso-io' keyring file into \
a 3.x keyring. The 2.x connection string comes from \
CRYPTEX_V2_CONNECTION, or a prompt.",
)
.arg(
Arg::new("SERVICE")
.help("Directory of the new 3.x keyring ('default' for ~/.cryptex)")
.required(true)
.index(1),
)
.arg(
Arg::new("OLD_FILE")
.help("The 2.x keyring file, e.g. ~/.cryptex/keyring.db3")
.required(true)
.index(2),
),
)
.subcommand(
Command::new("list")
.about("List secret IDs. For 'os': lists all. For 'yubihsm' and 'nitrokey': requires a connection string. For file keyrings: requires the keyring directory.")
.arg(
Arg::new("SERVICE")
.help("Connection string ('yubihsm', 'nitrokey') or keyring directory (file keyrings)")
.required(false)
.index(1),
),
)
.get_matches();
dispatch(&matches);
}
fn dispatch(matches: &ArgMatches) {
let keyring_type = matches
.get_one::<String>("keyring")
.map(|s| s.as_str())
.unwrap_or("os");
match keyring_type {
"nitrokey" => {
#[cfg(feature = "nitrokey")]
dispatch_nitrokey(matches);
#[cfg(not(feature = "nitrokey"))]
die::<()>("Nitrokey support is not compiled in. Enable the 'nitrokey' feature.");
}
"yubihsm" => {
#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))]
dispatch_kms::<YubiHsmBackend>("YubiHSM", matches);
#[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))]
die::<()>(
"YubiHSM support is not compiled in. \
Enable the 'yubihsm-usb' or 'yubihsm-http' feature.",
);
}
"os" => dispatch_os(matches),
"sqlcipher" | "evfs" | "turso" | "turso-io" => dispatch_file(keyring_type, matches),
other => die::<()>(&format!(
"Unknown keyring type '{}'. Valid options: os, yubihsm, nitrokey, sqlcipher, evfs, turso, turso-io",
other
)),
}
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn dispatch_os(matches: &ArgMatches) {
if let Some(m) = matches.subcommand_matches("get") {
os_get(m);
} else if let Some(m) = matches.subcommand_matches("set") {
os_set(m);
} else if let Some(m) = matches.subcommand_matches("delete") {
os_delete(m);
} else if let Some(m) = matches.subcommand_matches("peek") {
os_peek(m);
} else if matches.subcommand_matches("list").is_some() {
os_list();
} else {
die::<()>("Please specify a command: get | set | delete | peek | list");
}
}
#[cfg(not(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
)))]
fn dispatch_os(_matches: &ArgMatches) {
die::<()>(
"No OS keyring available for this platform/feature combination. \
Use '--keyring yubihsm' or enable a platform keyring feature.",
);
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_get(matches: &ArgMatches) {
let mut keyring = os_open(matches);
let id = get_id(matches, true);
let secret = keyring
.get_secret(&id)
.unwrap_or_else(|e| die::<KeyRingSecret>(&e.to_string()));
io::stdout().write_all(secret.as_slice()).unwrap();
io::stdout().flush().unwrap();
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_set(matches: &ArgMatches) {
let mut keyring = os_open(matches);
let id = matches.get_one::<String>("ID").map(|s| s.as_str()).unwrap();
let mut secret = read_input(matches, "SECRET", true);
keyring
.set_secret(id, &secret)
.unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e)));
secret.zeroize();
println!("{}", "Success".green());
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_delete(matches: &ArgMatches) {
let mut keyring = os_open(matches);
let id = get_id(matches, true);
keyring
.delete_secret(&id)
.unwrap_or_else(|e| die::<()>(&e.to_string()));
println!("{}", "Success".green());
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_peek(matches: &ArgMatches) {
let id = get_id(matches, false);
let secrets = OsKeyRing::peek_secret(&id)
.unwrap_or_else(|e| die::<Vec<(String, KeyRingSecret)>>(&e.to_string()));
if secrets.len() == 1 && !id.is_empty() {
io::stdout().write_all(secrets[0].1.as_slice()).unwrap();
io::stdout().flush().unwrap();
println!();
} else {
for s in secrets {
print!("{} -> ", s.0);
io::stdout().write_all(s.1.as_slice()).unwrap();
println!();
io::stdout().flush().unwrap();
}
}
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
))]
fn os_list() {
let secret_names = OsKeyRing::list_secrets()
.unwrap_or_else(|e| die::<Vec<BTreeMap<String, String>>>(&e.to_string()));
for s in secret_names {
println!("{:?}", s);
}
}
#[cfg(all(target_os = "linux", feature = "linux-secret-service"))]
fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> {
let service = matches
.get_one::<String>("SERVICE")
.map(|s| s.as_str())
.unwrap();
get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e)))
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
))]
fn os_open(matches: &ArgMatches) -> OsKeyRing {
let service = matches
.get_one::<String>("SERVICE")
.map(|s| s.as_str())
.unwrap();
get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e)))
}
#[cfg(any(
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey"
))]
fn dispatch_kms<B: KmsBackend>(label: &str, matches: &ArgMatches)
where
KmsKeyRing<B>: NewKeyRing,
{
if let Some(m) = matches.subcommand_matches("get") {
let mut ring = kms_open::<B>(label, m);
let id = get_id(m, true);
let secret = ring
.get_secret(&id)
.unwrap_or_else(|e| die::<KeyRingSecret>(&e.to_string()));
io::stdout().write_all(secret.as_slice()).unwrap();
io::stdout().flush().unwrap();
} else if let Some(m) = matches.subcommand_matches("set") {
let mut ring = kms_open::<B>(label, m);
let id = m.get_one::<String>("ID").map(|s| s.as_str()).unwrap();
let mut secret = read_input(m, "SECRET", true);
ring.set_secret(id, &secret)
.unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e)));
secret.zeroize();
println!("{}", "Success".green());
} else if let Some(m) = matches.subcommand_matches("delete") {
let mut ring = kms_open::<B>(label, m);
let id = get_id(m, true);
ring.delete_secret(&id)
.unwrap_or_else(|e| die::<()>(&e.to_string()));
println!("{}", "Success".green());
} else if let Some(m) = matches.subcommand_matches("list") {
let entries = kms_open::<B>(label, m)
.list_secrets()
.unwrap_or_else(|e| die::<Vec<BTreeMap<String, String>>>(&e.to_string()));
for entry in entries {
println!("{:?}", entry);
}
} else if matches.subcommand_matches("peek").is_some() {
die::<()>(&format!(
"The 'peek' command is not supported for the {} backend.",
label
));
} else {
die::<()>("Please specify a command: get | set | delete | list");
}
}
#[cfg(any(
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey"
))]
fn kms_open<B: KmsBackend>(label: &str, matches: &ArgMatches) -> KmsKeyRing<B>
where
KmsKeyRing<B>: NewKeyRing,
{
let connstr = matches
.get_one::<String>("SERVICE")
.map(|s| s.as_str())
.unwrap_or_else(|| {
die(&format!(
"A {} connection string is required as the SERVICE argument",
label
))
});
KmsKeyRing::<B>::new(connstr)
.unwrap_or_else(|e| die(&format!("Failed to connect to {}: {}", label, e)))
}
#[cfg(feature = "nitrokey")]
fn dispatch_nitrokey(matches: &ArgMatches) {
if let Some(m) = matches.subcommand_matches("setup") {
let connstr = m
.get_one::<String>("SERVICE")
.map(|s| s.as_str())
.unwrap_or("");
eprintln!("Touch your security key to create the credential.");
let credential = NitrokeyKeyRing::setup(connstr)
.unwrap_or_else(|e| die(&format!("Setup failed: {}", e)));
println!("{}", credential);
} else {
dispatch_kms::<NitrokeyBackend>("Nitrokey", matches);
}
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
trait FileKeyring: cryptex::DynKeyRing {
fn ids(&self) -> cryptex::Result<Vec<String>>;
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
macro_rules! file_keyring_cli {
($($feature:literal => $keyring:ty),* $(,)?) => {$(
#[cfg(feature = $feature)]
impl FileKeyring for $keyring {
fn ids(&self) -> cryptex::Result<Vec<String>> {
self.keys()
}
}
)*};
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
file_keyring_cli!(
"file" => cryptex::sqlcipher::SqlCipherKeyring,
"encrypted-vfs" => cryptex::encrypted_vfs::EncryptedVfsKeyring,
"turso" => cryptex::turso::TursoKeyring,
"turso-encrypted-io" => cryptex::turso_encrypted_io::TursoEncryptedIoKeyring,
);
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
fn dispatch_file(kind: &str, matches: &ArgMatches) {
if let Some(m) = matches.subcommand_matches("get") {
let mut keyring = file_open(kind, m);
let id = get_id(m, true);
let secret = keyring
.get_secret(&id)
.unwrap_or_else(|e| die(&e.to_string()));
io::stdout().write_all(secret.as_slice()).unwrap();
io::stdout().flush().unwrap();
} else if let Some(m) = matches.subcommand_matches("set") {
let mut keyring = file_open(kind, m);
let id = m.get_one::<String>("ID").map(|s| s.as_str()).unwrap();
let mut secret = read_input(m, "SECRET", true);
keyring
.set_secret(id, &secret)
.unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e)));
secret.zeroize();
println!("{}", "Success".green());
} else if let Some(m) = matches.subcommand_matches("delete") {
let mut keyring = file_open(kind, m);
let id = get_id(m, true);
keyring
.delete_secret(&id)
.unwrap_or_else(|e| die::<()>(&e.to_string()));
println!("{}", "Success".green());
} else if let Some(m) = matches.subcommand_matches("list") {
if m.get_one::<String>("SERVICE").is_none() {
die::<()>("A file keyring needs its directory as SERVICE ('default' for ~/.cryptex)");
}
for id in file_open(kind, m)
.ids()
.unwrap_or_else(|e| die(&e.to_string()))
{
println!("{}", id);
}
} else if let Some(m) = matches.subcommand_matches("migrate") {
file_migrate(kind, m);
} else if matches.subcommand_matches("peek").is_some() {
die::<()>("The 'peek' command is only for OS keyrings.");
} else {
die::<()>("Please specify a command: get | set | delete | list | migrate");
}
}
#[cfg(not(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)))]
fn dispatch_file(kind: &str, _matches: &ArgMatches) {
die::<()>(&format!(
"The '{}' keyring is not compiled in. Enable its cargo feature.",
kind
));
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
fn boxed<K: FileKeyring + 'static>(keyring: K) -> Box<dyn FileKeyring> {
Box::new(keyring)
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
fn file_dir(matches: &ArgMatches) -> Option<PathBuf> {
match matches.get_one::<String>("SERVICE").map(|s| s.as_str()) {
None | Some("default") => None,
Some(dir) => Some(PathBuf::from(dir)),
}
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
fn connection<C: cryptex::file_common::CipherParam>(
env: &str,
needs_salt: bool,
) -> cryptex::file_common::ConnectionParams<C> {
if let Ok(mut conn) = std::env::var(env) {
let params = conn
.parse()
.unwrap_or_else(|e: cryptex::error::KeyRingError| {
die(&format!("Invalid {}: {}", env, e))
});
conn.zeroize();
return params;
}
let mut params = cryptex::file_common::ConnectionParams::<C>::default();
let mut password = rpassword::prompt_password("Keyring password: ")
.unwrap_or_else(|e| die(&format!("Unable to read the password: {}", e)));
params.password(password.as_bytes());
password.zeroize();
if needs_salt {
let salt = rpassword::prompt_password("Keyring salt: ")
.unwrap_or_else(|e| die(&format!("Unable to read the salt: {}", e)));
params.salt(salt.as_bytes());
}
params
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
fn file_open(kind: &str, matches: &ArgMatches) -> Box<dyn FileKeyring> {
let dir = file_dir(matches);
let opened: Option<cryptex::Result<Box<dyn FileKeyring>>> = match kind {
#[cfg(feature = "file")]
"sqlcipher" => Some(
cryptex::sqlcipher::SqlCipherKeyring::with_params(
&connection("CRYPTEX_CONNECTION", true),
dir,
)
.map(boxed),
),
#[cfg(feature = "encrypted-vfs")]
"evfs" => Some(
cryptex::encrypted_vfs::EncryptedVfsKeyring::with_params(
&connection("CRYPTEX_CONNECTION", false),
dir,
)
.map(boxed),
),
#[cfg(feature = "turso")]
"turso" => Some(
cryptex::turso::TursoKeyring::with_params(&connection("CRYPTEX_CONNECTION", true), dir)
.map(boxed),
),
#[cfg(feature = "turso-encrypted-io")]
"turso-io" => Some(
cryptex::turso_encrypted_io::TursoEncryptedIoKeyring::with_params(
&connection("CRYPTEX_CONNECTION", false),
dir,
)
.map(boxed),
),
_ => None,
};
match opened {
Some(Ok(keyring)) => keyring,
Some(Err(e)) => die(&format!("Unable to open the {} keyring: {}", kind, e)),
None => die(&format!(
"The '{}' keyring is not compiled in. Enable its cargo feature.",
kind
)),
}
}
#[cfg(all(feature = "encrypted-vfs", not(feature = "fips")))]
fn file_migrate(kind: &str, matches: &ArgMatches) {
if kind != "evfs" && kind != "turso-io" {
die::<()>("Only 'evfs' and 'turso-io' keyrings changed format in 3.0.");
}
let old_file = PathBuf::from(matches.get_one::<String>("OLD_FILE").unwrap());
let old: cryptex::migrate::V2ConnectionParams =
if std::env::var_os("CRYPTEX_V2_CONNECTION").is_some() {
connection("CRYPTEX_V2_CONNECTION", true)
} else {
let mut conn = rpassword::prompt_password("2.x connection string: ")
.unwrap_or_else(|e| die(&format!("Unable to read it: {}", e)));
let params = conn
.parse()
.unwrap_or_else(|e: cryptex::error::KeyRingError| {
die(&format!("Invalid 2.x connection string: {}", e))
});
conn.zeroize();
params
};
let mut keyring = file_open(kind, matches);
let moved = cryptex::migrate::migrate_v2(&old_file, &old, &mut *keyring)
.unwrap_or_else(|e| die(&format!("Migration failed: {}", e)));
println!("{}", format!("Moved {} secrets", moved).green());
}
#[cfg(all(
any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
),
not(all(feature = "encrypted-vfs", not(feature = "fips")))
))]
fn file_migrate(_kind: &str, _matches: &ArgMatches) {
die::<()>("Migration needs the 'encrypted-vfs' feature and a non-fips build.");
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
fn get_id(matches: &ArgMatches, read_stdin: bool) -> String {
let bytes = read_input(matches, "ID", read_stdin);
String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8"))
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec<u8> {
match matches.get_one::<String>(name).map(|s| s.as_str()) {
Some(text) => match get_file(text) {
Some(file) => match File::open(file.as_path()) {
Ok(mut f) => read_stream(&mut f),
Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())),
},
None => text.as_bytes().to_vec(),
},
None => {
if io::stdin().is_terminal() {
if read_stdin {
rpassword::prompt_password("Enter Secret: ")
.unwrap()
.as_bytes()
.to_vec()
} else {
Vec::new()
}
} else {
let mut f = io::stdin();
read_stream(&mut f)
}
}
}
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
fn read_stream<R: Read>(f: &mut R) -> Vec<u8> {
let mut bytes = Vec::new();
let mut buffer = [0u8; 4096];
loop {
match f.read(&mut buffer) {
Ok(0) => break,
Ok(n) => bytes.extend_from_slice(&buffer[..n]),
Err(_) => break,
}
}
bytes
}
#[cfg(any(
all(target_os = "macos", feature = "macos-keychain"),
all(target_os = "windows", feature = "windows-credentials"),
all(target_os = "linux", feature = "linux-secret-service"),
feature = "yubihsm-usb",
feature = "yubihsm-http",
feature = "nitrokey",
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
fn get_file(name: &str) -> Option<PathBuf> {
let mut file = PathBuf::from(name);
if file.as_path().is_file() {
let metadata = file
.as_path()
.symlink_metadata()
.expect("symlink_metadata call failed");
if metadata.file_type().is_symlink() {
match file.as_path().read_link() {
Ok(f) => file = f,
Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)),
}
}
Some(file)
} else {
None
}
}
fn die<R>(final_message: &str) -> R {
eprintln!("{}", final_message.red());
std::process::exit(1);
}