Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion bin/twcore/src/pack_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,10 @@ pub fn restore(path: &Path, id: &str, dry_run: bool) -> Result<()> {
let pinned = tw_pack::disk::read_pinned(path);
let after = if tw_pack::model::snapshot(&local).is_err() {
println!("the configuration here does not load; the whole version comes back");
tw_pack::restore::whole(&backup, &cur.text)
let last = tw_pack::backup::list(path)
.ok()
.and_then(|all| all.last().and_then(|b| tw_pack::backup::open(b).ok()));
tw_pack::restore::whole(&backup, &cur.text, last.as_ref())
} else {
let rows = tw_pack::restore::preview(&local, &backup, &pinned, true).map_err(model)?;
if rows.is_empty() {
Expand All @@ -396,6 +399,7 @@ pub fn restore(path: &Path, id: &str, dry_run: bool) -> Result<()> {
};
let kept = match r.kept {
Some(Kept::KeyInUse) => " (kept: a client set up on this machine uses it)",
Some(Kept::Referenced) => " (kept: something that stays refers to it)",
None => "",
};
println!(" {change} {}{kept}", describe(&r.item));
Expand Down
5 changes: 4 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,10 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt");
/// 新增、相同、冲突、错误)和 `POST /config/import`([`ImportRequest`]:逐项导入、覆盖、改名
/// 导入或跳过)。Lite 的通用偏好由 core 存:`GET` / `PUT /client-prefs`([`ClientPrefs`],
/// 不解析,最大 64 KiB),变了发 [`Event::ClientPrefsChanged`]。`PUT /pinned-keys`
/// ([`PinnedKeys`])报告接管的客户端在用哪几把密钥。导入覆盖、恢复改了或删了网关密钥时发
/// ([`PinnedKeys`]:`source` 是这个 Lite 的标识,几个 Lite 各报各的、core 取并集,30 天没更新
/// 的来源不算)报告接管的客户端在用哪几把密钥。恢复时留下的项目还引用着的不删
/// ([`KeptReason`] 的 `referenced`),所选项目引用的、本机已没有的一起恢复;不带密钥的包导入时
/// 比较和覆盖都沿用本机的密钥。导入覆盖、恢复改了或删了网关密钥时发
/// [`Event::GatewayKeysChanged`]。[`ConfigOrigin`] 删了 `rollback`,多了 `sync`、`import`、
/// `restore`、`repair`(一键修复以前记成 `ui`)。备份相关的端点在安全模式下照样可用。配置包的
/// 码是 `pack.*`,导入的是 `import.*`,备份与恢复的是 `backup.*`。停用着的上游可以缺凭据
Expand Down
11 changes: 10 additions & 1 deletion crates/tw-api/src/pack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,9 @@ slug_enum! {
pub enum KeptReason {
/// 本机接管的客户端正在用这把网关密钥:不删
KeyInUse = "key_in_use",
/// 恢复之后留下的项目还引用着它(留着的密钥绑的路由、没选的路由用的上游……):删了配置
/// 就不成立,所以留着
Referenced = "referenced",
}
}

Expand Down Expand Up @@ -380,9 +383,15 @@ pub struct ClientPrefs {
/// Lite 的通用偏好最大多少字节(写成 JSON 之后)
pub const CLIENT_PREFS_MAX: usize = 64 * 1024;

/// `PUT /pinned-keys`:本机接管的客户端正在用的网关密钥。恢复、导入、同步不删它们。
/// `PUT /pinned-keys`:这一个 Lite 接管的客户端正在用的网关密钥。恢复、导入、同步不删它们。
///
/// **按来源记**:几个 Lite 连着同一个 core(远程模式)时各报各的,core 取并集;一个来源报的
/// 换掉它自己上次报的。30 天没更新的来源不再算
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct PinnedKeys {
/// 这个 Lite 的标识,各实例固定的一个随机串。不给是空串(当作同一个来源)
#[serde(default)]
pub source: String,
pub names: Vec<String>,
}
100 changes: 71 additions & 29 deletions crates/tw-control/src/backups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,19 @@ use tw_types::{Msg, msg};
use crate::contract::RouterExt;
use crate::{ApplyError, ControlState, Fail, apply_fail, fail, unreadable_config};

/// 带着配置包内容的请求体最大多少字节:一个 [`tw_pack::MAX_BYTES`] 的包写成 base64,加上
/// 请求里别的几个字段。**只给这两个端点放宽**,别的照 axum 的默认(2 MiB)
pub const PACK_BODY_MAX: usize = tw_pack::MAX_BYTES / 3 * 4 + 1024 * 1024;

pub fn router() -> axum::Router<ControlState> {
let packs = axum::Router::new()
.at(ep::ImportPreview, import_preview)
.at(ep::ImportConfig, import)
.layer(axum::extract::DefaultBodyLimit::max(PACK_BODY_MAX));
axum::Router::new()
.merge(packs)
.at(ep::ConfigItems, items)
.at(ep::ExportConfig, export)
.at(ep::ImportPreview, import_preview)
.at(ep::ImportConfig, import)
.at(ep::Backups, backups)
.at(ep::BackupFile, backup_file)
.at(ep::RestorePreview, restore_preview)
Expand Down Expand Up @@ -256,21 +263,37 @@ fn passphrase(p: Option<&str>) -> Result<Option<&str>, Fail> {
}
}

fn open_pack(data_b64: &str, pass: Option<&str>) -> Result<Pack, Fail> {
/// 解开一个配置包。**在阻塞线程上**:口令解密要算 scrypt(零点几秒、上百 MB 内存),不能
/// 占着处理请求的线程
async fn open_pack(data_b64: &str, pass: Option<&str>) -> Result<Pack, Fail> {
let bytes = decode(data_b64)?;
let unseal = match pass {
Some(p) => Unseal::Passphrase(p),
None => Unseal::None,
};
tw_pack::read(&bytes, unseal).map_err(bad_pack)
}

fn file_of(pack: &Pack, pass: Option<&str>) -> Result<(String, String), Fail> {
let seal = match pass {
Some(p) => Seal::Passphrase(p),
None => Seal::None,
};
let bytes = tw_pack::write(pack, seal).map_err(bad_pack)?;
let pass = pass.map(str::to_string);
tokio::task::spawn_blocking(move || {
let unseal = match &pass {
Some(p) => Unseal::Passphrase(p),
None => Unseal::None,
};
tw_pack::read(&bytes, unseal)
})
.await
.map_err(crate::internal)?
.map_err(bad_pack)
}

/// 写成文件。口令加密同样在阻塞线程上
async fn file_of(pack: &Pack, pass: Option<&str>) -> Result<(String, String), Fail> {
let owned = pack.clone();
let pass = pass.map(str::to_string);
let bytes = tokio::task::spawn_blocking(move || {
let seal = match &pass {
Some(p) => Seal::Passphrase(p),
None => Seal::None,
};
tw_pack::write(&owned, seal)
})
.await
.map_err(crate::internal)?
.map_err(bad_pack)?;
Ok((
tw_pack::export::file_name(pack.manifest.created_at_ms),
base64::engine::general_purpose::STANDARD.encode(bytes),
Expand All @@ -291,6 +314,16 @@ fn fix_view(f: tw_config::repair::Fix) -> tw_api::ConfigFix {
}
}

fn prefs_too_large() -> Fail {
fail(
StatusCode::PAYLOAD_TOO_LARGE,
msg!(
"backup.prefs_too_large", limit = tw_api::CLIENT_PREFS_MAX / 1024 =>
"The client preferences are larger than {limit} KiB."
),
)
}

// ─────────────────────────────────────────────────────────── 此刻的样子

/// 磁盘上此刻的配置(原文和版本)连同它的插件、通用偏好
Expand All @@ -316,6 +349,13 @@ async fn land(
changed_keys: Vec<String>,
) -> Result<String, Fail> {
let path = s.config_path().to_path_buf();
// 偏好的上限导入、恢复也照样查:一份带着超大偏好的包不该绕过 `PUT /client-prefs` 的那道关
if core_keeps_prefs()
&& let Some(p) = &after.client_prefs
&& p.to_string().len() > tw_api::CLIENT_PREFS_MAX
{
return Err(prefs_too_large());
}
let _edit = s.gateway.plugins.edits.lock().await;
let undo =
tw_pack::disk::write_plugins(&path, &before.plugins, &after.plugins).map_err(|e| {
Expand All @@ -336,6 +376,9 @@ async fn land(
.await;
let version = match written {
Ok(v) => v,
// **配置已经写下去了**、只是网关换不进来:插件文件和偏好跟着磁盘上的配置,不还原 ——
// 还原的话 config.yaml 里批准的哈希就对不上磁盘上的插件文件了
Err(e @ ApplyError::Build(_)) => return Err(apply_fail(e)),
Err(e) => {
undo.restore();
if prefs_changed {
Expand Down Expand Up @@ -421,7 +464,7 @@ async fn export(
},
)
.map_err(|e| model_fail(e, None))?;
let (file_name, data_b64) = file_of(&out.pack, pass)?;
let (file_name, data_b64) = file_of(&out.pack, pass).await?;
Ok(Json(tw_api::ExportedFile {
file_name,
data_b64,
Expand Down Expand Up @@ -483,7 +526,7 @@ async fn import_preview(
State(s): State<ControlState>,
Json(req): Json<tw_api::ImportSource>,
) -> Result<Json<tw_api::ImportPreview>, Fail> {
let raw = open_pack(&req.data_b64, req.passphrase.as_deref())?;
let raw = open_pack(&req.data_b64, req.passphrase.as_deref()).await?;
let (incoming, repairs) =
tw_pack::import::prepare(raw.clone()).map_err(|e| import_fail(e, &raw))?;
let (cur, local) = current(&s, PackOrigin::Import)?;
Expand All @@ -502,7 +545,7 @@ async fn import(
State(s): State<ControlState>,
Json(req): Json<tw_api::ImportRequest>,
) -> Result<Json<tw_api::ConfigWritten>, Fail> {
let raw = open_pack(&req.data_b64, req.passphrase.as_deref())?;
let raw = open_pack(&req.data_b64, req.passphrase.as_deref()).await?;
// 预览时修过的那几处,这里照样修一遍(同一份字节,修出来一样)
let (incoming, _) = tw_pack::import::prepare(raw.clone()).map_err(|e| import_fail(e, &raw))?;
let (cur, local) = current(&s, PackOrigin::Import)?;
Expand Down Expand Up @@ -660,7 +703,7 @@ async fn backup_file(
.map_err(|e| model_fail(e, Some(&pack)))?;
let mut exported = out.pack;
exported.manifest.created_at_ms = pack.manifest.created_at_ms;
let (file_name, data_b64) = file_of(&exported, pass)?;
let (file_name, data_b64) = file_of(&exported, pass).await?;
Ok(Json(tw_api::ExportedFile {
file_name,
data_b64,
Expand All @@ -680,6 +723,7 @@ fn restore_row(r: tw_pack::restore::Row) -> tw_api::RestoreRow {
},
kept: r.kept.map(|k| match k {
Kept::KeyInUse => tw_api::KeptReason::KeyInUse,
Kept::Referenced => tw_api::KeptReason::Referenced,
}),
}
}
Expand Down Expand Up @@ -744,7 +788,11 @@ async fn restore(
.map(|xs| xs.iter().map(item_id).collect());
let (after, changed) = if model::snapshot(&local).is_err() {
// 安全模式:现在这份读不进来,整份换回去
let mut whole = tw_pack::restore::whole(&backup, &cur.text);
// 本机那几节取不到时(原文坏到读不成 YAML)用最近一个本机备份里的
let last = tw_pack::backup::list(s.config_path())
.ok()
.and_then(|all| all.last().and_then(|b| tw_pack::backup::open(b).ok()));
let mut whole = tw_pack::restore::whole(&backup, &cur.text, last.as_ref());
if !core_keeps_prefs() {
whole.client_prefs = local.client_prefs.clone();
}
Expand Down Expand Up @@ -780,13 +828,7 @@ async fn put_prefs(
if let Some(p) = &req.prefs
&& p.to_string().len() > tw_api::CLIENT_PREFS_MAX
{
return Err(fail(
StatusCode::PAYLOAD_TOO_LARGE,
msg!(
"backup.prefs_too_large", limit = tw_api::CLIENT_PREFS_MAX / 1024 =>
"The client preferences are larger than {limit} KiB."
),
));
return Err(prefs_too_large());
}
let path = s.config_path().to_path_buf();
if tw_pack::disk::read_prefs(&path) == req.prefs {
Expand All @@ -813,7 +855,7 @@ async fn pin_keys(
) -> Result<Json<()>, Fail> {
let names: BTreeSet<String> = req.names.into_iter().collect();
s.cfg
.set_pinned_keys(names)
.set_pinned_keys(&req.source, names)
.map_err(|e| io_fail(&tw_pack::disk::pinned_path(s.config_path()), e))?;
Ok(Json(()))
}
Expand Down
28 changes: 21 additions & 7 deletions crates/tw-control/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub struct ConfigManager {
/// 每换入一份配置响一次([`Self::applied`])。默认插件那一路等着它
applied: tokio::sync::Notify,
/// 固定密钥:本机接管的客户端在用的网关密钥,桌面端报上来(`PUT /pinned-keys`)
pinned: std::sync::Mutex<std::collections::BTreeSet<String>>,
pinned: std::sync::Mutex<std::collections::BTreeMap<String, tw_pack::disk::PinnedSource>>,
/// 同步位置上的备份版本。没开同步是 None
remote: std::sync::RwLock<Option<Arc<dyn crate::backups::RemoteBackups>>>,
/// 这份配置的同步服务,第一次用到时建(见 `crate::sync::service`)
Expand Down Expand Up @@ -119,7 +119,7 @@ impl ConfigManager {
gateway.set_config_dir(crate::plugins::dir_of(&path));
// 配置包、备份按「代码」「数据」分开比较插件,要插件那一套来拆
crate::backups::install_codec();
let pinned = tw_pack::disk::read_pinned(&path);
let pinned = tw_pack::disk::read_pinned_sources(&path);
Self {
path,
gateway,
Expand Down Expand Up @@ -372,6 +372,14 @@ impl ConfigManager {
/// 启动时:磁盘上此刻的样子和最新的备份版本不一样就留一版(第一次运行、升级之后、core
/// 没在跑时命令行改过)。来源记成外部改动 —— 说不清是谁改的
pub fn record_startup(&self) {
// 写插件文件和写配置之间断过电:插件文件先从备份里找回来
let healed = tw_pack::backup::heal_plugins(&self.path);
if !healed.is_empty() {
tracing::warn!(
plugins = ?healed,
"plugin files that did not match the configuration were put back from a backup"
);
}
if let Ok(cur) = self.current() {
self.backup(tw_pack::backup::record(
&self.path,
Expand All @@ -381,19 +389,25 @@ impl ConfigManager {
}
}

/// 本机接管的客户端在用的网关密钥(固定密钥)。恢复、导入、同步不删它们
/// 本机接管的客户端在用的网关密钥(固定密钥):各个来源报上来的并集,30 天没更新的来源
/// 不算。恢复、导入、同步不删它们
pub fn pinned_keys(&self) -> std::collections::BTreeSet<String> {
self.pinned.lock().map(|g| g.clone()).unwrap_or_default()
self.pinned
.lock()
.map(|g| tw_pack::disk::pinned_union(&g, now_ms()))
.unwrap_or_default()
}

/// 换掉固定密钥,存进数据目录(`pinned-keys.json`),重启之后还在
/// 一个来源(一个 Lite)报上来它的固定密钥:换掉它上次报的,存进数据目录
/// (`pinned-keys.json`),重启之后还在
pub fn set_pinned_keys(
&self,
source: &str,
names: std::collections::BTreeSet<String>,
) -> std::io::Result<()> {
tw_pack::disk::write_pinned(&self.path, &names)?;
let all = tw_pack::disk::write_pinned(&self.path, source, &names)?;
if let Ok(mut g) = self.pinned.lock() {
*g = names;
*g = all;
}
Ok(())
}
Expand Down
Loading
Loading