[edge] Epoch floor: an unreadable or corrupt floor refuses share links instead of resetting to 0; directory fsync'ed after the write

This commit is contained in:
2026-11-07 19:41:53 +01:00
parent cbb3e41ca7
commit 83b7b3b7d6
2 changed files with 60 additions and 7 deletions
+35 -7
View File
@@ -104,6 +104,8 @@ pub struct Shared {
revocations: ArcSwap<RevocationState>, revocations: ArcSwap<RevocationState>,
/// The highest revocation epoch seen since start; a file with a lower one is refused. /// The highest revocation epoch seen since start; a file with a lower one is refused.
epoch_seen: std::sync::atomic::AtomicU32, epoch_seen: std::sync::atomic::AtomicU32,
/// Set when the saved epoch floor could not be read: share links stay refused.
floor_error: Option<String>,
pub throttle: crate::share::Throttle, pub throttle: crate::share::Throttle,
cert_states: Mutex<HashMap<String, CertState>>, cert_states: Mutex<HashMap<String, CertState>>,
pub acme_wake: tokio::sync::Notify, pub acme_wake: tokio::sync::Notify,
@@ -122,7 +124,13 @@ fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
impl Shared { impl Shared {
pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> { pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> {
let floor = read_epoch_floor(&rt); let (floor, floor_error) = match read_epoch_floor(&rt) {
Ok(f) => (f, None),
Err(e) => {
log::error!(target: "ianitor::share", "{e}");
(u32::MAX, Some(e))
}
};
let certs = Arc::new(CertStore::default()); let certs = Arc::new(CertStore::default());
certs.replace_files(rt.file_certs.clone()); certs.replace_files(rt.file_certs.clone());
let (changed, _) = tokio::sync::watch::channel(1); let (changed, _) = tokio::sync::watch::channel(1);
@@ -138,6 +146,7 @@ impl Shared {
credentials_dir, credentials_dir,
revocations: ArcSwap::from_pointee(RevocationState::default()), revocations: ArcSwap::from_pointee(RevocationState::default()),
epoch_seen: std::sync::atomic::AtomicU32::new(floor), epoch_seen: std::sync::atomic::AtomicU32::new(floor),
floor_error,
throttle: crate::share::Throttle::default(), throttle: crate::share::Throttle::default(),
cert_states: Mutex::new(HashMap::new()), cert_states: Mutex::new(HashMap::new()),
acme_wake: tokio::sync::Notify::new(), acme_wake: tokio::sync::Notify::new(),
@@ -360,6 +369,9 @@ impl Shared {
.ok_or_else(|| fail("a link id is not 32 hex digits".into()))?, .ok_or_else(|| fail("a link id is not 32 hex digits".into()))?,
); );
} }
if let Some(e) = &self.floor_error {
return Err(fail(e.clone()));
}
// The epoch only goes up: a lower one would bring stopped links back. // The epoch only goes up: a lower one would bring stopped links back.
let seen = self.epoch_seen.load(Ordering::SeqCst); let seen = self.epoch_seen.load(Ordering::SeqCst);
if file.epoch < seen { if file.epoch < seen {
@@ -427,11 +439,23 @@ fn epoch_floor_path(rt: &Runtime) -> PathBuf {
Path::new(&rt.cfg.state_dir).join("share-epoch-floor") Path::new(&rt.cfg.state_dir).join("share-epoch-floor")
} }
fn read_epoch_floor(rt: &Runtime) -> u32 { /// Missing: 0. Unreadable or not a number: an error, and share links stay refused (failing
std::fs::read_to_string(epoch_floor_path(rt)) /// open would forget which links were stopped).
.ok() fn read_epoch_floor(rt: &Runtime) -> Result<u32, String> {
.and_then(|s| s.trim().parse().ok()) let path = epoch_floor_path(rt);
.unwrap_or(0) match std::fs::read_to_string(&path) {
Ok(s) => s.trim().parse().map_err(|_| {
format!(
"{} is not a number; share links are refused until it is fixed",
path.display()
)
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
Err(e) => Err(format!(
"cannot read {} ({e}); share links are refused until it is fixed",
path.display()
)),
}
} }
fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> { fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
@@ -446,7 +470,11 @@ fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
f.write_all(format!("{epoch}\n").as_bytes())?; f.write_all(format!("{epoch}\n").as_bytes())?;
f.sync_all()?; f.sync_all()?;
} }
std::fs::rename(&tmp, &path) std::fs::rename(&tmp, &path)?;
match path.parent() {
Some(dir) => std::fs::File::open(dir)?.sync_all(),
None => Ok(()),
}
} }
fn poisoned() -> AdminError { fn poisoned() -> AdminError {
+25
View File
@@ -531,4 +531,29 @@ mod unix {
.await; .await;
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302); assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 302);
} }
#[tokio::test(flavor = "multi_thread")]
async fn an_unreadable_epoch_floor_refuses_share_links() {
let mut e = env().await;
let t = link(HOST, 15, "/", now() + 3600, None);
let cookie = share_cookie(&e.get(HOST, &format!("/?share={t}"), None).await);
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
std::fs::write(e.edge.dir.join("state/share-epoch-floor"), "garbage").unwrap();
e.edge.restart();
assert_eq!(
e.get(HOST, "/", Some(&cookie)).await.status,
302,
"fails closed"
);
let r = e
.edge
.admin("POST", "/v1/share-revocations/reload", None)
.await;
assert_eq!(r.status, 422, "{}", r.text);
assert!(e.edge.stderr().contains("share-epoch-floor"));
// A missing floor is simply 0.
std::fs::remove_file(e.edge.dir.join("state/share-epoch-floor")).unwrap();
e.edge.restart();
assert_eq!(e.get(HOST, "/", Some(&cookie)).await.status, 200);
}
} }