use super::super::*;
use super::{
atomic_write, auth_snapshot_path, auth_wal_path, cancel_all_temporary_leases, open_blob,
push_audit_record, seal_blob, sync_parent_directory,
};
#[derive(Debug)]
pub(crate) enum WalState {
Intact,
Uncertain,
}
#[derive(Debug)]
pub(crate) struct WalAppendError {
pub(crate) failure: AuthFailure,
pub(crate) wal: WalState,
}
impl WalAppendError {
fn intact(failure: AuthFailure) -> Self {
Self {
failure,
wal: WalState::Intact,
}
}
fn uncertain(failure: AuthFailure) -> Self {
Self {
failure,
wal: WalState::Uncertain,
}
}
}
pub(crate) fn append_record(
config: &AuthConfig,
inner: &AuthStateInner,
record: &WalRecord,
) -> Result<(), AuthFailure> {
inner.mark_snapshot_stale();
append_wal(config, &inner.admin_key(), record).map_err(|WalAppendError { failure, wal }| {
match wal {
WalState::Intact => {}
WalState::Uncertain => {
inner.safe_mode.store(true, Ordering::Release);
cancel_all_temporary_leases(inner);
}
}
failure
})
}
pub(crate) fn append_mutation(
config: &AuthConfig,
inner: &AuthStateInner,
mutation: StateMutation,
audit: AuditRecord,
) -> Result<(), AuthFailure> {
append_record(
config,
inner,
&WalRecord::Mutation {
mutation,
audit: audit.clone(),
},
)?;
push_audit_record(inner, audit);
Ok(())
}
pub(crate) fn append_audit(
config: &AuthConfig,
inner: &AuthStateInner,
audit: AuditRecord,
) -> Result<(), AuthFailure> {
append_record(config, inner, &WalRecord::Audit(audit.clone()))?;
push_audit_record(inner, audit);
Ok(())
}
pub(crate) fn append_wal(
config: &AuthConfig,
admin_key: &AesKeyType,
record: &WalRecord,
) -> Result<(), WalAppendError> {
let plain = serde_json::to_vec(record)
.map_err(|error| {
AuthFailure::internal(format!("failed to encode auth WAL record: {error}"))
})
.map_err(WalAppendError::uncertain)?;
let sealed = seal_blob(admin_key, &plain).map_err(WalAppendError::uncertain)?;
let length = u32::try_from(sealed.len())
.map_err(|_| AuthFailure::internal("auth WAL record is too large"))
.map_err(WalAppendError::uncertain)?;
let path = auth_wal_path(&config.state_dir);
let created = !path.exists();
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|error| {
WalAppendError::intact(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to open `{}`: {error}", path.display()),
true,
))
})?;
#[cfg(unix)]
file.set_permissions(std::fs::Permissions::from_mode(0o600))
.map_err(|error| {
WalAppendError::intact(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to secure `{}`: {error}", path.display()),
false,
))
})?;
let start_len = file
.metadata()
.map(|metadata| metadata.len())
.map_err(|error| {
WalAppendError::intact(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to inspect `{}`: {error}", path.display()),
true,
))
})?;
if let Err(error) = file
.write_all(&length.to_be_bytes())
.and_then(|()| file.write_all(&sealed))
.and_then(|()| file.sync_data())
{
let rolled_back = file
.set_len(start_len)
.and_then(|()| file.sync_data())
.is_ok();
return Err(if rolled_back {
WalAppendError::intact(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to durably append `{}`: {error}", path.display()),
true,
))
} else {
WalAppendError::uncertain(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!(
"failed to durably append `{}` and could not restore the previous WAL length: {error}",
path.display()
),
false,
))
});
}
if created {
sync_parent_directory(&path).map_err(WalAppendError::uncertain)?;
}
Ok(())
}
const MAX_WAL_RECORD_LEN: usize = 1024 * 1024;
pub(super) enum WalRecordError {
TooLarge,
Truncated(std::io::Error),
}
pub(super) fn read_wal_record(
file: &mut File,
prefix: [u8; 4],
sealed: &mut Vec<u8>,
) -> Result<(), WalRecordError> {
let length = u32::from_be_bytes(prefix) as usize;
if length > MAX_WAL_RECORD_LEN {
return Err(WalRecordError::TooLarge);
}
sealed.resize(length, 0);
file.read_exact(sealed).map_err(WalRecordError::Truncated)
}
fn frame_begins(file: &mut impl Read, first: &mut u8) -> std::io::Result<bool> {
loop {
match file.read(std::slice::from_mut(first)) {
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
result => return result.map(|read| read != 0),
}
}
}
pub(crate) fn read_wal(path: &Path, admin_key: &AesKeyType) -> Result<Vec<WalRecord>, AuthFailure> {
let mut file = File::open(path).map_err(|error| {
AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to open `{}`: {error}", path.display()),
false,
)
})?;
let mut records = Vec::new();
let mut sealed = Vec::new();
loop {
let mut length = [0_u8; 4];
let [first, ..] = &mut length;
match frame_begins(&mut file, first) {
Ok(false) => break,
Ok(true) => {}
Err(error) => {
return Err(AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to read auth WAL length: {error}"),
false,
));
}
}
file.read_exact(&mut length[1..]).map_err(|error| {
AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("truncated auth WAL length: {error}"),
false,
)
})?;
read_wal_record(&mut file, length, &mut sealed).map_err(|error| match error {
WalRecordError::TooLarge => AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
"auth WAL record exceeds 1 MiB",
false,
),
WalRecordError::Truncated(error) => AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("truncated auth WAL record: {error}"),
false,
),
})?;
let plain = open_blob(admin_key, &sealed)?;
records.push(serde_json::from_slice(&plain).map_err(|error| {
AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to decode auth WAL record: {error}"),
false,
)
})?);
}
Ok(records)
}
pub(crate) fn write_snapshot_and_truncate_wal(
config: &AuthConfig,
admin_key: &AesKeyType,
snapshot: &PersistedSnapshot,
) -> Result<(), AuthFailure> {
let plain = serde_json::to_vec(snapshot).map_err(|error| {
AuthFailure::internal(format!("failed to encode auth snapshot: {error}"))
})?;
let sealed = seal_blob(admin_key, &plain)?;
let snapshot_path = auth_snapshot_path(&config.state_dir);
atomic_write(&snapshot_path, &sealed, 0o600)?;
truncate_auth_wal(&config.state_dir)
}
pub(crate) fn truncate_auth_wal(state_dir: &Path) -> Result<(), AuthFailure> {
let wal_path = auth_wal_path(state_dir);
let created = !wal_path.exists();
let wal = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&wal_path)
.map_err(|error| {
AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to truncate `{}`: {error}", wal_path.display()),
true,
)
})?;
wal.sync_all().map_err(|error| {
AuthFailure::new(
codes::TEMPORARY_KEY_STORE_UNAVAILABLE,
format!("failed to sync `{}`: {error}", wal_path.display()),
true,
)
})?;
if created {
sync_parent_directory(&wal_path)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::{Error, ErrorKind, Read};
use super::frame_begins;
struct Script(Vec<Result<&'static [u8], ErrorKind>>);
impl Read for Script {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self.0.remove(0) {
Ok(bytes) => {
buf[..bytes.len()].copy_from_slice(bytes);
Ok(bytes.len())
}
Err(kind) => Err(Error::from(kind)),
}
}
}
#[test]
fn an_interrupted_read_between_frames_is_retried() {
let mut first = 0;
let mut file = Script(vec![Err(ErrorKind::Interrupted), Ok(&[7])]);
assert!(frame_begins(&mut file, &mut first).unwrap());
assert_eq!(first, 7);
let mut file = Script(vec![Err(ErrorKind::Interrupted), Ok(&[])]);
assert!(!frame_begins(&mut file, &mut first).unwrap());
let mut file = Script(vec![Err(ErrorKind::PermissionDenied)]);
assert!(frame_begins(&mut file, &mut first).is_err());
}
}