fix(store): check the db import before creating the state db

This commit is contained in:
Zakk committed 2026-11-08 21:13:53 +11:00
1 parent 62b1390401
commit 4afab4cb97
4 files changed
+235 -39

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
Fixed
- A refused `--store db` start no longer leaves an empty state database, or its data directory, behind.
-1
View File
@@ -780,7 +780,6 @@ pub async fn run(cli: Cli) -> anyhow::Result<()> {
let startup = (|| -> anyhow::Result<_> {
#[cfg(feature = "native-api")]
let mut config = if cli.store == ConfigStore::Db {
std::fs::create_dir_all(&cli.data_dir)?;
// DbStore needs an absolute, lexically normal entry; a missing -c
// is fine once the db holds a revision.
let entry =
@@ -14,7 +14,7 @@ use honk_config::parser::{LoadedConfig, SourceLimits, SourceSnapshot};
use super::super::secrets::ListenerSecrets;
use super::db::{DbStore, StoreError, StoredSecrets};
use crate::configuration::SourceUpdate;
use crate::state::StateDb;
use crate::state::{DB_FILE, STATE_DIR, StateDb};
pub(crate) struct DatabaseStartup {
pub(crate) store: Arc<DbStore>,
@@ -107,11 +107,19 @@ pub(crate) fn stripped_config_matches(original: &Config, stripped: &mut Config)
impl DatabaseStartup {
/// `entry` must be absolute and lexically normal; it is read only while the db is empty.
/// A db that does not exist yet is created only after the file has passed every check.
pub(crate) fn open(
entry: &Path,
data_dir: &Path,
diagnostics: &mut Vec<DetailedDiagnostic>,
) -> anyhow::Result<Self> {
let fresh = if db_exists(data_dir) {
None
} else {
let fresh = FreshImport::load(entry, data_dir, diagnostics)?;
std::fs::create_dir_all(data_dir)?;
Some(fresh)
};
let state = StateDb::open(data_dir).map_err(|error| store_error(error.into()))?;
let store = Arc::new(DbStore::open(Arc::new(state), entry).map_err(store_error)?);
if let Some((head, _)) = store.cached_head() {
@@ -131,47 +139,18 @@ impl DatabaseStartup {
head: Some(head),
});
}
let (config, sources) = crate::load_operator_config_captured(store.entry(), diagnostics)
.with_context(|| {
format!(
"the configuration db is empty and {} cannot be imported",
entry.display()
)
})?;
let originals = sources
.ok_or_else(|| anyhow!("--store db imports a dae source tree"))?
.sources;
let native = &config.experimental.native_api;
ensure!(
native.enabled && native.config_write && native.credentialed(),
"--store db needs experimental.native_api with enabled, config_write and a credential"
);
no_clash_api(&config)?;
same_data_dir(&config, data_dir)?;
let (loaded, forbidden) =
import_tree(store.entry(), &config, &originals).map_err(|error| match error {
ImportError::SecretCopy(path) => anyhow!(
"listener secrets in {} cannot be stripped completely; remove copies of secret values",
path.display()
),
ImportError::Load(error) => error.into(),
ImportError::Changed => anyhow!(
"{} does not read back the same once listener secrets are stripped",
entry.display()
),
})?;
let secrets = StoredSecrets {
native_api: config.experimental.native_api.secret.clone(),
clash_api: config.experimental.clash_api.secret.clone(),
let fresh = match fresh {
Some(fresh) => fresh,
None => FreshImport::load(store.entry(), data_dir, diagnostics)?,
};
Ok(Self {
store,
config,
sources: update(loaded.sources.clone()),
config: fresh.config,
sources: update(fresh.stripped.clone()),
import: Some(Import {
stripped: loaded.sources,
forbidden,
secrets,
stripped: fresh.stripped,
forbidden: fresh.forbidden,
secrets: fresh.secrets,
}),
head: None,
})
@@ -202,6 +181,67 @@ impl DatabaseStartup {
}
}
/// What `-c` imports as revision 1, with every precondition already checked.
struct FreshImport {
config: Config,
stripped: Vec<SourceSnapshot>,
forbidden: ListenerSecrets,
secrets: StoredSecrets,
}
impl FreshImport {
fn load(
entry: &Path,
data_dir: &Path,
diagnostics: &mut Vec<DetailedDiagnostic>,
) -> anyhow::Result<Self> {
let (config, sources) = crate::load_operator_config_captured(entry, diagnostics)
.with_context(|| {
format!(
"the configuration db is empty and {} cannot be imported",
entry.display()
)
})?;
let originals = sources
.ok_or_else(|| anyhow!("--store db imports a dae source tree"))?
.sources;
let native = &config.experimental.native_api;
ensure!(
native.enabled && native.config_write && native.credentialed(),
"--store db needs experimental.native_api with enabled, config_write and a credential"
);
no_clash_api(&config)?;
same_data_dir(&config, data_dir)?;
let (loaded, forbidden) =
import_tree(entry, &config, &originals).map_err(|error| match error {
ImportError::SecretCopy(path) => anyhow!(
"listener secrets in {} cannot be stripped completely; remove copies of secret values",
path.display()
),
ImportError::Load(error) => error.into(),
ImportError::Changed => anyhow!(
"{} does not read back the same once listener secrets are stripped",
entry.display()
),
})?;
let secrets = StoredSecrets {
native_api: config.experimental.native_api.secret.clone(),
clash_api: config.experimental.clash_api.secret.clone(),
};
Ok(Self {
config,
stripped: loaded.sources,
forbidden,
secrets,
})
}
}
/// A symlink in its place counts, so that `StateDb::open` reports the refusal.
fn db_exists(data_dir: &Path) -> bool {
std::fs::symlink_metadata(data_dir.join(STATE_DIR).join(DB_FILE)).is_ok()
}
fn update(sources: Vec<SourceSnapshot>) -> SourceUpdate {
SourceUpdate {
sources,
@@ -245,3 +245,157 @@ fn clash_controller_in_the_head_refuses_startup() {
"{error}"
);
}
struct Refusal {
name: &'static str,
/// Breaks one precondition of the tree that `tree` writes.
edit: fn(entry: &Path, auth: &Path),
needle: &'static str,
}
fn replace_in(path: &Path, from: &str, to: &str) {
let content = fs::read_to_string(path).unwrap();
assert!(content.contains(from), "{from} not in {content}");
fs::write(path, content.replace(from, to)).unwrap();
}
const REFUSALS: &[Refusal] = &[
Refusal {
name: "native api disabled",
edit: |_, auth| replace_in(auth, "enabled: true", "enabled: false"),
needle: "--store db needs experimental.native_api",
},
Refusal {
name: "config_write off",
edit: |_, auth| replace_in(auth, "config_write: true", "config_write: false"),
needle: "--store db needs experimental.native_api",
},
Refusal {
name: "clash controller",
edit: |_, auth| replace_in(auth, "native_api {", CONTROLLER),
needle: "without the Clash API",
},
Refusal {
name: "data dir mismatch",
edit: |entry, _| replace_in(entry, "data_dir: '", "data_dir: '/elsewhere"),
needle: "differs from --data-dir",
},
Refusal {
name: "secret copy",
edit: |entry, _| {
let mut main = fs::read_to_string(entry).unwrap();
main.push_str("# old startup-token copied here\n");
fs::write(entry, main).unwrap();
},
needle: "copies",
},
Refusal {
name: "missing entry",
edit: |entry, _| fs::remove_file(entry).unwrap(),
needle: "cannot be imported",
},
];
fn refused(entry: &Path, data_dir: &Path) -> String {
DatabaseStartup::open(entry, data_dir, &mut Vec::new())
.err()
.expect("the start must be refused")
.to_string()
}
#[test]
fn a_refused_import_leaves_nothing_behind() {
for case in REFUSALS {
for data_dir_exists in [false, true] {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().canonicalize().unwrap().join("data");
if data_dir_exists {
fs::create_dir(&data_dir).unwrap();
}
let (directory, entry) = tree(&data_dir);
(case.edit)(&entry, &directory.path().join("auth.dae"));
let error = refused(&entry, &data_dir);
assert!(
error.contains(case.needle),
"{} (data dir exists: {data_dir_exists}): {error}",
case.name
);
assert_eq!(data_dir.exists(), data_dir_exists, "{}", case.name);
assert!(!data_dir.join("state").exists(), "{}", case.name);
}
}
}
#[test]
fn a_refused_start_on_an_existing_db_keeps_it() {
for case in REFUSALS.iter().filter(|case| case.name != "missing entry") {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().canonicalize().unwrap();
let (directory, entry) = tree(&data_dir);
// An empty db left by an earlier start; a db with a head is covered above.
drop(DbStore::open_in(&data_dir, &entry).unwrap());
(case.edit)(&entry, &directory.path().join("auth.dae"));
assert!(
refused(&entry, &data_dir).contains(case.needle),
"{}",
case.name
);
assert_eq!(
DbStore::open_in(&data_dir, &entry).unwrap().head(),
Ok(None)
);
}
}
#[test]
fn a_good_config_creates_the_data_dir_and_records_revision_one() {
let root = tempfile::tempdir().unwrap();
let data_dir = root
.path()
.canonicalize()
.unwrap()
.join("nested")
.join("data");
let (_directory, entry) = tree(&data_dir);
let mut startup = DatabaseStartup::open(&entry, &data_dir, &mut Vec::new()).unwrap();
assert!(data_dir.join("state").join("honk.db").exists());
startup.record().unwrap();
assert_eq!(startup.store.head(), Ok(Some(1)));
}
#[test]
fn the_first_failing_precondition_is_the_one_reported() {
// Native API, Clash controller and data dir all wrong, then the first one fixed in turn.
let steps = [
"--store db needs experimental.native_api",
"without the Clash API",
"differs from --data-dir",
];
for existing_empty_db in [false, true] {
let root = tempfile::tempdir().unwrap();
let data_dir = root.path().canonicalize().unwrap().join("data");
let (directory, entry) = tree(&root.path().join("elsewhere"));
let auth = directory.path().join("auth.dae");
replace_in(&auth, "native_api {", CONTROLLER);
replace_in(&auth, "enabled: true", "enabled: false");
if existing_empty_db {
fs::create_dir(&data_dir).unwrap();
drop(DbStore::open_in(&data_dir, &entry).unwrap());
}
for needle in steps {
let error = refused(&entry, &data_dir);
assert!(error.contains(needle), "{needle}: {error}");
match needle {
"--store db needs experimental.native_api" => {
replace_in(&auth, "enabled: false", "enabled: true")
}
"without the Clash API" => replace_in(
&auth,
"external_controller: '127.0.0.1:9090'",
"external_controller: ''",
),
_ => {}
}
}
}
}