fix(native-api): keep dependency identity across an unchanged reload

This commit is contained in:
eries authored and Zakk committed 2026-10-20 05:35:02 +11:00
1 parent 90d783a3df
commit cd065120df
5 files changed
+146 -3

No files matched your search

@@ -613,12 +613,27 @@ impl Worker {
.first()
.and_then(|main| accepted.ids.get(&main.path))
.cloned();
(accepted.ids.clone(), main)
(
accepted.ids.clone(),
main,
!accepted.update.dependencies.is_empty(),
)
});
let capture = if accepted.as_ref().is_some_and(|(_, _, captured)| *captured) {
let active = self.active.read().await.clone();
let deferred = self
.subscriptions
.deferred_subscriptions()
.await
.map_err(|_| unavailable())?;
Some((active, self.data_dir.clone(), deferred))
} else {
None
};
tokio::task::spawn_blocking(move || {
let (ids, main) = accepted
.as_ref()
.map_or((None, None), |(ids, main)| (Some(ids), main.as_deref()));
.map_or((None, None), |(ids, main, _)| (Some(ids), main.as_deref()));
let reject = |error, diagnostics: &[DetailedDiagnostic], sources: &[SourceSnapshot]| {
config_error(error, diagnostics, sources, main, ids)
};
@@ -635,6 +650,24 @@ impl Worker {
let loaded = store
.load(&HashMap::new(), &mut diagnostics)
.map_err(|error| reject(error, &diagnostics, &[]))?;
// Reload admission permits unavailable geo assets; failed fingerprint capture
// must not tighten that contract or retain a stale dependency baseline.
let dependencies = capture
.and_then(|(active, data_dir, deferred)| {
offline::capture_for_coordinator(
loaded.clone(),
store.dependency_root(),
&active,
&data_dir,
SourceLimits::DEFAULT,
&mut Vec::new(),
&deferred,
None,
)
.ok()
.map(|captured| captured.dependencies)
})
.unwrap_or_default();
let mut config = crate::admit_operator_config(
loaded.config,
loaded.sources[0].source.clone(),
@@ -646,7 +679,7 @@ impl Worker {
config,
Some(SourceUpdate {
sources: loaded.sources,
dependencies: Vec::new(),
dependencies,
geo_sources: None,
}),
diagnostics,
@@ -1411,6 +1411,75 @@ async fn identical_bytes_over_a_changed_loaded_file_are_not_a_success() {
server.close().await;
}
#[tokio::test]
async fn an_update_follows_a_reload_over_an_externally_edited_dependency() {
if crate::native_api::logs::tests::run_isolated(
"native_api::config::tests::geodata::an_update_follows_a_reload_over_an_externally_edited_dependency",
) {
return;
}
let server = AssetServer::new(geosite("new.example"), geoip(203), false).await;
let fixture = Fixture::new_custom(Access::Admin, false, |root, files| {
// Real reloads resolve assets through the process-wide data directory.
honk_config::paths::set_data_dir(root.join("state")).unwrap();
setup(root, files, server.address);
})
.await;
let hosts = fixture.path("hosts.rules");
std::fs::write(&hosts, "full:alias.test 192.0.2.1\n").unwrap();
let before = fixture.get(CONFIG).await;
let main = source(&before, &fixture.originals["main.dae"]);
let candidate = format!(
"{}dns {{\n use_host: '{}'\n}}\n",
fixture.originals["main.dae"],
hosts.display()
);
let write = accepted(fixture.replace(main, &candidate).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&write).await["status"], "succeeded");
let written = fixture.get(CONFIG).await;
std::fs::write(&hosts, "full:alias.test 192.0.2.2\n").unwrap();
let reload = accepted(fixture.request(Method::POST, RELOAD).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&reload).await["status"], "succeeded");
let reloaded = fixture.get(CONFIG).await;
let operation = accepted(fixture.request(Method::POST, UPDATE).send().await.unwrap()).await;
let terminal = fixture.terminal(&operation).await;
assert_eq!(terminal["status"], "succeeded", "{terminal}");
assert_ne!(reloaded["revision"], written["revision"]);
let updated = fixture.get(CONFIG).await;
let reload = accepted(fixture.request(Method::POST, RELOAD).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&reload).await["status"], "succeeded");
assert_eq!(fixture.get(CONFIG).await["revision"], updated["revision"]);
fixture.shutdown().await;
server.close().await;
}
#[tokio::test]
async fn a_reload_keeps_runtime_admission_when_a_geo_asset_cannot_be_captured() {
if crate::native_api::logs::tests::run_isolated(
"native_api::config::tests::geodata::a_reload_keeps_runtime_admission_when_a_geo_asset_cannot_be_captured",
) {
return;
}
let fixture = Fixture::new_custom(Access::Admin, false, |root, files| {
honk_config::paths::set_data_dir(root.join("state")).unwrap();
setup_rules(root, files);
})
.await;
let before = fixture.get(CONFIG).await;
let main = source(&before, &fixture.originals["main.dae"]);
let candidate = format!("{}# Capture dependencies.\n", fixture.originals["main.dae"]);
let write = accepted(fixture.replace(main, &candidate).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&write).await["status"], "succeeded");
let asset = fixture.path("state/geosite.dat");
std::fs::remove_file(&asset).unwrap();
// A regular proc file whose reads fail even when the test runs as root.
std::os::unix::fs::symlink("/proc/self/mem", &asset).unwrap();
let reload = accepted(fixture.request(Method::POST, RELOAD).send().await.unwrap()).await;
let terminal = fixture.terminal(&reload).await;
assert_eq!(terminal["status"], "succeeded", "{terminal}");
fixture.shutdown().await;
}
/// A reload keeps a router whose asset bytes are unchanged, so it can go on
/// naming a packaged file after an identical copy starts shadowing it.
#[tokio::test]
@@ -919,3 +919,42 @@ async fn removed_destination_settings_survive_export_reload_and_sighup() {
assert_eq!(fixture.reloads.load(Ordering::SeqCst), 2);
fixture.shutdown().await;
}
#[tokio::test]
async fn unchanged_reload_keeps_the_revision_of_a_write_with_captured_dependencies() {
let fixture = Fixture::new(Access::Admin, false).await;
std::fs::write(fixture.path("hosts.rules"), "full:alias.test 192.0.2.1\n").unwrap();
let before = fixture.get(CONFIG).await;
let main = source(&before, &fixture.originals["main.dae"]);
let candidate = format!(
"{}dns {{\n use_host: '{}'\n}}\n",
fixture.originals["main.dae"],
fixture.path("hosts.rules").display()
);
let operation = accepted(fixture.replace(main, &candidate).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&operation).await["status"], "succeeded");
let written = fixture.get(CONFIG).await;
assert_ne!(written["revision"], before["revision"]);
let reload = accepted(fixture.request(Method::POST, RELOAD).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&reload).await["status"], "succeeded");
assert_eq!(fixture.get(CONFIG).await["revision"], written["revision"]);
fixture.shutdown().await;
}
#[tokio::test]
async fn unchanged_reload_keeps_a_startup_revision_without_dependency_snapshots() {
let fixture = Fixture::new_custom(Access::Admin, false, |root, files| {
let hosts = root.join("hosts.rules");
std::fs::write(&hosts, "full:alias.test 192.0.2.1\n").unwrap();
files
.get_mut("main.dae")
.unwrap()
.push_str(&format!("dns {{\n use_host: '{}'\n}}\n", hosts.display()));
})
.await;
let before = fixture.get(CONFIG).await;
let reload = accepted(fixture.request(Method::POST, RELOAD).send().await.unwrap()).await;
assert_eq!(fixture.terminal(&reload).await["status"], "succeeded");
assert_eq!(fixture.get(CONFIG).await["revision"], before["revision"]);
fixture.shutdown().await;
}
+1
View File
@@ -198,6 +198,7 @@ RSS comes from `/proc/self/status`. Cgroup-v2 membership and mount discovery sel
### Accepted configuration and reload operations
The source manager requires a genuine `.dae` startup captured by the file loader. Programmatic configs and compatibility serde loaders do not provide lossless sources; their configuration/validation/reload capabilities remain unavailable. GET describes the accepted snapshot, not a fresh disk scan: opaque source IDs, exact-byte SHA-256 hashes, main/include kinds, write permissions and safe diagnostics. Source `path` and rule `file` retain canonical entry-directory-relative names, such as `config.d/routing.dae`; source `absolute_path` additionally exposes the canonical absolute path. Source hashes, configuration revision and runtime generation are distinct: accepting comments-only changes advances revision without requiring a new runtime generation; effective group membership changes revision, but health observations do not.
Reloads refresh any previously captured dependency fingerprints; unchanged sources and fingerprints retain their configuration revision.
Admitted anonymous loopback requests read the same configuration data as bearer-authenticated requests. Accepted content includes ordinary credentials, share links and paths; only declared native/Clash listener-secret values are masked, including duplicate and overridden declarations and occurrences elsewhere in the source. Parser spans identify the secret values while preserving nonsecret text and line structure. Credential-bearing sources remain read-only with hashes of their original bytes. A write whose content contains a masked value, in either its raw or JSON-escaped spelling, returns `403 permission_denied`. A value shorter than eight bytes is neither masked nor refused: it can be written into an ordinary source and is read back unmasked. The required `secrets_redacted` boolean reports whether listener-secret values were withheld; masked content is never an editable round-trip payload. Native settings and listener credentials cannot be changed or moved through this API; edit them locally and restart. To make a main file editable, first place listener credentials in a dedicated read-only include locally.
+1
View File
@@ -199,6 +199,7 @@ RSS 来自 `/proc/self/status`;cgroup v2 依据实际 membership/mountinfo 定
### 配置来源、校验与操作
只有真实 `.dae` 启动加载时捕获的源集合才启用配置管理;程序内构造的 Config 或 serde 格式加载不能冒充无损来源,其配置能力不可用。GET 返回最后已接受的快照,不临时重扫磁盘。源 ID 不含路径,源 `path` 与规则 `file` 保留规范化的入口目录相对名称(例如 `config.d/routing.dae`),源 `absolute_path` 另行提供规范化绝对路径;原文 SHA-256、字节数、加载时间与逐源 `writable` 单独提供。源集合与校验最多 32 个来源、8 MiB 原始字节,依赖的每次实体化也计入数量和字节预算;geodata 文件是引擎本来就整体加载的运行时资产,只参与哈希冲突检测,不计入预算;HTTP JSON body 的 64 KiB 上限仍独立生效,超限返回 413。因此 capabilities 中 `config.max_bytes` 为 61440,即 65536 字节正文上限扣除 4096 字节创建信封后单次请求能携带的最大替换或新建内容;`config_validate.max_bytes` 为 8 MiB 预算,因为完整校验还计入从磁盘读取的依赖。`resources.config` 不含 `content` 字段;替换或新建正文超过 `config.max_bytes` 时返回 `413 request_too_large`。
Reload 会刷新此前已捕获的依赖指纹;来源与指纹未变化时保留原配置 revision。
获准访问的匿名 loopback 请求与 bearer 认证请求读取相同的配置数据。已接受正文包含普通凭据、分享链接及路径;仅遮蔽声明的原生/Clash 监听凭据值,包括重复、被覆盖的声明及这些值在源中其他位置的出现。解析器提供的范围用于识别凭据值,非凭据文本与行结构保持不变。凭据源仍只读,哈希仍对应原始字节。写入内容含有被遮蔽的值(原文或 JSON 转义写法)时返回 `403 permission_denied`。不足八字节的值既不遮蔽也不拒绝写入,可以写进普通源,读取时原样返回。必有的 `secrets_redacted` 布尔值表示是否遮蔽了监听凭据值;遮蔽后的正文不能用于编辑后回写。