use std::{
fs::{File, OpenOptions},
io::Read,
path::{Path, PathBuf},
};
use serde::{Serialize, de::DeserializeOwned};
use crate::platform;
pub(crate) const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
#[derive(Clone)]
pub struct Location {
path: PathBuf,
refusal: Option<String>,
previous: Option<Snapshot>,
}
#[derive(Clone)]
struct Snapshot {
file: &'static str,
bytes: std::sync::Arc<[u8]>,
}
impl Location {
pub fn beside(namespace: &Path) -> Result<Self, String> {
let namespace = platform::resolve_target(namespace).map_err(|error| error.to_string())?;
let name = namespace
.file_name()
.ok_or("Provider storage requires a named directory.")?;
let mut name = name.to_os_string();
name.push(".provider");
let path = namespace.with_file_name(name);
let path = platform::resolve_target(&path).map_err(|error| error.to_string())?;
if platform::is_within(&path, &namespace) {
return Err("Provider storage cannot resolve into its profile namespace.".into());
}
Ok(Self {
path,
refusal: None,
previous: None,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn refuse(mut self, reason: String) -> Self {
self.refusal = Some(reason);
self
}
pub(crate) fn is_refused(&self) -> bool {
self.refusal.is_some()
}
#[doc(hidden)]
pub fn with_snapshot(mut self, file: &'static str, bytes: Vec<u8>) -> Self {
self.previous = Some(Snapshot {
file,
bytes: bytes.into(),
});
self
}
pub(crate) fn refusal(&self, file: &str) -> Result<Option<String>, String> {
let Some(reason) = &self.refusal else {
return Ok(None);
};
if platform::entry_missing(&self.path.join(file)) {
Ok(Some(reason.clone()))
} else {
Err(reason.clone())
}
}
}
pub(crate) struct Storage {
pub(crate) directory: PathBuf,
previous: Option<Snapshot>,
}
impl Storage {
pub fn new(location: &Location) -> Result<Self, String> {
Self::open(location, true)
}
pub fn inspect(location: &Location) -> Result<Self, String> {
Self::open(location, false)
}
fn open(location: &Location, create: bool) -> Result<Self, String> {
if let Some(reason) = &location.refusal {
return Err(reason.clone());
}
let directory = location.path.clone();
if create {
platform::create_private_dir_all(&directory).map_err(|error| error.to_string())?;
}
let previous = (!create).then(|| location.previous.clone()).flatten();
match platform::is_private_dir(&directory) {
Ok(true) => Ok(Self {
directory,
previous,
}),
Err(error) if !create && error.kind() == std::io::ErrorKind::NotFound => Ok(Self {
directory,
previous,
}),
Err(error) => Err(error.to_string()),
Ok(false) => Err(format!(
"Auth directory must be {}.",
platform::PRIVATE_DIRECTORY
)),
}
}
pub async fn lock(&self, name: &str) -> Result<File, String> {
platform::credential_files::lock(&self.directory.join(format!("{name}.lock")))
.await
.map_err(|error| error.to_string())
}
pub fn read<T: DeserializeOwned>(&self, name: &str) -> Result<Option<T>, String> {
let file = match platform::open_no_follow(
OpenOptions::new().read(true),
&self.directory.join(name),
) {
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return self
.previous
.as_ref()
.filter(|snapshot| snapshot.file == name)
.map(|snapshot| decode(name, &snapshot.bytes))
.transpose();
}
Err(error) => return Err(error.to_string()),
};
check_private_file(&file)?;
let mut data = Vec::new();
file.take(MAX_CREDENTIAL_BYTES as u64 + 1)
.read_to_end(&mut data)
.map_err(|e| e.to_string())?;
if data.len() > MAX_CREDENTIAL_BYTES {
return Err("Credential file is too large.".into());
}
decode(name, &data).map(Some)
}
pub fn save(&self, name: &str, value: &impl Serialize) -> Result<(), String> {
platform::credential_files::replace(&self.directory, &self.directory.join(name), |file| {
serde_json::to_writer(file, value).map_err(|_| "Cannot encode credentials.".to_owned())
})?;
self.sync()
}
pub fn remove(&self, name: &str) -> Result<(), String> {
match platform::credential_files::remove(&self.directory.join(name)) {
Ok(()) => self.sync(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.to_string()),
}
}
fn sync(&self) -> Result<(), String> {
platform::sync_dir(&self.directory).map_err(|e| e.to_string())
}
}
fn check_private_file(file: &File) -> Result<(), String> {
if !platform::is_private_file(file).map_err(|e| e.to_string())? {
return Err(format!(
"Auth files must be regular, single-link files {}.",
platform::PRIVATE_FILE
));
}
Ok(())
}
fn decode<T: DeserializeOwned>(name: &str, bytes: &[u8]) -> Result<T, String> {
if bytes.len() > MAX_CREDENTIAL_BYTES {
return Err("Credential file is too large.".into());
}
serde_json::from_slice(bytes)
.map_err(|_| format!("Invalid credential file {name}; sign in again."))
}