diff --git a/.gitignore b/.gitignore index c000c47..74318f7 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,6 @@ __pycache__/ # Downloaded upstream metadata used by the review workflow. /.community-proposals/ + +# Generated local development release artifacts. +/releases/*-local-dev* diff --git a/Cargo.lock b/Cargo.lock index 4827d44..497cc82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,6 +329,18 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -498,6 +510,17 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "log" version = "0.4.34" @@ -608,6 +631,19 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rusqlite" +version = "0.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rustc_version" version = "0.4.1" @@ -707,6 +743,12 @@ version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + [[package]] name = "spki" version = "0.7.3" @@ -770,6 +812,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -825,7 +873,9 @@ dependencies = [ "gimli", "globset", "ignore", + "libc", "rayon", + "rusqlite", "serde", "serde_json", "sha2", diff --git a/Cargo.toml b/Cargo.toml index 9353512..87371d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ description = "Lossless core WebAssembly auditing and decentralized version hist [features] default = ["client"] client = [] -server = [] +server = ["dep:rusqlite"] [[bin]] name = "wasm-git" @@ -37,12 +37,16 @@ ed25519-dalek = "=2.2.0" getrandom = "=0.3.4" zeroize = "=1.9.1" gimli = { version = "=0.34.0", default-features = false, features = ["read", "std"] } +rusqlite = { version = "=0.43.0", default-features = false, features = ["bundled", "limits"], optional = true } [target.'cfg(not(target_family = "wasm"))'.dependencies] rayon = "=1.11.0" +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [target.'cfg(windows)'.dependencies] -windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO"] } +windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } [dev-dependencies] wat = "=1.263.0" diff --git a/docs/git-workflows.md b/docs/git-workflows.md index e78d5bf..89adea3 100644 --- a/docs/git-workflows.md +++ b/docs/git-workflows.md @@ -314,6 +314,9 @@ index 统一使用九字节 `WASMGIDX\x06` 头和按字段位置编码的二进 Core 头、引用和恢复证据,不静默修复损坏元数据。不读取或迁移旧 JSON 格式。见[二进制格式](binary-format.md)。 工作区命令共享 index.lock;对象与引用使用 write.lock,历史写入同时 CAS 审定的分支名和旧 ID。 +原生平台使用持续存在的版本化锁文件,实际内核锁随进程退出释放;维护者不得删除或替换其 inode。 +WASIp1 使用独占创建锁,异常退出后须人工维护,已有原生锁文件不能被其删除或当作空闲锁。 +旧格式锁或不同后端的转换须先停止全部使用者并确认没有活动操作,不根据 PID 或文件存在猜测能否接管。 所有文件的逻辑冲突先预检;新文件独占创建,已跟踪文件通过同目录完整临时文件替换。 文件与目录可以相互转换,包括多层路径:先核对所有阻挡项,再移除应删除的受控文件, 清理由受控文件形成的空目录,最后建立目标父目录并写入模块。 diff --git a/docs/patch.md b/docs/patch.md index 7ecf00e..a39c06d 100644 --- a/docs/patch.md +++ b/docs/patch.md @@ -55,7 +55,8 @@ wasm-git commit ./peer restored.wasm -m 'apply reviewed byte patch' 记录实际不可变提交 ID。`diff --repo` 使用同一批读取方式,`HEAD HEAD` 不会因两次读取之间的提交而变成不同输入。 `inspect --repo` 和 `apply --repo` 也返回实际输入提交 ID。 释放锁后的计算始终使用已复制的字节;后续引用变化不改变本次输入。 -`--check --repo` 仍会短暂创建和删除 `.wasm-git/write.lock`,需要仓库可写且没有其他持锁操作; +`--check --repo` 仍需取得仓库 writer 锁;原生平台保留稳定锁文件并持有内核锁,WASIp1 使用独占创建的锁文件, +需要仓库可写且没有其他持锁操作; 不创建输出文件不等于零文件系统写入。 补丁中的摘要属于完整原始文件,与包含类型和长度 envelope 的仓库对象 ID 不同。 diff --git a/docs/ref-transactions.md b/docs/ref-transactions.md index 62207a2..06c331d 100644 --- a/docs/ref-transactions.md +++ b/docs/ref-transactions.md @@ -90,7 +90,7 @@ prepare 保存接受项及其拒绝结果,并持有共享锁,不输出拒绝 commit 先同步 `.wasm-git/ref-transaction.bin`,保存完整引用前像、逐项旧/新值、原始 upstream 和 reflog 字节。该记录是持久提交决定:随后顺序写入配置、引用和完整日志,最后同步删除记录。返回 I/O 错误时会明确说明提交可能已经发生,不能把错误当作回滚。 -每次获取共享 writer 锁后,查询和写入都会先检查这份记录。恢复使用保存的前像验证完整对象库和其他元数据,再一次性预检所有当前引用、upstream 和 reflog:只能是各项原像或目标像。随后幂等补齐最终结果和固定日志字节,避免重复追加。若有后来人工写入的第三种内容,整次恢复先失败,保留内容和记录,所有后续受锁操作也停止。应检查并恢复对应原像/目标像,再重试查询。进程崩溃遗留的 writer 锁仍沿用现有规则,需要人工检查并移除;不会根据 PID 猜测并自动解锁。 +每次获取共享 writer 锁后,查询和写入都会先检查这份记录。恢复使用保存的前像验证完整对象库和其他元数据,再一次性预检所有当前引用、upstream 和 reflog:只能是各项原像或目标像。随后幂等补齐最终结果和固定日志字节,避免重复追加。若有后来人工写入的第三种内容,整次恢复先失败,保留内容和记录,所有后续受锁操作也停止。应检查并恢复对应原像/目标像,再重试查询。Unix writer 锁在操作正常结束时显式解锁;进程异常退出后须等待仍持有该锁的继承描述符关闭。稳定锁文件持续保留;恢复不猜测 PID,也不删除该文件。旧格式锁及 WASIp1 存在型锁仍需停用全部使用者、确认没有活动操作后受控维护。 一致性面向遵守共享锁的 wasm-git 读写操作。直接读取底层多个引用文件的外部程序可能观察到安装中间态;旧版本也不识别新恢复记录,不应在恢复未完成时混用。 @@ -98,7 +98,7 @@ commit 先同步 `.wasm-git/ref-transaction.bin`,保存完整引用前像、 回归覆盖混合更新/创建/删除/校验、旧值失败整批保持、同快照修订解析、NUL 与 C 引号、交互 prepare 的真实锁、EOF/abort、跨 worktree 保护、两向前缀替换和多笔事务。恢复测试在配置、删除、引用写入及 reflog 每个检查点中断,再从普通查询恢复,并验证引用、upstream 和日志原字节;完整安装后再次恢复也只保留一次日志。损坏记录、重复项、缺失对象和第三种人工编辑必须失败保持。 -HEAD 测试覆盖主/linked worktree 从任一入口打开恢复、符号与 detached 两向格式转换、第三种规范编码注册/HEAD/日志内容的失败保持、旧 journal 兼容及 stale writer 锁的人工处理。24 组独立 Git 对照检查 ref/oid 租约、detached/unborn、NUL 和指针操作后的引用值及原字节。 +HEAD 测试覆盖主/linked worktree 从任一入口打开恢复、符号与 detached 两向格式转换、第三种规范编码注册/HEAD/日志内容的失败保持、旧 journal 兼容及旧格式 writer 锁的保守拒绝。24 组独立 Git 对照检查 ref/oid 租约、detached/unborn、NUL 和指针操作后的引用值及原字节。 逐项模式另覆盖成功/拒绝混合、全拒绝保持、只为接受项记日志、原生分支保护、选项覆盖、交互拒绝输出时机,以及过滤后的接受子集逐写入前缀恢复。独立 Git 仓库对照语义拒绝、名称冲突、prepare/abort/EOF/commit、NUL、格式错误及最终引用值;Wasm 原字节、index 和工作树也必须保持。 diff --git a/docs/server.md b/docs/server.md index b2b981d..7fc6e23 100644 --- a/docs/server.md +++ b/docs/server.md @@ -102,7 +102,8 @@ Tree 对象为 kind 3,tree commit 为 format 2,包含这些对象的 bundle 本地 clone、bundle/网络 clone、unbundle、fetch 安装和服务端 receive 共用此规则, 并保留完整快照中合法的不可达对象与历史。对象安装中断可留下未引用但闭包完整的对象, 引用在所需对象完整安装前不发布;重试仍可验证已有存储,不需要先删除合法 dangling 对象。 -引用批次通过持久 journal 在再次获取 writer 锁时向前恢复引用和 reflog;最终发布或同步失败仍明确报告不确定结果。 +引用批次通过持久 journal 向前恢复引用和 reflog;严格入口只恢复与原操作精确匹配的范围, +普通严格读取遇到待恢复 journal 时拒绝。最终发布或同步失败仍明确报告不确定结果。 ## 一致性与失败结果 @@ -218,7 +219,7 @@ base 来自对方已知提交闭包,或本次传输携带的完整根提交模 编译后服务器只读取二进制策略,不会把 JSON 存进仓库。示例中的摘要须替换为实际 token 的 SHA-256: ```json -{"version":1,"principals":[{"name":"alice","token_sha256":"<64 lowercase SHA-256 hex digits>","grants":[{"repository":"alice.*","read":true,"write":["refs/heads/*","refs/tags/*"],"force":false,"create":true}]}]} +{"version":3,"principals":[{"name":"alice","token_sha256":"<64 lowercase SHA-256 hex digits>","grants":[{"repository":"alice.*","read":true,"write":["refs/heads/*","refs/tags/*"],"force":false,"create":true,"expires_at":null}]}]} ``` ```sh @@ -230,7 +231,129 @@ wasm-git-server --root /srv/wasm-git --policy /etc/wasm-git/policy.bin --allow-w HTTP token 的 SHA-256 与策略中的凭据比较,日志只记 principal 名称。 引用写入要求匹配 write 规则;强制更新还需匹配 force 规则及服务器 `--allow-force`。 fork 要求源仓库 read 和目标名称 create;不会因可读取源仓库而获得其他租户的目标权限。 -策略改变后重启服务生效。SSH 通过管理员设置的 forced-command 固定 +首次启动将编译策略装入服务根的原生授权库,同时保存初始化回执;初始化操作 ID 为编译策略文件的 +SHA-256,回执与该策略一同原子提交。之后所有实例均读取该库,不重新加载启动文件。 +策略更新使用 `wasm-git-server --format json policy-set ROOT REQUEST_JSON`,请求包含版本、 +唯一 `operation_id`、`expected_generation` 和完整新策略。授权库同时原子保存当前策略和原操作回执; +相同操作及内容可重放,不同内容不得复用操作 ID。代号冲突也产生绑定原输入的持久回执;命令成功只表示 +返回了回执,调用方须区分 `applied` 与 `generation_conflict`。`policy-query ROOT REQUEST_JSON` 按操作 ID 查询回执; +查询无记录只表示查询时未提交,不证明其他在途请求不会稍后提交。`policy-status ROOT` 查询当前代号及摘要, +不能代替原操作回执。授权库使用 SQLite 事务保存当前策略和不可覆盖、不可删除的原生回执; +操作 ID 通过索引点查,不按全部历史重写;回执本身没有独立的终生操作次数上限,审计索引仍有容量上限。 +磁盘不足或无法提交时不报告策略已经应用,须按原操作查询或重试。请求及机器输出由 +`integration-validate` 的相应原生协议校验。 + +原有 v1 授权库不会被静默初始化或丢弃。维护窗口中停止不兼容实例、保存一致备份后,使用 +`wasm-git-server --format json policy-migrate ROOT REQUEST_JSON`,请求绑定原文件的完整 SHA-256。 +迁移核对所有旧回执,在不可寻址的临时数据库中建立完整事务,持久化后才替换原路径;源内容不匹配时不替换。 +迁移回执保存在新库中,回复丢失可按相同源摘要重放。后续策略代已推进时仍返回原迁移回执,不将策略回退。 +机器请求及回执同样使用 `integration-validate` 的原生迁移校验接口。旧 v1 程序遇到新数据库格式会拒绝访问。 +授权库备份须使用一致数据库备份或停写后的完整快照;不能在事务活动时只复制主文件而遗漏恢复所需 journal。 +恢复先经原生接口完成数据库恢复和持久同步,未确认成功时不开放新授权操作。 + +每个 HTTP/stdio 请求在服务根的稳定锁上读取当前策略并持锁到响应写出;首次提交策略更新取得独占锁, +`applied` 表示该代提交时旧持锁操作已经结束,之后的受保护动作按当时最新策略判断。重放返回的历史回执 +只证明原代曾经生效,不证明后来未发生重新授权;确认当前状态须核对当前代号、摘要和协调顺序。 +不能取得锁或无法确认持久化时不报告屏障完成。 +旧引用事务如已有持久提交决定,后续恢复只滚前原决定;上传和保留查询仍按当前权限及原 actor 约束。 +引用事务在发布前汇总所需权限的截止上界并统一检查,grant 的 `expires_at` 为独占 Unix 秒截止时间。 +使用严格操作凭据的入口将该上界与原操作期限求交;保留和上传状态在原子发布前检查, +读取在首次写出响应前检查。已经开始的单次响应可以完成;首次交付前失去权限时不返回受保护内容, +已经提交或结果未知的写入仍须按原操作核对,不改判为从未提交。 +授权检查属于持有方决定点;已经完成该有效授权决定后的持久同步或既有决定的恢复,不因晚到而变成新操作。 + +### 严格操作凭据 + +受信协调器通过 `wasm-git-server --format json operation-credential-issue ROOT REQUEST_JSON` +发放操作凭据,使用 `operation-credential-query` 核对原发放结果。请求和回执由 +[原生契约](../src/protocol_operation_credentials.rs)及 `integration-validate` 维护;Hub 不自行计算原生请求摘要。 +协调器必须从原身份、受理、授予及请求期限取最早上界,毫秒期限向下取整为秒,不能自行续期。 +原生库绑定实际主体、精确请求及 payload 摘要、凭据摘要和期限;当前主体策略仍须允许该动作。 +首次发放还核对并绑定当前策略代号。任何策略更新都会使旧代凭据失效,之后重新授予权限也不能使其复活; +当前授权下的新查询使用新代凭据核对原结果,已经提交的决定不因此撤销。 +相同发放请求重放原回执;换输入、凭据或期限不得复用原操作。原生写入动作还按仓库、主体及 +会话分片或保留阶段独立去重,因此换发放 ID 也不能为同一动作延长期限。 + +新的凭据发放与审计登记在同一事务中将授权库升级到数据库版本 6。旧程序不理解该版本并拒绝访问; +新服务必须以 `--require-operation-credentials --policy BOOTSTRAP_FILE` 启动 HTTP 入口, +不能回落到普通主体 token 或 stdio principal。升级在根独占屏障内等待在途请求结束, +但本地管理权限和不遵循已有根屏障的更旧程序仍须由部署隔离;不要用旧文件覆盖已升级数据库。 +版本 3、4 的历史发放回执仍可查询;升级审计库不会重建历史原请求或发放归属, +历史凭据的恢复限制见下文。 + +严格入口开放原生读取、有持久回执的 scoped 上传及发布保留;直接引用发布、旧无主体上传、PR 和 fork +不属于其支持范围。严格分片使用[原操作分片契约](../src/protocol_chunks.rs),旧 Slice 仅保留普通策略入口用法, +不得为它新发严格凭据,历史凭据也不能在严格入口执行该动作。 +每次分片、查询和续传独立发放精确凭据。期限到达或策略改变后,可用当前授权发放新的查询凭据, +核对原操作,不能换写入身份重做。查询自己的原操作要求当前仓库读取权及真实主体匹配, +不要求重新取得原写入权;查询回执不会授予新的写入、续传或跨主体恢复权限。 + +### 本地运维与受限恢复 + +本地管理入口接收 JSON 请求文件并以 JSON 返回结果: + +```sh +wasm-git-server --format json operation-context /srv/wasm-git context.json +wasm-git-server --format json operation-recover /srv/wasm-git recovery.json +wasm-git-server --format json audit-query /srv/wasm-git audit-page.json +wasm-git-server --format json capacity-query /srv/wasm-git capacity.json +``` + +这四个入口仅支持 Linux。进程使用实际有效 UID,要求它为 root 或服务根的所有者,服务根不可由 +group/other 写入;路径不得包含符号链接或 `..`,祖先目录的所有者和写权限也须可信。 +`operation-context` 按原操作 ID 查找已登记的原发放请求;`audit-query` 分页读取服务根审计索引, +翻页时保留首次结果的 high-water,直到没有下一页;它固定查询范围,观察仍可在读取后回填。 +`capacity-query` 查询指定仓库的记录容量。严格网络读取与容量查询不会回放待恢复的引用 journal; +遇到该状态时先按 journal 对应的原操作执行受限恢复,不能借普通读取恢复其他操作。 +调用方用原生 `integration-validate` 校验请求、机器输出和实际进程退出码。 +请求与响应的唯一契约见[恢复](../src/protocol_recovery.rs)、[审计](../src/protocol_audit.rs)和 +[容量](../src/protocol_capacity.rs)源码,不要自行推断或重建原始请求。 + +原主体撤权或凭据过期后,管理员可用与原发放回执严格匹配的原请求,运行 `operation-recover` 的 +`Inspect` 或 `Close`。恢复在服务根授权屏障取得独占锁,等待先前持锁请求结束,然后核对原主体、 +仓库及上传会话或发布保留范围。`Inspect` 只观察或恢复该范围已有的持久决定,不创建终止决定。 +`Close` 可关闭未完成的上传或尚未转正的保留;确认 v4 apply 没有 journal 且已排除在途操作时才记录中断。 +无法判定的旧版进行中上传保持未知,已提交或已转正的结果保留。恢复不提供新上传、正文读取或新的发布、转正决定, +也不续期或更换原操作 ID。恢复 ID 绑定原操作、动作和本地操作人,重试时保持相同身份和输入。 +独占屏障只协调参与该服务根锁协议的程序,本地直接写入或不兼容旧程序仍须由部署隔离。 + +旧凭据回执只保留请求摘要,缺少完整原请求和原始审计归属,`operation-context` 可能无记录。 +管理员须提供保存的原请求,核对其与原回执严格一致后,才可登记为 `LegacyImported` 以供恢复; +记录的是核验者和观察时间,不能补造历史发放者或时间,也不能用其发起新动作。 + +通过初步认证授权的严格写操作及本地恢复每次尝试都在执行前持久登记;原生回执仍是仓库决定的事实来源。 +`Unknown`、`Unobserved` 或缺失观察均不表示原操作未执行;未观察到决定时,尚未被关闭屏障排除的 +原请求仍可能迟到。显式 `reconcile` 可将同一原操作的恢复观察回填到指定尝试,记录的是该范围的 +状态观察,不宣称该次尝试导致了状态。批量对账原子提交,重试保留已经完成的历史观察。 +审计索引在累计新任务受理水位处拒绝新工作,撤权和本地恢复不受该水位阻断;分页结果同时报告水位和累计使用量。 +存储故障时仍须恢复存储并按原操作查询或重试。 + +### 分片决定与清理 + +分片以原操作身份、真实主体、仓库、上传会话、固定发布输入、位置及字节摘要绑定。 +原生库先同步可恢复字节,再在最终授权检查之后持久记录接受决定,随后安装上传分片。 +每个位置独立保存决定,不因另一分片写入而重写所有分片回执。已提交决定可在重开或查询时滚前, +既有决定的恢复不重新冒用发起者或延长旧凭据期限;查询访问仍须经过当前授权。 + +接受决定和数据是否仍可用分别核验。取消、完成和过期清理先持久关闭该会话的数据安装,再删除数据并同步目录; +清理完成后仍保留接受回执,迟到重放不能重新创建已清理数据。未完成清理和目录同步失败须沿原操作恢复, +不能由文件缺席推断从未接受,也不能由暂存文件存在推断某次凭据已执行。 +普通会话查询的 Open 状态不证明某个分片的结果;分片查询无决定只表示查询时未观察到接受, +不阻止仍有效的旧请求迟到。要确认不会再接受,先取得会话关闭屏障,再核对相关原分片。 +会话与保留记录的活跃容量和迁移规则见下文;分片决定与会话数据清理分别核验。 + +原生 CLI 对不完整、损坏或无法绑定的写入回执保留结果未知并要求查询原操作;跨语言消费者不得解析人类诊断文本 +来判断是否提交。静态能力报告不证明实际服务根、入口隔离或恢复链路已通过接入验收。 + +此屏障要求所有服务器实例运行支持该屏障的版本,并访问同一受控服务根、同一稳定锁 inode 和提供一致进程间共享/独占锁、 +原子替换及持久同步语义的文件系统;不得在服务运行时删除或替换授权库、锁文件或根目录。 +不参与该屏障的旧服务实例须先停止或隔离,不能仅依赖新实例报告撤权。 +本地管理员、hook 及直接写仓库的人属于可信管理边界,绕过服务器的本地写入不受该屏障保护。 +已写入操作系统缓冲的响应不保证客户端在屏障返回前已收到;阻塞的 stdio 或 I/O 可使屏障超时而失败。 +Windows 不提供目录 fsync,不能据成功响应推断断电后目录项一定持久。主体 `name` 是稳定身份, +不得跨不同主体复用;同一主体轮换 token 时保留名称。 + +SSH 通过管理员设置的 forced-command 固定 `--stdio --root /srv/wasm-git --policy ... --principal alice`;身份不能来自客户端请求体。 `--read-only` 可限制 SSH key,也可限制 HTTP 服务。不同分支不构成读取隔离,私有数据应放在不同仓库。 @@ -241,10 +364,23 @@ wasm-git push ./peer origin main:main HEAD:refs/tags/release --atomic `publish_batch` 将 1–4,096 个显式 branch/tag 更新放在同一事务中。所有旧 ID 租约、目标对象、 快进/标签替换规则、工作区保护和命名冲突先检查;任一失败均不发布引用。原子批次使用本地 -持久化引用事务日志,崩溃后任何加锁查询先完成整批恢复;裸服务器 HEAD 可更新,已跟踪工作区 +持久化引用事务日志,崩溃后按原事务完成整批恢复;严格入口遵循上文的原操作恢复边界。裸服务器 HEAD 可更新,已跟踪工作区 的当前分支仍受保护。响应携带请求摘要收据,传输故障时客户端明确报告发布结果未知。 默认非原子 `--tags` 仍逐项报告结果;带 `--atomic` 时拒绝整个批次,不谎报部分成功为原子成功。 +### 会话与保留容量 + +每仓库的 scoped 上传会话和发布保留分别按单条记录存储;新会话及新的保留准备各自受 4,096 条 +活跃记录和 64 MiB 活跃记录字节水位约束。关闭、完成或转正等终态记录保留,但不占活跃水位; +`capacity-query` 分别返回活跃与累计记录数和编码字节数。累计值仅覆盖这两类记录,不含仓库对象 +或分片正文;累计扫描也有上限,查询失败不能当成零。磁盘或同步失败后先恢复存储,再按原 ID 查询 +或重试,不能依靠换 ID 绕过未知结果。 + +旧会话与保留账本在首次使用新存储时迁移,包括通过 `capacity-query` 首次打开:新记录持久化后, +原账本路径以原子 marker 切换权威来源。 +升级前先做一致备份,在维护窗口停止所有旧版写入者和本地维护程序,不得混用旧版;保留 marker 与 +新记录目录一同备份、还原。不要手工删除迁移残留或以旧账本覆盖已切换的数据。 + ## 接收检查与审计接口 `--pre-receive /absolute/program` 和 `--post-receive /absolute/program` 只运行管理员指定的 @@ -260,11 +396,12 @@ stdin 为原生二进制 `Vec`,同时提供以下环境变量: 钩子应检查隔离 bundle,不要递归更新正在接收的仓库。接收后钩子失败不会把已完成推送报告为失败, 其失败写 stderr 和二进制审计事件;上层可据此实现合并准入、索引通知或 CI 调度。 -服务根的 `receive-audit.bin` 为长度分帧的原生记录,包含版本、事务 ID、时间、身份、仓库、 +普通接收的 `receive-audit.bin` 为长度分帧的原生记录,包含版本、事务 ID、时间、身份、仓库、 旧/新引用及 prepared/accepted/rejected/unknown 状态,fork 另记目标名称。 prepared 事件在发布前持久化;崩溃或最终审计写入失败可能只留下 prepared,必须结合实际引用核对, 不能把它视为已接受。接收后事件失败不改变已完成事务的事实。管理员负责保留与轮转日志; -日志是操作审计,不是提交作者签名或不可篡改证明。 +日志是操作审计,不是提交作者签名或不可篡改证明。该旧日志只辅助核对普通或历史接收; +严格操作的尝试和恢复以服务根审计索引及相应原生回执核对。 ```sh wasm-git-server audit-log /srv/wasm-git/receive-audit.bin @@ -276,8 +413,11 @@ wasm-git-server audit-log /srv/wasm-git/receive-audit.bin 服务端在已有固定格式文件的 inode 上取得进程间锁,协调 HTTP worker 与独立 SSH 进程, 不会因网络读者竞争本地 fail-fast writer lock 而互相拒绝。读取引用只检查引用目标提交, -不解压所有 Wasm;完整 transfer/fsck 另做对象验证。服务不会给只读查询新建锁文件。 -本地 CLI 维护仍保留原有写锁及崩溃检查规则,遇到其占用会明确报忙。 +不解压所有 Wasm;完整 transfer/fsck 另做对象验证。服务协调锁复用已有格式文件。 +原生仓库的 writer、index 和传输状态锁使用持久的版本化文件,首次采用该后端时可能创建锁文件; +Unix 资源锁正常结束时显式解锁;进程异常退出后,仍持锁的继承描述符须关闭才能释放。文件存在不表示仍被占用。不得删除或替换原生锁 inode。 +旧存在型锁保持原样拒绝,须停用全部使用者、确认没有活动操作后受控移除旧格式锁。 +WASIp1 保留独占创建锁和异常退出后的维护语义,遇到已有原生锁文件时拒绝访问;不同后端不得未经维护转换而混用。 接入循环会回收任意已完成 worker,不等待最早的慢连接;16 个活动连接全满时快速拒绝。 连接有 15 秒累计 I/O 时限;完整请求缓存后的校验与落盘处理时间不计入其中, diff --git a/docs/trace.md b/docs/trace.md index 787b7ff..29d3adc 100644 --- a/docs/trace.md +++ b/docs/trace.md @@ -106,7 +106,8 @@ Compact2 import 的共享类型可用 `import[0]/group[n]/shared_type` 选择; 相同 Wasm blob 只复制一次;无关分支和未引用对象不会作为查询证据,但其损坏仍使仓库校验失败。 释放锁后,查询使用已复制的不可变数据,其他提交不会改变本次输入。 -查询不修改对象、引用或历史,但读取快照时仍短暂创建和删除 `.wasm-git/write.lock`,需要仓库可写且未被其他操作锁定。 +查询不修改对象、引用或历史,但读取快照时仍取得 writer 锁,需要仓库可写且未被其他操作锁定。 +原生平台的版本化锁文件持续保留,内核锁在显式解锁或所有仍持锁的描述符关闭时释放;WASIp1 使用独占创建的锁文件,异常退出后须受控维护。 工作预算不限制现有仓库快照的读取内存;快照仍加载并校验整个对象库。 快照加载、输入图校验和起点路径解析也不计入输入字节比较预算。 diff --git a/documents/DEVELOPMENT.eu_US.md b/documents/DEVELOPMENT.eu_US.md index 8cd5de7..7e9c0f6 100644 --- a/documents/DEVELOPMENT.eu_US.md +++ b/documents/DEVELOPMENT.eu_US.md @@ -71,6 +71,10 @@ is not a fuzz campaign or an AddressSanitizer run. Tests marked `ignored` remain unexecuted unless their required external tools/corpora are supplied and they are explicitly selected. Report pass, failure, ignored, and filtered counts separately. +The Linux HTTPS and recovery cases in `server_chunk_receipts` require `python3` +with its `ssl` module, `openssl`, and `curl`. Their temporary service roots and +ancestors must meet the [local recovery path requirements](../docs/server.md#本地运维与受限恢复). + The Git reference integration tests require an independent Git executable with `update-ref --batch-updates` support (Git 2.50 or newer). They normalize hash width and absent-OID output spelling, and probe the dangling-symref protection fixed diff --git a/documents/DEVELOPMENT.zh_CN.md b/documents/DEVELOPMENT.zh_CN.md index 96fb640..b0adf99 100644 --- a/documents/DEVELOPMENT.zh_CN.md +++ b/documents/DEVELOPMENT.zh_CN.md @@ -57,6 +57,9 @@ cargo check --locked --manifest-path fuzz/Cargo.toml --bin raw_audit Fuzz 目标编译检查不是实际 fuzz 或 ASan 运行。Ignored 项只有在外部工具/语料齐备并明确 选取时才执行;分别报告 passed、failed、ignored、filtered。 +Linux 下 `server_chunk_receipts` 的 HTTPS 与恢复用例需要带 `ssl` 模块的 `python3`、 +`openssl` 和 `curl`。临时服务根及其祖先须符合[本地恢复路径要求](../docs/server.md#本地运维与受限恢复)。 + Git 对照集成测试需要独立 Git 可执行文件支持 `update-ref --batch-updates` (Git 2.50 或更新版本)。测试统一摘要宽度和缺失 OID 的输出写法,并探测 Git 2.52 修复的 dangling symref 保护。对于涉及该修复的两种情况,旧 Git diff --git a/documents/SERVER_ADMINISTRATION.eu_US.md b/documents/SERVER_ADMINISTRATION.eu_US.md index a488ed6..8aa18b6 100644 --- a/documents/SERVER_ADMINISTRATION.eu_US.md +++ b/documents/SERVER_ADMINISTRATION.eu_US.md @@ -102,7 +102,7 @@ Example external input: ```json { - "version": 1, + "version": 3, "principals": [ { "name": "release-bot", @@ -137,9 +137,52 @@ namespace; principals and configured remote names remain single components. HTTP write enablement is still explicit. A compiled policy and `--token-file` are mutually exclusive. -Treat policy replacement as a controlled configuration rollout. Restart instances -to load the new policy; do not assume hot reload. Never let an untrusted client -select an SSH principal or the server filesystem root. +The compiled file bootstraps a root once. Subsequent policy updates use the +root's `policy-set` CAS and durable operation receipt; `policy-query` recovers a +particular update after a lost reply. HTTP and stdio instances sharing that root +use the same authorization gate. The deployment, filesystem, identity and +natural-expiry limits are specified in [server authorization](../docs/server.md#多用户权限与原子发布). +Never let an untrusted client select an SSH principal or the server root. + +Use native `operation-credential-issue` / `operation-credential-query` with the +HTTP `--require-operation-credentials` entry point to bind original operation +deadlines. First issuance atomically upgrades the authorization database; +older binaries and ordinary authentication entry points then reject that root. +Exact request binding, immutable mutation identities, query recovery, and +deployment constraints are specified in [strict operation credentials](../docs/server.md#严格操作凭据). +Strict uploads use the original-operation Chunk and QueryChunk contracts of +`scoped-upload-rpc`; ordinary Slice is not accepted by that entry point. +Accepted decisions survive staged-data cleanup, as specified in +[chunk decisions and cleanup](../docs/server.md#分片决定与清理). + +On Linux, a local administrator can use `wasm-git-server --format json` +with `operation-context`, `operation-recover`, `audit-query`, and `capacity-query` +to inspect original operations, perform restricted recovery, and query audit and +repository capacity. After a principal is revoked, recovery accepts the exact +original issuance request only to inspect or close the upload or retention scope. +It does not renew authority, upload or read content, or make new publication or promotion decisions. +Recovery takes the root's exclusive authorization gate and preserves committed +results. See [local administration and restricted recovery](../docs/server.md#本地运维与受限恢复) +for identity and path requirements, JSON request files, audit evidence, and legacy credentials. + +Grant `release_retention` only to the trusted principal responsible for release +decisions; repository read permission is also required. Single-token mode cannot +use release retention. The holder durably records prepare, promote, and close for +the original operation. A close tombstone rejects a late prepare, and a promoted +reference cannot be closed. Promotion and close convey the coordinator's +authoritative decision; the repository does not decide the release. Fixed reads +are limited to the selected commit and files, which must be local at preparation +and are protected from GC and pool eviction. Versioned native types are defined in +`src/protocol.rs`. Cross-language callers can use `--format json retention-rpc`, +`upload-binding`, `upload-recovery`, and `scoped-upload-rpc`, checking the process status. These +commands read native-type JSON on stdin and use `WASM_GIT_REMOTE_TOKEN` for credentials. +`--format json integration-capabilities` reports the tool, contract versions, and +authorization limits. `--format json integration-validate` validates requests, +responses, and the actual process exit code using `IntegrationValidation` in +`src/protocol.rs`. Node callers must embed the original, unparsed JSON bytes in +the validation request and use `JSON.parse` only after validation succeeds. This +entry rejects floats and integers outside JavaScript's safe range; native binary +`u64` values retain their full width. ## 5. SSH transport @@ -223,6 +266,9 @@ accepted, partial, rejected, unknown, per-reference reasons, and post-hook failu Post-update is still attempted when post-receive fails. A completion-audit write can itself fail after publication; retain service stderr and query actual refs when reconciling outcomes. Audit output is JSON only when explicitly rendered. +`receive-audit.bin` is supplementary evidence for ordinary or historical receives; +use the root audit index and native receipts for strict operations. `Unknown`, +`Unobserved`, or an incomplete audit observation does not prove non-execution. ## 7. Author-signature policy @@ -332,7 +378,33 @@ primarily useful for finite tests. Current bounds include 64 MiB per RPC packet, 64 KiB metadata, 1 MiB transfer chunks, 4 GiB per bundle, 32 pending uploads, and an 8 GiB staged-upload reservation -budget per repository. Upload expiry is 24 hours. Each HTTP connection has a +budget per repository. Upload expiry is 24 hours. +Scoped uploads bind the authenticated principal, repository, target, session, and +content digest. Legacy unscoped upload RPCs are rejected. Expired staging chunks +may be uploaded again under an open session; cancellation leaves a tombstone. +A v4 receive decision and its exact reference receipt share the native journal. +Query the original session after recovery; an explicit close aborts a v4 operation +only when it has no durable decision and no in-flight worker. It cannot be replayed. Legacy `Applying` +records remain unknown and require reconciliation. Older programs cannot recover +a v4 journal; service and local maintenance commands must support that version. +Scoped upload sessions and release retentions each admit new records up to +4,096 active records and 64 MiB of active encoded record data. Tombstones and +completed or promoted terminal records remain but do not consume active capacity. +`capacity-query` reports active and total counts and encoded bytes separately; +totals exclude repository objects and chunk payloads. After a storage failure, +restore storage before querying or retrying with the original ID. +Before migrating old ledgers to per-record storage, take a consistent backup and +stop old writers and maintenance programs during a maintenance window; do not mix +versions. A first `capacity-query` can trigger migration. Preserve the migration +marker together with the new record directory. +See [session and retention capacity](../docs/server.md#会话与保留容量). +For a chunked upload through the ordinary client, supply a unique 64-hex-digit +`WASM_GIT_UPLOAD_SESSION` and an existing private `WASM_GIT_UPLOAD_RECOVERY_DIR`. +Before sending, the client persists the binding and full payload there. +`upload-recovery` validates both; use the same principal to query or resume. +The caller removes these recovery files after reconciling the outcome. + +Each HTTP connection has a 15-second cumulative I/O budget. Processing after a complete request is buffered does not consume that budget, so verification and durable storage on a slow host do not prevent an otherwise completed publication from returning its receipt. @@ -357,6 +429,11 @@ linked-worktree metadata together. Preserve hard links if storage efficiency matters. Back up service policy, author trust, and private credentials separately with appropriate access control. A portable bundle covers its selected repository history, not all operational configuration or unsaved workspace state. +Back up the root authorization SQLite database, its recovery journal and audit +index, and the retention and scoped-upload markers and records together with the +repository. Before restoring, reconcile release decisions, completed reference +writes, and the replay horizon; do not overwrite newer tombstones with an old +backup or treat unknown outcomes as absent. A partial or pool-evicted repository is not a self-contained backup. Either hydrate it before export or back up its required pool replicas, pins, and ownership state @@ -364,11 +441,17 @@ as a coordinated set. Validate the backup by restoring into a new directory, running `fsck`, and exporting selected historic modules for byte comparison. After an interrupted operation, retain journals, incomplete audit tails, and -service diagnostics. Reopen through the normal engine so durable transaction -recovery can run. Query refs before retrying an uncertain push. Do not manually +service diagnostics. For strict operations, recover with the exact original +request through `operation-recover`; ordinary strict reads and capacity queries +reject a pending reference journal. Other local engine workflows retain their +normal transaction recovery. Query refs before retrying an uncertain push. Do not manually remove packs, promised-object markers, or pool pins to suppress an error. -Persistent writer/index locks require confirmation that no writer remains before -manual removal; process-held pool locks have different lifetime semantics. +Native writer/index/transfer lock files remain in place. Unix operations explicitly +unlock on normal completion; after a crash, every inherited descriptor still +holding the lock must close. Never unlink the versioned inodes. +Legacy and WASIp1 create-new locks require a controlled maintenance window and +confirmation that no process remains before removal. Do not switch lock backends +on a shared repository during operation. Use `gc DIR -n` to review a collection plan. Normal GC compresses without pruning; `--prune=now` explicitly requests reclamation outside retained roots. Recovering diff --git a/documents/SERVER_ADMINISTRATION.zh_CN.md b/documents/SERVER_ADMINISTRATION.zh_CN.md index e8e8115..ff613d0 100644 --- a/documents/SERVER_ADMINISTRATION.zh_CN.md +++ b/documents/SERVER_ADMINISTRATION.zh_CN.md @@ -85,7 +85,7 @@ wasm-git-server --root /srv/wasm-git --policy policy.bin --allow-write ```json { - "version": 1, + "version": 3, "principals": [ { "name": "release-bot", @@ -113,9 +113,37 @@ wasm-git-server --root /srv/wasm-git --policy policy.bin --allow-write `create` 仅授予预期的服务端 fork 目标。强推还需服务端 `--allow-force` 与客户端精确 lease。 HTTP 写开关仍需显式启用;编译策略与 `--token-file` 互斥。 -策略替换应作为配置发布管理,重启实例加载新策略,不假设热更新。 +编译文件只用于服务根首次初始化;后续用 `policy-set` 条件更新,通过 `policy-query` 按原操作 +恢复回执。同一服务根的 HTTP 和 stdio 实例共用授权屏障。部署、文件系统、身份及自然过期的 +限制见[服务器授权](../docs/server.md#多用户权限与原子发布)。 不得允许不可信客户端自行选择 SSH principal 或服务根目录。 +需要绑定原操作有效期时,使用原生 `operation-credential-issue` / `operation-credential-query` +及 HTTP `--require-operation-credentials`。首次发放原子升级授权数据库,旧程序和普通认证入口随后拒绝访问; +精确请求、不可续期动作身份、查询恢复及部署边界见[严格操作凭据](../docs/server.md#严格操作凭据)。 +严格分片使用 `scoped-upload-rpc` 的原操作 Chunk 与 QueryChunk 契约;普通 Slice 不可用于严格入口。 +接受回执独立于暂存数据清理,查询与重放的含义见[分片决定与清理](../docs/server.md#分片决定与清理)。 + +Linux 本地管理员可用 `wasm-git-server --format json operation-context`、`operation-recover`、 +`audit-query` 和 `capacity-query` 查询原操作、受限恢复、审计及仓库容量。原主体撤权后, +恢复只允许以严格匹配的原发放请求检查或关闭上传/保留范围;不续期、上传、读取正文或作出新的发布、转正决定。 +它使用服务根的独占授权屏障,保留已提交结果。身份和路径要求、JSON 请求文件用法、审计证据及 +旧凭据处理见[本地运维与受限恢复](../docs/server.md#本地运维与受限恢复)。 + +`release_retention` 仅授予实际负责发布决定的受信服务主体,并同时要求仓库读取权限; +单 token 模式不能使用发布保留接口。持有方为原操作持久记录准备、转正和关闭, +先关闭后到达的准备被拒绝;已转正引用不能通过关闭释放。转正或关闭只接受协调方对其 +权威提交或终止决定的通知,不由仓库作发布决定。固定读取只返回该操作所选提交和文件。 +准备时所选文件必须已在本地,GC 和 pool 驱逐均保留受保护内容。 +保留和上传会话的版本化类型见 `src/protocol.rs`;跨语言调用使用客户端的 +`--format json retention-rpc`、`upload-binding`、`upload-recovery` 和 `scoped-upload-rpc`,并核对进程状态。 +这些命令通过标准输入接收原生类型的 JSON,凭据仍由 `WASM_GIT_REMOTE_TOKEN` 提供。 +`--format json integration-capabilities` 报告本机工具及契约版本和授权边界; +`--format json integration-validate` 使用 `src/protocol.rs` 中的 `IntegrationValidation` 类型校验 +请求、响应及实际进程退出码。Node 调用方应将未解析的原始 JSON 字节嵌入校验请求, +校验成功后才用 `JSON.parse`;该入口拒绝浮点数与超过 JavaScript 安全整数范围的数值。 +原生二进制协议的 `u64` 宽度不受此限制。 + ## 5. SSH 传输 ```sh @@ -182,6 +210,8 @@ Pre-receive 失败阻止发布;post-receive 失败不会撤销已经接受的 rejected/unknown/post-hook-failed 等结果。Post-receive 失败后仍尝试 post-update。 发布后的完成审计本身也可能写失败,因此需保留 stderr,并查询 实际引用核对结果。仅显式渲染审计时输出 JSON。 +`receive-audit.bin` 用于普通或历史接收的辅助核对;严格操作应结合服务根审计索引和原生回执。 +`Unknown`、`Unobserved` 或未完成的审计观察都不能证明原操作未执行。 ## 7. 作者签名策略 @@ -266,6 +296,21 @@ CPU/内存限制,并允许服务根和必要 hook 数据访问。 当前限制包括单 RPC packet 64 MiB、metadata 64 KiB、传输 chunk 1 MiB、bundle 4 GiB, 每仓库最多 32 个 pending upload、8 GiB staging 预留预算,上传 24 小时过期。 +网络上传绑定已认证主体、仓库、目标、会话与内容摘要;旧无作用域上传 RPC 被拒绝。 +超时清理分片后,同一开放会话可重新上传;取消留下墓碑。v4 接收决定与引用事务同存 journal, +恢复完成后按原会话查询实际引用结果;显式关闭时,没有持久决定且已排除在途处理的 v4 操作记为中断, +不得重放同一会话。旧版 `Applying` 缺少该依据,继续保持未知并人工核对。 +旧版程序不能恢复 v4 journal;同一仓库的服务和本地维护命令须使用支持该 journal 的版本。 +Scoped 上传会话和发布保留分别以 4,096 条、64 MiB 活跃记录为新建水位;墓碑及完成、转正等 +终态保留且不占活跃水位。`capacity-query` 可查各自活跃与累计记录数量及编码字节数;累计值不含 +仓库对象或分片正文。存储故障后先恢复存储,再按原 ID 查询或重试。 +旧账本向单条记录存储迁移前须备份,并在维护窗口停止旧版写入者和维护程序,不得混用版本; +首次 `capacity-query` 也可能触发迁移。迁移 marker 与新记录目录必须一起保留。 +详见[会话与保留容量](../docs/server.md#会话与保留容量)。 +普通客户端需分片上传时,调用方先提供唯一的 64 位十六进制 `WASM_GIT_UPLOAD_SESSION` 和 +已有私有目录 `WASM_GIT_UPLOAD_RECOVERY_DIR`。客户端在发送前将该会话的绑定及完整待传数据 +持久写入目录;`upload-recovery` 校验恢复记录及数据,再用同一身份查询或续传。处理完结果后 +由调用方清理这些恢复文件,不得与其他会话共用标识。 每个 HTTP 连接有 15 秒累计 I/O 预算,完整请求缓存后的处理时间不计入其中, 避免慢主机完成校验和持久化发布后无法发送回执;零碎读取不会重置预算。 服务端处理受请求大小和并发数约束,不会因固定墙钟期限而取消;hook 组的独立期限见前文。 @@ -280,19 +325,24 @@ CPU/内存限制,并允许服务根和必要 hook 数据访问。 一致性文件系统备份应停止写入者,或通过协调快照同时捕获对象、pack、ref、恢复控制记录和 linked-worktree 元数据。需要节省空间时保留硬链接。 +备份还须包含服务根授权 SQLite 数据库及其恢复所需 journal、审计索引,以及保留与上传会话的 +marker 和单条记录;恢复前协调原发布决定、已发生的引用写入和允许的重放范围, +不得以旧备份覆盖新墓碑或将未知结果当作未发生。 服务策略、作者信任与私钥凭据应按权限单独备份。 可移植 bundle 覆盖其选定历史,不代表全部运行配置和未保存工作区。 Partial 或 pool-evicted 仓库并非自包含备份:导出前先 hydrate,或整体备份所需 pool 副本、 pin 与拥有者状态。将备份还原到新目录,运行 fsck,再导出历史模块逐字节比较。 -中断后保留 journal、不完整审计尾和服务诊断;通过正常引擎重新打开,让持久事务恢复运行。 +中断后保留 journal、不完整审计尾和服务诊断;严格操作通过 `operation-recover` 按精确原请求恢复, +普通严格读取与容量查询遇到待恢复的引用 journal 时拒绝。其他本地引擎流程仍按既有方式恢复事务。 不确定 push 先查 ref。不要手动删除 pack、promise 或 pin 来消除报错。 -移除持久 writer/index 锁前必须确认无写入者;进程持有的 pool 锁有不同生命周期。 使用 `gc DIR -n` 审阅计划。正常 GC 压缩且不 prune;`--prune=now` 明确回收保留根之外对象。 真正删除的无引用历史需其他保留副本或备份恢复。 审计轮换应按完整记录并与写入者协调;截断尾需要调查时保留原文件。 +原生 writer、index、传输锁的文件持续保留。Unix 操作正常结束时显式解锁;异常退出后须等仍持锁的继承描述符关闭,不得删除版本化 inode。 +旧格式或 WASIp1 的独占创建锁须在停止全部使用者并确认没有活动操作后受控处理,运行中不混用锁后端。 ## 13. 运维验收 diff --git a/documents/WASMHUB.eu_US.md b/documents/WASMHUB.eu_US.md index ed25fc1..db91e43 100644 --- a/documents/WASMHUB.eu_US.md +++ b/documents/WASMHUB.eu_US.md @@ -179,8 +179,9 @@ Without that restriction, any authorized target branch writer may report a check Use separate policy principals for authors, reviewers and CI; a shared token has one identity and cannot provide independent approvals. -Access and protection policies are loaded at server startup; restart the service -after replacing them. The author trust file is read for each verification/admission, +Access policy updates use the root authorization store and fence described in +[server authorization](../docs/server.md#多用户权限与原子发布). Protection policy is loaded at startup; restart the service +after replacing it. The author trust file is read for each verification/admission, so an atomic trust update applies to subsequent operations without a restart. Merge supports fast-forward, a two-parent semantic merge, or a one-parent squash. diff --git a/documents/WASMHUB.zh_CN.md b/documents/WASMHUB.zh_CN.md index 9c7357f..a095eff 100644 --- a/documents/WASMHUB.zh_CN.md +++ b/documents/WASMHUB.zh_CN.md @@ -143,7 +143,8 @@ wasm-git-server --root /srv/wasm-git --policy principals.bin --allow-write \ 普通写者冒充 CI;不设置时,任一授权目标写者均可上报。作者、审阅者和 CI 应使用不同策略 身份,共享 token 只有一个身份,不能提供独立审批。 -访问与分支保护策略在服务端启动时加载,替换后须重启服务。作者信任文件在每次验证/准入 +访问策略由服务根授权库管理,更新及屏障见[服务器授权](../docs/server.md#多用户权限与原子发布); +分支保护策略在服务端启动时加载,替换后须重启服务。作者信任文件在每次验证/准入 时读取,原子替换后的信任更新对后续操作生效,无需重启。 合并支持 fast-forward、双父语义 merge、单父 squash。目标仍须等于已审 base。请求中的 diff --git a/src/command_output.rs b/src/command_output.rs index 5cdc75c..617f403 100644 --- a/src/command_output.rs +++ b/src/command_output.rs @@ -1,6 +1,7 @@ //! Presentation/automation transport; deliberately separate from repository and //! network encodings. A machine response is one versioned record, even on error. -use serde_json::{json, Value}; +use serde_json::Value; +use crate::protocol::{CommandEnvelope, CommandError, CommandResult}; use std::io::{IsTerminal, Write}; #[derive(Clone, Copy, PartialEq, Eq)] @@ -66,21 +67,21 @@ impl Format { return; } let result = if let Some(value) = data { - json!({"kind":"data", "value":value}) + CommandResult::Data { value } } else if output.is_empty() { - json!({"kind":"empty"}) + CommandResult::Empty } else { - json!({"kind":"text", "text":output}) + CommandResult::Text { text: output.to_owned() } }; - let record = json!({"protocol":"wasm-git.command", "version":1, - "command":command, "ok":code == 0, "exit_code":code, "result":result, - "error":error.map(|message| json!({"code":"command_failed", "message":message}))}); + let record = CommandEnvelope { protocol: "wasm-git.command".into(), version: 1, + command: command.into(), ok: code == 0, exit_code: code, result, + error: error.map(|message| CommandError { code: "command_failed".into(), message: message.into() }) }; let bytes = if self == Self::Json { let mut bytes = serde_json::to_vec(&record).expect("serializable command response"); bytes.push(b'\n'); bytes } else { - binary(&record) + binary(&serde_json::to_value(&record).expect("serializable command response")) }; let mut stdout = std::io::stdout().lock(); if let Err(error) = stdout.write_all(&bytes).and_then(|()| stdout.flush()) { @@ -208,6 +209,7 @@ fn binary(value: &Value) -> Vec { #[cfg(test)] mod tests { use super::*; + use serde_json::json; #[test] fn binary_v1_golden_bytes_are_host_independent() { diff --git a/src/infrastructure/database/policy_ledger.rs b/src/infrastructure/database/policy_ledger.rs new file mode 100644 index 0000000..421a22f --- /dev/null +++ b/src/infrastructure/database/policy_ledger.rs @@ -0,0 +1,3646 @@ +//! SQLite persistence for the root policy and its immutable operation receipts. +//! The caller holds the root authorization gate around every operation. + +#[cfg(test)] +use crate::protocol::AuditEvidenceObservation; +use crate::protocol::{ + AuditAttribution, AuditItem, AuditObservation, AuditObservationScope, AuditObservationSource, + AuditOperationScope, AuditOperator, AuditQueryReply, AuditQueryRequest, + AuditRecordedObservation, AuditSummary, AuditTarget, Operation, OperationCredentialReceipt, + OperationCredentialRequest, PolicyMigrationReceipt, PolicyMigrationRequest, PolicyQueryReply, + PolicyQueryRequest, PolicyStatus, PolicyUpdateOutcome, PolicyUpdateReceipt, + PolicyUpdateRequest, RecoveryAuditAction, Request, ServerPolicy, AUDIT_PAGE_MAX_BYTES, + NODE_SAFE_INTEGER_MAX, +}; +use rusqlite::{ + limits::Limit, params, Connection, OpenFlags, OptionalExtension, TransactionBehavior, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard, TryLockError}; +use std::time::{Duration, Instant}; + +const FILE: &str = ".wasm-git-authorization.bin"; +const SQLITE_HEADER: &[u8; 16] = b"SQLite format 3\0"; +const LEGACY_HEADER: &[u8; 8] = b"WGTM\0\0\0\x01"; +const APPLICATION_ID: i64 = 0x5747_504c; +const SCHEMA_VERSION: i64 = 2; +const CREDENTIAL_SCHEMA_VERSION: i64 = 3; +const CHUNK_RECEIPT_SCHEMA_VERSION: i64 = 4; +const AUDIT_SCHEMA_VERSION: i64 = 5; +const AUDIT_CREDENTIAL_SCHEMA_VERSION: i64 = 6; +const MAX_POLICY_BYTES: usize = 16 * 1024 * 1024; +const MAX_RECEIPT_BYTES: usize = 4096; +const MAX_AUDIT_RECORD_BYTES: usize = 128 * 1024; +const MAX_AUDIT_OBSERVATION_BYTES: usize = 4096; +// Admission watermarks stop new work, never revocation or original-operation +// recovery. A finite shared reserve cannot bound delayed closes/retries. +const MAX_AUDIT_ADMISSION_ENTRIES: u64 = 1_000_000; +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +// SQLite's Unix file locks are process-scoped: closing another descriptor for +// the same database can release its locks. Serialize all local connections and +// the extra descriptor used for durable-publication recovery. The caller's +// root gate still excludes writers across processes. +static PROCESS_DATABASE_LOCK: Mutex<()> = Mutex::new(()); + +fn process_lock() -> Result, String> { + let deadline = Instant::now() + BUSY_TIMEOUT; + loop { + match PROCESS_DATABASE_LOCK.try_lock() { + Ok(guard) => return Ok(guard), + Err(TryLockError::WouldBlock) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(2)); + } + Err(error) => return Err(format!("authorization database busy: {error}")), + } + } +} + +const SCHEMA: &str = r#" + PRAGMA application_id = 1464291404; + PRAGMA user_version = 2; + CREATE TABLE policy_receipts ( + operation_id TEXT PRIMARY KEY NOT NULL CHECK(length(operation_id) = 64), + applied_generation INTEGER UNIQUE CHECK(applied_generation IS NULL OR applied_generation > 0), + receipt BLOB NOT NULL CHECK(length(receipt) BETWEEN 1 AND 4096) + ) WITHOUT ROWID; + CREATE TRIGGER policy_receipts_no_update BEFORE UPDATE ON policy_receipts + BEGIN SELECT RAISE(ABORT, 'policy receipts are immutable'); END; + CREATE TRIGGER policy_receipts_no_delete BEFORE DELETE ON policy_receipts + BEGIN SELECT RAISE(ABORT, 'policy receipts are immutable'); END; + CREATE TABLE policy_migration ( + singleton INTEGER PRIMARY KEY CHECK(singleton = 1), + receipt BLOB NOT NULL CHECK(length(receipt) BETWEEN 1 AND 4096) + ); + CREATE TRIGGER policy_migration_no_update BEFORE UPDATE ON policy_migration + BEGIN SELECT RAISE(ABORT, 'policy migration receipt is immutable'); END; + CREATE TRIGGER policy_migration_no_delete BEFORE DELETE ON policy_migration + BEGIN SELECT RAISE(ABORT, 'policy migration receipt is immutable'); END; + CREATE TABLE policy_current ( + singleton INTEGER PRIMARY KEY CHECK(singleton = 1), + generation INTEGER NOT NULL CHECK(generation >= 0 AND generation <= 9007199254740991), + policy BLOB, + policy_sha256 TEXT, + current_operation TEXT REFERENCES policy_receipts(operation_id), + CHECK((generation = 0 AND policy IS NULL AND policy_sha256 IS NULL AND current_operation IS NULL) + OR (generation > 0 AND policy IS NOT NULL AND length(policy) <= 16777216 + AND length(policy_sha256) = 64 AND current_operation IS NOT NULL)) + ); + INSERT INTO policy_current(singleton, generation) VALUES (1, 0); +"#; + +// Old v2 databases have none of these objects; v3 and v4 use the same objects. +// Creating the first new credential upgrades v2/v3 to v4 in the same +// transaction, so earlier binaries fail closed. Exact SQL verifies both unique +// indexes and immutable triggers rather than trusting their names alone. +const CREDENTIAL_TABLE_SQL: &str = "CREATE TABLE operation_credentials (\n\ + operation_id TEXT PRIMARY KEY NOT NULL CHECK(length(operation_id) = 64),\n\ + token_sha256 TEXT NOT NULL CHECK(length(token_sha256) = 64),\n\ + effect_key TEXT CHECK(effect_key IS NULL OR length(effect_key) = 64),\n\ + receipt BLOB NOT NULL CHECK(length(receipt) BETWEEN 1 AND 4096)\n\ +) WITHOUT ROWID"; +const CREDENTIAL_INDEX_SQL: &str = + "CREATE UNIQUE INDEX operation_credentials_token ON operation_credentials(token_sha256)"; +const CREDENTIAL_EFFECT_SQL: &str = + "CREATE UNIQUE INDEX operation_credentials_effect ON operation_credentials(effect_key)"; +const CREDENTIAL_UPDATE_SQL: &str = "CREATE TRIGGER operation_credentials_no_update BEFORE UPDATE ON operation_credentials BEGIN SELECT RAISE(ABORT, 'operation credentials are immutable'); END"; +const CREDENTIAL_DELETE_SQL: &str = "CREATE TRIGGER operation_credentials_no_delete BEFORE DELETE ON operation_credentials BEGIN SELECT RAISE(ABORT, 'operation credentials are immutable'); END"; +const CREDENTIAL_OBJECTS: [(&str, &str, &str); 5] = [ + ("operation_credentials", "table", CREDENTIAL_TABLE_SQL), + ("operation_credentials_token", "index", CREDENTIAL_INDEX_SQL), + ( + "operation_credentials_effect", + "index", + CREDENTIAL_EFFECT_SQL, + ), + ( + "operation_credentials_no_update", + "trigger", + CREDENTIAL_UPDATE_SQL, + ), + ( + "operation_credentials_no_delete", + "trigger", + CREDENTIAL_DELETE_SQL, + ), +]; + +const AUDIT_TABLE_SQL: &str = "CREATE TABLE audit_index (\n\ + sequence INTEGER PRIMARY KEY AUTOINCREMENT CHECK(sequence BETWEEN 1 AND 9007199254740991),\n\ + kind INTEGER NOT NULL CHECK(kind BETWEEN 1 AND 5),\n\ + identity TEXT NOT NULL CHECK(length(identity) = 64),\n\ + record BLOB NOT NULL CHECK(length(record) BETWEEN 1 AND 131072),\n\ + observation BLOB CHECK(observation IS NULL OR length(observation) BETWEEN 1 AND 4096),\n\ + CHECK(kind IN (4, 5) OR observation IS NULL)\n\ +)"; +const AUDIT_UNIQUE_SQL: &str = "CREATE UNIQUE INDEX audit_original_identity ON audit_index(kind, identity) WHERE kind IN (1, 2, 3)"; +const AUDIT_LOOKUP_SQL: &str = "CREATE INDEX audit_lookup ON audit_index(kind, identity)"; +const AUDIT_IMMUTABLE_SQL: &str = "CREATE TRIGGER audit_identity_no_update BEFORE UPDATE OF sequence, kind, identity, record ON audit_index BEGIN SELECT RAISE(ABORT, 'audit identity is immutable'); END"; +const AUDIT_NO_DELETE_SQL: &str = "CREATE TRIGGER audit_no_delete BEFORE DELETE ON audit_index BEGIN SELECT RAISE(ABORT, 'audit records are immutable'); END"; +const AUDIT_OBSERVATION_SQL: &str = "CREATE TRIGGER audit_observation_once BEFORE UPDATE OF observation ON audit_index WHEN OLD.observation IS NOT NULL AND NEW.observation IS NOT OLD.observation BEGIN SELECT RAISE(ABORT, 'audit observation is immutable'); END"; +const AUDIT_OBJECTS: [(&str, &str, &str); 6] = [ + ("audit_index", "table", AUDIT_TABLE_SQL), + ("audit_original_identity", "index", AUDIT_UNIQUE_SQL), + ("audit_lookup", "index", AUDIT_LOOKUP_SQL), + ("audit_identity_no_update", "trigger", AUDIT_IMMUTABLE_SQL), + ("audit_no_delete", "trigger", AUDIT_NO_DELETE_SQL), + ("audit_observation_once", "trigger", AUDIT_OBSERVATION_SQL), +]; + +fn audit_schema(connection: &Connection) -> Result { + let mut statement = database(connection.prepare( + "SELECT name, type, tbl_name, sql FROM sqlite_schema WHERE name IN (?1, ?2, ?3, ?4, ?5, ?6)", + ))?; + let mut rows = database(statement.query(params![ + AUDIT_OBJECTS[0].0, + AUDIT_OBJECTS[1].0, + AUDIT_OBJECTS[2].0, + AUDIT_OBJECTS[3].0, + AUDIT_OBJECTS[4].0, + AUDIT_OBJECTS[5].0, + ]))?; + let mut found = [false; AUDIT_OBJECTS.len()]; + while let Some(row) = database(rows.next())? { + let name: String = database(row.get(0))?; + let kind: String = database(row.get(1))?; + let table: String = database(row.get(2))?; + let sql: Option = database(row.get(3))?; + let index = AUDIT_OBJECTS + .iter() + .position(|object| object.0 == name) + .ok_or("unknown audit schema object")?; + let (_, expected_kind, expected_sql) = AUDIT_OBJECTS[index]; + if found[index] + || kind != expected_kind + || table != "audit_index" + || sql.as_deref() != Some(expected_sql) + { + return Err("audit schema is invalid".into()); + } + found[index] = true; + } + if found.iter().all(|present| *present) { + Ok(true) + } else if found.iter().all(|present| !*present) { + Ok(false) + } else { + Err("audit schema is incomplete".into()) + } +} + +/// The caller is already inside an immediate transaction. Older binaries reject +/// both new versions; a policy-only root does not acquire credential support. +fn ensure_audit_schema(connection: &Connection) -> Result<(), String> { + let version: i64 = database(connection.query_row("PRAGMA user_version", [], |row| row.get(0)))?; + if matches!( + version, + AUDIT_SCHEMA_VERSION | AUDIT_CREDENTIAL_SCHEMA_VERSION + ) { + if !audit_schema(connection)? { + return Err("audit schema is incomplete".into()); + } + return Ok(()); + } + if audit_schema(connection)? { + return Err("unexpected audit schema".into()); + } + let target = match version { + SCHEMA_VERSION => AUDIT_SCHEMA_VERSION, + CREDENTIAL_SCHEMA_VERSION | CHUNK_RECEIPT_SCHEMA_VERSION => AUDIT_CREDENTIAL_SCHEMA_VERSION, + _ => return Err("unsupported audit schema upgrade".into()), + }; + for (_, _, sql) in AUDIT_OBJECTS { + database(connection.execute_batch(sql))?; + } + match target { + AUDIT_SCHEMA_VERSION => database(connection.execute_batch("PRAGMA user_version = 5"))?, + AUDIT_CREDENTIAL_SCHEMA_VERSION => { + database(connection.execute_batch("PRAGMA user_version = 6"))? + } + _ => unreachable!(), + } + Ok(()) +} + +fn credential_schema(connection: &Connection) -> Result { + let mut statement = database(connection.prepare( + "SELECT name, type, tbl_name, sql FROM sqlite_schema WHERE name IN (?1, ?2, ?3, ?4, ?5)", + ))?; + let mut rows = database(statement.query(params![ + CREDENTIAL_OBJECTS[0].0, + CREDENTIAL_OBJECTS[1].0, + CREDENTIAL_OBJECTS[2].0, + CREDENTIAL_OBJECTS[3].0, + CREDENTIAL_OBJECTS[4].0, + ]))?; + let mut found = [false; CREDENTIAL_OBJECTS.len()]; + while let Some(row) = database(rows.next())? { + let name: String = database(row.get(0))?; + let kind: String = database(row.get(1))?; + let table: String = database(row.get(2))?; + let sql: Option = database(row.get(3))?; + let index = CREDENTIAL_OBJECTS + .iter() + .position(|object| object.0 == name) + .ok_or("unknown credential schema object")?; + let (_, expected_kind, expected_sql) = CREDENTIAL_OBJECTS[index]; + if found[index] + || kind != expected_kind + || table != "operation_credentials" + || sql.as_deref() != Some(expected_sql) + { + return Err("operation credential schema is invalid".into()); + } + found[index] = true; + } + if found.iter().all(|present| *present) { + Ok(true) + } else if found.iter().all(|present| !*present) { + Ok(false) + } else { + Err("operation credential schema is incomplete".into()) + } +} + +fn create_credential_schema(connection: &Connection) -> Result<(), String> { + for (_, _, sql) in CREDENTIAL_OBJECTS { + database(connection.execute_batch(sql))?; + } + Ok(()) +} + +fn credential_features(connection: &Connection) -> Result<(bool, bool), String> { + let version: i64 = database(connection.query_row("PRAGMA user_version", [], |row| row.get(0)))?; + match (version, credential_schema(connection)?) { + (SCHEMA_VERSION, false) => Ok((false, false)), + (CREDENTIAL_SCHEMA_VERSION, true) => Ok((true, false)), + (CHUNK_RECEIPT_SCHEMA_VERSION, true) => Ok((true, true)), + (AUDIT_SCHEMA_VERSION, false) => Ok((false, false)), + (AUDIT_CREDENTIAL_SCHEMA_VERSION, true) => Ok((true, true)), + _ => Err("operation credential database version or schema is invalid".into()), + } +} + +fn database(result: rusqlite::Result) -> Result { + result.map_err(|error| format!("authorization database: {error}")) +} + +fn configure(connection: &Connection) -> Result<(), String> { + database(connection.busy_timeout(BUSY_TIMEOUT))?; + database(connection.set_limit(Limit::SQLITE_LIMIT_LENGTH, (MAX_POLICY_BYTES + 8192) as i32))?; + database(connection.execute_batch("PRAGMA foreign_keys = ON; PRAGMA synchronous = EXTRA;"))?; + let synchronous: i64 = database(connection.query_row("PRAGMA synchronous", [], |r| r.get(0)))?; + let foreign_keys: i64 = + database(connection.query_row("PRAGMA foreign_keys", [], |r| r.get(0)))?; + let journal_mode: String = + database(connection.query_row("PRAGMA journal_mode", [], |r| r.get(0)))?; + if synchronous != 3 || foreign_keys != 1 || journal_mode != "delete" { + return Err("authorization database durability configuration unavailable".into()); + } + Ok(()) +} + +fn connect(path: &Path) -> Result { + let flags = OpenFlags::SQLITE_OPEN_READ_WRITE + | OpenFlags::SQLITE_OPEN_NO_MUTEX + | OpenFlags::SQLITE_OPEN_PRIVATE_CACHE + | OpenFlags::SQLITE_OPEN_NOFOLLOW; + let connection = database(Connection::open_with_flags(path, flags))?; + if database(connection.is_readonly("main"))? { + return Err("authorization database requires writable crash recovery".into()); + } + configure(&connection)?; + Ok(connection) +} + +fn check_schema(connection: &Connection) -> Result<(), String> { + let application: i64 = + database(connection.query_row("PRAGMA application_id", [], |r| r.get(0)))?; + let version: i64 = database(connection.query_row("PRAGMA user_version", [], |r| r.get(0)))?; + if application != APPLICATION_ID + || !matches!( + version, + SCHEMA_VERSION + | CREDENTIAL_SCHEMA_VERSION + | CHUNK_RECEIPT_SCHEMA_VERSION + | AUDIT_SCHEMA_VERSION + | AUDIT_CREDENTIAL_SCHEMA_VERSION + ) + { + return Err("unsupported authorization database identity or version".into()); + } + let objects: i64 = database(connection.query_row( + "SELECT count(*) FROM sqlite_schema WHERE (type = 'table' AND name IN ('policy_receipts','policy_current','policy_migration')) OR (type = 'trigger' AND name IN ('policy_receipts_no_update','policy_receipts_no_delete','policy_migration_no_update','policy_migration_no_delete'))", + [], |r| r.get(0), + ))?; + if objects != 7 { + return Err("authorization database schema is incomplete".into()); + } + credential_features(connection)?; + let audit_present = audit_schema(connection)?; + if audit_present + != matches!( + version, + AUDIT_SCHEMA_VERSION | AUDIT_CREDENTIAL_SCHEMA_VERSION + ) + { + return Err("authorization database audit version or schema is invalid".into()); + } + Ok(()) +} + +fn existing(root: &Path) -> Result, String> { + existing_with_sync(root, sync_existing) +} + +fn sync_existing(path: &Path, root: &Path) -> Result<(), String> { + OpenOptions::new() + .read(true) + .write(true) + .open(path) + .and_then(|file| file.sync_all()) + .map_err(|error| format!("sync authorization database: {error}"))?; + crate::output::sync_directory(root) +} + +fn existing_with_sync( + root: &Path, + sync: impl FnOnce(&Path, &Path) -> Result<(), String>, +) -> Result, String> { + let path = root.join(FILE); + match fs::symlink_metadata(&path) { + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(format!("inspect authorization database: {error}")), + Ok(metadata) if !metadata.is_file() || metadata.file_type().is_symlink() => { + return Err("authorization database must be a regular file".into()) + } + Ok(_) => (), + } + let mut file = + File::open(&path).map_err(|error| format!("open authorization database: {error}"))?; + let mut header = [0u8; 16]; + file.read_exact(&mut header[..8]) + .map_err(|error| format!("invalid authorization database header: {error}"))?; + if header.starts_with(LEGACY_HEADER) { + return Err( + "legacy policy ledger requires an explicit maintenance-window migration".into(), + ); + } + file.read_exact(&mut header[8..]) + .map_err(|error| format!("invalid authorization database header: {error}"))?; + if &header != SQLITE_HEADER { + return Err("invalid authorization database header".into()); + } + drop(file); + let connection = connect(&path)?; + check_schema(&connection)?; + // A previous create/link or migration/rename may have succeeded while its + // directory sync failed. Do not return a receipt or use its policy until + // recovery and both syncs have succeeded, including on a later retry. + sync(&path, root).map_err(|error| { + format!("authorization durability unknown; retry the original operation: {error}") + })?; + Ok(Some(connection)) +} + +pub(super) struct Current { + pub generation: u64, + pub policy: Option, + pub operation_credentials: bool, + pub chunk_receipts: bool, + digest: Option, +} + +fn receipt(connection: &Connection, id: &str) -> Result, String> { + let value: Option<(Option, Vec)> = database( + connection + .query_row( + "SELECT applied_generation, receipt FROM policy_receipts WHERE operation_id = ?1", + [id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional(), + )?; + let Some((applied_generation, bytes)) = value else { + return Ok(None); + }; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("authorization receipt exceeds bound".into()); + } + let receipt: PolicyUpdateReceipt = crate::binary::decode(&bytes)?; + receipt.validate()?; + let expected_generation = match receipt.outcome { + PolicyUpdateOutcome::Applied => Some(receipt.generation as i64), + PolicyUpdateOutcome::GenerationConflict => None, + }; + if receipt.operation_id != id || applied_generation != expected_generation { + return Err("authorization receipt identity or index mismatch".into()); + } + Ok(Some(receipt)) +} + +fn current_in(connection: &Connection) -> Result { + let (operation_credentials, chunk_receipts) = credential_features(connection)?; + let (generation, policy, digest, operation): (i64, Option>, Option, Option) = + database(connection.query_row( + "SELECT generation, policy, policy_sha256, current_operation FROM policy_current WHERE singleton = 1", + [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)), + ))?; + let generation = u64::try_from(generation).map_err(|_| "invalid policy generation")?; + if generation > NODE_SAFE_INTEGER_MAX { + return Err("invalid policy generation".into()); + } + if generation == 0 { + if policy.is_some() || digest.is_some() || operation.is_some() { + return Err("invalid uninitialized policy state".into()); + } + return Ok(Current { + generation, + policy: None, + operation_credentials, + chunk_receipts, + digest: None, + }); + } + let bytes = policy.ok_or("missing current policy")?; + if bytes.len() > MAX_POLICY_BYTES { + return Err("policy exceeds 16 MiB".into()); + } + let policy: ServerPolicy = crate::binary::decode(&bytes)?; + policy.validate()?; + let digest = digest.ok_or("missing policy digest")?; + if policy.digest()? != digest { + return Err("current policy digest mismatch".into()); + } + let operation = operation.ok_or("missing current policy operation")?; + let applied = receipt(connection, &operation)?.ok_or("current policy receipt is missing")?; + if applied.outcome != PolicyUpdateOutcome::Applied + || applied.generation != generation + || applied.policy_sha256 != digest + { + return Err("current policy receipt mismatch".into()); + } + Ok(Current { + generation, + policy: Some(policy), + operation_credentials, + chunk_receipts, + digest: Some(digest), + }) +} + +pub(super) fn current(root: &Path) -> Result, String> { + let _process_lock = process_lock()?; + existing(root)? + .map(|connection| current_in(&connection)) + .transpose() +} + +pub(super) fn status(root: &Path) -> Result { + let current = current(root)?.ok_or("authorization store is not initialized")?; + Ok(PolicyStatus { + version: 1, + generation: current.generation, + policy_sha256: current + .digest + .ok_or("authorization store is not initialized")?, + }) +} + +pub(super) fn query(root: &Path, request: &PolicyQueryRequest) -> Result { + request.validate()?; + let _process_lock = process_lock()?; + let receipt = match existing(root)? { + Some(connection) => { + current_in(&connection)?; + receipt(&connection, &request.operation_id)? + } + None => None, + }; + Ok(PolicyQueryReply { + version: 1, + operation_id: request.operation_id.clone(), + receipt, + }) +} + +#[derive(Clone, Copy)] +enum CredentialIndex { + Operation, + Token, + Effect, +} + +fn credential_lookup( + connection: &Connection, + key: &str, + index: CredentialIndex, +) -> Result, String> { + let sql = match index { + CredentialIndex::Operation => "SELECT operation_id, token_sha256, effect_key, receipt FROM operation_credentials WHERE operation_id = ?1", + CredentialIndex::Token => "SELECT operation_id, token_sha256, effect_key, receipt FROM operation_credentials WHERE token_sha256 = ?1", + CredentialIndex::Effect => "SELECT operation_id, token_sha256, effect_key, receipt FROM operation_credentials WHERE effect_key = ?1", + }; + let value: Option<(String, String, Option, Vec)> = database( + connection + .query_row(sql, [key], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)) + }) + .optional(), + )?; + let Some((operation_id, token_sha256, effect_key, bytes)) = value else { + return Ok(None); + }; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("operation credential receipt exceeds bound".into()); + } + let receipt: OperationCredentialReceipt = crate::binary::decode(&bytes)?; + receipt.validate()?; + if receipt.operation_id != operation_id + || receipt.token_sha256 != token_sha256 + || receipt.effect_key != effect_key + || match index { + CredentialIndex::Operation => operation_id != key, + CredentialIndex::Token => token_sha256 != key, + CredentialIndex::Effect => effect_key.as_deref() != Some(key), + } + { + return Err("operation credential identity or index mismatch".into()); + } + Ok(Some(receipt)) +} + +fn check_policy_credentials(connection: &Connection, policy: &ServerPolicy) -> Result<(), String> { + if credential_features(connection)?.0 { + for principal in &policy.principals { + if let Some(token) = &principal.token_sha256 { + if credential_lookup(connection, token, CredentialIndex::Token)?.is_some() { + return Err("policy credential collides with an operation credential".into()); + } + } + } + } + Ok(()) +} + +fn credential_decide( + connection: &Connection, + proposed: &OperationCredentialReceipt, +) -> Result { + credential_decide_with_check(connection, proposed, || { + super::AuthorizationLimit::until(proposed.expires_at).require_current() + }) +} + +fn credential_decide_with_check( + connection: &Connection, + proposed: &OperationCredentialReceipt, + check: impl FnOnce() -> Result<(), String>, +) -> Result { + proposed.validate()?; + let current = current_in(connection)?; + let exists = current.operation_credentials; + let chunk_receipts = current.chunk_receipts; + let policy = current + .policy + .ok_or("authorization store is not initialized")?; + if exists { + if let Some(prior) = credential_lookup( + connection, + &proposed.operation_id, + CredentialIndex::Operation, + )? { + if &prior != proposed { + return Err("operation credential identity conflict".into()); + } + return Ok(prior); + } + } + if current.generation != proposed.policy_generation { + return Err("operation credential policy generation is no longer current".into()); + } + if !policy + .principals + .iter() + .any(|principal| principal.name == proposed.actor) + { + return Err("operation credential principal does not exist".into()); + } + if policy + .principals + .iter() + .any(|principal| principal.token_sha256.as_deref() == Some(proposed.token_sha256.as_str())) + { + return Err("operation credential collides with a policy credential".into()); + } + if exists + && credential_lookup(connection, &proposed.token_sha256, CredentialIndex::Token)?.is_some() + { + return Err("operation credential token is already assigned".into()); + } + if let Some(effect) = &proposed.effect_key { + if exists && credential_lookup(connection, effect, CredentialIndex::Effect)?.is_some() { + return Err("operation credential effect is already assigned".into()); + } + } + if !exists { + create_credential_schema(connection)?; + } + if !chunk_receipts { + let version: i64 = + database(connection.query_row("PRAGMA user_version", [], |row| row.get(0)))?; + if version == AUDIT_SCHEMA_VERSION { + database(connection.execute_batch("PRAGMA user_version = 6"))?; + } else { + database(connection.execute_batch("PRAGMA user_version = 4"))?; + } + } + let bytes = crate::binary::encode(proposed)?; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("operation credential receipt exceeds bound".into()); + } + // Replays return above, but a new immutable decision must not reserve the + // effect identity if authority expired while waiting for the transaction. + check()?; + database(connection.execute( + "INSERT INTO operation_credentials(operation_id, token_sha256, effect_key, receipt) VALUES (?1, ?2, ?3, ?4)", + params![proposed.operation_id, proposed.token_sha256, proposed.effect_key, bytes], + ))?; + Ok(proposed.clone()) +} + +#[cfg(test)] +pub(super) fn credential_issue( + root: &Path, + proposed: &OperationCredentialReceipt, +) -> Result { + proposed.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + let result = credential_decide(&tx, proposed)?; + tx.commit().map_err(|error| { + format!("operation credential outcome unknown; query the original operation: {error}") + })?; + Ok(result) +} + +fn credential_read( + root: &Path, + key: &str, + by_token: bool, +) -> Result, String> { + crate::binary::oid(key)?; + let _process_lock = process_lock()?; + let connection = existing(root)?.ok_or("authorization store is not initialized")?; + let current = current_in(&connection)?; + if current.policy.is_none() { + return Err("authorization store is not initialized".into()); + } + if current.operation_credentials { + credential_lookup( + &connection, + key, + if by_token { + CredentialIndex::Token + } else { + CredentialIndex::Operation + }, + ) + } else { + Ok(None) + } +} + +pub(super) fn credential_by_token( + root: &Path, + token_sha256: &str, +) -> Result, String> { + credential_read(root, token_sha256, true) +} + +pub(super) fn credential_query( + root: &Path, + operation_id: &str, +) -> Result, String> { + credential_read(root, operation_id, false) +} + +fn decide( + connection: &Connection, + request: &PolicyUpdateRequest, +) -> Result { + let current = current_in(connection)?; + if let Some(receipt) = receipt(connection, &request.operation_id)? { + receipt + .validate_update(request) + .map_err(|_| "policy operation identity conflict")?; + return Ok(receipt); + } + let outcome = if current.generation == request.expected_generation { + PolicyUpdateOutcome::Applied + } else { + PolicyUpdateOutcome::GenerationConflict + }; + if outcome == PolicyUpdateOutcome::Applied { + check_policy_credentials(connection, &request.policy)?; + } + let receipt = PolicyUpdateReceipt { + version: 1, + operation_id: request.operation_id.clone(), + expected_generation: request.expected_generation, + outcome, + generation: if outcome == PolicyUpdateOutcome::Applied { + current.generation + 1 + } else { + current.generation + }, + policy_sha256: request.policy.digest()?, + }; + receipt.validate()?; + let bytes = crate::binary::encode(&receipt)?; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("authorization receipt exceeds bound".into()); + } + let applied_generation = + (outcome == PolicyUpdateOutcome::Applied).then_some(receipt.generation as i64); + database(connection.execute( + "INSERT INTO policy_receipts(operation_id, applied_generation, receipt) VALUES (?1, ?2, ?3)", + params![receipt.operation_id, applied_generation, bytes], + ))?; + if outcome == PolicyUpdateOutcome::Applied { + let policy = crate::binary::encode(&request.policy)?; + if policy.len() > MAX_POLICY_BYTES { + return Err("policy exceeds 16 MiB".into()); + } + let changed = database(connection.execute( + "UPDATE policy_current SET generation = ?1, policy = ?2, policy_sha256 = ?3, current_operation = ?4 WHERE singleton = 1 AND generation = ?5", + params![receipt.generation as i64, policy, receipt.policy_sha256, receipt.operation_id, current.generation as i64], + ))?; + if changed != 1 { + return Err("policy generation changed during transaction".into()); + } + } + Ok(receipt) +} + +#[cfg(test)] +fn transaction( + connection: &mut Connection, + request: &PolicyUpdateRequest, +) -> Result { + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + let result = decide(&tx, request)?; + tx.commit().map_err(|error| { + format!("policy decision outcome unknown; query the original operation: {error}") + })?; + Ok(result) +} + +struct Staging { + path: PathBuf, + cleanup: bool, +} +impl Drop for Staging { + fn drop(&mut self) { + if self.cleanup { + for suffix in ["", "-journal", "-wal", "-shm"] { + let mut name = self.path.as_os_str().to_os_string(); + name.push(suffix); + if let Err(error) = fs::remove_file(PathBuf::from(name)) { + if error.kind() != io::ErrorKind::NotFound { + crate::cli_error(&format!("policy staging cleanup failed: {error}")); + } + } + } + } + } +} + +fn stage(root: &Path) -> Result { + let random = getrandom::u64().map_err(|error| error.to_string())?; + let path = root.join(format!( + ".wasm-git-policy-{}-{random:x}.tmp", + crate::platform_fs::process_id() + )); + let mut options = OpenOptions::new(); + options.read(true).write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let file = options + .open(&path) + .map_err(|error| format!("create policy staging: {error}"))?; + drop(file); + Ok(Staging { + path, + cleanup: true, + }) +} + +fn seal(connection: Connection, path: &Path) -> Result<(), String> { + connection + .close() + .map_err(|(_, error)| format!("close policy staging: {error}"))?; + for suffix in ["-journal", "-wal", "-shm"] { + let mut name = path.as_os_str().to_os_string(); + name.push(suffix); + match fs::symlink_metadata(PathBuf::from(name)) { + Err(error) if error.kind() == io::ErrorKind::NotFound => (), + Err(error) => return Err(format!("inspect policy staging journal: {error}")), + Ok(_) => return Err("policy staging retained an unresolved journal".into()), + } + } + OpenOptions::new() + .read(true) + .write(true) + .open(path) + .and_then(|file| file.sync_all()) + .map_err(|error| format!("sync policy staging: {error}")) +} + +#[cfg(test)] +fn create(root: &Path, request: &PolicyUpdateRequest) -> Result { + create_with_hooks( + root, + request, + |path| fs::remove_file(path), + crate::output::sync_directory, + ) +} + +#[cfg(test)] +fn create_with_hooks( + root: &Path, + request: &PolicyUpdateRequest, + remove_staging: impl FnOnce(&Path) -> io::Result<()>, + sync_directory: impl FnMut(&Path) -> Result<(), String>, +) -> Result { + create_with_decision( + root, + |connection| decide(connection, request), + remove_staging, + sync_directory, + ) +} + +fn create_with_decision( + root: &Path, + decision: impl FnOnce(&Connection) -> Result, + remove_staging: impl FnOnce(&Path) -> io::Result<()>, + mut sync_directory: impl FnMut(&Path) -> Result<(), String>, +) -> Result { + let mut staging = stage(root)?; + let mut connection = connect(&staging.path)?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + database(tx.execute_batch(SCHEMA))?; + let result = decision(&tx)?; + database(tx.commit())?; + seal(connection, &staging.path)?; + fs::hard_link(&staging.path, root.join(FILE)) + .map_err(|error| format!("publish policy database: {error}"))?; + sync_directory(root).map_err(|error| { + format!("policy outcome unknown; query the original operation: {error}") + })?; + remove_staging(&staging.path).map_err(|error| { + format!("authorization ledger published; query the original operation; staging cleanup failed: {error}") + })?; + staging.cleanup = false; + sync_directory(root).map_err(|error| { + format!("policy outcome unknown; query the original operation: {error}") + })?; + Ok(result) +} + +#[cfg(test)] +pub(super) fn set( + root: &Path, + request: &PolicyUpdateRequest, +) -> Result { + request.validate()?; + let _process_lock = process_lock()?; + match existing(root)? { + Some(mut connection) => transaction(&mut connection, request), + None => create(root, request), + } +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct StoredAuditRecord { + version: u32, + detail: StoredAuditDetail, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +enum StoredAuditDetail { + Policy { + attribution: AuditAttribution, + }, + Credential { + original: Box, + attribution: AuditAttribution, + }, + Recovery { + original_operation_id: String, + action: RecoveryAuditAction, + operator: AuditOperator, + recorded_at_unix_millis: u64, + }, + OperationAttempt { + started_at_unix_millis: u64, + }, + RecoveryAttempt { + started_at_unix_millis: u64, + }, +} + +impl StoredAuditRecord { + fn kind(&self) -> i64 { + match &self.detail { + StoredAuditDetail::Policy { .. } => 1, + StoredAuditDetail::Credential { .. } => 2, + StoredAuditDetail::Recovery { .. } => 3, + StoredAuditDetail::OperationAttempt { .. } => 4, + StoredAuditDetail::RecoveryAttempt { .. } => 5, + } + } + + fn validate(&self, identity: &str) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported audit record version".into()); + } + crate::binary::oid(identity)?; + match &self.detail { + StoredAuditDetail::Policy { attribution } => attribution.validate(), + StoredAuditDetail::Credential { + original, + attribution, + } => { + original.validate()?; + if original.operation_id != identity { + return Err("audit credential identity mismatch".into()); + } + attribution.validate() + } + StoredAuditDetail::Recovery { + original_operation_id, + operator, + recorded_at_unix_millis, + .. + } => { + crate::binary::oid(original_operation_id)?; + operator.validate()?; + audit_time_valid(*recorded_at_unix_millis) + } + StoredAuditDetail::OperationAttempt { + started_at_unix_millis, + } + | StoredAuditDetail::RecoveryAttempt { + started_at_unix_millis, + } => audit_time_valid(*started_at_unix_millis), + } + } +} + +struct AuditRow { + sequence: u64, + kind: i64, + identity: String, + record: StoredAuditRecord, + observation: Option, +} + +type RawAuditRow = (i64, i64, String, Vec, Option>); + +fn raw_audit_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { + Ok(( + row.get(0)?, + row.get(1)?, + row.get(2)?, + row.get(3)?, + row.get(4)?, + )) +} + +fn decode_audit_row(raw: RawAuditRow) -> Result { + let (sequence, kind, identity, bytes, observed) = raw; + let sequence = u64::try_from(sequence).map_err(|_| "invalid audit sequence")?; + if sequence == 0 || sequence > NODE_SAFE_INTEGER_MAX || bytes.len() > MAX_AUDIT_RECORD_BYTES { + return Err("invalid audit record bounds".into()); + } + let record: StoredAuditRecord = crate::binary::decode(&bytes)?; + record.validate(&identity)?; + if kind != record.kind() { + return Err("audit record kind mismatch".into()); + } + let observation = observed + .map(|bytes| -> Result { + if bytes.len() > MAX_AUDIT_OBSERVATION_BYTES { + return Err("audit observation exceeds bounds".into()); + } + let value: AuditRecordedObservation = crate::binary::decode(&bytes)?; + value.validate()?; + Ok(value) + }) + .transpose()?; + if observation.is_some() && !matches!(kind, 4 | 5) { + return Err("audit observation has no attempt".into()); + } + Ok(AuditRow { + sequence, + kind, + identity, + record, + observation, + }) +} + +fn audit_row_by_key( + connection: &Connection, + kind: i64, + identity: &str, +) -> Result, String> { + let row: Option = database(connection.query_row( + "SELECT sequence, kind, identity, record, observation FROM audit_index WHERE kind = ?1 AND identity = ?2", + params![kind, identity], raw_audit_row, + ).optional())?; + row.map(decode_audit_row).transpose() +} + +fn audit_row_by_sequence( + connection: &Connection, + sequence: u64, +) -> Result, String> { + if sequence == 0 || sequence > NODE_SAFE_INTEGER_MAX { + return Err("invalid audit attempt".into()); + } + let row: Option = database(connection.query_row( + "SELECT sequence, kind, identity, record, observation FROM audit_index WHERE sequence = ?1", + [sequence as i64], raw_audit_row, + ).optional())?; + row.map(decode_audit_row).transpose() +} + +fn audit_time_valid(value: u64) -> Result<(), String> { + if value > NODE_SAFE_INTEGER_MAX { + return Err("audit time exceeds bound".into()); + } + Ok(()) +} + +fn audit_now() -> Result { + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|error| format!("audit clock: {error}"))? + .as_millis(); + let time = u64::try_from(millis).map_err(|_| "audit clock exceeds bound")?; + audit_time_valid(time)?; + Ok(time) +} + +fn audit_high_water(connection: &Connection) -> Result { + let maximum: i64 = database(connection.query_row( + "SELECT COALESCE(MAX(sequence), 0) FROM audit_index", + [], + |row| row.get(0), + ))?; + let allocated: Option = database( + connection + .query_row( + "SELECT seq FROM sqlite_sequence WHERE name = 'audit_index'", + [], + |row| row.get(0), + ) + .optional(), + )?; + if maximum < 0 || allocated.unwrap_or(0) != maximum || maximum as u64 > NODE_SAFE_INTEGER_MAX { + return Err("audit sequence history is incomplete".into()); + } + Ok(maximum as u64) +} + +// Imports must not turn a missing new audit record into apparent legacy +// history. This bounded-capacity check detects internal sequence holes before +// the first import, without scanning every record for ordinary operations. +fn audit_verify_contiguous(connection: &Connection) -> Result<(), String> { + let maximum = audit_high_water(connection)?; + let count: i64 = + database(connection.query_row("SELECT COUNT(*) FROM audit_index", [], |row| row.get(0)))?; + if count < 0 || count as u64 != maximum { + return Err("audit sequence history is incomplete".into()); + } + Ok(()) +} + +fn audit_insert( + connection: &Connection, + identity: &str, + detail: StoredAuditDetail, + reserved: bool, +) -> Result { + audit_insert_with_limit( + connection, + identity, + detail, + reserved, + MAX_AUDIT_ADMISSION_ENTRIES, + ) +} + +fn audit_insert_with_limit( + connection: &Connection, + identity: &str, + detail: StoredAuditDetail, + reserved: bool, + admission_limit: u64, +) -> Result { + let record = StoredAuditRecord { version: 1, detail }; + record.validate(identity)?; + let maximum = audit_high_water(connection)?; + let limit = if reserved { + NODE_SAFE_INTEGER_MAX + } else { + admission_limit + }; + if maximum >= limit { + return Err("audit capacity exceeded".into()); + } + let bytes = crate::binary::encode(&record)?; + if bytes.is_empty() || bytes.len() > MAX_AUDIT_RECORD_BYTES { + return Err("audit record exceeds bound".into()); + } + database(connection.execute( + "INSERT INTO audit_index(kind, identity, record) VALUES (?1, ?2, ?3)", + params![record.kind(), identity, bytes], + ))?; + let sequence = + u64::try_from(connection.last_insert_rowid()).map_err(|_| "invalid audit sequence")?; + if sequence != maximum + 1 { + return Err("audit sequence is not contiguous".into()); + } + Ok(sequence) +} + +fn require_audit(connection: &Connection) -> Result<(), String> { + let version: i64 = database(connection.query_row("PRAGMA user_version", [], |row| row.get(0)))?; + if !matches!( + version, + AUDIT_SCHEMA_VERSION | AUDIT_CREDENTIAL_SCHEMA_VERSION + ) || !audit_schema(connection)? + { + return Err("audit index is unavailable".into()); + } + Ok(()) +} + +fn audited_credential( + connection: &Connection, + operation_id: &str, +) -> Result, String> { + let Some(row) = audit_row_by_key(connection, 2, operation_id)? else { + return Ok(None); + }; + let StoredAuditDetail::Credential { + original, + attribution, + } = row.record.detail + else { + return Err("invalid audit credential record".into()); + }; + let receipt = credential_lookup(connection, operation_id, CredentialIndex::Operation)? + .ok_or("audit credential receipt is missing")?; + receipt.validate_request(&original)?; + Ok(Some((*original, attribution))) +} + +fn audited_recovery( + connection: &Connection, + recovery_id: &str, +) -> Result, String> { + let Some(row) = audit_row_by_key(connection, 3, recovery_id)? else { + return Ok(None); + }; + let StoredAuditDetail::Recovery { + original_operation_id, + action, + operator, + recorded_at_unix_millis, + } = row.record.detail + else { + return Err("invalid recovery audit record".into()); + }; + if audited_credential(connection, &original_operation_id)?.is_none() { + return Err("recovery audit original evidence is missing".into()); + } + Ok(Some(( + original_operation_id, + action, + operator, + recorded_at_unix_millis, + ))) +} + +fn audited_policy_decide( + connection: &Connection, + request: &PolicyUpdateRequest, + operator: &AuditOperator, +) -> Result { + ensure_audit_schema(connection)?; + let prior = receipt(connection, &request.operation_id)?; + let result = decide(connection, request)?; + if let Some(row) = audit_row_by_key(connection, 1, &request.operation_id)? { + let StoredAuditDetail::Policy { attribution } = row.record.detail else { + return Err("invalid audit policy record".into()); + }; + attribution.validate()?; + if prior.is_none() { + return Err("audit policy receipt is missing".into()); + } + return Ok(result); + } + let time = audit_now()?; + let attribution = if prior.is_some() { + audit_verify_contiguous(connection)?; + AuditAttribution::LegacyImported { + observer: operator.clone(), + observed_at_unix_millis: time, + } + } else { + AuditAttribution::Recorded { + operator: operator.clone(), + unix_millis: time, + } + }; + audit_insert( + connection, + &request.operation_id, + StoredAuditDetail::Policy { attribution }, + true, + )?; + Ok(result) +} + +pub(super) fn set_audited( + root: &Path, + request: &PolicyUpdateRequest, + operator: &AuditOperator, +) -> Result { + request.validate()?; + operator.validate()?; + let _process_lock = process_lock()?; + match existing(root)? { + Some(mut connection) => { + let tx = + database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + let result = audited_policy_decide(&tx, request, operator)?; + tx.commit().map_err(|error| { + format!("policy and audit outcome unknown; query the original operation: {error}") + })?; + Ok(result) + } + None => create_with_decision( + root, + |connection| audited_policy_decide(connection, request, operator), + |path| fs::remove_file(path), + crate::output::sync_directory, + ), + } +} + +pub(super) fn bootstrap_audited( + root: &Path, + policy: ServerPolicy, + operator: &AuditOperator, +) -> Result<(), String> { + let digest = policy.digest()?; + let request = PolicyUpdateRequest { + version: 1, + operation_id: digest, + expected_generation: 0, + policy, + }; + let result = set_audited(root, &request, operator)?; + if result.outcome != PolicyUpdateOutcome::Applied || result.generation != 1 { + return Err("policy bootstrap operation identity or generation conflict".into()); + } + Ok(()) +} + +fn audit_import_original( + connection: &Connection, + original: &OperationCredentialRequest, + operator: &AuditOperator, +) -> Result<(), String> { + original.validate()?; + operator.validate()?; + let expected = original.receipt()?; + let actual = credential_lookup( + connection, + &original.operation_id, + CredentialIndex::Operation, + )? + .ok_or("original credential receipt is missing")?; + if actual != expected { + return Err("original credential request does not match its receipt".into()); + } + if let Some((stored, _)) = audited_credential(connection, &original.operation_id)? { + if crate::binary::encode(&stored)? != crate::binary::encode(original)? { + return Err("original credential evidence conflict".into()); + } + return Ok(()); + } + audit_verify_contiguous(connection)?; + let attribution = AuditAttribution::LegacyImported { + observer: operator.clone(), + observed_at_unix_millis: audit_now()?, + }; + audit_insert( + connection, + &original.operation_id, + StoredAuditDetail::Credential { + original: Box::new(original.clone()), + attribution, + }, + true, + )?; + Ok(()) +} + +#[cfg(test)] +pub(super) fn audit_import_legacy( + root: &Path, + original: &OperationCredentialRequest, + operator: &AuditOperator, +) -> Result<(), String> { + original.validate()?; + operator.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + ensure_audit_schema(&tx)?; + current_in(&tx)?; + audit_import_original(&tx, original, operator)?; + tx.commit().map_err(|error| { + format!("legacy audit import outcome unknown; query the original operation: {error}") + }) +} + +pub(super) fn credential_issue_audited( + root: &Path, + original: &OperationCredentialRequest, + operator: &AuditOperator, +) -> Result { + let proposed = original.receipt()?; + operator.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + ensure_audit_schema(&tx)?; + let exists = current_in(&tx)?.operation_credentials; + let prior = if exists { + credential_lookup(&tx, &proposed.operation_id, CredentialIndex::Operation)? + } else { + None + }; + let result = credential_decide(&tx, &proposed)?; + if let Some((stored, _)) = audited_credential(&tx, &proposed.operation_id)? { + if crate::binary::encode(&stored)? != crate::binary::encode(original)? { + return Err("original credential evidence conflict".into()); + } + } else if prior.is_some() { + audit_import_original(&tx, original, operator)?; + } else { + let attribution = AuditAttribution::Recorded { + operator: operator.clone(), + unix_millis: audit_now()?, + }; + audit_insert( + &tx, + &proposed.operation_id, + StoredAuditDetail::Credential { + original: Box::new(original.clone()), + attribution, + }, + false, + )?; + } + tx.commit().map_err(|error| { + format!("credential and audit outcome unknown; query the original operation: {error}") + })?; + Ok(result) +} + +pub(super) fn audit_start_operation( + root: &Path, + credential: &OperationCredentialReceipt, + request: &Request, + payload_sha256: &str, +) -> Result { + credential.validate()?; + crate::binary::oid(payload_sha256)?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + require_audit(&tx)?; + let (original, attribution) = audited_credential(&tx, &credential.operation_id)? + .ok_or("original operation audit evidence is missing")?; + if matches!(attribution, AuditAttribution::LegacyImported { .. }) { + return Err("legacy imported credentials are limited to recovery".into()); + } + if original.receipt()? != *credential + || original.payload_sha256 != payload_sha256 + || crate::binary::encode(&original.request)? != crate::binary::encode(request)? + || request.credential_digest(payload_sha256)? != credential.request_sha256 + || request.credential_effect_key(&credential.actor)? != credential.effect_key + || credential.effect_key.is_none() + { + return Err("operation does not match its audited credential".into()); + } + let current = current_in(&tx)?; + let policy = current + .policy + .ok_or("authorization store is not initialized")?; + if current.generation != credential.policy_generation + || !policy + .principals + .iter() + .any(|principal| principal.name == credential.actor) + || audit_now()? / 1000 >= credential.expires_at + { + return Err("operation credential is no longer current".into()); + } + let attempt = audit_insert( + &tx, + &credential.operation_id, + StoredAuditDetail::OperationAttempt { + started_at_unix_millis: audit_now()?, + }, + false, + )?; + tx.commit().map_err(|error| { + format!("operation audit start outcome unknown; inspect the audit index: {error}") + })?; + Ok(attempt) +} + +pub(super) fn audit_operation_context( + root: &Path, + operation_id: &str, +) -> Result, String> { + crate::binary::oid(operation_id)?; + let _process_lock = process_lock()?; + let connection = existing(root)?.ok_or("authorization store is not initialized")?; + current_in(&connection)?; + let version: i64 = database(connection.query_row("PRAGMA user_version", [], |row| row.get(0)))?; + if !matches!( + version, + AUDIT_SCHEMA_VERSION | AUDIT_CREDENTIAL_SCHEMA_VERSION + ) { + return Ok(None); + } + require_audit(&connection)?; + Ok(audited_credential(&connection, operation_id)?.map(|(original, _)| original)) +} + +pub(super) fn audit_begin_recovery( + root: &Path, + recovery_id: &str, + original: &OperationCredentialRequest, + action: RecoveryAuditAction, + operator: &AuditOperator, +) -> Result { + crate::binary::oid(recovery_id)?; + original.validate()?; + operator.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + ensure_audit_schema(&tx)?; + current_in(&tx)?; + audit_import_original(&tx, original, operator)?; + if let Some((prior_original, prior_action, prior_operator, _)) = + audited_recovery(&tx, recovery_id)? + { + if prior_original != original.operation_id + || prior_action != action + || prior_operator != *operator + { + return Err("recovery audit identity conflict".into()); + } + } else { + audit_insert( + &tx, + recovery_id, + StoredAuditDetail::Recovery { + original_operation_id: original.operation_id.clone(), + action, + operator: operator.clone(), + recorded_at_unix_millis: audit_now()?, + }, + true, + )?; + } + let attempt = audit_insert( + &tx, + recovery_id, + StoredAuditDetail::RecoveryAttempt { + started_at_unix_millis: audit_now()?, + }, + true, + )?; + tx.commit().map_err(|error| { + format!("recovery audit start outcome unknown; inspect the audit index: {error}") + })?; + Ok(attempt) +} + +fn audit_target_context( + connection: &Connection, + target: &AuditTarget, +) -> Result<(AuditRow, OperationCredentialRequest), String> { + target.validate()?; + let (kind, identity, sequence) = match target { + AuditTarget::Operation { + operation_id, + attempt_id, + } => (4, operation_id, *attempt_id), + AuditTarget::Recovery { + recovery_id, + attempt_id, + } => (5, recovery_id, *attempt_id), + }; + let row = audit_row_by_sequence(connection, sequence)?.ok_or("audit attempt is missing")?; + if row.kind != kind || row.identity != *identity { + return Err("audit attempt identity mismatch".into()); + } + let operation_id = if kind == 4 { + identity.clone() + } else { + audited_recovery(connection, identity)? + .ok_or("recovery audit is missing")? + .0 + }; + let (original, _) = audited_credential(connection, &operation_id)? + .ok_or("original operation audit evidence is missing")?; + Ok((row, original)) +} + +fn audit_validate_scope( + original: &OperationCredentialRequest, + observation: &AuditObservation, +) -> Result<(), String> { + observation.validate()?; + let allowed = match &original.request.operation { + Operation::UploadChunk { .. } + | Operation::QueryChunk { .. } + | Operation::ScopedUploadSlice { .. } => matches!( + observation.scope, + AuditObservationScope::Chunk | AuditObservationScope::UploadSession + ), + Operation::ApplyScopedUpload { .. } + | Operation::CancelScopedUpload { .. } + | Operation::QueryScopedUpload { .. } => { + observation.scope == AuditObservationScope::UploadSession + } + Operation::ReleaseRetention { .. } => observation.scope == AuditObservationScope::Retention, + _ => false, + }; + if !allowed { + return Err("audit observation scope does not match the original operation".into()); + } + Ok(()) +} + +fn audit_write_observation( + connection: &Connection, + row: &AuditRow, + source: AuditObservationSource, + observation: &AuditObservation, +) -> Result<(), String> { + source.validate()?; + observation.validate()?; + if let Some(prior) = &row.observation { + if prior.source == source && prior.observation == *observation { + return Ok(()); + } + return Err("audit attempt observation conflict".into()); + } + let record = AuditRecordedObservation { + observed_at_unix_millis: audit_now()?, + source, + observation: observation.clone(), + }; + record.validate()?; + let bytes = crate::binary::encode(&record)?; + if bytes.len() > MAX_AUDIT_OBSERVATION_BYTES { + return Err("audit observation exceeds bound".into()); + } + let changed = database(connection.execute( + "UPDATE audit_index SET observation = ?1 WHERE sequence = ?2 AND observation IS NULL", + params![bytes, row.sequence as i64], + ))?; + if changed != 1 { + return Err("audit attempt observation changed concurrently".into()); + } + Ok(()) +} + +pub(super) fn audit_observe( + root: &Path, + target: &AuditTarget, + observation: &AuditObservation, +) -> Result<(), String> { + target.validate()?; + observation.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + require_audit(&tx)?; + let (row, original) = audit_target_context(&tx, target)?; + audit_validate_scope(&original, observation)?; + let source = match target { + AuditTarget::Operation { .. } => AuditObservationSource::OriginalAttempt, + AuditTarget::Recovery { + recovery_id, + attempt_id, + } => AuditObservationSource::RecoveryAttempt { + recovery_id: recovery_id.clone(), + attempt_id: *attempt_id, + }, + }; + audit_write_observation(&tx, &row, source, observation)?; + tx.commit().map_err(|error| { + format!("audit observation outcome unknown; inspect the original attempt: {error}") + }) +} + +/// The recovery attempt must itself already contain exactly this scoped +/// observation. Reconciliation records who made that observation and does not +/// assert that the target attempt caused the observed native state. +#[cfg(test)] +pub(super) fn audit_reconcile( + root: &Path, + recovery_id: &str, + recovery_attempt_id: u64, + target: &AuditTarget, + observation: &AuditObservation, +) -> Result<(), String> { + audit_reconcile_many( + root, + recovery_id, + recovery_attempt_id, + std::slice::from_ref(target), + observation, + ) +} + +pub(super) fn audit_reconcile_many( + root: &Path, + recovery_id: &str, + recovery_attempt_id: u64, + targets: &[AuditTarget], + observation: &AuditObservation, +) -> Result<(), String> { + let recovery = AuditTarget::Recovery { + recovery_id: recovery_id.into(), + attempt_id: recovery_attempt_id, + }; + recovery.validate()?; + if targets.len() > crate::protocol::AUDIT_PAGE_MAX_ITEMS as usize { + return Err("too many audit reconciliation targets".into()); + } + for target in targets { + target.validate()?; + if &recovery == target { + return Err("recovery cannot reconcile itself".into()); + } + } + observation.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + require_audit(&tx)?; + let (source_row, source_original) = audit_target_context(&tx, &recovery)?; + audit_validate_scope(&source_original, observation)?; + let source = AuditObservationSource::RecoveryAttempt { + recovery_id: recovery_id.into(), + attempt_id: recovery_attempt_id, + }; + match &source_row.observation { + Some(record) if record.source == source && record.observation == *observation => (), + _ => return Err("recovery attempt has no matching observation".into()), + } + for target in targets { + let (target_row, target_original) = audit_target_context(&tx, target)?; + if crate::binary::encode(&source_original)? != crate::binary::encode(&target_original)? { + return Err("recovery and target original operations differ".into()); + } + if let Some(prior) = &target_row.observation { + if matches!(&prior.source, AuditObservationSource::RecoveryAttempt { recovery_id: prior_id, .. } if prior_id == recovery_id) + { + // A retried recovery has a new observation attempt. Keep the + // earlier validated historical observation, not a rewritten + // claim that the original action caused today's state. + audit_check_observation_source(&tx, &target_row, &target_original)?; + continue; + } + } + audit_write_observation(&tx, &target_row, source.clone(), observation)?; + } + tx.commit().map_err(|error| { + format!("audit reconciliation outcome unknown; inspect the original attempt: {error}") + }) +} + +fn audit_check_observation_source( + connection: &Connection, + row: &AuditRow, + original: &OperationCredentialRequest, +) -> Result<(), String> { + let Some(observation) = &row.observation else { + return Ok(()); + }; + audit_validate_scope(original, &observation.observation)?; + match &observation.source { + AuditObservationSource::OriginalAttempt if row.kind == 4 => Ok(()), + AuditObservationSource::OriginalAttempt => Err("invalid audit observation source".into()), + AuditObservationSource::RecoveryAttempt { + recovery_id, + attempt_id, + } => { + let source = AuditTarget::Recovery { + recovery_id: recovery_id.clone(), + attempt_id: *attempt_id, + }; + let (source_row, source_original) = audit_target_context(connection, &source)?; + if crate::binary::encode(&source_original)? != crate::binary::encode(original)? { + return Err("audit observation source has a different original operation".into()); + } + if source_row.sequence != row.sequence { + let expected = AuditObservationSource::RecoveryAttempt { + recovery_id: recovery_id.clone(), + attempt_id: *attempt_id, + }; + match source_row.observation { + Some(source_observation) + if source_observation.source == expected + && source_observation.observation == observation.observation => {} + _ => return Err("audit recovery observation source is missing".into()), + } + } + Ok(()) + } + } +} + +fn audit_summary(connection: &Connection, row: AuditRow) -> Result { + let item = match &row.record.detail { + StoredAuditDetail::Policy { attribution } => { + let receipt = + receipt(connection, &row.identity)?.ok_or("audit policy receipt is missing")?; + AuditItem::Policy { + receipt, + attribution: attribution.clone(), + } + } + StoredAuditDetail::Credential { .. } => { + let (original, attribution) = audited_credential(connection, &row.identity)? + .ok_or("audit credential evidence is missing")?; + let receipt = original.receipt()?; + AuditItem::Credential { + operation_id: row.identity.clone(), + scope: AuditOperationScope::from_original(&original)?, + request_sha256: receipt.request_sha256, + attribution, + } + } + StoredAuditDetail::Recovery { .. } => { + let (operation_id, action, operator, recorded_at_unix_millis) = + audited_recovery(connection, &row.identity)?.ok_or("recovery audit is missing")?; + let (original, _) = audited_credential(connection, &operation_id)? + .ok_or("original audit evidence is missing")?; + AuditItem::Recovery { + recovery_id: row.identity.clone(), + original_operation_id: operation_id, + scope: AuditOperationScope::from_original(&original)?, + action, + operator, + recorded_at_unix_millis, + } + } + StoredAuditDetail::OperationAttempt { + started_at_unix_millis, + } => { + let (original, _) = audited_credential(connection, &row.identity)? + .ok_or("original audit evidence is missing")?; + audit_check_observation_source(connection, &row, &original)?; + AuditItem::OperationAttempt { + operation_id: row.identity.clone(), + scope: AuditOperationScope::from_original(&original)?, + started_at_unix_millis: *started_at_unix_millis, + observation: row.observation.clone(), + } + } + StoredAuditDetail::RecoveryAttempt { + started_at_unix_millis, + } => { + let (operation_id, action, operator, _) = + audited_recovery(connection, &row.identity)?.ok_or("recovery audit is missing")?; + let (original, _) = audited_credential(connection, &operation_id)? + .ok_or("original audit evidence is missing")?; + audit_check_observation_source(connection, &row, &original)?; + AuditItem::RecoveryAttempt { + recovery_id: row.identity.clone(), + original_operation_id: operation_id, + scope: AuditOperationScope::from_original(&original)?, + action, + operator, + started_at_unix_millis: *started_at_unix_millis, + observation: row.observation.clone(), + } + } + }; + let summary = AuditSummary { + version: 1, + sequence: row.sequence, + item, + }; + summary.validate()?; + Ok(summary) +} + +pub(super) fn audit_query( + root: &Path, + request: &AuditQueryRequest, +) -> Result { + request.validate()?; + let _process_lock = process_lock()?; + let mut connection = existing(root)?.ok_or("authorization store is not initialized")?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Deferred))?; + require_audit(&tx)?; + current_in(&tx)?; + let current_high_water = audit_high_water(&tx)?; + let high_water = request.high_water.unwrap_or(current_high_water); + if high_water > current_high_water || request.after > high_water { + return Err("invalid audit page high-water mark".into()); + } + let mut items = Vec::new(); + let mut last = request.after; + { + let mut statement = database(tx.prepare( + "SELECT sequence, kind, identity, record, observation FROM audit_index WHERE sequence > ?1 AND sequence <= ?2 ORDER BY sequence LIMIT ?3", + ))?; + let mut rows = database(statement.query(params![ + request.after as i64, + high_water as i64, + request.limit as i64 + ]))?; + while let Some(raw) = database(rows.next())? { + let row = decode_audit_row(database(raw_audit_row(raw))?)?; + if row.sequence != last + 1 { + return Err("audit page sequence gap".into()); + } + let summary = audit_summary(&tx, row)?; + let candidate_last = summary.sequence; + items.push(summary); + let candidate = AuditQueryReply { + version: 1, + high_water, + max_admission_entries: MAX_AUDIT_ADMISSION_ENTRIES, + items: items.clone(), + next_after: (candidate_last < high_water).then_some(candidate_last), + }; + if serde_json::to_vec(&candidate) + .map_err(|error| error.to_string())? + .len() + > AUDIT_PAGE_MAX_BYTES + { + items.pop(); + if items.is_empty() { + return Err("audit summary exceeds page bound".into()); + } + break; + } + last = candidate_last; + } + } + if items.len() < request.limit as usize && last < high_water { + // A byte-bounded page may stop before its item limit. The next row must + // nevertheless exist; a later page validates and returns it. + if audit_row_by_sequence(&tx, last + 1)?.is_none() { + return Err("audit page sequence gap".into()); + } + } + let reply = AuditQueryReply { + version: 1, + high_water, + max_admission_entries: MAX_AUDIT_ADMISSION_ENTRIES, + items, + next_after: (last < high_water).then_some(last), + }; + reply.validate_for(request)?; + database(tx.commit())?; + Ok(reply) +} + +pub(super) fn migration_receipt( + root: &Path, + request: &PolicyMigrationRequest, +) -> Result { + request.validate()?; + let _process_lock = process_lock()?; + let connection = existing(root)?.ok_or("authorization store is not initialized")?; + current_in(&connection)?; + let bytes: Vec = database(connection.query_row( + "SELECT receipt FROM policy_migration WHERE singleton = 1", + [], + |row| row.get(0), + ))?; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("policy migration receipt exceeds bound".into()); + } + let receipt: PolicyMigrationReceipt = crate::binary::decode(&bytes)?; + receipt.validate_request(request)?; + Ok(receipt) +} + +fn source_digest(path: &Path) -> Result { + let metadata = + fs::symlink_metadata(path).map_err(|error| format!("inspect legacy policy: {error}"))?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > MAX_POLICY_BYTES as u64 + { + return Err("legacy policy must be a bounded regular file".into()); + } + let bytes = fs::read(path).map_err(|error| format!("read legacy policy: {error}"))?; + if !bytes.starts_with(LEGACY_HEADER) { + return Err("legacy policy format changed during migration".into()); + } + Ok(format!("{:x}", Sha256::digest(&bytes))) +} + +pub(super) fn migrate( + root: &Path, + policy: Option<&ServerPolicy>, + generation: u64, + receipts: &BTreeMap, + migration: &PolicyMigrationReceipt, +) -> Result<(), String> { + let _process_lock = process_lock()?; + migrate_with_sync( + root, + policy, + generation, + receipts, + migration, + crate::output::sync_directory, + ) +} + +fn migrate_with_sync( + root: &Path, + policy: Option<&ServerPolicy>, + generation: u64, + receipts: &BTreeMap, + migration: &PolicyMigrationReceipt, + sync_directory: impl FnOnce(&Path) -> Result<(), String>, +) -> Result<(), String> { + migration.validate()?; + if migration.generation != generation + || migration.receipts != receipts.len() as u64 + || migration.policy_sha256 != policy.map(ServerPolicy::digest).transpose()? + { + return Err("legacy policy migration receipt does not match the source".into()); + } + let source = root.join(FILE); + if source_digest(&source)? != migration.source_sha256 { + return Err("legacy policy source digest mismatch".into()); + } + let mut staging = stage(root)?; + let mut connection = connect(&staging.path)?; + let tx = database(connection.transaction_with_behavior(TransactionBehavior::Immediate))?; + database(tx.execute_batch(SCHEMA))?; + let mut current_operation = None; + for (id, receipt) in receipts { + receipt.validate()?; + if &receipt.operation_id != id { + return Err("legacy policy receipt identity mismatch".into()); + } + let applied = if receipt.outcome == PolicyUpdateOutcome::Applied { + if receipt.generation == generation { + current_operation = Some(id.clone()); + } + Some(receipt.generation as i64) + } else { + None + }; + let bytes = crate::binary::encode(receipt)?; + if bytes.len() > MAX_RECEIPT_BYTES { + return Err("legacy policy receipt exceeds bound".into()); + } + database(tx.execute("INSERT INTO policy_receipts(operation_id, applied_generation, receipt) VALUES (?1, ?2, ?3)", params![id, applied, bytes]))?; + } + if generation > 0 { + let policy = policy.ok_or("legacy current policy is missing")?; + let bytes = crate::binary::encode(policy)?; + if bytes.len() > MAX_POLICY_BYTES { + return Err("legacy policy exceeds bound".into()); + } + let digest = policy.digest()?; + let operation = current_operation.ok_or("legacy current policy receipt is missing")?; + database(tx.execute("UPDATE policy_current SET generation = ?1, policy = ?2, policy_sha256 = ?3, current_operation = ?4 WHERE singleton = 1 AND generation = 0", + params![generation as i64, bytes, digest, operation]))?; + } else if policy.is_some() { + return Err("legacy uninitialized policy is invalid".into()); + } + current_in(&tx)?; + database(tx.execute( + "INSERT INTO policy_migration(singleton, receipt) VALUES (1, ?1)", + [crate::binary::encode(migration)?], + ))?; + database(tx.commit())?; + seal(connection, &staging.path)?; + if source_digest(&source)? != migration.source_sha256 { + return Err("legacy policy changed during migration".into()); + } + fs::rename(&staging.path, &source) + .map_err(|error| format!("publish migrated policy database: {error}"))?; + staging.cleanup = false; + sync_directory(root).map_err(|error| { + format!("policy migration outcome unknown; retry the original migration: {error}") + })?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "wasm-git-policy-sqlite-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&root).unwrap(); + Self(root) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + fn policy() -> ServerPolicy { + ServerPolicy { + version: crate::protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + } + } + fn update(id: String, generation: u64, policy: ServerPolicy) -> PolicyUpdateRequest { + PolicyUpdateRequest { + version: 1, + operation_id: id, + expected_generation: generation, + policy, + } + } + + fn policy_with_principals() -> ServerPolicy { + use crate::protocol::PolicyPrincipal; + ServerPolicy { + version: crate::protocol::SERVER_POLICY_VERSION, + principals: vec![ + PolicyPrincipal { + name: "alice".into(), + token_sha256: Some("a".repeat(64)), + grants: Vec::new(), + }, + PolicyPrincipal { + name: "bob".into(), + token_sha256: None, + grants: Vec::new(), + }, + ], + } + } + + fn credential(index: u64) -> OperationCredentialReceipt { + OperationCredentialReceipt { + version: 1, + operation_id: format!("{index:064x}"), + actor: "alice".into(), + policy_generation: 1, + token_sha256: format!("{:064x}", index + 10_000), + request_sha256: format!("{:064x}", index + 20_000), + effect_key: Some(format!("{:064x}", index + 30_000)), + expires_at: NODE_SAFE_INTEGER_MAX, + } + } + + fn audit_operator(name: &str) -> AuditOperator { + AuditOperator { + version: 1, + identity: name.into(), + } + } + + fn audit_original(index: u64) -> OperationCredentialRequest { + use crate::protocol::RetentionCommand; + OperationCredentialRequest { + version: 1, + operation_id: format!("{index:064x}"), + policy_generation: 1, + actor: "alice".into(), + token_sha256: format!("{:064x}", index + 10_000), + request: Request { + version: 1, + repository: "project".into(), + operation: Operation::ReleaseRetention { + command: RetentionCommand::Prepare { + operation: format!("{:064x}", index + 20_000), + commit: "c".repeat(64), + paths: vec!["module.wasm".into()], + }, + }, + }, + payload_sha256: format!("{:x}", Sha256::digest([])), + expires_at: NODE_SAFE_INTEGER_MAX, + } + } + + fn audit_page(root: &Path) -> AuditQueryReply { + audit_query( + root, + &AuditQueryRequest { + version: 1, + after: 0, + high_water: None, + limit: 100, + }, + ) + .unwrap() + } + + #[test] + fn audited_policy_and_credentials_commit_together_and_page_at_a_fixed_watermark() { + let root = Temp::new(); + let operator = audit_operator("unix:uid:1000"); + let policy = update("f".repeat(64), 0, policy_with_principals()); + assert_eq!( + set_audited(&root.0, &policy, &operator).unwrap().generation, + 1 + ); + let state = current(&root.0).unwrap().unwrap(); + assert!(!state.operation_credentials && !state.chunk_receipts); + assert_eq!( + existing(&root.0) + .unwrap() + .unwrap() + .query_row("PRAGMA user_version", [], |row| row.get::<_, i64>(0)) + .unwrap(), + AUDIT_SCHEMA_VERSION + ); + let original = audit_original(1); + let receipt = credential_issue_audited(&root.0, &original, &operator).unwrap(); + assert_eq!(receipt, original.receipt().unwrap()); + assert_eq!( + crate::binary::encode( + &audit_operation_context(&root.0, &original.operation_id) + .unwrap() + .unwrap() + ) + .unwrap(), + crate::binary::encode(&original).unwrap() + ); + assert!(current(&root.0).unwrap().unwrap().chunk_receipts); + let first_request = AuditQueryRequest { + version: 1, + after: 0, + high_water: None, + limit: 1, + }; + let first = audit_query(&root.0, &first_request).unwrap(); + assert_eq!(first.high_water, 2); + assert_eq!(first.next_after, Some(1)); + assert!( + matches!(&first.items[0].item, AuditItem::Policy { attribution: AuditAttribution::Recorded { operator: actual, .. }, .. } if actual == &operator) + ); + let attempt = audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + assert_eq!(attempt, 3); + let next = audit_query( + &root.0, + &AuditQueryRequest { + version: 1, + after: 1, + high_water: Some(first.high_water), + limit: 2, + }, + ) + .unwrap(); + assert_eq!(next.items.len(), 1); + assert_eq!(next.items[0].sequence, 2); + assert_eq!(next.next_after, None); + assert_eq!(audit_page(&root.0).high_water, 3); + let changed_operator = audit_operator("unix:uid:2000"); + credential_issue_audited(&root.0, &original, &changed_operator).unwrap(); + set_audited(&root.0, &policy, &changed_operator).unwrap(); + let records = audit_page(&root.0); + assert_eq!(records.items.len(), 3); + assert!( + matches!(&records.items[1].item, AuditItem::Credential { attribution: AuditAttribution::Recorded { operator: actual, .. }, .. } if actual == &operator) + ); + assert!( + audit_start_operation(&root.0, &receipt, &original.request, &"0".repeat(64)).is_err() + ); + } + + #[test] + fn attempts_are_independent_and_recovery_observes_without_claiming_the_effect() { + let root = Temp::new(); + let issuer = audit_operator("unix:uid:1000"); + let recovery_operator = audit_operator("unix:uid:2000"); + bootstrap_audited(&root.0, policy_with_principals(), &issuer).unwrap(); + let original = audit_original(2); + let receipt = credential_issue_audited(&root.0, &original, &issuer).unwrap(); + let first = audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + let second = audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + assert_ne!(first, second); + let observation = AuditObservation { + version: 1, + scope: AuditObservationScope::Retention, + evidence: AuditEvidenceObservation::Unobserved, + }; + let first_target = AuditTarget::Operation { + operation_id: original.operation_id.clone(), + attempt_id: first, + }; + let second_target = AuditTarget::Operation { + operation_id: original.operation_id.clone(), + attempt_id: second, + }; + audit_observe(&root.0, &first_target, &observation).unwrap(); + audit_observe(&root.0, &first_target, &observation).unwrap(); + let different = AuditObservation { + evidence: AuditEvidenceObservation::Unknown, + ..observation.clone() + }; + assert!(audit_observe(&root.0, &first_target, &different).is_err()); + assert!(matches!( + &audit_page(&root.0).items[(second - 1) as usize].item, + AuditItem::OperationAttempt { + observation: None, + .. + } + )); + let revoked = update("d".repeat(64), 1, policy()); + set_audited(&root.0, &revoked, &issuer).unwrap(); + assert!(audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256 + ) + .is_err()); + let recovery_id = "e".repeat(64); + let recovery_attempt = audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Inspect, + &recovery_operator, + ) + .unwrap(); + assert!(audit_reconcile( + &root.0, + &recovery_id, + recovery_attempt, + &second_target, + &observation + ) + .is_err()); + let recovery_target = AuditTarget::Recovery { + recovery_id: recovery_id.clone(), + attempt_id: recovery_attempt, + }; + audit_observe(&root.0, &recovery_target, &observation).unwrap(); + audit_reconcile( + &root.0, + &recovery_id, + recovery_attempt, + &second_target, + &observation, + ) + .unwrap(); + audit_reconcile( + &root.0, + &recovery_id, + recovery_attempt, + &second_target, + &observation, + ) + .unwrap(); + assert!(audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Close, + &recovery_operator + ) + .is_err()); + let repeated = audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Inspect, + &recovery_operator, + ) + .unwrap(); + assert_ne!(recovery_attempt, repeated); + let page = audit_page(&root.0); + assert!(matches!(&page.items[(second - 1) as usize].item, + AuditItem::OperationAttempt { observation: Some(AuditRecordedObservation { + source: AuditObservationSource::RecoveryAttempt { recovery_id: actual, attempt_id }, + observation: AuditObservation { evidence: AuditEvidenceObservation::Unobserved, .. }, .. }), .. } + if actual == &recovery_id && *attempt_id == recovery_attempt)); + assert!(matches!( + &page.items[(repeated - 1) as usize].item, + AuditItem::RecoveryAttempt { + observation: None, + .. + } + )); + } + + #[test] + fn legacy_credential_import_validates_the_exact_original_and_never_invents_issuer() { + let root = Temp::new(); + old_v2(&root.0); + let original = audit_original(3); + let receipt = credential_issue(&root.0, &original.receipt().unwrap()).unwrap(); + assert!(audit_operation_context(&root.0, &original.operation_id) + .unwrap() + .is_none()); + let operator = audit_operator("unix:uid:2000"); + let mut changed = original.clone(); + changed.payload_sha256 = "0".repeat(64); + assert!(audit_import_legacy(&root.0, &changed, &operator).is_err()); + audit_import_legacy(&root.0, &original, &operator).unwrap(); + assert!( + matches!(&audit_page(&root.0).items[0].item, AuditItem::Credential { + attribution: AuditAttribution::LegacyImported { observer, .. }, .. } if observer == &operator) + ); + assert!(audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256 + ) + .is_err()); + assert!(audit_begin_recovery( + &root.0, + &"d".repeat(64), + &original, + RecoveryAuditAction::Inspect, + &operator + ) + .is_ok()); + } + + #[test] + fn recovery_reconciliation_is_atomic_and_replay_preserves_prior_observations() { + let root = Temp::new(); + let operator = audit_operator("unix:uid:1000"); + bootstrap_audited(&root.0, policy_with_principals(), &operator).unwrap(); + let original = audit_original(72); + let receipt = credential_issue_audited(&root.0, &original, &operator).unwrap(); + let first = audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + let second = audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + let targets = [first, second].map(|attempt_id| AuditTarget::Operation { + operation_id: original.operation_id.clone(), + attempt_id, + }); + let recovery_id = "c".repeat(64); + let attempt = audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Inspect, + &operator, + ) + .unwrap(); + let observation = AuditObservation { + version: 1, + scope: AuditObservationScope::Retention, + evidence: AuditEvidenceObservation::Unobserved, + }; + audit_observe( + &root.0, + &AuditTarget::Recovery { + recovery_id: recovery_id.clone(), + attempt_id: attempt, + }, + &observation, + ) + .unwrap(); + let bad = AuditTarget::Operation { + operation_id: original.operation_id.clone(), + attempt_id: 9999, + }; + assert!(audit_reconcile_many( + &root.0, + &recovery_id, + attempt, + &[targets[0].clone(), bad], + &observation + ) + .is_err()); + assert!(matches!( + &audit_page(&root.0).items[(first - 1) as usize].item, + AuditItem::OperationAttempt { + observation: None, + .. + } + )); + audit_reconcile_many(&root.0, &recovery_id, attempt, &targets, &observation).unwrap(); + let repeated = audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Inspect, + &operator, + ) + .unwrap(); + let later = AuditObservation { + evidence: AuditEvidenceObservation::Unknown, + ..observation + }; + audit_observe( + &root.0, + &AuditTarget::Recovery { + recovery_id: recovery_id.clone(), + attempt_id: repeated, + }, + &later, + ) + .unwrap(); + audit_reconcile_many(&root.0, &recovery_id, repeated, &targets, &later).unwrap(); + assert!( + matches!(&audit_page(&root.0).items[(first - 1) as usize].item, + AuditItem::OperationAttempt { observation: Some(AuditRecordedObservation { + source: AuditObservationSource::RecoveryAttempt { attempt_id, .. }, + observation: AuditObservation { evidence: AuditEvidenceObservation::Unobserved, .. }, .. }), .. } if *attempt_id == attempt) + ); + } + + #[test] + fn audit_admission_watermark_does_not_exhaust_recovery_capacity() { + let root = Temp::new(); + let operator = audit_operator("unix:uid:1000"); + bootstrap_audited(&root.0, policy_with_principals(), &operator).unwrap(); + let original = audit_original(73); + credential_issue_audited(&root.0, &original, &operator).unwrap(); + let recovery_id = "b".repeat(64); + audit_begin_recovery( + &root.0, + &recovery_id, + &original, + RecoveryAuditAction::Close, + &operator, + ) + .unwrap(); + let connection = existing(&root.0).unwrap().unwrap(); + let watermark = audit_high_water(&connection).unwrap(); + let start = audit_now().unwrap(); + assert!(audit_insert_with_limit( + &connection, + &original.operation_id, + StoredAuditDetail::OperationAttempt { + started_at_unix_millis: start + }, + false, + watermark + ) + .is_err()); + audit_insert_with_limit( + &connection, + &recovery_id, + StoredAuditDetail::RecoveryAttempt { + started_at_unix_millis: start, + }, + true, + watermark, + ) + .unwrap(); + assert_eq!(audit_high_water(&connection).unwrap(), watermark + 1); + drop(connection); + assert_eq!(audit_page(&root.0).items.len() as u64, watermark + 1); + } + + #[test] + fn failed_audit_insert_rolls_back_policy_and_credential_decisions() { + let root = Temp::new(); + let operator = audit_operator("unix:uid:1000"); + bootstrap_audited(&root.0, policy_with_principals(), &operator).unwrap(); + let connection = existing(&root.0).unwrap().unwrap(); + connection.execute_batch("CREATE TRIGGER injected_audit_failure BEFORE INSERT ON audit_index BEGIN SELECT RAISE(ABORT, 'injected audit failure'); END").unwrap(); + drop(connection); + let original = audit_original(4); + assert!(credential_issue_audited(&root.0, &original, &operator).is_err()); + assert!(!current(&root.0).unwrap().unwrap().operation_credentials); + let policy = update("b".repeat(64), 1, policy_with_principals()); + assert!(set_audited(&root.0, &policy, &operator).is_err()); + assert_eq!(status(&root.0).unwrap().generation, 1); + assert!(query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: policy.operation_id.clone() + } + ) + .unwrap() + .receipt + .is_none()); + let connection = existing(&root.0).unwrap().unwrap(); + connection + .execute_batch("DROP TRIGGER injected_audit_failure") + .unwrap(); + drop(connection); + assert!(credential_issue_audited(&root.0, &original, &operator).is_ok()); + assert_eq!( + set_audited(&root.0, &policy, &operator).unwrap().generation, + 2 + ); + } + + #[test] + fn corrupt_or_missing_audit_entries_fail_closed() { + let root = Temp::new(); + let operator = audit_operator("unix:uid:1000"); + bootstrap_audited(&root.0, policy_with_principals(), &operator).unwrap(); + let original = audit_original(5); + let receipt = credential_issue_audited(&root.0, &original, &operator).unwrap(); + audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256, + ) + .unwrap(); + let connection = existing(&root.0).unwrap().unwrap(); + connection + .execute_batch( + "DROP TRIGGER audit_no_delete; DELETE FROM audit_index WHERE sequence = 2", + ) + .unwrap(); + connection.execute_batch(AUDIT_NO_DELETE_SQL).unwrap(); + drop(connection); + assert!(audit_query( + &root.0, + &AuditQueryRequest { + version: 1, + after: 0, + high_water: None, + limit: 100 + } + ) + .is_err()); + assert!(audit_import_legacy(&root.0, &original, &operator).is_err()); + assert!(audit_start_operation( + &root.0, + &receipt, + &original.request, + &original.payload_sha256 + ) + .is_err()); + } + + fn old_v2(root: &Path) { + let path = root.join(FILE); + drop( + OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .unwrap(), + ); + let mut connection = connect(&path).unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + tx.execute_batch(SCHEMA).unwrap(); + decide(&tx, &update("f".repeat(64), 0, policy_with_principals())).unwrap(); + tx.commit().unwrap(); + } + + fn install_v3_credential(root: &Path, record: &OperationCredentialReceipt) { + record.validate().unwrap(); + let mut connection = existing(root).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + assert_eq!(credential_features(&tx).unwrap(), (false, false)); + create_credential_schema(&tx).unwrap(); + tx.execute_batch("PRAGMA user_version = 3").unwrap(); + tx.execute( + "INSERT INTO operation_credentials(operation_id, token_sha256, effect_key, receipt) VALUES (?1, ?2, ?3, ?4)", + params![record.operation_id, record.token_sha256, record.effect_key, crate::binary::encode(record).unwrap()], + ) + .unwrap(); + tx.commit().unwrap(); + } + + #[test] + fn old_v2_credentials_initialize_atomically_without_changing_policy() { + let root = Temp::new(); + old_v2(&root.0); + let record = credential(1); + assert!(credential_query(&root.0, &record.operation_id) + .unwrap() + .is_none()); + assert!(credential_by_token(&root.0, &record.token_sha256) + .unwrap() + .is_none()); + assert!(!credential_schema(&existing(&root.0).unwrap().unwrap()).unwrap()); + let initial = current(&root.0).unwrap().unwrap(); + assert!(!initial.operation_credentials); + assert!(!initial.chunk_receipts); + let before = status(&root.0).unwrap(); + assert_eq!(credential_issue(&root.0, &record).unwrap(), record); + assert_eq!( + credential_query(&root.0, &record.operation_id).unwrap(), + Some(record.clone()) + ); + assert_eq!( + credential_by_token(&root.0, &record.token_sha256).unwrap(), + Some(record) + ); + let after = status(&root.0).unwrap(); + assert_eq!(before.generation, after.generation); + assert_eq!(before.policy_sha256, after.policy_sha256); + let connection = existing(&root.0).unwrap().unwrap(); + assert!(credential_schema(&connection).unwrap()); + let version: i64 = connection + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .unwrap(); + assert_eq!(version, CHUNK_RECEIPT_SCHEMA_VERSION); + assert_ne!(version, SCHEMA_VERSION); + assert_ne!(version, CREDENTIAL_SCHEMA_VERSION); + let current = current_in(&connection).unwrap(); + assert!(current.operation_credentials); + assert!(current.chunk_receipts); + assert!(connection + .execute( + "UPDATE operation_credentials SET token_sha256 = ?1", + ["b".repeat(64)] + ) + .is_err()); + assert!(connection + .execute("DELETE FROM operation_credentials", []) + .is_err()); + } + + #[test] + fn v3_history_replays_without_upgrade_and_fresh_issue_upgrades_atomically() { + let root = Temp::new(); + old_v2(&root.0); + let mut original = credential(1); + original.expires_at = 1; + install_v3_credential(&root.0, &original); + + let before = status(&root.0).unwrap(); + let state = current(&root.0).unwrap().unwrap(); + assert!(state.operation_credentials); + assert!(!state.chunk_receipts); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original.clone()) + ); + assert_eq!( + credential_by_token(&root.0, &original.token_sha256).unwrap(), + Some(original.clone()) + ); + assert_eq!(credential_issue(&root.0, &original).unwrap(), original); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + + let mut duplicate_token = credential(3); + duplicate_token.token_sha256 = original.token_sha256.clone(); + assert!(credential_issue(&root.0, &duplicate_token).is_err()); + let mut duplicate_effect = credential(4); + duplicate_effect.effect_key = original.effect_key.clone(); + assert!(credential_issue(&root.0, &duplicate_effect).is_err()); + let mut stale = credential(5); + stale.policy_generation = 2; + assert!(credential_issue(&root.0, &stale).is_err()); + let mut missing_actor = credential(6); + missing_actor.actor = "missing".into(); + assert!(credential_issue(&root.0, &missing_actor).is_err()); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + + let fresh = credential(2); + let mut connection = existing(&root.0).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + let error = credential_decide_with_check(&tx, &fresh, || { + assert_eq!(credential_features(&tx).unwrap(), (true, true)); + Err("injected expired authority".into()) + }) + .unwrap_err(); + assert!(error.contains("expired")); + drop(tx); + drop(connection); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + assert!(credential_query(&root.0, &fresh.operation_id) + .unwrap() + .is_none()); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original.clone()) + ); + + let mut expired = fresh.clone(); + expired.expires_at = 1; + assert!(credential_issue(&root.0, &expired).is_err()); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + assert_eq!(credential_issue(&root.0, &fresh).unwrap(), fresh); + let state = current(&root.0).unwrap().unwrap(); + assert!(state.operation_credentials && state.chunk_receipts); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original) + ); + let after = status(&root.0).unwrap(); + assert_eq!(before.generation, after.generation); + assert_eq!(before.policy_sha256, after.policy_sha256); + } + + #[test] + fn v3_to_v4_disk_full_rolls_back_version_and_new_receipts() { + let root = Temp::new(); + old_v2(&root.0); + let original = credential(1); + install_v3_credential(&root.0, &original); + let mut connection = existing(&root.0).unwrap().unwrap(); + let pages: i64 = connection + .query_row("PRAGMA page_count", [], |row| row.get(0)) + .unwrap(); + let maximum: i64 = connection + .query_row(&format!("PRAGMA max_page_count = {pages}"), [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(maximum, pages); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + let mut full = false; + for index in 2..=1000 { + if let Err(error) = credential_decide(&tx, &credential(index)) { + assert!(error.to_ascii_lowercase().contains("full"), "{error}"); + full = true; + break; + } + } + assert!(full, "database did not reach its fixed page limit"); + drop(tx); + drop(connection); + let state = current(&root.0).unwrap().unwrap(); + assert!(state.operation_credentials); + assert!(!state.chunk_receipts); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original) + ); + assert!(credential_query(&root.0, &credential(2).operation_id) + .unwrap() + .is_none()); + assert_eq!( + credential_issue(&root.0, &credential(2)).unwrap(), + credential(2) + ); + assert!(current(&root.0).unwrap().unwrap().chunk_receipts); + } + + #[test] + fn v3_policy_updates_keep_history_and_reject_credential_token_collisions() { + let root = Temp::new(); + old_v2(&root.0); + let original = credential(1); + install_v3_credential(&root.0, &original); + let mut collision = policy_with_principals(); + collision.principals[1].token_sha256 = Some(original.token_sha256.clone()); + assert!(set(&root.0, &update("a".repeat(64), 1, collision)) + .unwrap_err() + .contains("collides with an operation credential")); + assert_eq!(status(&root.0).unwrap().generation, 1); + let applied = set( + &root.0, + &update("b".repeat(64), 1, policy_with_principals()), + ) + .unwrap(); + assert_eq!(applied.generation, 2); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + assert_eq!(credential_issue(&root.0, &original).unwrap(), original); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + let prior = query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: "f".repeat(64), + }, + ) + .unwrap() + .receipt + .unwrap(); + assert_eq!(prior.generation, 1); + let mut fresh = credential(2); + fresh.policy_generation = 2; + credential_issue(&root.0, &fresh).unwrap(); + assert!(current(&root.0).unwrap().unwrap().chunk_receipts); + assert_eq!(status(&root.0).unwrap().generation, 2); + } + + #[test] + fn v1_migration_receipt_remains_queryable_in_v3_and_v4() { + let root = Temp::new(); + let source = include_bytes!("../../../tests/fixtures/policy-v1.bin"); + fs::write(root.0.join(FILE), source).unwrap(); + let request = PolicyMigrationRequest { + version: 1, + source_sha256: format!("{:x}", Sha256::digest(source)), + }; + let initial = super::super::migrate(&root.0, &request).unwrap(); + set( + &root.0, + &update("d".repeat(64), 1, policy_with_principals()), + ) + .unwrap(); + let mut original = credential(1); + original.policy_generation = 2; + install_v3_credential(&root.0, &original); + assert!(current(&root.0).unwrap().unwrap().operation_credentials); + assert!(!current(&root.0).unwrap().unwrap().chunk_receipts); + let v3 = super::super::migrate(&root.0, &request).unwrap(); + assert_eq!(v3.generation, initial.generation); + assert_eq!(v3.receipts, initial.receipts); + assert_eq!(v3.policy_sha256, initial.policy_sha256); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original) + ); + let mut fresh = credential(2); + fresh.policy_generation = 2; + credential_issue(&root.0, &fresh).unwrap(); + assert!(current(&root.0).unwrap().unwrap().chunk_receipts); + let v4 = super::super::migrate(&root.0, &request).unwrap(); + assert_eq!(v4.generation, initial.generation); + assert_eq!(v4.receipts, initial.receipts); + assert_eq!(v4.policy_sha256, initial.policy_sha256); + assert_eq!(status(&root.0).unwrap().generation, 2); + } + + #[test] + fn credential_replay_and_collision_rules_survive_principal_removal() { + let root = Temp::new(); + set( + &root.0, + &update("f".repeat(64), 0, policy_with_principals()), + ) + .unwrap(); + let mut first = credential(1); + first.expires_at = 1; + // Simulate issuance while this deadline was current, then exercise + // replay and uniqueness after its deadline has passed. + let mut connection = existing(&root.0).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + assert_eq!( + credential_decide_with_check(&tx, &first, || Ok(())).unwrap(), + first + ); + tx.commit().unwrap(); + drop(connection); + assert_eq!(credential_issue(&root.0, &first).unwrap(), first); + for field in 0..6 { + let mut changed = first.clone(); + match field { + 0 => changed.actor = "bob".into(), + 1 => changed.token_sha256 = "b".repeat(64), + 2 => changed.request_sha256 = "c".repeat(64), + 3 => changed.expires_at += 1, + 4 => changed.effect_key = None, + _ => changed.policy_generation += 1, + } + assert!(credential_issue(&root.0, &changed) + .unwrap_err() + .contains("identity conflict")); + } + let mut same_token = credential(2); + same_token.token_sha256 = first.token_sha256.clone(); + assert!(credential_issue(&root.0, &same_token) + .unwrap_err() + .contains("token is already assigned")); + let mut same_effect = credential(3); + same_effect.effect_key = first.effect_key.clone(); + assert!(credential_issue(&root.0, &same_effect) + .unwrap_err() + .contains("effect is already assigned")); + let mut same_principal_token = credential(4); + same_principal_token.token_sha256 = "a".repeat(64); + assert!(credential_issue(&root.0, &same_principal_token) + .unwrap_err() + .contains("policy credential")); + let mut absent = credential(5); + absent.actor = "missing".into(); + assert!(credential_issue(&root.0, &absent) + .unwrap_err() + .contains("principal does not exist")); + + let mut changed_policy = policy_with_principals(); + changed_policy.principals.remove(0); + let mut policy_token_collision = changed_policy.clone(); + policy_token_collision.principals[0].token_sha256 = Some(first.token_sha256.clone()); + let rejected = update("e".repeat(64), 1, policy_token_collision); + assert!(set(&root.0, &rejected) + .unwrap_err() + .contains("collides with an operation credential")); + assert_eq!(status(&root.0).unwrap().generation, 1); + assert!(query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: rejected.operation_id + } + ) + .unwrap() + .receipt + .is_none()); + set(&root.0, &update("d".repeat(64), 1, changed_policy)).unwrap(); + assert_eq!(credential_issue(&root.0, &first).unwrap(), first); + assert_eq!( + credential_query(&root.0, &first.operation_id).unwrap(), + Some(first.clone()) + ); + assert_eq!( + credential_by_token(&root.0, &first.token_sha256).unwrap(), + Some(first.clone()) + ); + let mut renewed = credential(9); + renewed.actor = "bob".into(); + renewed.policy_generation = 2; + renewed.effect_key = first.effect_key.clone(); + assert!(credential_issue(&root.0, &renewed) + .unwrap_err() + .contains("effect is already assigned")); + let mut removed_actor = credential(6); + removed_actor.actor = "alice".into(); + removed_actor.policy_generation = 2; + assert!(credential_issue(&root.0, &removed_actor) + .unwrap_err() + .contains("principal does not exist")); + let mut second_query = credential(7); + second_query.actor = "bob".into(); + second_query.effect_key = None; + assert!(credential_issue(&root.0, &second_query) + .unwrap_err() + .contains("policy generation")); + assert!(credential_query(&root.0, &second_query.operation_id) + .unwrap() + .is_none()); + second_query.policy_generation = 2; + let mut third_query = credential(8); + third_query.actor = "bob".into(); + third_query.policy_generation = 2; + third_query.effect_key = None; + credential_issue(&root.0, &second_query).unwrap(); + credential_issue(&root.0, &third_query).unwrap(); + } + + #[test] + fn credential_indexes_retain_more_than_the_old_capacity() { + let root = Temp::new(); + set( + &root.0, + &update("f".repeat(64), 0, policy_with_principals()), + ) + .unwrap(); + let mut connection = existing(&root.0).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + for index in 0..=4100 { + let record = credential(index); + assert_eq!(credential_decide(&tx, &record).unwrap(), record); + } + tx.commit().unwrap(); + for (sql, key, index_name) in [ + ("EXPLAIN QUERY PLAN SELECT receipt FROM operation_credentials WHERE operation_id = ?1", credential(1).operation_id, "PRIMARY KEY"), + ("EXPLAIN QUERY PLAN SELECT receipt FROM operation_credentials WHERE token_sha256 = ?1", credential(1).token_sha256, "operation_credentials_token"), + ("EXPLAIN QUERY PLAN SELECT receipt FROM operation_credentials WHERE effect_key = ?1", credential(1).effect_key.unwrap(), "operation_credentials_effect"), + ] { + let plan: String = connection.query_row(sql, [key], |row| row.get(3)).unwrap(); + assert!(plan.contains(index_name), "{plan}"); + } + drop(connection); + for index in [0, 4100] { + let record = credential(index); + assert_eq!( + credential_query(&root.0, &record.operation_id).unwrap(), + Some(record.clone()) + ); + assert_eq!( + credential_by_token(&root.0, &record.token_sha256).unwrap(), + Some(record) + ); + } + credential_issue(&root.0, &credential(4101)).unwrap(); + } + + #[test] + fn credential_schema_and_indexes_fail_closed_on_corruption() { + for damage in [ + "partial", + "present_in_v2", + "v3_without", + "v4_without", + "unknown_version", + "nonunique", + "index_mismatch", + "effect_mismatch", + ] { + let root = Temp::new(); + old_v2(&root.0); + let first = credential(1); + if matches!(damage, "index_mismatch" | "effect_mismatch") { + credential_issue(&root.0, &first).unwrap(); + } + let connection = connect(&root.0.join(FILE)).unwrap(); + if damage == "partial" { + connection.execute_batch(CREDENTIAL_TABLE_SQL).unwrap(); + } else if damage == "present_in_v2" { + create_credential_schema(&connection).unwrap(); + } else if damage == "v3_without" { + connection.execute_batch("PRAGMA user_version = 3").unwrap(); + } else if damage == "v4_without" { + connection.execute_batch("PRAGMA user_version = 4").unwrap(); + } else if damage == "unknown_version" { + connection.execute_batch("PRAGMA user_version = 5").unwrap(); + } else if damage == "nonunique" { + create_credential_schema(&connection).unwrap(); + connection.execute_batch("DROP INDEX operation_credentials_token; CREATE INDEX operation_credentials_token ON operation_credentials(token_sha256)").unwrap(); + } else { + connection + .execute_batch("DROP TRIGGER operation_credentials_no_update") + .unwrap(); + let column = if damage == "index_mismatch" { + "token_sha256" + } else { + "effect_key" + }; + connection + .execute( + &format!("UPDATE operation_credentials SET {column} = ?1"), + ["b".repeat(64)], + ) + .unwrap(); + connection.execute_batch(CREDENTIAL_UPDATE_SQL).unwrap(); + } + drop(connection); + assert!( + credential_query(&root.0, &first.operation_id).is_err(), + "{damage}" + ); + let mut second = credential(2); + if damage == "index_mismatch" { + second.token_sha256 = "b".repeat(64); + } else if damage == "effect_mismatch" { + second.effect_key = Some("b".repeat(64)); + } + assert!(credential_issue(&root.0, &second).is_err(), "{damage}"); + if !matches!(damage, "index_mismatch" | "effect_mismatch") { + assert!(status(&root.0).is_err(), "{damage}"); + } + } + } + + #[test] + fn credential_schema_and_first_receipt_roll_back_when_disk_is_full() { + let root = Temp::new(); + old_v2(&root.0); + let mut connection = existing(&root.0).unwrap().unwrap(); + let pages: i64 = connection + .query_row("PRAGMA page_count", [], |row| row.get(0)) + .unwrap(); + let maximum: i64 = connection + .query_row(&format!("PRAGMA max_page_count = {pages}"), [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(maximum, pages); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + assert!(credential_decide(&tx, &credential(1)).is_err()); + drop(tx); + drop(connection); + assert!(credential_query(&root.0, &credential(1).operation_id) + .unwrap() + .is_none()); + assert!(!credential_schema(&existing(&root.0).unwrap().unwrap()).unwrap()); + assert!(!current(&root.0).unwrap().unwrap().operation_credentials); + assert_eq!( + credential_issue(&root.0, &credential(1)).unwrap(), + credential(1) + ); + } + + #[test] + fn expiry_at_first_insert_rolls_back_the_schema_and_effect_identity() { + let root = Temp::new(); + old_v2(&root.0); + let record = credential(1); + let mut connection = existing(&root.0).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + let error = + credential_decide_with_check(&tx, &record, || Err("injected expired authority".into())) + .unwrap_err(); + assert!(error.contains("expired")); + drop(tx); + drop(connection); + assert!(credential_query(&root.0, &record.operation_id) + .unwrap() + .is_none()); + assert!(!current(&root.0).unwrap().unwrap().operation_credentials); + assert_eq!(credential_issue(&root.0, &record).unwrap(), record); + + let mut expired = credential(2); + expired.expires_at = 1; + assert!(credential_issue(&root.0, &expired).is_err()); + assert!(credential_query(&root.0, &expired.operation_id) + .unwrap() + .is_none()); + assert_eq!( + credential_issue(&root.0, &credential(2)).unwrap(), + credential(2) + ); + } + + #[cfg(unix)] + #[test] + fn crash_credential_writer_child() { + use std::io::Write; + let Some(root) = std::env::var_os("WASM_GIT_CREDENTIAL_CRASH_ROOT") else { + return; + }; + let mut connection = existing(Path::new(&root)).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + let index = std::env::var("WASM_GIT_CREDENTIAL_CRASH_INDEX") + .ok() + .map(|value| value.parse().unwrap()) + .unwrap_or(1); + credential_decide(&tx, &credential(index)).unwrap(); + tx.cache_flush().unwrap(); + println!("credential-ledger-ready"); + std::io::stdout().flush().unwrap(); + let _ = std::io::stdin().read(&mut [0u8]); + } + + #[cfg(unix)] + fn kill_credential_writer(root: &Path, index: u64) { + use std::io::{BufRead, BufReader}; + use std::process::{Command, Stdio}; + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "server::policy::ledger::tests::crash_credential_writer_child", + "--nocapture", + ]) + .env("WASM_GIT_CREDENTIAL_CRASH_ROOT", root) + .env("WASM_GIT_CREDENTIAL_CRASH_INDEX", index.to_string()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = child.stdout.take().unwrap(); + let (send, receive) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(output).lines() { + if line.unwrap_or_default().contains("credential-ledger-ready") { + let _ = send.send(()); + return; + } + } + }); + if receive.recv_timeout(Duration::from_secs(10)).is_err() { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + panic!("credential writer did not reach its transaction boundary"); + } + child.kill().unwrap(); + child.wait().unwrap(); + reader.join().unwrap(); + } + + #[cfg(unix)] + #[test] + fn killed_first_credential_writer_rolls_back_schema_and_receipt() { + let root = Temp::new(); + old_v2(&root.0); + kill_credential_writer(&root.0, 1); + let record = credential(1); + assert!(credential_query(&root.0, &record.operation_id) + .unwrap() + .is_none()); + assert!(!credential_schema(&existing(&root.0).unwrap().unwrap()).unwrap()); + assert!(!current(&root.0).unwrap().unwrap().operation_credentials); + assert_eq!(credential_issue(&root.0, &record).unwrap(), record); + } + + #[cfg(unix)] + #[test] + fn killed_v3_upgrade_rolls_back_version_and_preserves_history() { + let root = Temp::new(); + old_v2(&root.0); + let original = credential(1); + install_v3_credential(&root.0, &original); + kill_credential_writer(&root.0, 2); + let state = current(&root.0).unwrap().unwrap(); + assert!(state.operation_credentials); + assert!(!state.chunk_receipts); + assert_eq!( + credential_query(&root.0, &original.operation_id).unwrap(), + Some(original) + ); + assert!(credential_query(&root.0, &credential(2).operation_id) + .unwrap() + .is_none()); + assert_eq!( + credential_issue(&root.0, &credential(2)).unwrap(), + credential(2) + ); + assert!(current(&root.0).unwrap().unwrap().chunk_receipts); + } + + #[test] + fn indexed_receipts_continue_beyond_the_old_capacity() { + let root = Temp::new(); + set(&root.0, &update(format!("{:064x}", 0), 0, policy())).unwrap(); + let mut connection = existing(&root.0).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + for index in 1..=4100 { + let request = update(format!("{index:064x}"), 0, policy()); + assert_eq!( + decide(&tx, &request).unwrap().outcome, + PolicyUpdateOutcome::GenerationConflict + ); + } + tx.commit().unwrap(); + let plan: String = connection + .query_row( + "EXPLAIN QUERY PLAN SELECT receipt FROM policy_receipts WHERE operation_id = ?1", + [format!("{:064x}", 1)], + |row| row.get(3), + ) + .unwrap(); + assert!(plan.contains("PRIMARY KEY"), "{plan}"); + assert!(connection + .execute( + "DELETE FROM policy_receipts WHERE operation_id = ?1", + [format!("{:064x}", 1)] + ) + .is_err()); + drop(connection); + let request = update(format!("{:064x}", 4101), 1, policy()); + assert_eq!(set(&root.0, &request).unwrap().generation, 2); + let query = PolicyQueryRequest { + version: 1, + operation_id: format!("{:064x}", 1), + }; + assert_eq!( + self::query(&root.0, &query) + .unwrap() + .receipt + .unwrap() + .outcome, + PolicyUpdateOutcome::GenerationConflict + ); + assert_eq!(set(&root.0, &request).unwrap().generation, 2); + } + + #[test] + fn failed_staging_cleanup_keeps_the_original_conflict_receipt() { + let root = Temp::new(); + let request = update("e".repeat(64), 7, policy()); + let error = create_with_hooks( + &root.0, + &request, + |_| Err(io::Error::other("injected unlink failure")), + crate::output::sync_directory, + ) + .unwrap_err(); + assert!(error.contains("authorization ledger published")); + assert!(error.contains("query the original operation")); + let current = current(&root.0).unwrap().unwrap(); + assert_eq!(current.generation, 0); + assert!(current.policy.is_none()); + let reply = query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: request.operation_id.clone(), + }, + ) + .unwrap(); + let receipt = reply.receipt.unwrap(); + receipt.validate_update(&request).unwrap(); + assert_eq!(receipt.outcome, PolicyUpdateOutcome::GenerationConflict); + assert_eq!(receipt.generation, 0); + } + + #[test] + fn failed_initial_publication_sync_requires_durable_retry() { + let root = Temp::new(); + let request = update("c".repeat(64), 0, policy()); + let error = create_with_hooks( + &root.0, + &request, + |path| fs::remove_file(path), + |_| Err("injected publication directory sync failure".into()), + ) + .unwrap_err(); + assert!(error.contains("outcome unknown")); + assert!(root.0.join(FILE).exists()); + + let error = existing_with_sync(&root.0, |path, _| { + OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .sync_all() + .unwrap(); + Err("injected retry directory sync failure".into()) + }) + .err() + .unwrap(); + assert!(error.contains("durability unknown")); + assert!(error.contains("injected retry")); + + let reply = query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: request.operation_id.clone(), + }, + ) + .unwrap(); + let receipt = reply.receipt.unwrap(); + receipt.validate_update(&request).unwrap(); + assert_eq!(receipt.outcome, PolicyUpdateOutcome::Applied); + assert_eq!(receipt.generation, 1); + assert_eq!(set(&root.0, &request).unwrap().generation, 1); + } + + #[test] + fn failed_migration_sync_requires_durable_retry() { + let root = Temp::new(); + let source = include_bytes!("../../../tests/fixtures/policy-v1.bin"); + fs::write(root.0.join(FILE), source).unwrap(); + let legacy: super::super::LegacyStore = crate::binary::decode(source).unwrap(); + legacy.validate().unwrap(); + let migration = PolicyMigrationReceipt { + version: 1, + source_sha256: format!("{:x}", Sha256::digest(source)), + source_version: 1, + target_version: 2, + generation: legacy.generation, + policy_sha256: legacy + .policy + .as_ref() + .map(ServerPolicy::digest) + .transpose() + .unwrap(), + receipts: legacy.receipts.len() as u64, + }; + let request = PolicyMigrationRequest { + version: 1, + source_sha256: migration.source_sha256.clone(), + }; + let error = migrate_with_sync( + &root.0, + legacy.policy.as_ref(), + legacy.generation, + &legacy.receipts, + &migration, + |_| Err("injected migration directory sync failure".into()), + ) + .unwrap_err(); + assert!(error.contains("migration outcome unknown")); + assert!(fs::read(root.0.join(FILE)) + .unwrap() + .starts_with(SQLITE_HEADER)); + let error = existing_with_sync(&root.0, |path, _| { + OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .sync_all() + .unwrap(); + Err("injected retry directory sync failure".into()) + }) + .err() + .unwrap(); + assert!(error.contains("durability unknown")); + + let recovered = migration_receipt(&root.0, &request).unwrap(); + recovered.validate_request(&request).unwrap(); + assert_eq!(recovered.generation, 1); + assert_eq!(recovered.receipts, 2); + assert_eq!( + set( + &root.0, + &update("d".repeat(64), 1, policy_with_principals()) + ) + .unwrap() + .generation, + 2 + ); + let mut new_credential = credential(1); + new_credential.policy_generation = 2; + credential_issue(&root.0, &new_credential).unwrap(); + assert!(current(&root.0).unwrap().unwrap().operation_credentials); + let repeated = migration_receipt(&root.0, &request).unwrap(); + assert_eq!(repeated.generation, 1); + assert_eq!(repeated.receipts, 2); + } + + #[test] + fn sqlite_full_rolls_back_policy_and_receipt_together() { + use crate::protocol::PolicyPrincipal; + let root = Temp::new(); + set(&root.0, &update("a".repeat(64), 0, policy())).unwrap(); + let mut connection = existing(&root.0).unwrap().unwrap(); + let pages: i64 = connection + .query_row("PRAGMA page_count", [], |row| row.get(0)) + .unwrap(); + let maximum: i64 = connection + .query_row(&format!("PRAGMA max_page_count = {pages}"), [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(maximum, pages); + let many = (0..4096) + .map(|index| PolicyPrincipal { + name: format!("user{index:04}{}", "x".repeat(90)), + token_sha256: None, + grants: Vec::new(), + }) + .collect(); + let request = update( + "b".repeat(64), + 1, + ServerPolicy { + version: crate::protocol::SERVER_POLICY_VERSION, + principals: many, + }, + ); + assert!(transaction(&mut connection, &request).is_err()); + drop(connection); + assert_eq!(status(&root.0).unwrap().generation, 1); + assert!(query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: request.operation_id.clone() + } + ) + .unwrap() + .receipt + .is_none()); + assert_eq!(set(&root.0, &request).unwrap().generation, 2); + } + + #[cfg(unix)] + #[test] + fn crash_writer_child() { + use std::io::Write; + let Some(root) = std::env::var_os("WASM_GIT_LEDGER_CRASH_ROOT") else { + return; + }; + let mut connection = existing(Path::new(&root)).unwrap().unwrap(); + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .unwrap(); + decide(&tx, &update("f".repeat(64), 1, policy())).unwrap(); + tx.cache_flush().unwrap(); + println!("policy-ledger-ready"); + std::io::stdout().flush().unwrap(); + let _ = std::io::stdin().read(&mut [0u8]); + } + + #[cfg(unix)] + #[test] + fn killed_writer_rolls_back_hot_journal_and_allows_original_retry() { + use std::io::{BufRead, BufReader}; + use std::process::{Command, Stdio}; + let root = Temp::new(); + set(&root.0, &update("a".repeat(64), 0, policy())).unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "server::policy::ledger::tests::crash_writer_child", + "--nocapture", + ]) + .env("WASM_GIT_LEDGER_CRASH_ROOT", &root.0) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let output = child.stdout.take().unwrap(); + let (send, receive) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(output).lines() { + if line.unwrap_or_default().contains("policy-ledger-ready") { + let _ = send.send(()); + return; + } + } + }); + if receive.recv_timeout(Duration::from_secs(10)).is_err() { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + panic!("writer did not reach its transaction boundary"); + } + child.kill().unwrap(); + child.wait().unwrap(); + reader.join().unwrap(); + assert_eq!(status(&root.0).unwrap().generation, 1); + let request = update("f".repeat(64), 1, policy()); + assert!(query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: request.operation_id.clone() + } + ) + .unwrap() + .receipt + .is_none()); + assert_eq!(set(&root.0, &request).unwrap().generation, 2); + } +} diff --git a/src/infrastructure/repository_record_store.rs b/src/infrastructure/repository_record_store.rs new file mode 100644 index 0000000..3dd8b14 --- /dev/null +++ b/src/infrastructure/repository_record_store.rs @@ -0,0 +1,739 @@ +//! Per-identity repository records. Callers hold their domain lock throughout. +use super::*; + +pub(super) const MAX_ACTIVE_RECORDS: u64 = 4096; +pub(super) const MAX_ACTIVE_BYTES: u64 = 64 * 1024 * 1024; +// An old 64 MiB ledger record can gain a receipt from an old 64 MiB journal; +// direct failure receipts also need room for their bounded response metadata. +pub(super) const MAX_RECORD_BYTES: u64 = 2 * 64 * 1024 * 1024 + 1024 * 1024; +const MAX_LEGACY_BYTES: u64 = 64 * 1024 * 1024; +const MAX_CAPACITY_SCAN: u64 = 1_000_000; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Bucket { + Active, + Terminal, + Pinned, +} +impl Bucket { + fn name(self) -> &'static str { + match self { + Self::Active => "active", + Self::Terminal => "terminal", + Self::Pinned => "pinned", + } + } +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Envelope { + version: u32, + id: String, + payload: Vec, +} + +pub(super) struct Seed { + pub id: String, + pub bucket: Bucket, + pub payload: Vec, +} + +pub(super) struct StoreError { + pub message: String, + pub outcome_unknown: bool, +} +impl From for StoreError { + fn from(message: String) -> Self { + Self { + message, + outcome_unknown: false, + } + } +} + +pub(super) type Validate = fn(&str, Bucket, &[u8]) -> RepositoryResult<()>; +pub(super) type Compare = fn(&str, &[u8], Bucket, &[u8]) -> RepositoryResult<()>; + +pub(super) struct RecordStore<'a> { + repo: &'a Repository, + root: PathBuf, +} + +fn owner_matches(path: &Path, marker: &[u8]) -> RepositoryResult { + let metadata = fs::symlink_metadata(path).map_err(|e| e.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() != marker.len() as u64 + { + return Ok(false); + } + Ok(read_regular(path)? == marker) +} + +struct MigrationScan { + owner_present: bool, + records: BTreeSet, + owner_temps: Vec, +} + +// A renamed root was complete before publication; a staging directory may +// contain any matching prefix of the migration. Neither may hide later data. +fn inspect_migration( + path: &Path, + marker: &[u8], + seeds: &BTreeMap<&str, &Seed>, + staging: bool, +) -> RepositoryResult { + require_directory(path)?; + let owner = path.join("owner"); + let owner_present = match fs::symlink_metadata(&owner) { + Ok(_) if owner_matches(&owner, marker)? => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound && staging => false, + _ => return Err("unrecognized repository record migration owner".into()), + }; + let mut scan = MigrationScan { + owner_present, + records: BTreeSet::new(), + owner_temps: Vec::new(), + }; + let mut directories = BTreeSet::new(); + for entry in fs::read_dir(path).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let name = entry + .file_name() + .into_string() + .map_err(|_| "invalid migration entry")?; + if name == "owner" { + continue; + } + if staging && name.starts_with(".wasm-git-output-") { + // Only the old owner publication used sibling output files here. + // Its interrupted write can contain a prefix of the owner marker. + let metadata = fs::symlink_metadata(entry.path()).map_err(|e| e.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > marker.len() as u64 + || !marker.starts_with(&read_regular(&entry.path())?) + { + return Err("unrecognized repository record migration temporary file".into()); + } + scan.owner_temps.push(entry.path()); + continue; + } + if !owner_present { + return Err("unrecognized repository record migration directory".into()); + } + let bucket = match name.as_str() { + "active" => Bucket::Active, + "terminal" => Bucket::Terminal, + "pinned" => Bucket::Pinned, + _ => return Err("unrecognized repository record migration entry".into()), + }; + require_directory(&entry.path())?; + directories.insert(name); + for record in fs::read_dir(entry.path()).map_err(|e| e.to_string())? { + let record = record.map_err(|e| e.to_string())?; + let id = record + .file_name() + .into_string() + .map_err(|_| "invalid migration record filename")?; + require_id(&id)?; + let seed = seeds + .get(id.as_str()) + .ok_or("repository record migration contains an additional record")?; + let expected = RecordStore::encode(&seed.id, &seed.payload)?; + let metadata = fs::symlink_metadata(record.path()).map_err(|e| e.to_string())?; + if seed.bucket != bucket + || !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() != expected.len() as u64 + || read_regular(&record.path())? != expected + || !scan.records.insert(id) + { + return Err("repository record migration conflicts with the legacy ledger".into()); + } + } + } + if !staging && (directories.len() != 3 || scan.records.len() != seeds.len()) { + return Err("repository record migration root does not match the legacy ledger".into()); + } + Ok(scan) +} + +impl<'a> RecordStore<'a> { + /// The old file is authoritative until the marker is durably published. + pub(super) fn open( + repo: &'a Repository, + name: &str, + legacy: impl FnOnce(Option<&[u8]>) -> RepositoryResult>, + ) -> RepositoryResult { + let marker = format!("wasm-git-record-store:{name}:1\n").into_bytes(); + let old = repo.common_metadata.join(format!("{name}.bin")); + let root = repo.common_metadata.join(format!("{name}-records")); + let staging = repo + .common_metadata + .join("tmp") + .join(format!("{name}-records-migration")); + let bytes = match fs::symlink_metadata(&old) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e.to_string()), + Ok(m) if !m.is_file() || m.file_type().is_symlink() || m.len() > MAX_LEGACY_BYTES => { + return Err("invalid repository record store marker or legacy file".into()) + } + Ok(_) => Some(read_regular(&old)?), + }; + if bytes.as_deref() == Some(marker.as_slice()) { + let store = Self { repo, root }; + store.verify_layout(&marker)?; + // A previous marker rename might have returned an uncertain fence. + sync_directory(&repo.common_metadata)?; + return Ok(store); + } + let seeds = legacy(bytes.as_deref())?; + let mut expected = BTreeMap::new(); + for seed in &seeds { + require_id(&seed.id)?; + if expected.insert(seed.id.as_str(), seed).is_some() { + return Err("duplicate repository record migration identity".into()); + } + } + let exists = |path: &Path| -> RepositoryResult { + match fs::symlink_metadata(path) { + Ok(_) => Ok(true), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e.to_string()), + } + }; + let root_exists = exists(&root)?; + let staging_exists = exists(&staging)?; + if root_exists && staging_exists { + return Err("conflicting repository record migration directories".into()); + } + let (directory, scan) = if root_exists { + (&root, inspect_migration(&root, &marker, &expected, false)?) + } else if staging_exists { + ( + &staging, + inspect_migration(&staging, &marker, &expected, true)?, + ) + } else { + fs::create_dir(&staging).map_err(|e| e.to_string())?; + ( + &staging, + MigrationScan { + owner_present: false, + records: BTreeSet::new(), + owner_temps: Vec::new(), + }, + ) + }; + for path in &scan.owner_temps { + fs::remove_file(path).map_err(|e| e.to_string())?; + } + if !scan.owner_present { + write_new_file(&directory.join("owner"), &marker)?; + } + for bucket in [Bucket::Active, Bucket::Terminal, Bucket::Pinned] { + let path = directory.join(bucket.name()); + match fs::create_dir(&path) { + Ok(()) => (), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + require_directory(&path)? + } + Err(e) => return Err(e.to_string()), + } + } + for seed in &seeds { + let path = directory.join(seed.bucket.name()).join(&seed.id); + if scan.records.contains(&seed.id) { + // An interrupted old migration may have written complete bytes + // but not reached its file sync yet. + OpenOptions::new() + .write(true) + .open(&path) + .and_then(|file| file.sync_all()) + .map_err(|e| e.to_string())?; + } else { + // Stage outside the migration directory, so a stopped write + // cannot leave a partial file under an authoritative ID. + repo.atomic_write(&path, &Self::encode(&seed.id, &seed.payload)?)?; + } + } + for bucket in [Bucket::Active, Bucket::Terminal, Bucket::Pinned] { + sync_directory(&directory.join(bucket.name()))?; + } + sync_directory(directory)?; + if !root_exists { + fs::rename(&staging, &root).map_err(|e| e.to_string())?; + } + sync_directory(&repo.common_metadata.join("tmp"))?; + sync_directory(&repo.common_metadata)?; + repo.atomic_write(&old, &marker)?; + let store = Self { repo, root }; + store.verify_layout(&marker)?; + Ok(store) + } + + fn verify_layout(&self, marker: &[u8]) -> RepositoryResult<()> { + require_directory(&self.root)?; + if !owner_matches(&self.root.join("owner"), marker)? { + return Err("invalid repository record store owner".into()); + } + for bucket in [Bucket::Active, Bucket::Terminal, Bucket::Pinned] { + require_directory(&self.directory(bucket))?; + } + Ok(()) + } + + fn directory(&self, bucket: Bucket) -> PathBuf { + self.root.join(bucket.name()) + } + fn path(&self, bucket: Bucket, id: &str) -> PathBuf { + self.directory(bucket).join(id) + } + + fn encode(id: &str, payload: &[u8]) -> RepositoryResult> { + require_id(id)?; + let bytes = crate::binary::encode(&Envelope { + version: 1, + id: id.into(), + payload: payload.to_vec(), + })?; + if bytes.len() as u64 > MAX_RECORD_BYTES { + return Err("repository record exceeds its size bound".into()); + } + Ok(bytes) + } + pub(super) fn encoded_len(&self, id: &str, payload: &[u8]) -> RepositoryResult { + Ok(Self::encode(id, payload)?.len() as u64) + } + fn read(&self, bucket: Bucket, id: &str) -> RepositoryResult>> { + require_id(id)?; + let path = self.path(bucket, id); + let meta = match fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.to_string()), + Ok(m) => m, + }; + if !meta.is_file() || meta.file_type().is_symlink() || meta.len() > MAX_RECORD_BYTES { + return Err("invalid repository record file".into()); + } + let envelope: Envelope = crate::binary::decode(&read_regular(&path)?)?; + if envelope.version != 1 || envelope.id != id { + return Err("repository record identity mismatch".into()); + } + Ok(Some(envelope.payload)) + } + pub(super) fn fence(&self, bucket: Bucket) -> RepositoryResult<()> { + sync_directory(&self.directory(bucket)) + } + + pub(super) fn get( + &self, + id: &str, + validate: Validate, + compare: Compare, + ) -> RepositoryResult)>> { + self.get_inner(id, validate, compare, true) + } + + fn get_inner( + &self, + id: &str, + validate: Validate, + compare: Compare, + fence_active: bool, + ) -> RepositoryResult)>> { + let active = self.read(Bucket::Active, id)?; + let terminal = self.read(Bucket::Terminal, id)?; + let pinned = self.read(Bucket::Pinned, id)?; + if terminal.is_some() && pinned.is_some() { + return Err("conflicting terminal repository records".into()); + } + let finished = terminal + .map(|v| (Bucket::Terminal, v)) + .or_else(|| pinned.map(|v| (Bucket::Pinned, v))); + if let Some((bucket, payload)) = finished { + validate(id, bucket, &payload)?; + if let Some(active) = active { + validate(id, Bucket::Active, &active)?; + compare(id, &active, bucket, &payload)?; + self.fence(bucket)?; + fs::remove_file(self.path(Bucket::Active, id)).map_err(|e| e.to_string())?; + self.fence(Bucket::Active)?; + } else { + self.fence(bucket)?; + } + return Ok(Some((bucket, payload))); + } + if let Some(payload) = active { + validate(id, Bucket::Active, &payload)?; + if fence_active { + self.fence(Bucket::Active)?; + } + Ok(Some((Bucket::Active, payload))) + } else { + for bucket in [Bucket::Active, Bucket::Terminal, Bucket::Pinned] { + self.fence(bucket)?; + } + Ok(None) + } + } + + pub(super) fn write( + &self, + id: &str, + bucket: Bucket, + payload: &[u8], + validate: Validate, + compare: Compare, + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), StoreError> { + validate(id, bucket, payload)?; + let bytes = Self::encode(id, payload)?; + for final_bucket in [Bucket::Terminal, Bucket::Pinned] { + if let Some(existing) = self.read(final_bucket, id)? { + validate(id, final_bucket, &existing)?; + if bucket == final_bucket && existing == payload { + self.get(id, validate, compare)?; + return Ok(()); + } + return Err( + "immutable terminal repository record conflicts with this transition" + .to_owned() + .into(), + ); + } + } + if bucket != Bucket::Active { + if let Some(active) = self.read(Bucket::Active, id)? { + validate(id, Bucket::Active, &active)?; + compare(id, &active, bucket, payload)?; + } + } + let mut passed = false; + self.repo + .atomic_write_checked(&self.path(bucket, id), &bytes, || { + before_publish()?; + passed = true; + Ok(()) + }) + .map_err(|message| StoreError { + message, + outcome_unknown: passed, + })?; + if bucket != Bucket::Active { + let active = self.path(Bucket::Active, id); + match fs::remove_file(active) { + Ok(()) => self.fence(Bucket::Active).map_err(|message| StoreError { + message, + outcome_unknown: true, + })?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(e) => { + return Err(StoreError { + message: e.to_string(), + outcome_unknown: true, + }) + } + } + } + Ok(()) + } + + fn ids( + &self, + bucket: Bucket, + ) -> RepositoryResult>> { + let entries = fs::read_dir(self.directory(bucket)).map_err(|e| e.to_string())?; + Ok(entries.map(|entry| { + let entry = entry.map_err(|e| e.to_string())?; + let id = entry + .file_name() + .into_string() + .map_err(|_| "invalid repository record filename")?; + require_id(&id)?; + Ok(id) + })) + } + + pub(super) fn active_stats( + &self, + validate: Validate, + compare: Compare, + ) -> RepositoryResult<(u64, u64)> { + let mut count = 0u64; + let mut bytes = 0u64; + let mut visited = 0u64; + self.fence(Bucket::Active)?; + for id in self.ids(Bucket::Active)? { + visited += 1; + if visited > MAX_ACTIVE_RECORDS { + return Err("active repository record index exceeds its bound".into()); + } + let id = id?; + if self + .get_inner(&id, validate, compare, false)? + .is_some_and(|(bucket, _)| bucket == Bucket::Active) + { + count += 1; + bytes = bytes + .checked_add( + fs::metadata(self.path(Bucket::Active, &id)) + .map_err(|e| e.to_string())? + .len(), + ) + .ok_or("repository capacity overflow")?; + } + } + Ok((count, bytes)) + } + + pub(super) fn capacity( + &self, + validate: Validate, + compare: Compare, + ) -> RepositoryResult { + let (active_records, active_bytes) = self.active_stats(validate, compare)?; + let mut total_records = 0u64; + let mut total_bytes = 0u64; + for bucket in [Bucket::Active, Bucket::Terminal, Bucket::Pinned] { + for id in self.ids(bucket)? { + let id = id?; + if bucket == Bucket::Terminal { + match fs::symlink_metadata(self.path(Bucket::Pinned, &id)) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(e) => return Err(e.to_string()), + Ok(_) => return Err("conflicting terminal repository records".into()), + } + } + total_records += 1; + if total_records > MAX_CAPACITY_SCAN { + return Err( + "repository capacity cannot be determined: scan bound exceeded".into(), + ); + } + let metadata = + fs::symlink_metadata(self.path(bucket, &id)).map_err(|e| e.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > MAX_RECORD_BYTES + { + return Err("invalid repository record file".into()); + } + total_bytes = total_bytes + .checked_add(metadata.len()) + .ok_or("repository capacity overflow")?; + } + } + Ok(crate::protocol::AdmissionCapacity { + active_records, + active_bytes, + total_records, + total_bytes, + max_active_records: MAX_ACTIVE_RECORDS, + max_active_bytes: MAX_ACTIVE_BYTES, + }) + } + + pub(super) fn for_each( + &self, + bucket: Bucket, + validate: Validate, + compare: Compare, + mut visit: impl FnMut(&str, &[u8]) -> RepositoryResult<()>, + ) -> RepositoryResult<()> { + let mut visited = 0u64; + for id in self.ids(bucket)? { + visited += 1; + if bucket == Bucket::Active && visited > MAX_ACTIVE_RECORDS { + return Err("active repository record index exceeds its bound".into()); + } + let id = id?; + if let Some((actual, payload)) = self.get(&id, validate, compare)? { + if actual == bucket { + visit(&id, &payload)?; + } + } + } + Ok(()) + } + + #[cfg(test)] + pub(super) fn seed_fixture( + &self, + id: &str, + bucket: Bucket, + payload: &[u8], + ) -> RepositoryResult<()> { + fs::write(self.path(bucket, id), Self::encode(id, payload)?).map_err(|e| e.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + const NAME: &str = "migration-test"; + const LEGACY: &[u8] = b"legacy migration fixture"; + + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-record-migration-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn seeds() -> Vec { + vec![ + Seed { + id: "a".repeat(64), + bucket: Bucket::Active, + payload: b"active".to_vec(), + }, + Seed { + id: "b".repeat(64), + bucket: Bucket::Terminal, + payload: b"terminal".to_vec(), + }, + ] + } + + fn fixture() -> (Temp, Repository) { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + fs::write(repo.common_metadata.join(format!("{NAME}.bin")), LEGACY).unwrap(); + (temp, repo) + } + + fn open(repo: &Repository) -> RepositoryResult> { + RecordStore::open(repo, NAME, |bytes| { + if bytes != Some(LEGACY) { + return Err("unexpected legacy fixture".into()); + } + Ok(seeds()) + }) + } + + fn marker() -> Vec { + format!("wasm-git-record-store:{NAME}:1\n").into_bytes() + } + fn legacy_path(repo: &Repository) -> PathBuf { + repo.common_metadata.join(format!("{NAME}.bin")) + } + fn staging_path(repo: &Repository) -> PathBuf { + repo.common_metadata + .join("tmp") + .join(format!("{NAME}-records-migration")) + } + + #[test] + fn migration_preserves_additional_or_changed_records_after_legacy_reappears() { + for case in 0..4 { + let (_temp, repo) = fixture(); + let store = open(&repo).unwrap(); + let path = match case { + 0 => { + let id = "a".repeat(64); + store.seed_fixture(&id, Bucket::Active, b"changed").unwrap(); + store.path(Bucket::Active, &id) + } + 1 => { + let id = "c".repeat(64); + store + .seed_fixture(&id, Bucket::Terminal, b"new tombstone") + .unwrap(); + store.path(Bucket::Terminal, &id) + } + 2 => { + let id = "a".repeat(64); + store + .seed_fixture(&id, Bucket::Terminal, b"active") + .unwrap(); + store.path(Bucket::Terminal, &id) + } + _ => { + let path = store.root.join("unexpected"); + fs::write(&path, b"preserve").unwrap(); + path + } + }; + let before = fs::read(&path).unwrap(); + fs::write(legacy_path(&repo), LEGACY).unwrap(); + assert!(open(&repo).is_err()); + assert_eq!(fs::read(path).unwrap(), before); + assert_eq!(fs::read(legacy_path(&repo)).unwrap().as_slice(), LEGACY); + } + } + + #[test] + fn migration_resumes_matching_staging_and_reuses_complete_root() { + let (_temp, repo) = fixture(); + let staging = staging_path(&repo); + fs::create_dir(&staging).unwrap(); + fs::write(staging.join("owner"), marker()).unwrap(); + fs::write( + staging.join(".wasm-git-output-interrupted.tmp"), + &marker()[..8], + ) + .unwrap(); + fs::create_dir(staging.join("active")).unwrap(); + let records = seeds(); + let first = &records[0]; + fs::write( + staging.join("active").join(&first.id), + RecordStore::encode(&first.id, &first.payload).unwrap(), + ) + .unwrap(); + let store = open(&repo).unwrap(); + assert!(!staging.exists()); + assert_eq!( + store.read(Bucket::Active, &"a".repeat(64)).unwrap(), + Some(b"active".to_vec()) + ); + assert_eq!( + store.read(Bucket::Terminal, &"b".repeat(64)).unwrap(), + Some(b"terminal".to_vec()) + ); + fs::write(legacy_path(&repo), LEGACY).unwrap(); + open(&repo).unwrap(); + assert_eq!(fs::read(legacy_path(&repo)).unwrap(), marker()); + } + + #[test] + fn migration_rejects_incomplete_or_unrecognized_existing_records() { + for unexpected in [false, true] { + let (_temp, repo) = fixture(); + let staging = staging_path(&repo); + fs::create_dir(&staging).unwrap(); + fs::write(staging.join("owner"), marker()).unwrap(); + fs::create_dir(staging.join("active")).unwrap(); + let id = if unexpected { + "c".repeat(64) + } else { + "a".repeat(64) + }; + let path = staging.join("active").join(id); + let bytes = b"unrecognized bytes"; + fs::write(&path, bytes).unwrap(); + assert!(open(&repo).is_err()); + assert_eq!(fs::read(path).unwrap().as_slice(), bytes.as_slice()); + assert_eq!(fs::read(legacy_path(&repo)).unwrap().as_slice(), LEGACY); + assert!(staging.exists()); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 5821a96..6b2551f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -433,12 +433,19 @@ pub fn client_main() { "version" | "--version" | "-v" if args.len() == 2 => Ok(format!("wasm-git {}", env!("CARGO_PKG_VERSION"))), "version" if args.len() == 3 && args[2] == "--build-options" => serde_json::to_string_pretty(&json!({"version":env!("CARGO_PKG_VERSION"),"backend":"native_wasm_git","original_wasm_bytes":true,"pointer_width":usize::BITS,"object_hash":"sha256","client":cfg!(feature="client"),"server":cfg!(feature="server"),"host_os":if cfg!(target_os="wasi") { "wasi" } else { std::env::consts::OS },"host_arch":std::env::consts::ARCH,"host_threads":!cfg!(target_family="wasm"),"host_processes":!cfg!(target_family="wasm"),"host_network":!cfg!(target_family="wasm"),"directory_fsync":cfg!(unix)})).map_err(|error|error.to_string()), "pool" => remote::pool_cli(&args[1..]), + "retention-rpc" => remote::retention_cli(&args[2..]), + "integration-capabilities" if args.len() == 2 => serde_json::to_string(&protocol::IntegrationCapabilities::current()).map_err(|e| e.to_string()), + "integration-validate" => remote::integration_validate_cli(&args[2..]), + "upload-binding" => remote::upload_binding_cli(&args[2..]), + "upload-recovery" => remote::upload_recovery_cli(&args[2..]), + "scoped-upload-rpc" => remote::scoped_upload_cli(&args[2..]), "features" => features::run(&args[1..]), "validate" => feature_set::run(&args[1..]), "pr" => remote::pull_cli(&args[2..]), "clone" | "fetch" if remote::selective_requested(&args[1..]) => remote::run_selective(&args[1..]), "promisor" | "hydrate" | "clone-status" => remote::run_selective(&args[1..]), - "keygen" | "trust-author" | "untrust-author" | "commit-signed" | "sign-commit" | "verify-commit" => repository::signing_cli(&args[1..]), + "sign-commit" => repository::signing_cli_formatted(&args[1..], format.machine()), + "keygen" | "trust-author" | "untrust-author" | "commit-signed" | "verify-commit" => repository::signing_cli(&args[1..]), "inspect" => cmd_inspect(&args[2..]), "debug-map" => debug_cli::run(&args[2..]), "diff" => cmd_diff(&args[2..]), @@ -482,7 +489,7 @@ pub fn client_main() { "status" | "add" | "rm" | "mv" | "restore" | "reset" | "stash" | "config" | "tag" | "reflog" | "rev-parse" | "cat-file" | "ls-files" => porcelain::run(&args[1..]), "commit" if args.get(3).is_some_and(|arg| arg.starts_with('-')) => { - porcelain::run(&args[1..]) + porcelain::run_formatted(&args[1..], format.machine()) } "branch" | "switch" => porcelain::run(&args[1..]), "commit" if args.len() >= 3 && !command_args::help_requested(&args[1..]) => { @@ -492,7 +499,8 @@ pub fn client_main() { "merge" if args.len() >= 3 && !command_args::help_requested(&args[1..]) => { porcelain::with_clean_history(&args[2], |_| repository::run(&args[1..])) } - "init" | "commit" | "log" | "show" | "clone" | "fork" | "bundle" | "unbundle" | "fsck" | "merge" => repository::run(&args[1..]), + "bundle" => repository::run_formatted(&args[1..], format.machine()), + "init" | "commit" | "log" | "show" | "clone" | "fork" | "unbundle" | "fsck" | "merge" => repository::run(&args[1..]), "help" | "--help" | "-h" => Ok(usage_text()), other => Err(if format.machine() { format!("unknown command: {other}") } else { format!("unknown command: {other}\n{}", usage_text()) }), }; @@ -1327,7 +1335,21 @@ pub fn server_main() { if format.machine() && !matches!( command.as_str(), - "compile-policy" | "compile-protection" | "audit-log" | "--help" | "-h" + "compile-policy" + | "compile-protection" + | "audit-log" + | "policy-set" + | "policy-query" + | "policy-status" + | "policy-migrate" + | "operation-credential-issue" + | "operation-credential-query" + | "operation-recover" + | "operation-context" + | "audit-query" + | "capacity-query" + | "--help" + | "-h" ) { format.emit("server", "", 1, Some("running servers require --format native; stdout carries readiness or the binary network protocol"), false); diff --git a/src/platform_fs.rs b/src/platform_fs.rs index 72d2177..604ba81 100644 --- a/src/platform_fs.rs +++ b/src/platform_fs.rs @@ -3,9 +3,243 @@ #[cfg(not(target_os = "wasi"))] pub(crate) use std::fs::canonicalize; -/// Serialize service requests without preventing ordinary reads of the format -/// inode. Windows byte-range locks are mandatory even for another handle in -/// this process, so reserve one byte beyond EOF instead of locking its contents. +pub(crate) const NATIVE_LOCK_FORMAT: &[u8] = b"WGTLCK\0\x02"; + +pub(crate) struct ResourceLock { + _file: std::fs::File, + #[cfg(unix)] + lock_path: std::path::PathBuf, + #[cfg(target_os = "wasi")] + legacy_path: std::path::PathBuf, +} + +impl ResourceLock { + pub(crate) fn relocated(&mut self, path: &std::path::Path) { + #[cfg(target_os = "wasi")] + { + self.legacy_path = path.to_owned(); + } + #[cfg(unix)] + { + self.lock_path = path.to_owned(); + } + #[cfg(not(any(unix, target_os = "wasi")))] + let _ = path; + } +} + +#[cfg(unix)] +impl Drop for ResourceLock { + fn drop(&mut self) { + // A concurrent fork can temporarily inherit this open file + // description before CLOEXEC takes effect. Unlock explicitly when the + // operation ends instead of waiting for that child to exec or exit. + if let Err(error) = self._file.unlock() { + crate::cli_error(&format!("cannot release lock {}: {error}", self.lock_path.display())); + } + } +} + +#[cfg(target_os = "wasi")] +impl Drop for ResourceLock { + fn drop(&mut self) { + // WASIp1 has no native process lock. This guard created the path + // exclusively; a crash can leave it for controlled maintenance. + let _ = std::fs::remove_file(&self.legacy_path); + } +} + +/// A stable inode arbitrates one named resource. Existing legacy create-new +/// locks are never interpreted as abandoned, even when their PID is absent. +#[cfg(any(unix, windows))] +pub(crate) fn acquire_lock( + path: &std::path::Path, + staging: &std::path::Path, +) -> Result { + use std::io::Read; + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + + let error = |action: &str, cause: std::io::Error| { + format!("cannot {action} {}: {cause}", path.display()) + }; + match std::fs::symlink_metadata(path) { + Ok(_) => {} + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => { + let time = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + let staged = staging.join(format!( + "native-lock-{}-{time}-{}", + process_id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + crate::output::write_new_file(&staged, NATIVE_LOCK_FORMAT)?; + // Atomic create-if-absent protects an old writer which won the + // race and ensures no initialized native inode is replaced. + let published = std::fs::hard_link(&staged, path); + std::fs::remove_file(&staged).map_err(|cause| { + format!( + "cannot remove lock staging file {}: {cause}", + staged.display() + ) + })?; + match published { + Ok(()) => crate::output::sync_directory( + path.parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(std::path::Path::new(".")), + )?, + Err(cause) if cause.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(cause) => return Err(error("publish lock", cause)), + } + } + Err(cause) => return Err(error("inspect lock", cause)), + } + let metadata = std::fs::symlink_metadata(path).map_err(|cause| error("inspect lock", cause))?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err(format!("invalid lock: {}", path.display())); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true); + protect_lock_open(&mut options); + let file = options + .open(path) + .map_err(|cause| error("open lock", cause))?; + try_service_lock(&file) + .map_err(|cause| format!("resource is locked: {}: {cause}", path.display()))?; + let mut guard = ResourceLock { + _file: file, + #[cfg(unix)] + lock_path: path.to_owned(), + }; + if !lock_file_matches_path(&guard._file, path).map_err(|cause| error("verify lock", cause))? { + return Err(format!("invalid or replaced lock: {}", path.display())); + } + let mut marker = Vec::new(); + (&mut guard._file) + .take((NATIVE_LOCK_FORMAT.len() + 1) as u64) + .read_to_end(&mut marker) + .map_err(|cause| error("read lock", cause))?; + if marker != NATIVE_LOCK_FORMAT { + return Err(format!("resource is locked by an incompatible or legacy lock: {}; stop every process using this resource, verify no operation remains active, and remove only the legacy lock under controlled maintenance before retrying", path.display())); + } + Ok(guard) +} + +/// WASIp1 has no native file locking. Preserve exclusive-create semantics, +/// but never open or remove an existing native v2 inode. Both formats compete +/// for this same pathname, so different backends cannot silently coexist. +#[cfg(target_os = "wasi")] +pub(crate) fn acquire_lock( + path: &std::path::Path, + _staging: &std::path::Path, +) -> Result { + use std::io::Write; + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(path) + .map_err(|error| { + if error.kind() == std::io::ErrorKind::AlreadyExists { + format!("resource is locked or uses the native v2 lock format: {}; WASIp1 cannot acquire an existing lock and must not remove a native lock", path.display()) + } else { + format!("cannot create lock {}: {error}", path.display()) + } + })?; + let mut guard = ResourceLock { + _file: file, + legacy_path: path.to_owned(), + }; + guard + ._file + .write_all(&[b"WGTLCK\0\x01".as_slice(), &0u32.to_be_bytes()].concat()) + .map_err(|error| format!("cannot write lock {}: {error}", path.display()))?; + guard + ._file + .sync_all() + .map_err(|error| format!("cannot sync lock {}: {error}", path.display()))?; + Ok(guard) +} + +#[cfg(not(any(unix, windows, target_os = "wasi")))] +pub(crate) fn acquire_lock( + _path: &std::path::Path, + _staging: &std::path::Path, +) -> Result { + Err("repository locking is unavailable on this target".into()) +} + +/// The lock's directory must be protected against out-of-band replacement. +/// Keep Windows' normal sharing so a held worktree lock can move with its tree. +pub(crate) fn protect_lock_open(options: &mut std::fs::OpenOptions) { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // Refuse a final-component symlink and avoid waiting on a substituted + // FIFO between inspection and open. + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + #[cfg(not(unix))] + let _ = options; +} + +#[cfg(unix)] +pub(crate) fn lock_file_matches_path( + file: &std::fs::File, + path: &std::path::Path, +) -> std::io::Result { + use std::os::unix::fs::MetadataExt; + let path_metadata = std::fs::symlink_metadata(path)?; + let file_metadata = file.metadata()?; + Ok(path_metadata.is_file() + && !path_metadata.file_type().is_symlink() + && file_metadata.is_file() + && path_metadata.dev() == file_metadata.dev() + && path_metadata.ino() == file_metadata.ino()) +} + +#[cfg(windows)] +pub(crate) fn lock_file_matches_path( + file: &std::fs::File, + path: &std::path::Path, +) -> std::io::Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, + }; + + fn identity(file: &std::fs::File) -> std::io::Result<(u32, u32, u32)> { + let mut info = BY_HANDLE_FILE_INFORMATION::default(); + // SAFETY: the live file handle and writable information struct are valid. + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(( + info.dwVolumeSerialNumber, + info.nFileIndexHigh, + info.nFileIndexLow, + )) + } + let metadata = std::fs::symlink_metadata(path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() || !file.metadata()?.is_file() { + return Ok(false); + } + let path_file = std::fs::File::open(path)?; + Ok(identity(file)? == identity(&path_file)?) +} + +#[cfg(not(any(unix, windows)))] +pub(crate) fn lock_file_matches_path( + _file: &std::fs::File, + _path: &std::path::Path, +) -> std::io::Result { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "native repository writer locks are unavailable", + )) +} + +/// Serialize native guards without preventing ordinary reads of their files. +/// Windows byte-range locks are mandatory even for another handle in this +/// process, so reserve one byte beyond EOF instead of locking its contents. pub(crate) fn try_service_lock(file: &std::fs::File) -> Result<(), std::fs::TryLockError> { #[cfg(not(windows))] { @@ -94,3 +328,126 @@ pub(crate) fn canonicalize( Ok(path) } } + +#[cfg(all(test, target_os = "linux"))] +mod lock_tests { + use super::*; + use std::fs::{self, File}; + use std::io::{Read, Write}; + use std::os::fd::{AsRawFd, FromRawFd}; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + + struct Temp(std::path::PathBuf); + impl Temp { + fn new() -> Self { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".tmp"); + fs::create_dir_all(&root).unwrap(); + let path = root.join(format!("native-lock-fork-test-{}", std::process::id())); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temp { + fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } + } + + struct ChildGuard { pid: libc::pid_t, reaped: bool } + impl ChildGuard { + fn wait(&mut self) -> std::io::Result { + let deadline = Instant::now() + Duration::from_secs(10); + let mut status = 0; + loop { + // SAFETY: pid is the child returned by this test's fork. + let result = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) }; + if result == self.pid { self.reaped = true; return Ok(status); } + if result < 0 { + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ECHILD) { self.reaped = true; } + if error.raw_os_error() != Some(libc::EINTR) { return Err(error); } + } + if Instant::now() >= deadline { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "child did not exit")); + } + std::thread::sleep(Duration::from_millis(5)); + } + } + } + impl Drop for ChildGuard { + fn drop(&mut self) { + if !self.reaped { + // SAFETY: this is our unreaped child, so its PID cannot be reused. + unsafe { libc::kill(self.pid, libc::SIGKILL); } + if let Err(error) = self.wait() { eprintln!("could not reap test child: {error}"); } + } + } + } + + fn pipe() -> (File, File) { + let mut fds = [-1; 2]; + // SAFETY: fds points to two writable integers; ownership is transferred + // to exactly one File per descriptor after successful pipe2. + assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + unsafe { (File::from_raw_fd(fds[0]), File::from_raw_fd(fds[1])) } + } + + #[test] + fn normal_drop_unlocks_even_while_forked_child_waits_before_exec() { + let temp = Temp::new(); + let path = temp.0.join("write.lock"); + let guard = acquire_lock(&path, &temp.0).unwrap(); + let (drop_tx, drop_rx) = mpsc::channel(); + let (dropped_tx, dropped_rx) = mpsc::channel(); + let owner = std::thread::spawn(move || { + let _ = drop_rx.recv(); + drop(guard); + let _ = dropped_tx.send(()); + }); + let (mut notify_read, notify_write) = pipe(); + let (release_read, mut release_write) = pipe(); + let notify_read_fd = notify_read.as_raw_fd(); + let notify_write_fd = notify_write.as_raw_fd(); + let release_read_fd = release_read.as_raw_fd(); + let release_write_fd = release_write.as_raw_fd(); + // SAFETY: another thread owns the guard. After fork the child calls + // only async-signal-safe libc functions before exec or _exit. + let pid = unsafe { libc::fork() }; + if pid == 0 { + unsafe { + libc::close(notify_read_fd); + libc::close(release_write_fd); + let ready = [1u8]; + if libc::write(notify_write_fd, ready.as_ptr().cast(), 1) != 1 { libc::_exit(120); } + let mut resume = [0u8]; + if libc::read(release_read_fd, resume.as_mut_ptr().cast(), 1) != 1 { libc::_exit(121); } + let argv = [c"true".as_ptr(), std::ptr::null()]; + let env = [std::ptr::null()]; + libc::execve(c"/bin/true".as_ptr(), argv.as_ptr(), env.as_ptr()); + libc::_exit(122); + } + } + assert!(pid > 0, "fork failed"); + let mut child = ChildGuard { pid, reaped: false }; + drop(notify_write); + drop(release_read); + let (ready_tx, ready_rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut byte = [0u8; 1]; + let _ = ready_tx.send(notify_read.read_exact(&mut byte)); + }); + ready_rx.recv_timeout(Duration::from_secs(10)).unwrap().unwrap(); + assert!(acquire_lock(&path, &temp.0).is_err()); + drop_tx.send(()).unwrap(); + dropped_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + owner.join().unwrap(); + // The child is definitely alive and has not yet executed CLOEXEC. + let reacquired = acquire_lock(&path, &temp.0).unwrap(); + drop(reacquired); + release_write.write_all(&[1]).unwrap(); + drop(release_write); + let status = child.wait().unwrap(); + assert!(libc::WIFEXITED(status)); + assert_eq!(libc::WEXITSTATUS(status), 0); + reader.join().unwrap(); + } +} diff --git a/src/porcelain.rs b/src/porcelain.rs index 73d7426..431a475 100644 --- a/src/porcelain.rs +++ b/src/porcelain.rs @@ -144,15 +144,7 @@ struct State { metadata: PathBuf, } -struct Lock(PathBuf, File); - -impl Drop for Lock { - fn drop(&mut self) { - // Keep the descriptor alive until cleanup finishes. - let _ = self.1.sync_all(); - let _ = fs::remove_file(&self.0); - } -} +type Lock = crate::platform_fs::ResourceLock; fn error(action: &str, path: &Path, error: std::io::Error) -> String { format!("cannot {action} {}: {error}", path.display()) @@ -582,12 +574,7 @@ impl State { fn lock(&self) -> Result { self.metadata_directories()?; let path = self.metadata.join("index.lock"); - let file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .map_err(|e| error("lock worktree metadata", &path, e))?; - Ok(Lock(path, file)) + crate::platform_fs::acquire_lock(&path, &self.metadata.join("tmp")) } fn index(&self) -> Result, String> { @@ -922,6 +909,10 @@ fn json_text(value: &impl Serialize) -> Result { /// The first argument is the command name. Existing file-based commit and /// checkout remain in repository::run; this dispatcher handles staged commit. pub fn run(args: &[String]) -> Result { + run_formatted(args, false) +} + +pub(crate) fn run_formatted(args: &[String], machine: bool) -> Result { if crate::command_args::help_requested(args) { return Ok(USAGE.into()); } @@ -934,7 +925,7 @@ pub fn run(args: &[String]) -> Result { match args[0].as_str() { "add" if args.len() > 2 => add(&state, &args[2..]), "status" if args.len() == 2 => status(&state), - "commit" => commit(&state, args), + "commit" => commit(&state, args, machine), "rm" => remove(&state, args), "mv" => match path_operands(&args[2..]).as_slice() { [old, new] => move_tracked(&state, old, new), @@ -1090,7 +1081,7 @@ pub fn move_linked_worktree(source: &str, target: &str, new_path: &str) -> Resul let result = source.move_linked_worktree(&state.repo.root, Path::new(new_path)); if !state.repo.root.exists() { if let Ok(moved) = crate::platform_fs::canonicalize(new_path) { - lock.0 = moved.join(".wasm-git/index.lock"); + lock.relocated(&moved.join(".wasm-git/index.lock")); } } json_text(&result?) @@ -1534,7 +1525,7 @@ fn status(state: &State) -> Result { } json_text(&report) } -fn commit(state: &State, args: &[String]) -> Result { +fn commit(state: &State, args: &[String], machine: bool) -> Result { let mut amend = false; let mut allow_empty = false; let mut message = None; @@ -1637,7 +1628,18 @@ fn commit(state: &State, args: &[String]) -> Result { state .save_index(&index) .map_err(|e| format!("commit {id} published, but index publication failed: {e}"))?; - Ok(format!("{} {id}", snapshot.head)) + if machine { + let result = crate::protocol::TreeCommitResult { + version: 1, + head: snapshot.head.clone(), + previous: head.cloned(), + commit: id, + }; + result.validate()?; + serde_json::to_string(&result).map_err(|e| e.to_string()) + } else { + Ok(format!("{} {id}", snapshot.head)) + } } #[derive(Clone, Debug, PartialEq, Eq)] struct Change { diff --git a/src/protocol.rs b/src/protocol.rs index 19f885c..d2b645c 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -6,12 +6,41 @@ use std::io::{Cursor, Read, Write}; const MAGIC: &[u8; 8] = b"WGTRPC02"; pub const TRANSFER_CHUNK: usize = 1024 * 1024; +pub const SCOPED_UPLOAD_STATUS_VERSION: u32 = 2; +pub const RETENTION_VERSION: u32 = 2; +pub const SERVER_POLICY_VERSION: u32 = 3; +pub const NODE_SAFE_INTEGER_MAX: u64 = 9_007_199_254_740_991; pub const MAX_BUNDLE_BYTES: u64 = 4 * 1024 * 1024 * 1024; pub const MAX_PACKET_BYTES: usize = 64 * 1024 * 1024; const MAX_METADATA_BYTES: usize = 65_536; const HEADER_BYTES: usize = 20; -#[derive(Debug, Serialize, Deserialize)] +#[path = "protocol_operation_credentials.rs"] +mod operation_credentials; +pub use operation_credentials::{ + OperationCredentialQuery, OperationCredentialQueryReply, OperationCredentialReceipt, + OperationCredentialRequest, +}; +#[path = "protocol_chunks.rs"] +mod chunks; +pub use chunks::{ + ScopedChunkCleanupReason, ScopedChunkData, ScopedChunkIdentity, ScopedChunkState, + ScopedChunkStatus, +}; +#[path = "protocol_capacity.rs"] +mod capacity; +pub use capacity::{AdmissionCapacity, RepositoryCapacity}; +#[path = "protocol_recovery.rs"] +mod recovery; +pub use recovery::{ + CapacityQueryReply, CapacityQueryRequest, OperationContextReply, OperationRecoveryReply, + OperationRecoveryRequest, RecoveryState, RecoveryUploadState, +}; +#[path = "protocol_audit.rs"] +mod audit; +pub use audit::*; + +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Request { pub version: u32, @@ -42,6 +71,268 @@ pub fn repository_component(name: &str) -> Result<(), String> { Ok(()) } +/// Native administrator input shared by the policy store and integrations. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ServerPolicy { + pub version: u32, + pub principals: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyPrincipal { + pub name: String, + pub token_sha256: Option, + pub grants: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyGrant { + pub repository: String, + pub read: bool, + pub write: Vec, + pub force: bool, + pub create: bool, + #[serde(default)] + pub release_retention: bool, + /// Exclusive UTC Unix-second boundary. None means no time limit. + #[serde(default)] + pub expires_at: Option, +} + +impl ServerPolicy { + pub fn validate(&self) -> Result<(), String> { + if self.version != SERVER_POLICY_VERSION || self.principals.len() > 4096 { + return Err("invalid policy version or principal count".into()); + } + let mut names = std::collections::BTreeSet::new(); + let mut tokens = std::collections::BTreeSet::new(); + for principal in &self.principals { + repository_component(&principal.name)?; + if !names.insert(&principal.name) { + return Err("duplicate policy principal".into()); + } + if let Some(hash) = &principal.token_sha256 { + crate::binary::oid(hash)?; + if !tokens.insert(hash) { + return Err("duplicate policy credential".into()); + } + } + for grant in &principal.grants { + if grant.expires_at.is_some_and(|t| t > NODE_SAFE_INTEGER_MAX) { + return Err("policy expiry exceeds the interoperable integer bound".into()); + } + let prefix = grant + .repository + .strip_suffix('*') + .unwrap_or(&grant.repository); + if grant.repository != "*" { + repository_name(prefix.strip_suffix('/').unwrap_or(prefix))?; + } + for reference in &grant.write { + let prefix = reference.strip_suffix('*').unwrap_or(reference); + if !(prefix.starts_with("refs/heads/") || prefix.starts_with("refs/tags/")) + || prefix.contains('*') + || prefix.contains("..") + || prefix.bytes().any(|b| b <= 32 || b >= 127) + { + return Err("policy write rules require refs/heads/ or refs/tags/ prefixes and an optional final '*'".into()); + } + } + } + } + Ok(()) + } + + pub fn digest(&self) -> Result { + use sha2::Digest; + self.validate()?; + Ok(format!( + "{:x}", + sha2::Sha256::digest(crate::binary::encode(self)?) + )) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyUpdateRequest { + pub version: u32, + pub operation_id: String, + pub expected_generation: u64, + pub policy: ServerPolicy, +} +impl PolicyUpdateRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 || self.expected_generation >= NODE_SAFE_INTEGER_MAX { + return Err("invalid policy update version or generation".into()); + } + crate::binary::oid(&self.operation_id)?; + self.policy.validate() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PolicyUpdateOutcome { + Applied, + GenerationConflict, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyUpdateReceipt { + pub version: u32, + pub operation_id: String, + pub expected_generation: u64, + pub outcome: PolicyUpdateOutcome, + /// Applied generation, or current generation observed by a conflict. + pub generation: u64, + pub policy_sha256: String, +} +impl PolicyUpdateReceipt { + pub fn validate(&self) -> Result<(), String> { + crate::binary::oid(&self.operation_id)?; + crate::binary::oid(&self.policy_sha256)?; + if self.version != 1 + || self.expected_generation >= NODE_SAFE_INTEGER_MAX + || self.generation > NODE_SAFE_INTEGER_MAX + || match self.outcome { + PolicyUpdateOutcome::Applied => self.generation != self.expected_generation + 1, + PolicyUpdateOutcome::GenerationConflict => { + self.generation == self.expected_generation + } + } + { + return Err("invalid policy update receipt".into()); + } + Ok(()) + } + pub fn validate_update(&self, request: &PolicyUpdateRequest) -> Result<(), String> { + request.validate()?; + self.validate()?; + if self.operation_id != request.operation_id + || self.expected_generation != request.expected_generation + || self.policy_sha256 != request.policy.digest()? + { + return Err("policy update receipt does not match the requested operation".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyQueryRequest { + pub version: u32, + pub operation_id: String, +} +impl PolicyQueryRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("invalid policy query version".into()); + } + crate::binary::oid(&self.operation_id)?; + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyQueryReply { + pub version: u32, + pub operation_id: String, + #[serde(deserialize_with = "present_option")] + pub receipt: Option, +} +impl PolicyQueryReply { + pub fn validate_update(&self, request: &PolicyUpdateRequest) -> Result<(), String> { + request.validate()?; + if self.version != 1 || self.operation_id != request.operation_id { + return Err("policy query operation mismatch".into()); + } + if let Some(receipt) = &self.receipt { + receipt.validate_update(request)?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyStatus { + pub version: u32, + pub generation: u64, + pub policy_sha256: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyMigrationRequest { + pub version: u32, + pub source_sha256: String, +} +impl PolicyMigrationRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("invalid policy migration request version".into()); + } + crate::binary::oid(&self.source_sha256).map(|_| ()) + } +} + +/// Historical receipt for an exact source image, not the current policy state. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyMigrationReceipt { + pub version: u32, + pub source_sha256: String, + pub source_version: u32, + pub target_version: u32, + pub generation: u64, + #[serde(deserialize_with = "present_option")] + pub policy_sha256: Option, + pub receipts: u64, +} +impl PolicyMigrationReceipt { + pub fn validate(&self) -> Result<(), String> { + crate::binary::oid(&self.source_sha256)?; + if self.version != 1 + || self.source_version != 1 + || self.target_version != 2 + || self.generation > NODE_SAFE_INTEGER_MAX + || self.receipts > NODE_SAFE_INTEGER_MAX + || self.receipts < self.generation + || (self.generation == 0) != self.policy_sha256.is_none() + { + return Err("invalid policy migration receipt".into()); + } + if let Some(digest) = &self.policy_sha256 { + crate::binary::oid(digest)?; + } + Ok(()) + } + pub fn validate_request(&self, request: &PolicyMigrationRequest) -> Result<(), String> { + request.validate()?; + self.validate()?; + if self.source_sha256 != request.source_sha256 { + return Err("policy migration source mismatch".into()); + } + Ok(()) + } +} +impl PolicyStatus { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 || self.generation == 0 || self.generation > NODE_SAFE_INTEGER_MAX { + return Err("invalid policy status version or generation".into()); + } + crate::binary::oid(&self.policy_sha256)?; + Ok(()) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RefNamespace { @@ -49,8 +340,8 @@ pub enum RefNamespace { Tag, } -#[derive(Debug, Serialize, Deserialize)] - +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub enum Operation { Advertise {}, Fetch {}, @@ -104,13 +395,1468 @@ pub enum Operation { dry_run: bool, }, PullRequest {}, + ReleaseRetention { + command: RetentionCommand, + }, + ScopedUploadSlice { + session: String, + binding: UploadBinding, + offset: u64, + }, + ApplyScopedUpload { + session: String, + binding: UploadBinding, + }, + CancelScopedUpload { + session: String, + binding: UploadBinding, + }, + QueryScopedUpload { + session: String, + binding: UploadBinding, + }, + UploadChunk { + chunk: ScopedChunkIdentity, + }, + QueryChunk { + chunk: ScopedChunkIdentity, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum ScopedUploadState { + Open, + Applying, + Finished { + response: Response, + payload: Vec, + }, + Canceled, + /// A v4 operation has not yet recorded its native decision. + ApplyingV4 { + repository: String, + }, + /// The v4 operation was interrupted before any native decision. + Aborted { + repository: String, + }, + /// The durable native decision, including the exact reference results. + FinishedV4 { + receipt: Box, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedUploadStatus { + pub version: u32, + #[serde(deserialize_with = "present_option")] + pub state: Option, +} + +impl ScopedUploadStatus { + pub fn validate_for( + &self, + repository: &str, + session: &str, + binding: &UploadBinding, + ) -> Result<(), String> { + if self.version != SCOPED_UPLOAD_STATUS_VERSION { + return Err("unsupported scoped upload status".into()); + } + repository_name(repository)?; + crate::binary::oid(session)?; + binding.validate()?; + match &self.state { + Some( + ScopedUploadState::ApplyingV4 { repository: actual } + | ScopedUploadState::Aborted { repository: actual }, + ) if actual != repository => Err("scoped upload repository mismatch".into()), + Some(ScopedUploadState::Finished { response, payload }) + if response.version != 1 || payload.len() > MAX_PACKET_BYTES => + { + Err("invalid legacy scoped upload receipt".into()) + } + Some(ScopedUploadState::FinishedV4 { receipt }) => { + receipt.validate()?; + if receipt.aborted + || receipt.scope.repository != repository + || receipt.scope.session != session + || crate::binary::encode(&receipt.scope.binding)? + != crate::binary::encode(binding)? + { + return Err("scoped upload receipt identity mismatch".into()); + } + Ok(()) + } + _ => Ok(()), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedExecution { + pub actor: String, + pub repository: String, + pub session: String, + pub binding: UploadBinding, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedReceipt { + pub version: u32, + pub scope: ScopedExecution, + pub updates: Vec, + pub rejections: Vec>, + pub dry_run: bool, + pub aborted: bool, + pub response: Response, + pub payload: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UploadBindingRequest { + pub version: u32, + #[serde(with = "publication")] + pub operation: Box, +} + +impl UploadBindingRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported upload binding request version".into()); + } + match self.operation.as_ref() { + Operation::Push { .. } | Operation::UpdateRef { .. } => { + let targets = upload_targets(&self.operation, &[])?; + UploadBinding { + version: 1, + digest: "0".repeat(64), + total: 1, + operation: self.operation.clone(), + targets, + } + .validate() + } + Operation::PublishBatch {} + | Operation::PublishOptions {} + | Operation::CheckBatch {} + | Operation::PublishPartial { .. } => Ok(()), + _ => Err("invalid upload binding operation".into()), + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UploadRecovery { + pub version: u32, + pub repository_url: String, + pub session: String, + pub binding: UploadBinding, + pub payload_file: String, +} + +impl UploadRecovery { + pub fn validate(&self, payload: &[u8]) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported upload recovery version".into()); + } + crate::remote::validate_remote_url(&self.repository_url)?; + crate::binary::oid(&self.session)?; + if self.payload_file != format!("upload-{}.bin", self.session) { + return Err("invalid upload recovery payload name".into()); + } + self.binding.validate_payload(payload) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum ScopedUploadCommand { + Slice { + session: String, + binding: UploadBinding, + offset: u64, + bytes: Vec, + }, + Apply { + session: String, + binding: UploadBinding, + }, + Cancel { + session: String, + binding: UploadBinding, + }, + Query { + session: String, + binding: UploadBinding, + }, + Chunk { + chunk: ScopedChunkIdentity, + bytes: Vec, + }, + QueryChunk { + chunk: ScopedChunkIdentity, + }, } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedUploadRequest { + pub version: u32, + pub command: ScopedUploadCommand, +} + +impl ScopedUploadRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported scoped upload request version".into()); + } + let (session, binding) = match &self.command { + ScopedUploadCommand::Chunk { chunk, bytes } => { + chunk.validate_payload(bytes)?; + (&chunk.scope.session, &chunk.scope.binding) + } + ScopedUploadCommand::QueryChunk { chunk } => { + chunk.validate()?; + (&chunk.scope.session, &chunk.scope.binding) + } + ScopedUploadCommand::Slice { + session, + binding, + offset, + bytes, + } => { + binding.validate_slice(*offset, bytes.len())?; + (session, binding) + } + ScopedUploadCommand::Apply { session, binding } + | ScopedUploadCommand::Cancel { session, binding } + | ScopedUploadCommand::Query { session, binding } => (session, binding), + }; + crate::binary::oid(session)?; + binding.validate() + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum ScopedUploadReply { + Acknowledged { + version: u32, + session: String, + }, + Applied { + version: u32, + session: String, + response: Response, + payload: Vec, + }, + Status { + version: u32, + session: String, + status: ScopedUploadStatus, + }, + Chunk { + version: u32, + status: ScopedChunkStatus, + }, +} + +impl ScopedUploadReply { + pub fn validate_for( + &self, + repository: &str, + request: &ScopedUploadRequest, + ) -> Result<(), String> { + repository_name(repository)?; + request.validate()?; + match (&request.command, self) { + ( + ScopedUploadCommand::Chunk { chunk, .. }, + ScopedUploadReply::Chunk { version: 1, status }, + ) => { + chunk.validate_scope(repository, &chunk.scope.actor)?; + status.validate_for(chunk)?; + if !matches!(status.state, ScopedChunkState::Accepted { .. }) { + return Err("chunk acknowledgement has no accepted decision".into()); + } + Ok(()) + } + ( + ScopedUploadCommand::QueryChunk { chunk }, + ScopedUploadReply::Chunk { version: 1, status }, + ) => { + chunk.validate_scope(repository, &chunk.scope.actor)?; + status.validate_for(chunk) + } + ( + ScopedUploadCommand::Slice { session, .. } + | ScopedUploadCommand::Cancel { session, .. }, + ScopedUploadReply::Acknowledged { + version: 1, + session: actual, + }, + ) if session == actual => Ok(()), + ( + ScopedUploadCommand::Query { session, binding }, + ScopedUploadReply::Status { + version: 1, + session: actual, + status, + }, + ) if session == actual => status.validate_for(repository, session, binding), + ( + ScopedUploadCommand::Apply { session, binding }, + ScopedUploadReply::Applied { + version: 1, + session: actual, + response, + payload, + }, + ) if session == actual => { + if response.version != 1 + || !response.ok + || response.publication_unknown + || response.error.is_some() + || response.state.is_some() + { + return Err("invalid scoped apply response".into()); + } + match binding.operation.as_ref() { + Operation::Push { .. } => { + crate::binary::oid(response.tip.as_deref().ok_or("missing push tip")?)?; + } + Operation::UpdateRef { new, .. } if response.tip == *new => (), + Operation::PublishBatch {} + | Operation::PublishOptions {} + | Operation::CheckBatch {} + | Operation::PublishPartial { .. } + if response.tip.as_deref() == Some(binding.digest.as_str()) => {} + _ => return Err("scoped apply response does not match operation".into()), + } + if matches!(*binding.operation, Operation::PublishPartial { .. }) { + let receipt: PartialReceipt = crate::binary::decode(payload)?; + if receipt.rejections.len() != binding.targets.len() { + return Err("partial receipt count mismatch".into()); + } + } else if !payload.is_empty() { + return Err("unexpected scoped apply payload".into()); + } + Ok(()) + } + _ => Err("scoped upload response does not match request".into()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UploadTarget { + pub reference: String, + pub force: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UploadBinding { + pub version: u32, + pub digest: String, + pub total: u64, + #[serde(with = "publication")] + pub operation: Box, + pub targets: Vec, +} + +impl UploadBinding { + pub fn validate_slice(&self, offset: u64, length: usize) -> Result<(), String> { + self.validate()?; + if !offset.is_multiple_of(TRANSFER_CHUNK as u64) + || offset >= self.total + || length as u64 != (self.total - offset).min(TRANSFER_CHUNK as u64) + { + return Err("invalid scoped upload slice bounds".into()); + } + Ok(()) + } + + pub fn for_payload(operation: Operation, payload: &[u8]) -> Result { + use sha2::{Digest, Sha256}; + let targets = upload_targets(&operation, payload)?; + let result = Self { + version: 1, + digest: format!("{:x}", Sha256::digest(payload)), + total: payload.len() as u64, + operation: Box::new(operation), + targets, + }; + result.validate()?; + Ok(result) + } + + pub fn validate(&self) -> Result<(), String> { + crate::binary::oid(&self.digest)?; + if self.version != 1 + || self.total == 0 + || self.total > MAX_BUNDLE_BYTES + || self.targets.is_empty() + || self.targets.len() > 4096 + { + return Err("invalid scoped upload binding".into()); + } + for target in &self.targets { + let name = target + .reference + .strip_prefix("refs/heads/") + .or_else(|| target.reference.strip_prefix("refs/tags/")) + .ok_or("invalid upload target namespace")?; + crate::repository::validate_ref_name(name)?; + } + match self.operation.as_ref() { + Operation::Push { .. } | Operation::UpdateRef { .. } => { + if upload_targets(&self.operation, &[])? != self.targets { + return Err("upload target does not match operation".into()); + } + } + Operation::PublishBatch {} + | Operation::PublishOptions {} + | Operation::CheckBatch {} + | Operation::PublishPartial { .. } => (), + _ => return Err("invalid scoped upload operation".into()), + } + Ok(()) + } + + pub fn validate_payload(&self, payload: &[u8]) -> Result<(), String> { + use sha2::{Digest, Sha256}; + self.validate()?; + if payload.len() as u64 != self.total + || format!("{:x}", Sha256::digest(payload)) != self.digest + { + return Err("uploaded bundle checksum mismatch".into()); + } + if upload_targets(&self.operation, payload)? != self.targets { + return Err("uploaded targets do not match binding".into()); + } + Ok(()) + } +} + +fn upload_targets(operation: &Operation, payload: &[u8]) -> Result, String> { + match operation { + Operation::Push { branch, force, .. } => Ok(vec![UploadTarget { + reference: format!("refs/heads/{branch}"), + force: *force, + }]), + Operation::UpdateRef { + namespace, + name, + force, + .. + } => Ok(vec![UploadTarget { + reference: format!( + "refs/{}/{name}", + if matches!(namespace, RefNamespace::Branch) { + "heads" + } else { + "tags" + } + ), + force: *force, + }]), + Operation::PublishBatch {} + | Operation::PublishOptions {} + | Operation::CheckBatch {} + | Operation::PublishPartial { .. } => { + let (publication, _) = publication_payload(operation, payload)?; + Ok(publication + .updates + .into_iter() + .map(|u| UploadTarget { + reference: format!( + "refs/{}/{}", + if matches!(u.namespace, RefNamespace::Branch) { + "heads" + } else { + "tags" + }, + u.name + ), + force: u.force, + }) + .collect()) + } + _ => Err("invalid scoped upload operation".into()), + } +} + +/// The repository holder records protection; the coordinator owns the release +/// decision. IDs are 32-byte lowercase hexadecimal values scoped to a repo. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum RetentionCommand { + Prepare { + operation: String, + commit: String, + paths: Vec, + }, + Query { + operation: String, + }, + Promote { + operation: String, + }, + Close { + operation: String, + }, + Read { + operation: String, + path: String, + offset: u64, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum RetentionState { + Prepared, + Promoted, + Closed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RetainedFile { + pub blob: String, + pub sha256: String, + pub size: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RetentionRecord { + pub version: u32, + pub operation: String, + pub actor: String, + pub state: RetentionState, + #[serde(deserialize_with = "present_option")] + pub repository: Option, + #[serde(deserialize_with = "present_option")] + pub commit: Option, + pub files: std::collections::BTreeMap, +} + +impl RetentionRecord { + pub fn validate(&self) -> Result<(), String> { + if self.version != RETENTION_VERSION + || self.actor.is_empty() + || self.actor.len() > 128 + || self.files.len() > 128 + { + return Err("invalid release retention record".into()); + } + crate::binary::oid(&self.operation)?; + if let Some(repository) = &self.repository { + repository_name(repository)?; + } + match (&self.state, &self.commit) { + (RetentionState::Closed, None) if self.files.is_empty() => (), + (_, Some(commit)) if !self.files.is_empty() => { + crate::binary::oid(commit)?; + } + _ => return Err("invalid release retention contents".into()), + } + for (path, file) in &self.files { + crate::repository::validate_tree_path(path)?; + if path.len() > 1024 || file.size < 8 { + return Err("invalid retained file".into()); + } + crate::binary::oid(&file.blob)?; + crate::binary::oid(&file.sha256)?; + } + Ok(()) + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum RetentionReply { + State { + version: u32, + repository: String, + operation: String, + #[serde(deserialize_with = "present_option")] + record: Option, + }, + File { + version: u32, + repository: String, + actor: String, + operation: String, + commit: String, + path: String, + file: RetainedFile, + offset: u64, + bytes: Vec, + }, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RetentionRequest { + pub version: u32, + pub command: RetentionCommand, +} + +impl RetentionRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported retention request version".into()); + } + let operation = match &self.command { + RetentionCommand::Prepare { + operation, + commit, + paths, + } => { + crate::binary::oid(commit)?; + if paths.is_empty() || paths.len() > 128 { + return Err("release retention requires 1..=128 paths".into()); + } + let unique: std::collections::BTreeSet<_> = paths.iter().collect(); + if unique.len() != paths.len() { + return Err("duplicate release path".into()); + } + for path in paths { + crate::repository::validate_tree_path(path)?; + if path.len() > 1024 { + return Err("release path too long".into()); + } + } + operation + } + RetentionCommand::Read { + operation, path, .. + } => { + crate::repository::validate_tree_path(path)?; + if path.len() > 1024 { + return Err("release path too long".into()); + } + operation + } + RetentionCommand::Query { operation } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } => operation, + }; + crate::binary::oid(operation)?; + Ok(()) + } +} + +impl RetentionReply { + /// Validate a decoded response against the exact request before exposing it + /// to an integration. Transport errors remain unknown outcomes. + pub fn validate_for(&self, repository: &str, request: &RetentionCommand) -> Result<(), String> { + repository_name(repository)?; + let id = match request { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Query { operation } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } + | RetentionCommand::Read { operation, .. } => operation, + }; + crate::binary::oid(id)?; + match (request, self) { + ( + RetentionCommand::Read { path, offset, .. }, + RetentionReply::File { + version: RETENTION_VERSION, + repository: returned_repository, + actor, + operation, + commit, + path: returned, + file, + offset: got, + bytes, + }, + ) if returned_repository == repository + && !actor.is_empty() + && actor.len() <= 128 + && operation == id + && returned == path + && got == offset => + { + crate::repository::validate_tree_path(path)?; + crate::binary::oid(commit)?; + crate::binary::oid(&file.blob)?; + crate::binary::oid(&file.sha256)?; + if *offset >= file.size + || bytes.len() as u64 != (file.size - offset).min(TRANSFER_CHUNK as u64) + { + return Err("invalid retained file slice".into()); + } + if *offset == 0 && bytes.len() as u64 == file.size { + use sha2::{Digest, Sha256}; + if format!("{:x}", Sha256::digest(bytes)) != file.sha256 { + return Err("retained file checksum mismatch".into()); + } + } + Ok(()) + } + ( + RetentionCommand::Query { .. }, + RetentionReply::State { + version: RETENTION_VERSION, + repository: returned_repository, + operation, + record: None, + }, + ) if returned_repository == repository && operation == id => Ok(()), + ( + _, + RetentionReply::State { + version: RETENTION_VERSION, + repository: returned_repository, + operation, + record: Some(record), + }, + ) if returned_repository == repository + && operation == id + && record.version == RETENTION_VERSION + && &record.operation == id + && !record.actor.is_empty() => + { + record.validate()?; + if record.repository.as_deref() != Some(repository) + && !(record.repository.is_none() + && matches!(request, RetentionCommand::Query { .. })) + { + return Err("retention repository mismatch".into()); + } + match request { + RetentionCommand::Prepare { commit, paths, .. } => { + let selected: std::collections::BTreeSet<_> = paths.iter().collect(); + if record.state == RetentionState::Closed + || record.commit.as_ref() != Some(commit) + || selected.len() != paths.len() + || !record.files.keys().eq(selected) + { + return Err("retention prepare response mismatch".into()); + } + } + RetentionCommand::Promote { .. } + if record.state != RetentionState::Promoted => + { + return Err("retention promotion response mismatch".into()) + } + RetentionCommand::Close { .. } if record.state != RetentionState::Closed => { + return Err("retention close response mismatch".into()) + } + RetentionCommand::Read { .. } => { + return Err("retention response is not a file".into()) + } + _ => (), + } + Ok(()) + } + _ => Err("invalid release retention response".into()), + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IntegrationCapabilities { + pub version: u32, + pub tool_version: String, + pub target_os: String, + pub target_arch: String, + pub target_env: String, + pub rpc_version: u32, + pub retention_version: u32, + pub scoped_upload_request_version: u32, + pub scoped_upload_status_version: u32, + pub scoped_receipt_version: u32, + pub scoped_chunk_version: u32, + pub server_policy_version: u32, + pub node_safe_integer_max: u64, + pub authorization_natural_expiry: bool, + pub authorization_revocation_fence: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandError { + pub code: String, + pub message: String, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum CommandResult { + Data { value: T }, + Empty, + Text { text: String }, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandEnvelope { + pub protocol: String, + pub version: u32, + pub command: String, + pub ok: bool, + pub exit_code: i32, + pub result: CommandResult, + #[serde(deserialize_with = "present_option")] + pub error: Option, +} + +/// Machine result for a staged tree commit. `head` is the identity before +/// publication: a branch name or, for detached HEAD, its previous commit ID. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TreeCommitResult { + pub version: u32, + pub head: String, + /// Previous HEAD tip; `--amend` may retain different commit parents. + #[serde(deserialize_with = "present_option")] + pub previous: Option, + pub commit: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SignCommitResult { + pub version: u32, + pub head: String, + pub previous: String, + pub commit: String, + pub author: String, +} + +/// The identity and digest are derived from the same locked snapshot and +/// byte buffer used to publish the bundle, not from a later repository read. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundleResult { + pub version: u32, + pub head: String, + #[serde(deserialize_with = "present_option")] + pub tip: Option, + pub objects: u64, + pub bytes: u64, + pub sha256: String, +} + +fn validate_head_and_tip(head: &str, tip: Option<&str>) -> Result<(), String> { + crate::repository::validate_head_identity(head)?; + if let Some(tip) = tip { + crate::binary::oid(tip)?; + } + if crate::repository::is_detached_identity(head) && tip != Some(head) { + return Err("detached HEAD does not match its tip".into()); + } + Ok(()) +} + +impl TreeCommitResult { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported tree commit result version".into()); + } + validate_head_and_tip(&self.head, self.previous.as_deref())?; + crate::binary::oid(&self.commit).map(|_| ()) + } +} + +impl SignCommitResult { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported sign commit result version".into()); + } + validate_head_and_tip(&self.head, Some(&self.previous))?; + crate::binary::oid(&self.commit)?; + crate::repository::validate_author_identity(&self.author) + } +} + +impl BundleResult { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 + || self.bytes == 0 + || self.bytes > NODE_SAFE_INTEGER_MAX + || self.objects > NODE_SAFE_INTEGER_MAX + || (self.tip.is_some() && self.objects == 0) + { + return Err("invalid bundle result".into()); + } + validate_head_and_tip(&self.head, self.tip.as_deref())?; + crate::binary::oid(&self.sha256).map(|_| ()) + } +} + +impl CommandEnvelope { + pub fn validate_for(&self, command: &str, process_exit: i32) -> Result, String> { + if self.protocol != "wasm-git.command" + || self.version != 1 + || self.command != command + || self.exit_code != process_exit + || self.ok != (process_exit == 0) + { + return Err("command envelope or process status mismatch".into()); + } + match (&self.result, &self.error, self.ok) { + (CommandResult::Data { value }, None, true) => Ok(Some(value)), + (CommandResult::Empty, Some(error), false) + if error.code == "command_failed" && !error.message.is_empty() => + { + Ok(None) + } + _ => Err("invalid command result".into()), + } + } +} + +impl IntegrationCapabilities { + pub fn current() -> Self { + Self { + version: 1, + tool_version: env!("CARGO_PKG_VERSION").into(), + target_os: std::env::consts::OS.into(), + target_arch: std::env::consts::ARCH.into(), + target_env: if cfg!(target_env = "musl") { + "musl" + } else if cfg!(target_env = "gnu") { + "gnu" + } else if cfg!(target_env = "msvc") { + "msvc" + } else { + "other" + } + .into(), + rpc_version: 1, + retention_version: RETENTION_VERSION, + scoped_upload_request_version: 1, + scoped_upload_status_version: SCOPED_UPLOAD_STATUS_VERSION, + scoped_receipt_version: 4, + scoped_chunk_version: 1, + server_policy_version: SERVER_POLICY_VERSION, + node_safe_integer_max: NODE_SAFE_INTEGER_MAX, + authorization_natural_expiry: false, + authorization_revocation_fence: cfg!(all( + target_os = "linux", + target_arch = "x86_64", + any(target_env = "gnu", target_env = "musl") + )), + } + } + pub fn validate(&self) -> Result<(), String> { + if crate::binary::encode(self)? != crate::binary::encode(&Self::current())? { + return Err("integration capabilities do not match this native build".into()); + } + Ok(()) + } +} + +/// Check the original JSON before a JavaScript consumer can round numbers or +/// collapse duplicate object members, including members of dynamic maps. +/// This does not restrict u64 values in the native binary protocol. +pub fn validate_node_safe_json(input: &[u8]) -> Result<(), String> { + use serde::de::{Error, MapAccess, SeqAccess, Visitor}; + + struct CheckedValue; + impl<'de> Deserialize<'de> for CheckedValue { + fn deserialize>(deserializer: D) -> Result { + struct CheckedVisitor; + impl<'de> Visitor<'de> for CheckedVisitor { + type Value = CheckedValue; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("JSON with unique object keys and exact JavaScript-safe integers") + } + fn visit_bool(self, _: bool) -> Result { + Ok(CheckedValue) + } + fn visit_str(self, _: &str) -> Result { + Ok(CheckedValue) + } + fn visit_unit(self) -> Result { + Ok(CheckedValue) + } + fn visit_i64(self, value: i64) -> Result { + if value.unsigned_abs() <= NODE_SAFE_INTEGER_MAX { + Ok(CheckedValue) + } else { + Err(E::custom( + "JSON number is not an exact JavaScript safe integer", + )) + } + } + fn visit_u64(self, value: u64) -> Result { + if value <= NODE_SAFE_INTEGER_MAX { + Ok(CheckedValue) + } else { + Err(E::custom( + "JSON number is not an exact JavaScript safe integer", + )) + } + } + fn visit_f64(self, _: f64) -> Result { + Err(E::custom( + "JSON number is not an exact JavaScript safe integer", + )) + } + fn visit_seq>(self, mut seq: A) -> Result { + while seq.next_element::()?.is_some() {} + Ok(CheckedValue) + } + fn visit_map>(self, mut map: A) -> Result { + let mut keys = std::collections::HashSet::new(); + while let Some(key) = map.next_key::()? { + if !keys.insert(key) { + return Err(A::Error::custom("duplicate JSON object key")); + } + map.next_value::()?; + } + Ok(CheckedValue) + } + } + deserializer.deserialize_any(CheckedVisitor) + } + } + serde_json::from_slice::(input) + .map(|_| ()) + .map_err(|e| format!("invalid integration JSON: {e}")) +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum IntegrationValidation { + ChunkIdentity { + chunk: ScopedChunkIdentity, + }, + ChunkStatus { + chunk: ScopedChunkIdentity, + status: ScopedChunkStatus, + }, + OperationCredentialRequest { + request: OperationCredentialRequest, + }, + OperationCredentialQuery { + request: OperationCredentialQuery, + }, + OperationCredentialIssueCliReply { + request: OperationCredentialRequest, + process_exit: i32, + response: CommandEnvelope, + }, + OperationCredentialQueryCliReply { + request: OperationCredentialRequest, + process_exit: i32, + response: CommandEnvelope, + }, + PolicyMigrationRequest { + request: PolicyMigrationRequest, + }, + PolicyMigrationCliReply { + request: PolicyMigrationRequest, + process_exit: i32, + response: CommandEnvelope, + }, + PolicyUpdateRequest { + request: PolicyUpdateRequest, + }, + PolicyQueryRequest { + request: PolicyQueryRequest, + }, + PolicyUpdateCliReply { + request: PolicyUpdateRequest, + process_exit: i32, + response: CommandEnvelope, + }, + PolicyQueryCliReply { + request: PolicyUpdateRequest, + process_exit: i32, + response: CommandEnvelope, + }, + PolicyStatusCliReply { + process_exit: i32, + response: CommandEnvelope, + }, + RetentionRequest { + request: RetentionRequest, + }, + RetentionReply { + repository: String, + request: RetentionRequest, + reply: RetentionReply, + }, + UploadBinding { + binding: UploadBinding, + }, + UploadBindingRequest { + request: UploadBindingRequest, + }, + UploadBindingCliReply { + request: UploadBindingRequest, + process_exit: i32, + response: CommandEnvelope, + }, + UploadRequest { + request: ScopedUploadRequest, + }, + UploadReply { + repository: String, + request: ScopedUploadRequest, + reply: ScopedUploadReply, + }, + RetentionCliReply { + repository: String, + request: RetentionRequest, + process_exit: i32, + response: CommandEnvelope, + }, + UploadCliReply { + repository: String, + request: ScopedUploadRequest, + process_exit: i32, + response: CommandEnvelope, + }, + Capabilities { + capabilities: IntegrationCapabilities, + }, + CapabilitiesCliReply { + process_exit: i32, + response: CommandEnvelope, + }, + TreeCommitCliReply { + head: String, + #[serde(deserialize_with = "present_option")] + previous: Option, + process_exit: i32, + response: CommandEnvelope, + }, + SignCommitCliReply { + head: String, + previous: String, + author: String, + process_exit: i32, + response: CommandEnvelope, + }, + BundleCliReply { + head: String, + #[serde(deserialize_with = "present_option")] + tip: Option, + process_exit: i32, + response: CommandEnvelope, + }, + BundleUploadBinding { + bundle: BundleResult, + binding: UploadBinding, + }, + OperationRecoveryRequest { + request: OperationRecoveryRequest, + }, + OperationRecoveryCliReply { + request: OperationRecoveryRequest, + process_exit: i32, + response: Box>, + }, + OperationContextCliReply { + request: OperationCredentialQuery, + process_exit: i32, + response: CommandEnvelope, + }, + AuditQueryRequest { + request: AuditQueryRequest, + }, + AuditQueryCliReply { + request: AuditQueryRequest, + process_exit: i32, + response: CommandEnvelope, + }, + CapacityQueryRequest { + request: CapacityQueryRequest, + }, + CapacityQueryCliReply { + request: CapacityQueryRequest, + process_exit: i32, + response: CommandEnvelope, + }, +} + +impl IntegrationValidation { + pub fn validate(&self) -> Result<(), String> { + match self { + Self::OperationRecoveryRequest { request } => request.validate(), + Self::OperationRecoveryCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = response.validate_for("operation-recover", *process_exit)? { + reply.validate_for(request)?; + } + Ok(()) + } + Self::OperationContextCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = response.validate_for("operation-context", *process_exit)? { + reply.validate_for(request)?; + } + Ok(()) + } + Self::AuditQueryRequest { request } => request.validate(), + Self::AuditQueryCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = response.validate_for("audit-query", *process_exit)? { + reply.validate_for(request)?; + } + Ok(()) + } + Self::CapacityQueryRequest { request } => request.validate(), + Self::CapacityQueryCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = response.validate_for("capacity-query", *process_exit)? { + reply.validate_for(request)?; + } + Ok(()) + } + Self::ChunkIdentity { chunk } => chunk.validate(), + Self::ChunkStatus { chunk, status } => status.validate_for(chunk), + Self::OperationCredentialRequest { request } => request.validate(), + Self::OperationCredentialQuery { request } => request.validate(), + Self::OperationCredentialIssueCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(receipt) = + response.validate_for("operation-credential-issue", *process_exit)? + { + receipt.validate_request(request)?; + } + Ok(()) + } + Self::OperationCredentialQueryCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = + response.validate_for("operation-credential-query", *process_exit)? + { + reply.validate_request(request)?; + } + Ok(()) + } + Self::PolicyMigrationRequest { request } => request.validate(), + Self::PolicyMigrationCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(receipt) = response.validate_for("policy-migrate", *process_exit)? { + receipt.validate_request(request)?; + } + Ok(()) + } + Self::PolicyUpdateRequest { request } => request.validate(), + Self::PolicyQueryRequest { request } => request.validate(), + Self::PolicyUpdateCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(receipt) = response.validate_for("policy-set", *process_exit)? { + receipt.validate_update(request)?; + } + Ok(()) + } + Self::PolicyQueryCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(reply) = response.validate_for("policy-query", *process_exit)? { + reply.validate_update(request)?; + } + Ok(()) + } + Self::PolicyStatusCliReply { + process_exit, + response, + } => { + if let Some(status) = response.validate_for("policy-status", *process_exit)? { + status.validate()?; + } + Ok(()) + } + Self::RetentionRequest { request } => request.validate(), + Self::RetentionReply { + repository, + request, + reply, + } => { + request.validate()?; + reply.validate_for(repository, &request.command) + } + Self::UploadBinding { binding } => binding.validate(), + Self::UploadBindingRequest { request } => request.validate(), + Self::UploadBindingCliReply { + request, + process_exit, + response, + } => { + request.validate()?; + if let Some(binding) = response.validate_for("upload-binding", *process_exit)? { + binding.validate()?; + if crate::binary::encode(binding.operation.as_ref())? + != crate::binary::encode(request.operation.as_ref())? + { + return Err("upload binding operation mismatch".into()); + } + } + Ok(()) + } + Self::UploadRequest { request } => request.validate(), + Self::UploadReply { + repository, + request, + reply, + } => reply.validate_for(repository, request), + Self::RetentionCliReply { + repository, + request, + process_exit, + response, + } => { + repository_name(repository)?; + request.validate()?; + if let Some(reply) = response.validate_for("retention-rpc", *process_exit)? { + reply.validate_for(repository, &request.command)?; + } + Ok(()) + } + Self::UploadCliReply { + repository, + request, + process_exit, + response, + } => { + repository_name(repository)?; + request.validate()?; + if let Some(reply) = response.validate_for("scoped-upload-rpc", *process_exit)? { + reply.validate_for(repository, request)?; + } + Ok(()) + } + Self::Capabilities { capabilities } => capabilities.validate(), + Self::CapabilitiesCliReply { + process_exit, + response, + } => { + if let Some(capabilities) = + response.validate_for("integration-capabilities", *process_exit)? + { + capabilities.validate()?; + } + Ok(()) + } + Self::TreeCommitCliReply { + head, + previous, + process_exit, + response, + } => { + validate_head_and_tip(head, previous.as_deref())?; + if let Some(result) = response.validate_for("commit", *process_exit)? { + result.validate()?; + if &result.head != head || &result.previous != previous { + return Err("tree commit result identity mismatch".into()); + } + } + Ok(()) + } + Self::SignCommitCliReply { + head, + previous, + author, + process_exit, + response, + } => { + validate_head_and_tip(head, Some(previous))?; + crate::repository::validate_author_identity(author)?; + if let Some(result) = response.validate_for("sign-commit", *process_exit)? { + result.validate()?; + if &result.head != head + || &result.previous != previous + || &result.author != author + { + return Err("sign commit result identity mismatch".into()); + } + } + Ok(()) + } + Self::BundleCliReply { + head, + tip, + process_exit, + response, + } => { + validate_head_and_tip(head, tip.as_deref())?; + if let Some(result) = response.validate_for("bundle", *process_exit)? { + result.validate()?; + if &result.head != head || &result.tip != tip { + return Err("bundle result identity mismatch".into()); + } + } + Ok(()) + } + Self::BundleUploadBinding { bundle, binding } => { + bundle.validate()?; + binding.validate()?; + if bundle.bytes != binding.total || bundle.sha256 != binding.digest { + return Err("bundle and upload binding content mismatch".into()); + } + Ok(()) + } + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct RefUpdate { pub namespace: RefNamespace, pub name: String, + #[serde(deserialize_with = "present_option")] pub expected: Option, + #[serde(deserialize_with = "present_option")] pub new: Option, pub force: bool, } @@ -194,16 +1940,20 @@ mod publication { }, } #[derive(Deserialize)] + #[serde(deny_unknown_fields)] enum Owned { Push { branch: String, + #[serde(deserialize_with = "present_option")] expected: Option, force: bool, }, UpdateRef { namespace: RefNamespace, name: String, + #[serde(deserialize_with = "present_option")] expected: Option, + #[serde(deserialize_with = "present_option")] new: Option, force: bool, }, @@ -286,22 +2036,25 @@ mod publication { // A nullable mutation operand must still be present. Serde's ordinary Option // default would turn an omitted `new` into a deletion and an omitted lease into // the explicit absence expectation. deserialize_with also makes absence an error. -fn present_option<'de, D>(deserializer: D) -> Result, D::Error> +fn present_option<'de, D, T>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, + T: Deserialize<'de>, { - Option::::deserialize(deserializer) + Option::::deserialize(deserializer) } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Response { pub version: u32, pub ok: bool, - #[serde(default)] pub publication_unknown: bool, + #[serde(deserialize_with = "present_option")] pub error: Option, + #[serde(deserialize_with = "present_option")] pub state: Option, + #[serde(deserialize_with = "present_option")] pub tip: Option, } @@ -381,6 +2134,80 @@ pub fn read_complete_packet( #[cfg(test)] mod tests { use super::*; + + #[test] + fn policy_migration_receipts_bind_the_exact_source_and_preserve_empty_policy_state() { + let request = PolicyMigrationRequest { + version: 1, + source_sha256: "a".repeat(64), + }; + let receipt = PolicyMigrationReceipt { + version: 1, + source_sha256: request.source_sha256.clone(), + source_version: 1, + target_version: 2, + generation: 0, + policy_sha256: None, + receipts: 1, + }; + receipt.validate_request(&request).unwrap(); + let validation = IntegrationValidation::PolicyMigrationCliReply { + request: request.clone(), + process_exit: 0, + response: CommandEnvelope { + protocol: "wasm-git.command".into(), + version: 1, + command: "policy-migrate".into(), + ok: true, + exit_code: 0, + result: CommandResult::Data { + value: receipt.clone(), + }, + error: None, + }, + }; + validation.validate().unwrap(); + let mut invalid = receipt.clone(); + invalid.source_sha256 = "b".repeat(64); + assert!(invalid.validate_request(&request).is_err()); + invalid = receipt.clone(); + invalid.generation = 1; + assert!(invalid.validate().is_err()); + invalid.policy_sha256 = Some("c".repeat(64)); + invalid.receipts = 0; + assert!(invalid.validate().is_err()); + invalid.receipts = 1; + invalid.target_version = 3; + assert!(invalid.validate().is_err()); + let mut missing = serde_json::to_value(&receipt).unwrap(); + missing.as_object_mut().unwrap().remove("policy_sha256"); + assert!(serde_json::from_value::(missing).is_err()); + } + + #[test] + fn scoped_json_requires_explicit_leases_and_rejects_unknown_fields() { + let missing = + serde_json::json!({"version":1,"operation":{"Push":{"branch":"topic","force":false}}}); + assert!(serde_json::from_value::(missing).is_err()); + let extra = serde_json::json!({"version":1,"operation":{"Push":{"branch":"topic","expected":null,"force":false,"ignored":true}}}); + assert!(serde_json::from_value::(extra).is_err()); + let omitted_new = + serde_json::json!({"namespace":"branch","name":"topic","expected":null,"force":false}); + assert!(serde_json::from_value::(omitted_new).is_err()); + } + + #[test] + fn node_validation_checks_original_keys_and_numbers() { + assert!(validate_node_safe_json( + br#"{"value":9007199254740991,"items":[-9007199254740991,true,null,"text"]}"# + ) + .is_ok()); + assert!(validate_node_safe_json(br#"{"value":9007199254740992}"#).is_err()); + assert!(validate_node_safe_json(br#"{"value":-9007199254740992}"#).is_err()); + assert!(validate_node_safe_json(br#"{"value":1.0}"#).is_err()); + assert!(validate_node_safe_json(br#"{"items":[{"key":1,"\u006bey":2}]}"#).is_err()); + assert!(validate_node_safe_json(br#"{"value":1} {}"#).is_err()); + } fn request(operation: Operation) -> Request { Request { version: 1, diff --git a/src/protocol_audit.rs b/src/protocol_audit.rs new file mode 100644 index 0000000..72e99e5 --- /dev/null +++ b/src/protocol_audit.rs @@ -0,0 +1,463 @@ +//! Bounded local audit projections. Native receipts remain the source of +//! repository decisions; an observation is only evidence of one scoped read. +use super::*; + +pub const AUDIT_PAGE_MAX_ITEMS: u32 = 100; +pub const AUDIT_PAGE_MAX_BYTES: usize = 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditOperator { + pub version: u32, + pub identity: String, +} + +impl AuditOperator { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 + || self.identity.is_empty() + || self.identity.len() > 256 + || self.identity.chars().any(char::is_control) + { + return Err("invalid audit operator".into()); + } + Ok(()) + } +} + +/// A legacy import records its observer and observation time, not an invented +/// original issuer or issuance time. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum AuditAttribution { + Recorded { + operator: AuditOperator, + unix_millis: u64, + }, + LegacyImported { + observer: AuditOperator, + observed_at_unix_millis: u64, + }, +} + +impl AuditAttribution { + pub fn validate(&self) -> Result<(), String> { + let (operator, time) = match self { + Self::Recorded { + operator, + unix_millis, + } => (operator, unix_millis), + Self::LegacyImported { + observer, + observed_at_unix_millis, + } => (observer, observed_at_unix_millis), + }; + operator.validate()?; + if *time > NODE_SAFE_INTEGER_MAX { + return Err("invalid audit time".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum RecoveryAuditAction { + Inspect, + Close, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuditObservationScope { + Chunk, + UploadSession, + Retention, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum AuditEvidenceObservation { + /// No native decision was observed at this instant. A delayed original + /// request may still arrive unless the caller has fenced it separately. + Unobserved, + /// Hash of a canonical, validated native state or receipt, not a claim + /// that this particular operation caused that state. + Observed { + sha256: String, + }, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditObservation { + pub version: u32, + pub scope: AuditObservationScope, + pub evidence: AuditEvidenceObservation, +} + +impl AuditObservation { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("invalid audit observation version".into()); + } + if let AuditEvidenceObservation::Observed { sha256 } = &self.evidence { + crate::binary::oid(sha256)?; + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditRecordedObservation { + pub observed_at_unix_millis: u64, + pub source: AuditObservationSource, + pub observation: AuditObservation, +} + +impl AuditRecordedObservation { + pub fn validate(&self) -> Result<(), String> { + if self.observed_at_unix_millis > NODE_SAFE_INTEGER_MAX { + return Err("invalid audit observation time".into()); + } + self.source.validate()?; + self.observation.validate() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum AuditObservationSource { + OriginalAttempt, + RecoveryAttempt { + recovery_id: String, + attempt_id: u64, + }, +} + +impl AuditObservationSource { + pub fn validate(&self) -> Result<(), String> { + if let Self::RecoveryAttempt { + recovery_id, + attempt_id, + } = self + { + crate::binary::oid(recovery_id)?; + if *attempt_id == 0 || *attempt_id > NODE_SAFE_INTEGER_MAX { + return Err("invalid recovery audit attempt".into()); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum AuditTarget { + Operation { + operation_id: String, + attempt_id: u64, + }, + Recovery { + recovery_id: String, + attempt_id: u64, + }, +} + +impl AuditTarget { + pub fn validate(&self) -> Result<(), String> { + let (id, attempt_id) = match self { + Self::Operation { + operation_id, + attempt_id, + } => (operation_id, attempt_id), + Self::Recovery { + recovery_id, + attempt_id, + } => (recovery_id, attempt_id), + }; + crate::binary::oid(id)?; + if *attempt_id == 0 || *attempt_id > NODE_SAFE_INTEGER_MAX { + return Err("invalid audit attempt".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditOperationScope { + pub actor: String, + pub repository: String, + #[serde(deserialize_with = "present_option")] + pub session: Option, + #[serde(deserialize_with = "present_option")] + pub retention_operation: Option, +} + +impl AuditOperationScope { + pub(crate) fn from_original(original: &OperationCredentialRequest) -> Result { + original.validate()?; + let (session, retention_operation) = match &original.request.operation { + Operation::UploadChunk { chunk } | Operation::QueryChunk { chunk } => { + (Some(chunk.scope.session.clone()), None) + } + Operation::ScopedUploadSlice { session, .. } + | Operation::ApplyScopedUpload { session, .. } + | Operation::CancelScopedUpload { session, .. } + | Operation::QueryScopedUpload { session, .. } => (Some(session.clone()), None), + Operation::ReleaseRetention { command } => { + let id = match command { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Query { operation } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } + | RetentionCommand::Read { operation, .. } => operation, + }; + (None, Some(id.clone())) + } + _ => (None, None), + }; + let scope = Self { + actor: original.actor.clone(), + repository: original.request.repository.clone(), + session, + retention_operation, + }; + scope.validate()?; + Ok(scope) + } + + pub fn validate(&self) -> Result<(), String> { + repository_component(&self.actor)?; + repository_name(&self.repository)?; + if let Some(session) = &self.session { + crate::binary::oid(session)?; + } + if let Some(operation) = &self.retention_operation { + crate::binary::oid(operation)?; + } + if self.session.is_some() && self.retention_operation.is_some() { + return Err("invalid audit operation scope".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum AuditItem { + Policy { + receipt: PolicyUpdateReceipt, + attribution: AuditAttribution, + }, + Credential { + operation_id: String, + scope: AuditOperationScope, + request_sha256: String, + attribution: AuditAttribution, + }, + Recovery { + recovery_id: String, + original_operation_id: String, + scope: AuditOperationScope, + action: RecoveryAuditAction, + operator: AuditOperator, + recorded_at_unix_millis: u64, + }, + OperationAttempt { + operation_id: String, + scope: AuditOperationScope, + started_at_unix_millis: u64, + #[serde(deserialize_with = "present_option")] + observation: Option, + }, + RecoveryAttempt { + recovery_id: String, + original_operation_id: String, + scope: AuditOperationScope, + action: RecoveryAuditAction, + operator: AuditOperator, + started_at_unix_millis: u64, + #[serde(deserialize_with = "present_option")] + observation: Option, + }, +} + +impl AuditItem { + pub fn validate(&self) -> Result<(), String> { + match self { + Self::Policy { + receipt, + attribution, + } => { + receipt.validate()?; + attribution.validate() + } + Self::Credential { + operation_id, + scope, + request_sha256, + attribution, + } => { + crate::binary::oid(operation_id)?; + scope.validate()?; + crate::binary::oid(request_sha256)?; + attribution.validate() + } + Self::Recovery { + recovery_id, + original_operation_id, + scope, + operator, + recorded_at_unix_millis, + .. + } => { + crate::binary::oid(recovery_id)?; + crate::binary::oid(original_operation_id)?; + scope.validate()?; + operator.validate()?; + if *recorded_at_unix_millis > NODE_SAFE_INTEGER_MAX { + return Err("invalid recovery audit time".into()); + } + Ok(()) + } + Self::OperationAttempt { + operation_id, + scope, + started_at_unix_millis, + observation, + } => { + crate::binary::oid(operation_id)?; + scope.validate()?; + if *started_at_unix_millis > NODE_SAFE_INTEGER_MAX { + return Err("invalid operation attempt time".into()); + } + if let Some(observation) = observation { + observation.validate()?; + } + Ok(()) + } + Self::RecoveryAttempt { + recovery_id, + original_operation_id, + scope, + operator, + started_at_unix_millis, + observation, + .. + } => { + crate::binary::oid(recovery_id)?; + crate::binary::oid(original_operation_id)?; + scope.validate()?; + operator.validate()?; + if *started_at_unix_millis > NODE_SAFE_INTEGER_MAX { + return Err("invalid recovery attempt time".into()); + } + if let Some(observation) = observation { + observation.validate()?; + } + Ok(()) + } + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditSummary { + pub version: u32, + pub sequence: u64, + pub item: AuditItem, +} + +impl AuditSummary { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 || self.sequence == 0 || self.sequence > NODE_SAFE_INTEGER_MAX { + return Err("invalid audit sequence".into()); + } + self.item.validate() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditQueryRequest { + pub version: u32, + pub after: u64, + #[serde(deserialize_with = "present_option")] + pub high_water: Option, + pub limit: u32, +} + +impl AuditQueryRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 + || self.limit == 0 + || self.limit > AUDIT_PAGE_MAX_ITEMS + || self.after > NODE_SAFE_INTEGER_MAX + || self + .high_water + .is_some_and(|water| water > NODE_SAFE_INTEGER_MAX || self.after > water) + || (self.high_water.is_none() && self.after != 0) + { + return Err("invalid audit page request".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditQueryReply { + pub version: u32, + pub high_water: u64, + /// New work stops at this cumulative index watermark. Recovery and policy + /// revocation still have access; their records remain in high_water. + pub max_admission_entries: u64, + pub items: Vec, + #[serde(deserialize_with = "present_option")] + pub next_after: Option, +} + +impl AuditQueryReply { + pub fn validate_for(&self, request: &AuditQueryRequest) -> Result<(), String> { + request.validate()?; + if self.version != 1 + || self.high_water > NODE_SAFE_INTEGER_MAX + || self.max_admission_entries == 0 + || self.max_admission_entries > NODE_SAFE_INTEGER_MAX + || request + .high_water + .is_some_and(|water| water != self.high_water) + || request.after > self.high_water + || self.items.len() > request.limit as usize + { + return Err("invalid audit page header".into()); + } + let mut last = request.after; + for item in &self.items { + item.validate()?; + if item.sequence != last + 1 || item.sequence > self.high_water { + return Err("audit page sequence gap".into()); + } + last = item.sequence; + } + let expected_next = if last < self.high_water { + Some(last) + } else { + None + }; + if self.next_after != expected_next || (self.items.is_empty() && expected_next.is_some()) { + return Err("invalid audit page continuation".into()); + } + if serde_json::to_vec(self) + .map_err(|error| error.to_string())? + .len() + > AUDIT_PAGE_MAX_BYTES + { + return Err("audit page exceeds byte bound".into()); + } + Ok(()) + } +} diff --git a/src/protocol_capacity.rs b/src/protocol_capacity.rs new file mode 100644 index 0000000..84e5dc6 --- /dev/null +++ b/src/protocol_capacity.rs @@ -0,0 +1,88 @@ +use serde::{Deserialize, Serialize}; + +/// Encoded record bytes and counts; terminal records remain in the totals. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AdmissionCapacity { + pub active_records: u64, + pub active_bytes: u64, + pub total_records: u64, + pub total_bytes: u64, + pub max_active_records: u64, + pub max_active_bytes: u64, +} + +impl AdmissionCapacity { + pub fn validate(&self) -> Result<(), String> { + let values = [ + self.active_records, + self.active_bytes, + self.total_records, + self.total_bytes, + self.max_active_records, + self.max_active_bytes, + ]; + if values + .iter() + .any(|value| *value > super::NODE_SAFE_INTEGER_MAX) + || self.max_active_records == 0 + || self.max_active_bytes == 0 + || self.active_records > self.total_records + || self.active_bytes > self.total_bytes + { + return Err("invalid repository admission capacity".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RepositoryCapacity { + pub version: u32, + pub scoped: AdmissionCapacity, + pub retentions: AdmissionCapacity, +} + +impl RepositoryCapacity { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported repository capacity version".into()); + } + self.scoped.validate()?; + self.retentions.validate() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_safe_integers_without_hiding_over_watermark_usage() { + let mut usage = AdmissionCapacity { + active_records: 2, + active_bytes: 3, + total_records: 2, + total_bytes: 3, + max_active_records: 1, + max_active_bytes: 1, + }; + let mut status = RepositoryCapacity { + version: 1, + scoped: usage.clone(), + retentions: usage.clone(), + }; + assert!(status.validate().is_ok()); + usage.active_records = 3; + assert!(usage.validate().is_err()); + usage.active_records = 2; + usage.total_bytes = super::super::NODE_SAFE_INTEGER_MAX + 1; + assert!(usage.validate().is_err()); + status.version = 2; + assert!(status.validate().is_err()); + status.version = 1; + status.retentions.max_active_bytes = 0; + assert!(status.validate().is_err()); + } +} diff --git a/src/protocol_chunks.rs b/src/protocol_chunks.rs new file mode 100644 index 0000000..01b3dc7 --- /dev/null +++ b/src/protocol_chunks.rs @@ -0,0 +1,219 @@ +//! Original-operation chunk facts owned by the native repository holder. +use super::*; +use sha2::{Digest, Sha256}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedChunkIdentity { + pub version: u32, + pub operation_id: String, + pub scope: ScopedExecution, + pub offset: u64, + pub payload_sha256: String, +} + +impl ScopedChunkIdentity { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported chunk identity version".into()); + } + crate::binary::oid(&self.operation_id)?; + crate::binary::oid(&self.scope.session)?; + crate::binary::oid(&self.payload_sha256)?; + repository_component(&self.scope.actor)?; + repository_name(&self.scope.repository)?; + self.scope.binding.validate()?; + let length = self + .scope + .binding + .total + .saturating_sub(self.offset) + .min(TRANSFER_CHUNK as u64); + self.scope + .binding + .validate_slice(self.offset, length as usize) + } + + pub fn validate_scope(&self, repository: &str, actor: &str) -> Result<(), String> { + self.validate()?; + if self.scope.repository != repository || self.scope.actor != actor { + return Err("chunk scope does not match the authenticated request".into()); + } + Ok(()) + } + + pub fn validate_payload(&self, bytes: &[u8]) -> Result<(), String> { + self.validate()?; + self.scope + .binding + .validate_slice(self.offset, bytes.len())?; + if self.payload_sha256 != format!("{:x}", Sha256::digest(bytes)) { + return Err("chunk bytes do not match the original operation".into()); + } + Ok(()) + } + + pub fn upload_request(&self) -> Result { + self.validate()?; + Ok(Request { + version: 1, + repository: self.scope.repository.clone(), + operation: Operation::UploadChunk { + chunk: self.clone(), + }, + }) + } + + pub fn validate_credential( + &self, + credential: &OperationCredentialReceipt, + ) -> Result<(), String> { + self.validate()?; + credential.validate()?; + let request = self.upload_request()?; + if credential.operation_id != self.operation_id + || credential.actor != self.scope.actor + || credential.request_sha256 != request.credential_digest(&self.payload_sha256)? + || credential.effect_key != request.credential_effect_key(&self.scope.actor)? + { + return Err("chunk does not match the original issued operation".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ScopedChunkCleanupReason { + Completed, + Canceled, + Expired, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum ScopedChunkData { + Available, + Cleaned { reason: ScopedChunkCleanupReason }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum ScopedChunkState { + /// No decision was observed under the holder's lock. This is not a + /// permanent non-acceptance or a tombstone against a delayed original call. + Unobserved, + Accepted { + data: ScopedChunkData, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ScopedChunkStatus { + pub version: u32, + pub chunk: ScopedChunkIdentity, + pub state: ScopedChunkState, +} + +impl ScopedChunkStatus { + pub fn validate_for(&self, chunk: &ScopedChunkIdentity) -> Result<(), String> { + self.chunk.validate()?; + chunk.validate()?; + if self.version != 1 || crate::binary::encode(&self.chunk)? != crate::binary::encode(chunk)? + { + return Err("chunk result does not match the original operation".into()); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn chunk() -> ScopedChunkIdentity { + ScopedChunkIdentity { + version: 1, + operation_id: "a".repeat(64), + scope: ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: "b".repeat(64), + binding: UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: None, + force: false, + }, + &[1, 2], + ) + .unwrap(), + }, + offset: 0, + payload_sha256: format!("{:x}", Sha256::digest([1, 2])), + } + } + #[test] + fn chunk_results_bind_original_scope_bytes_offset_and_operation() { + let chunk = chunk(); + chunk.validate_payload(&[1, 2]).unwrap(); + assert!(chunk.validate_payload(&[2, 1]).is_err()); + let mut changed = chunk.clone(); + changed.scope.actor = "bob".into(); + for state in [ + ScopedChunkState::Unobserved, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available, + }, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { + reason: ScopedChunkCleanupReason::Expired, + }, + }, + ] { + let status = ScopedChunkStatus { + version: 1, + chunk: chunk.clone(), + state, + }; + status.validate_for(&chunk).unwrap(); + assert!(status.validate_for(&changed).is_err()); + } + let mut changed = chunk.clone(); + changed.offset = 1; + assert!(changed.validate().is_err()); + changed = chunk.clone(); + changed.operation_id = "c".repeat(64); + let credential = OperationCredentialRequest { + version: 1, + operation_id: chunk.operation_id.clone(), + policy_generation: 1, + actor: chunk.scope.actor.clone(), + token_sha256: "d".repeat(64), + request: chunk.upload_request().unwrap(), + payload_sha256: chunk.payload_sha256.clone(), + expires_at: 100, + } + .receipt() + .unwrap(); + chunk.validate_credential(&credential).unwrap(); + assert!(changed.validate_credential(&credential).is_err()); + let query = ScopedUploadRequest { + version: 1, + command: ScopedUploadCommand::QueryChunk { + chunk: chunk.clone(), + }, + }; + let reply = ScopedUploadReply::Chunk { + version: 1, + status: ScopedChunkStatus { + version: 1, + chunk, + state: ScopedChunkState::Unobserved, + }, + }; + reply.validate_for("project", &query).unwrap(); + assert!(reply.validate_for("other", &query).is_err()); + } +} diff --git a/src/protocol_operation_credentials.rs b/src/protocol_operation_credentials.rs new file mode 100644 index 0000000..b391994 --- /dev/null +++ b/src/protocol_operation_credentials.rs @@ -0,0 +1,208 @@ +//! The holder binds an issued credential to one exact native request. A +//! mutation's identity is independent of its input and of its bearer token. +use super::*; +use sha2::{Digest, Sha256}; + +fn hash(domain: &[u8], parts: &[&[u8]]) -> String { + let mut hash = Sha256::new(); + hash.update(domain); + for part in parts { + hash.update((part.len() as u64).to_be_bytes()); + hash.update(part); + } + format!("{:x}", hash.finalize()) +} + +impl Request { + /// The strict entry point excludes operations without native per-operation + /// replay and terminal state. Legacy clients use their existing entry point. + pub fn credential_effect_key(&self, actor: &str) -> Result, String> { + if self.version != 1 { return Err("unsupported credential RPC version".into()); } + repository_name(&self.repository)?; + repository_component(actor)?; + let identity = match &self.operation { + Operation::Advertise {} | Operation::Fetch {} | Operation::FetchSlice { .. } + | Operation::ObjectSlice { .. } | Operation::RefsPage { .. } + | Operation::QueryScopedUpload { .. } => return Ok(None), + Operation::QueryChunk { chunk } => { + chunk.validate_scope(&self.repository, actor)?; + return Ok(None); + } + Operation::UploadChunk { chunk } => { + chunk.validate_scope(&self.repository, actor)?; + format!("upload:{}:{}", chunk.scope.session, chunk.offset) + } + Operation::ScopedUploadSlice { session, binding, offset } => { + crate::binary::oid(session)?; binding.validate()?; + format!("upload:{session}:{offset}") + } + Operation::ApplyScopedUpload { session, binding } => { + crate::binary::oid(session)?; binding.validate()?; + format!("apply:{session}") + } + Operation::CancelScopedUpload { session, binding } => { + crate::binary::oid(session)?; binding.validate()?; + format!("cancel:{session}") + } + Operation::ReleaseRetention { command } => { + RetentionRequest { version: 1, command: command.clone() }.validate()?; + match command { + RetentionCommand::Query { .. } | RetentionCommand::Read { .. } => return Ok(None), + RetentionCommand::Prepare { operation, .. } => format!("retain:{operation}"), + RetentionCommand::Promote { operation } => format!("promote:{operation}"), + RetentionCommand::Close { operation } => format!("close:{operation}"), + } + } + _ => return Err("operation is not supported by the strict credential entry point".into()), + }; + Ok(Some(hash(b"wasm-git.mutation-identity.v1\0", &[actor.as_bytes(), self.repository.as_bytes(), identity.as_bytes()]))) + } + + pub fn credential_digest(&self, payload_sha256: &str) -> Result { + if self.version != 1 { return Err("unsupported credential RPC version".into()); } + repository_name(&self.repository)?; + crate::binary::oid(payload_sha256)?; + let metadata = crate::binary::encode(self)?; + if metadata.len() > MAX_METADATA_BYTES { return Err("credential request metadata exceeds bound".into()); } + Ok(hash(b"wasm-git.operation-request.v1\0", &[&metadata, payload_sha256.as_bytes()])) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationCredentialRequest { + pub version: u32, + pub operation_id: String, + pub policy_generation: u64, + pub actor: String, + pub token_sha256: String, + pub request: Request, + pub payload_sha256: String, + /// Exclusive UTC Unix-second bound chosen by the trusted issuer from all + /// original identity, admission, grant and operation deadline bounds. + pub expires_at: u64, +} + +impl OperationCredentialRequest { + pub fn receipt(&self) -> Result { + if let Operation::UploadChunk { chunk } = &self.request.operation { + if self.operation_id != chunk.operation_id || self.payload_sha256 != chunk.payload_sha256 { + return Err("chunk issuance must bind its original operation and bytes".into()); + } + } + let receipt = OperationCredentialReceipt { + version: self.version, operation_id: self.operation_id.clone(), policy_generation: self.policy_generation, actor: self.actor.clone(), + token_sha256: self.token_sha256.clone(), + request_sha256: self.request.credential_digest(&self.payload_sha256)?, + effect_key: self.request.credential_effect_key(&self.actor)?, expires_at: self.expires_at, + }; + receipt.validate()?; + Ok(receipt) + } + pub fn validate(&self) -> Result<(), String> { self.receipt().map(|_| ()) } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationCredentialReceipt { + pub version: u32, + pub operation_id: String, + pub policy_generation: u64, + pub actor: String, + pub token_sha256: String, + pub request_sha256: String, + #[serde(deserialize_with = "present_option")] + pub effect_key: Option, + pub expires_at: u64, +} + +impl OperationCredentialReceipt { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 || self.expires_at == 0 || self.expires_at > NODE_SAFE_INTEGER_MAX + || self.policy_generation == 0 || self.policy_generation > NODE_SAFE_INTEGER_MAX { + return Err("invalid operation credential version, generation or expiry".into()); + } + repository_component(&self.actor)?; + for id in [&self.operation_id, &self.token_sha256, &self.request_sha256] { crate::binary::oid(id)?; } + if let Some(key) = &self.effect_key { crate::binary::oid(key)?; } + Ok(()) + } + pub fn validate_request(&self, request: &OperationCredentialRequest) -> Result<(), String> { + self.validate()?; + if self != &request.receipt()? { return Err("operation credential does not match issuance".into()); } + Ok(()) + } + pub fn validate_rpc(&self, request: &Request, payload: &[u8]) -> Result<(), String> { + self.validate()?; + let digest = format!("{:x}", Sha256::digest(payload)); + if self.request_sha256 != request.credential_digest(&digest)? + || self.effect_key != request.credential_effect_key(&self.actor)? { + return Err("operation credential does not match the request".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationCredentialQuery { pub version: u32, pub operation_id: String } +impl OperationCredentialQuery { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { return Err("invalid operation credential query version".into()); } + crate::binary::oid(&self.operation_id).map(|_| ()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationCredentialQueryReply { + pub version: u32, pub operation_id: String, + #[serde(deserialize_with = "present_option")] + pub receipt: Option, +} +impl OperationCredentialQueryReply { + pub fn validate_request(&self, request: &OperationCredentialRequest) -> Result<(), String> { + request.validate()?; + if self.version != 1 || self.operation_id != request.operation_id { return Err("operation credential query mismatch".into()); } + if let Some(receipt) = &self.receipt { receipt.validate_request(request)?; } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn issuance() -> OperationCredentialRequest { + OperationCredentialRequest { version: 1, operation_id: "a".repeat(64), policy_generation: 1, actor: "alice".into(), + token_sha256: "b".repeat(64), expires_at: 100, + request: Request { version: 1, repository: "team/repo".into(), operation: Operation::ReleaseRetention { + command: RetentionCommand::Prepare { operation: "c".repeat(64), commit: "d".repeat(64), paths: vec!["main.wasm".into()] } } }, + payload_sha256: format!("{:x}", Sha256::digest([])) } + } + #[test] + fn credential_binds_exact_request_and_mutation_identity_cannot_be_renewed_by_new_input() { + let request = issuance(); let receipt = request.receipt().unwrap(); + receipt.validate_rpc(&request.request, &[]).unwrap(); + assert!(receipt.validate_rpc(&request.request, &[1]).is_err()); + let mut next = request.clone(); next.operation_id = "e".repeat(64); next.expires_at += 1; + next.request.operation = Operation::ReleaseRetention { command: RetentionCommand::Prepare { + operation: "c".repeat(64), commit: "f".repeat(64), paths: vec!["other.wasm".into()] } }; + let renewed = next.receipt().unwrap(); + assert_eq!(receipt.effect_key, renewed.effect_key); + assert_ne!(receipt.request_sha256, renewed.request_sha256); + assert!(receipt.validate_request(&next).is_err()); + next.actor = "bob".into(); assert_ne!(receipt.effect_key, next.receipt().unwrap().effect_key); + next.request.operation = Operation::ReleaseRetention { command: RetentionCommand::Query { operation: "c".repeat(64) } }; + assert_eq!(next.receipt().unwrap().effect_key, None); + next.request.operation = Operation::Push { branch: "main".into(), expected: None, force: false }; + assert!(next.receipt().is_err()); + } + #[test] + fn credential_rejects_unsafe_expiry_and_missing_nullable_identity() { + let mut request = issuance(); request.expires_at = NODE_SAFE_INTEGER_MAX + 1; + assert!(request.receipt().is_err()); request.expires_at = 100; + let mut value = serde_json::to_value(request.receipt().unwrap()).unwrap(); + value.as_object_mut().unwrap().remove("effect_key"); + assert!(serde_json::from_value::(value).is_err()); + } +} diff --git a/src/protocol_recovery.rs b/src/protocol_recovery.rs new file mode 100644 index 0000000..d78c739 --- /dev/null +++ b/src/protocol_recovery.rs @@ -0,0 +1,470 @@ +//! Restricted holder-side recovery. Issuance identifies an original mutation; +//! it never proves that mutation executed or renews its authorization. +use super::*; +use sha2::{Digest, Sha256}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationContextReply { + pub version: u32, + pub operation_id: String, + #[serde(deserialize_with = "present_option")] + pub original: Option, +} +impl OperationContextReply { + pub fn validate_for(&self, request: &OperationCredentialQuery) -> Result<(), String> { + request.validate()?; + if self.version != 1 || self.operation_id != request.operation_id { + return Err("operation context identity mismatch".into()); + } + if let Some(original) = &self.original { + original.validate()?; + if original.operation_id != self.operation_id { + return Err("original operation context mismatch".into()); + } + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CapacityQueryRequest { + pub version: u32, + pub repository: String, +} +impl CapacityQueryRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported capacity query version".into()); + } + repository_name(&self.repository) + } +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CapacityQueryReply { + pub version: u32, + pub repository: String, + pub capacity: RepositoryCapacity, +} +impl CapacityQueryReply { + pub fn validate_for(&self, request: &CapacityQueryRequest) -> Result<(), String> { + request.validate()?; + if self.version != 1 || self.repository != request.repository { + return Err("capacity result scope mismatch".into()); + } + self.capacity.validate() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationRecoveryRequest { + pub version: u32, + pub recovery_id: String, + pub original: OperationCredentialRequest, + pub action: RecoveryAuditAction, + #[serde(default)] + pub reconcile: Vec, +} + +impl OperationRecoveryRequest { + pub fn validate(&self) -> Result<(), String> { + if self.version != 1 { + return Err("unsupported operation recovery version".into()); + } + crate::binary::oid(&self.recovery_id)?; + self.original.validate()?; + if self.reconcile.len() > AUDIT_PAGE_MAX_ITEMS as usize { + return Err("too many recovery audit targets".into()); + } + for target in &self.reconcile { + target.validate()?; + } + if self.original.receipt()?.effect_key.is_none() { + return Err("recovery requires an original mutation credential".into()); + } + match &self.original.request.operation { + Operation::UploadChunk { chunk } => { + chunk.validate_scope(&self.original.request.repository, &self.original.actor)? + } + Operation::ScopedUploadSlice { + session, binding, .. + } => { + crate::binary::oid(session)?; + binding.validate()?; + } + Operation::ApplyScopedUpload { session, binding } + | Operation::CancelScopedUpload { session, binding } => { + crate::binary::oid(session)?; + binding.validate()?; + self.require_empty_original_payload()?; + } + Operation::ReleaseRetention { command } => { + if !matches!( + command, + RetentionCommand::Prepare { .. } + | RetentionCommand::Promote { .. } + | RetentionCommand::Close { .. } + ) { + return Err("recovery does not authorize retained file reads".into()); + } + RetentionRequest { + version: 1, + command: command.clone(), + } + .validate()?; + self.require_empty_original_payload()?; + } + _ => return Err("operation has no restricted recovery contract".into()), + } + Ok(()) + } + + fn require_empty_original_payload(&self) -> Result<(), String> { + if self.original.payload_sha256 != format!("{:x}", Sha256::digest([])) { + return Err("original operation requires an empty payload".into()); + } + Ok(()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum RecoveryUploadState { + /// No current scope decision. A delayed original request may still arrive. + Unobserved, + Open, + /// An older applying format cannot establish either commit or termination. + Unknown, + Canceled, + Aborted, + Finished { + receipt: Box, + }, + /// Legacy terminal state without a verifiable scoped result. + LegacyFinished, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub enum RecoveryState { + Upload { + session: String, + state: RecoveryUploadState, + /// The original chunk's durable decision survives scope cancellation. + #[serde(deserialize_with = "present_option")] + chunk: Option, + }, + Retention { + operation: String, + #[serde(deserialize_with = "present_option")] + record: Option, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperationRecoveryReply { + pub version: u32, + pub recovery_id: String, + pub attempt_id: u64, + pub original_operation_id: String, + pub actor: String, + pub repository: String, + pub operator: AuditOperator, + pub action: RecoveryAuditAction, + pub state: RecoveryState, +} + +impl OperationRecoveryReply { + pub fn validate_for(&self, request: &OperationRecoveryRequest) -> Result<(), String> { + request.validate()?; + self.operator.validate()?; + if self.version != 1 + || self.attempt_id == 0 + || self.attempt_id > NODE_SAFE_INTEGER_MAX + || self.recovery_id != request.recovery_id + || self.original_operation_id != request.original.operation_id + || self.actor != request.original.actor + || self.repository != request.original.request.repository + || self.action != request.action + { + return Err("recovery result does not match original scope".into()); + } + match (&self.state, &request.original.request.operation) { + ( + RecoveryState::Upload { + session, + state, + chunk, + }, + operation, + ) => { + let (expected, binding) = match operation { + Operation::UploadChunk { chunk } => { + (&chunk.scope.session, &chunk.scope.binding) + } + Operation::ScopedUploadSlice { + session, binding, .. + } + | Operation::ApplyScopedUpload { session, binding } + | Operation::CancelScopedUpload { session, binding } => (session, binding), + _ => return Err("recovery result has a different resource kind".into()), + }; + if session != expected { + return Err("recovery upload session mismatch".into()); + } + match (chunk, operation) { + (Some(status), Operation::UploadChunk { chunk }) => { + status.validate_for(chunk)? + } + (None, Operation::UploadChunk { .. }) | (Some(_), _) => { + return Err("recovery chunk decision mismatch".into()) + } + _ => (), + } + if let RecoveryUploadState::Finished { receipt } = state { + receipt.validate()?; + if receipt.aborted + || receipt.scope.repository != self.repository + || receipt.scope.actor != self.actor + || receipt.scope.session != *session + || crate::binary::encode(&receipt.scope.binding)? + != crate::binary::encode(binding)? + { + return Err("recovered receipt does not match original scope".into()); + } + } + if self.action == RecoveryAuditAction::Close + && matches!( + state, + RecoveryUploadState::Unobserved + | RecoveryUploadState::Open + | RecoveryUploadState::Unknown + ) + { + return Err("recovery close did not establish a terminal scope".into()); + } + } + ( + RecoveryState::Retention { operation, record }, + Operation::ReleaseRetention { command }, + ) => { + let expected = match command { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } => operation, + _ => return Err("unsupported original retention action".into()), + }; + if operation != expected { + return Err("recovery retention operation mismatch".into()); + } + if let Some(record) = record { + record.validate()?; + if record.actor != self.actor + || record.repository.as_deref() != Some(self.repository.as_str()) + || record.operation != *operation + { + return Err("recovery retention scope mismatch".into()); + } + if let RetentionCommand::Prepare { commit, paths, .. } = command { + if record.commit.is_some() + && (record.commit.as_ref() != Some(commit) + || record + .files + .keys() + .collect::>() + != paths.iter().collect()) + { + return Err("recovery retention preparation mismatch".into()); + } + } + } + if self.action == RecoveryAuditAction::Close + && !record.as_ref().is_some_and(|r| { + matches!(r.state, RetentionState::Closed | RetentionState::Promoted) + }) + { + return Err("recovery close did not establish a terminal retention".into()); + } + } + _ => return Err("recovery result has a different resource kind".into()), + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn original(operation: Operation) -> OperationCredentialRequest { + OperationCredentialRequest { + version: 1, + operation_id: "1".repeat(64), + policy_generation: 1, + actor: "alice".into(), + token_sha256: "2".repeat(64), + request: Request { + version: 1, + repository: "project".into(), + operation, + }, + payload_sha256: format!("{:x}", Sha256::digest([])), + expires_at: 100, + } + } + + fn reply(request: &OperationRecoveryRequest, state: RecoveryState) -> OperationRecoveryReply { + OperationRecoveryReply { + version: 1, + recovery_id: request.recovery_id.clone(), + attempt_id: 1, + original_operation_id: request.original.operation_id.clone(), + actor: request.original.actor.clone(), + repository: request.original.request.repository.clone(), + operator: AuditOperator { + version: 1, + identity: "unix:uid:1".into(), + }, + action: request.action, + state, + } + } + + #[test] + fn recovery_reply_checks_full_receipt_scope_and_retention_preparation() { + let update = RefUpdate { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some("a".repeat(64)), + force: false, + }; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: update.namespace.clone(), + name: update.name.clone(), + expected: update.expected.clone(), + new: update.new.clone(), + force: false, + }, + b"bundle", + ) + .unwrap(); + let session = "3".repeat(64); + let request = OperationRecoveryRequest { + version: 1, + recovery_id: "4".repeat(64), + original: original(Operation::ApplyScopedUpload { + session: session.clone(), + binding: binding.clone(), + }), + action: RecoveryAuditAction::Inspect, + reconcile: vec![], + }; + let scope = ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: session.clone(), + binding, + }; + let receipt = ScopedReceipt::success(&scope, &[update], &[None], false).unwrap(); + let mut result = reply( + &request, + RecoveryState::Upload { + session, + state: RecoveryUploadState::Finished { + receipt: Box::new(receipt), + }, + chunk: None, + }, + ); + result.validate_for(&request).unwrap(); + let mut wrong_actor = result.clone(); + if let RecoveryState::Upload { + state: RecoveryUploadState::Finished { receipt }, + .. + } = &mut wrong_actor.state + { + receipt.scope.actor = "bob".into(); + } + assert!(wrong_actor.validate_for(&request).is_err()); + let mut wrong_dry_run = result.clone(); + if let RecoveryState::Upload { + state: RecoveryUploadState::Finished { receipt }, + .. + } = &mut wrong_dry_run.state + { + receipt.dry_run = true; + } + assert!(wrong_dry_run.validate_for(&request).is_err()); + if let RecoveryState::Upload { + state: RecoveryUploadState::Finished { receipt }, + .. + } = &mut result.state + { + receipt.updates[0].name = "outside".into(); + } + assert!(result.validate_for(&request).is_err()); + + let operation = "5".repeat(64); + let commit = "6".repeat(64); + let request = OperationRecoveryRequest { + version: 1, + recovery_id: "7".repeat(64), + original: original(Operation::ReleaseRetention { + command: RetentionCommand::Prepare { + operation: operation.clone(), + commit: commit.clone(), + paths: vec!["app.wasm".into()], + }, + }), + action: RecoveryAuditAction::Inspect, + reconcile: vec![], + }; + let record = RetentionRecord { + version: RETENTION_VERSION, + operation: operation.clone(), + actor: "alice".into(), + repository: Some("project".into()), + state: RetentionState::Prepared, + commit: Some(commit), + files: std::collections::BTreeMap::from([( + "app.wasm".into(), + RetainedFile { + blob: "8".repeat(64), + sha256: "9".repeat(64), + size: 8, + }, + )]), + }; + let mut result = reply( + &request, + RecoveryState::Retention { + operation, + record: Some(record), + }, + ); + result.validate_for(&request).unwrap(); + let mut unbound = result.clone(); + if let RecoveryState::Retention { + record: Some(record), + .. + } = &mut unbound.state + { + record.repository = None; + } + assert!(unbound.validate_for(&request).is_err()); + if let RecoveryState::Retention { + record: Some(record), + .. + } = &mut result.state + { + record.commit = Some("a".repeat(64)); + } + assert!(result.validate_for(&request).is_err()); + } +} diff --git a/src/remote.rs b/src/remote.rs index 383f10a..7eee3fe 100644 --- a/src/remote.rs +++ b/src/remote.rs @@ -87,6 +87,10 @@ pub fn is_remote_url(value: &str) -> bool { value.starts_with("http://") || value.starts_with("https://") || value.starts_with("ssh://") } +pub(crate) fn validate_remote_url(value: &str) -> RepositoryResult<()> { + parse_url(value).map(|_| ()) +} + fn name(value: &str) -> RepositoryResult<()> { if value.is_empty() || value.len() > 64 @@ -863,13 +867,26 @@ fn exchange( if payload.len() as u64 > protocol::MAX_BUNDLE_BYTES { return Err("bundle exceeds the 4 GiB transfer limit".into()); } - let transfer = format!("{:x}", sha2::Sha256::digest(payload)); + let session = std::env::var("WASM_GIT_UPLOAD_SESSION").map_err(|_| { + "large uploads require WASM_GIT_UPLOAD_SESSION with a unique 64-digit hex ID" + })?; + crate::binary::oid(&session)?; + let recovery_directory = std::env::var_os("WASM_GIT_UPLOAD_RECOVERY_DIR") + .ok_or("large uploads require WASM_GIT_UPLOAD_RECOVERY_DIR")?; + let binding = protocol::UploadBinding::for_payload(operation, payload)?; + persist_upload_recovery( + Path::new(&recovery_directory), + remote, + &session, + &binding, + payload, + )?; for (i, chunk) in payload.chunks(protocol::TRANSFER_CHUNK).enumerate() { exchange( remote, - Operation::UploadSlice { - transfer: transfer.clone(), - total: payload.len() as u64, + Operation::ScopedUploadSlice { + session: session.clone(), + binding: binding.clone(), offset: (i * protocol::TRANSFER_CHUNK) as u64, }, chunk, @@ -878,15 +895,20 @@ fn exchange( } return exchange( remote, - Operation::ApplyUpload { - transfer, - operation: Box::new(operation), - }, + Operation::ApplyScopedUpload { session, binding }, &[], allow_http, ); } let endpoint = parse_url(&remote.url)?; + let retention_mutation = matches!( + &operation, + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Prepare { .. } + | protocol::RetentionCommand::Promote { .. } + | protocol::RetentionCommand::Close { .. } + } + ); let publishes = (matches!(&operation, Operation::PullRequest {}) && crate::binary::decode::(payload).is_ok_and(|p| p.mutates())) || matches!( @@ -899,8 +921,15 @@ fn exchange( | Operation::Fork { .. } ) || matches!(&operation, Operation::ApplyUpload { operation, .. } if !matches!(**operation, Operation::CheckBatch {} | Operation::PublishPartial { dry_run: true })); + let publishes = publishes + || matches!(&operation, Operation::ApplyScopedUpload { binding, .. } if !matches!(*binding.operation, Operation::CheckBatch {} | Operation::PublishPartial { dry_run: true })); + let upload_mutation = matches!(&operation, Operation::UploadChunk { .. } | Operation::ScopedUploadSlice { .. } | Operation::CancelScopedUpload { .. }); let uncertain = |error: String| { - if publishes { + if upload_mutation { + format!("remote upload outcome is unknown: {error}; query the original operation") + } else if retention_mutation { + format!("remote retention outcome is unknown: {error}; query the same operation") + } else if publishes { format!("remote publication outcome is unknown: {error}; inspect the remote before retrying") } else { error @@ -1010,7 +1039,13 @@ fn exchange( .as_deref() .unwrap_or("unspecified publication failure") }; - return Err(format!("remote publication outcome is unknown: {reason}")); + return Err(if upload_mutation { + format!("remote upload outcome is unknown: {reason}; query the original operation") + } else if retention_mutation { + format!("remote retention outcome is unknown: {reason}; query the same operation") + } else { + format!("remote publication outcome is unknown: {reason}") + }); } if !response.ok { return Err(format!( @@ -1026,6 +1061,291 @@ fn exchange( Ok((response, payload)) } +fn persist_upload_recovery( + directory: &Path, + remote: &Remote, + session: &str, + binding: &protocol::UploadBinding, + payload: &[u8], +) -> RepositoryResult<()> { + crate::binary::oid(session)?; + parse_url(&remote.url)?; + binding.validate_payload(payload)?; + let metadata = fs::symlink_metadata(directory).map_err(|e| e.to_string())?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err("upload recovery directory must be a real directory".into()); + } + let payload_name = format!("upload-{session}.bin"); + let payload_path = directory.join(&payload_name); + let state_path = directory.join(format!("upload-{session}.json")); + let record = protocol::UploadRecovery { + version: 1, + repository_url: remote.url.clone(), + session: session.into(), + binding: binding.clone(), + payload_file: payload_name, + }; + let state = serde_json::to_vec(&record).map_err(|e| e.to_string())?; + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut data = options + .open(&payload_path) + .map_err(|e| format!("create upload recovery payload: {e}"))?; + let mut file = match options.open(&state_path) { + Ok(file) => file, + Err(e) => { + drop(data); + fs::remove_file(&payload_path).map_err(|cleanup| { + format!("create upload recovery state: {e}; remove incomplete payload: {cleanup}") + })?; + return Err(format!("create upload recovery state: {e}")); + } + }; + let result = data + .write_all(payload) + .and_then(|()| data.sync_all()) + .and_then(|()| file.write_all(&state)) + .and_then(|()| file.sync_all()) + .map_err(|e| format!("persist upload recovery: {e}")); + drop(data); + drop(file); + if let Err(error) = result { + let a = fs::remove_file(&payload_path); + let b = fs::remove_file(&state_path); + return Err(format!("{error}; cleanup payload={a:?}, state={b:?}")); + } + crate::output::sync_directory(directory) +} + +/// JSON is decoded and validated by the same native types used by the server. +/// Credentials use the normal WASM_GIT_REMOTE_TOKEN mechanism, never arguments. +pub fn retention_cli(args: &[String]) -> RepositoryResult { + let [url] = args else { + return Err("usage: wasm-git --format json retention-rpc URL < REQUEST.json".into()); + }; + let mut input = Vec::new(); + std::io::stdin() + .lock() + .take(65_537) + .read_to_end(&mut input) + .map_err(|e| e.to_string())?; + if input.len() > 65_536 { + return Err("retention request exceeds 64 KiB".into()); + } + let request: protocol::RetentionRequest = + serde_json::from_slice(&input).map_err(|e| format!("invalid retention request: {e}"))?; + request.validate()?; + let remote = Remote { + version: 1, + name: "retention".into(), + url: url.clone(), + allow_insecure_http: false, + }; + let expected_repository = parse_url(&remote.url)?.repository().to_owned(); + let (_, bytes) = exchange( + &remote, + Operation::ReleaseRetention { + command: request.command.clone(), + }, + &[], + false, + )?; + let reply: protocol::RetentionReply = crate::binary::decode(&bytes)?; + reply.validate_for(&expected_repository, &request.command)?; + serde_json::to_string(&reply).map_err(|e| e.to_string()) +} + +pub fn integration_validate_cli(args: &[String]) -> RepositoryResult { + if !args.is_empty() { return Err("usage: wasm-git --format json integration-validate < VALIDATION.json".into()); } + let limit = protocol::MAX_PACKET_BYTES.saturating_mul(4); + let mut input = Vec::new(); + std::io::stdin().lock().take(limit as u64 + 1).read_to_end(&mut input).map_err(|e| e.to_string())?; + if input.len() > limit { return Err("integration validation input exceeds bound".into()); } + protocol::validate_node_safe_json(&input)?; + let request: protocol::IntegrationValidation = serde_json::from_slice(&input).map_err(|e| format!("invalid integration validation request: {e}"))?; + request.validate()?; + serde_json::to_string(&request).map_err(|e| e.to_string()) +} + +pub fn upload_binding_cli(args: &[String]) -> RepositoryResult { + let [path] = args else { + return Err( + "usage: wasm-git --format json upload-binding PAYLOAD_FILE < REQUEST.json".into(), + ); + }; + let mut input = Vec::new(); + std::io::stdin() + .lock() + .take(65_537) + .read_to_end(&mut input) + .map_err(|e| e.to_string())?; + if input.len() > 65_536 { + return Err("upload binding request exceeds 64 KiB".into()); + } + let request: protocol::UploadBindingRequest = serde_json::from_slice(&input) + .map_err(|e| format!("invalid upload binding request: {e}"))?; + request.validate()?; + let metadata = fs::symlink_metadata(path).map_err(|e| e.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() == 0 + || metadata.len() > protocol::MAX_BUNDLE_BYTES + { + return Err("invalid upload payload file".into()); + } + let payload = fs::read(path).map_err(|e| e.to_string())?; + if payload.len() as u64 != metadata.len() { + return Err("upload payload file changed during read".into()); + } + let binding = protocol::UploadBinding::for_payload(*request.operation, &payload)?; + serde_json::to_string(&binding).map_err(|e| e.to_string()) +} + +pub fn upload_recovery_cli(args: &[String]) -> RepositoryResult { + let [path] = args else { + return Err("usage: wasm-git --format json upload-recovery STATE_FILE".into()); + }; + let path = Path::new(path); + let metadata = fs::symlink_metadata(path).map_err(|e| e.to_string())?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 1024 * 1024 { + return Err("invalid upload recovery state file".into()); + } + let state: protocol::UploadRecovery = + serde_json::from_slice(&fs::read(path).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + crate::binary::oid(&state.session)?; + if state.payload_file != format!("upload-{}.bin", state.session) { + return Err("invalid upload recovery payload name".into()); + } + parse_url(&state.repository_url)?; + let payload_path = path + .parent() + .ok_or("recovery state has no parent directory")? + .join(&state.payload_file); + let metadata = fs::symlink_metadata(&payload_path).map_err(|e| e.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() != state.binding.total + || metadata.len() > protocol::MAX_BUNDLE_BYTES + { + return Err("invalid upload recovery payload".into()); + } + let payload = fs::read(payload_path).map_err(|e| e.to_string())?; + state.validate(&payload)?; + serde_json::to_string(&state).map_err(|e| e.to_string()) +} + +pub fn scoped_upload_cli(args: &[String]) -> RepositoryResult { + let [url] = args else { + return Err("usage: wasm-git --format json scoped-upload-rpc URL < REQUEST.json".into()); + }; + let mut input = Vec::new(); + std::io::stdin() + .lock() + .take(8 * 1024 * 1024 + 1) + .read_to_end(&mut input) + .map_err(|e| e.to_string())?; + if input.len() > 8 * 1024 * 1024 { + return Err("scoped upload request exceeds 8 MiB".into()); + } + let request: protocol::ScopedUploadRequest = serde_json::from_slice(&input) + .map_err(|e| format!("invalid scoped upload request: {e}"))?; + request.validate()?; + let validated_request = request.clone(); + let (session, binding, operation, payload, kind) = match request.command { + protocol::ScopedUploadCommand::Chunk { chunk, bytes } => ( + chunk.scope.session.clone(), chunk.scope.binding.clone(), Operation::UploadChunk { chunk }, bytes, 3, + ), + protocol::ScopedUploadCommand::QueryChunk { chunk } => ( + chunk.scope.session.clone(), chunk.scope.binding.clone(), Operation::QueryChunk { chunk }, Vec::new(), 3, + ), + protocol::ScopedUploadCommand::Slice { + session, + binding, + offset, + bytes, + } => ( + session.clone(), + binding.clone(), + Operation::ScopedUploadSlice { + session, + binding, + offset, + }, + bytes, + 0, + ), + protocol::ScopedUploadCommand::Apply { session, binding } => ( + session.clone(), + binding.clone(), + Operation::ApplyScopedUpload { session, binding }, + Vec::new(), + 1, + ), + protocol::ScopedUploadCommand::Cancel { session, binding } => ( + session.clone(), + binding.clone(), + Operation::CancelScopedUpload { session, binding }, + Vec::new(), + 0, + ), + protocol::ScopedUploadCommand::Query { session, binding } => ( + session.clone(), + binding.clone(), + Operation::QueryScopedUpload { session, binding }, + Vec::new(), + 2, + ), + }; + crate::binary::oid(&session)?; + binding.validate()?; + let remote = Remote { + version: 1, + name: "upload".into(), + url: url.clone(), + allow_insecure_http: false, + }; + let expected_repository = parse_url(&remote.url)?.repository().to_owned(); + let (response, payload) = exchange(&remote, operation, &payload, false)?; + let finish = || -> RepositoryResult { + let reply = match kind { + 3 => protocol::ScopedUploadReply::Chunk { version: 1, status: crate::binary::decode(&payload)? }, + 0 if payload.is_empty() => protocol::ScopedUploadReply::Acknowledged { + version: 1, + session, + }, + 1 => protocol::ScopedUploadReply::Applied { + version: 1, + session, + response, + payload, + }, + 2 => { + let status: protocol::ScopedUploadStatus = crate::binary::decode(&payload)?; + status.validate_for(&expected_repository, &session, &binding)?; + protocol::ScopedUploadReply::Status { + version: 1, + session, + status, + } + } + _ => return Err("invalid scoped upload response".into()), + }; + reply.validate_for(&expected_repository, &validated_request)?; + serde_json::to_string(&reply).map_err(|e| e.to_string()) + }; + finish().map_err(|error| { + if !matches!(&validated_request.command, protocol::ScopedUploadCommand::Query { .. } | protocol::ScopedUploadCommand::QueryChunk { .. }) { + format!("remote upload outcome is unknown: {error}; query the original operation") + } else { error } + }) +} + fn fetch_payload( remote: &Remote, allow_http: bool, @@ -2278,6 +2598,45 @@ pub fn run(args: &[String]) -> RepositoryResult { mod tests { use super::*; + #[test] + fn upload_recovery_preserves_original_session_binding_and_payload() { + let directory = std::env::temp_dir().join(format!( + "wasm-git-upload-recovery-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&directory).unwrap(); + let payload = b"frozen upload"; + let binding = protocol::UploadBinding::for_payload( + Operation::Push { + branch: "topic".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let remote = Remote { + version: 1, + name: "origin".into(), + url: "http://127.0.0.1:9419/project".into(), + allow_insecure_http: false, + }; + let session = "5".repeat(64); + persist_upload_recovery(&directory, &remote, &session, &binding, payload).unwrap(); + let state_path = directory.join(format!("upload-{session}.json")); + let state: protocol::UploadRecovery = serde_json::from_str( + &upload_recovery_cli(&[state_path.to_str().unwrap().into()]).unwrap(), + ) + .unwrap(); + assert_eq!(state.session, session); + assert_eq!(state.repository_url, remote.url); + assert!(persist_upload_recovery(&directory, &remote, &session, &binding, payload).is_err()); + fs::write(directory.join(&state.payload_file), b"corrupt").unwrap(); + assert!(upload_recovery_cli(&[state_path.to_str().unwrap().into()]).is_err()); + fs::remove_dir_all(directory).unwrap(); + } + #[test] fn rpc_timeout_is_bounded_and_defaults_to_five_minutes() { assert_eq!(rpc_timeout(None).unwrap(), Duration::from_secs(300)); diff --git a/src/repository.rs b/src/repository.rs index 0196fa6..1d35af4 100644 --- a/src/repository.rs +++ b/src/repository.rs @@ -4,8 +4,9 @@ //! versioned object envelope (including its type and payload length) is hashed //! with SHA-256. Commits form an immutable DAG; branch files are the only mutable //! history pointers. Bundles are self-contained and verified before publication. -//! Mutations and consistent snapshots use `.wasm-git/write.lock`; a crashed writer's -//! lock requires manual inspection and removal before another writer proceeds. +//! Mutations and consistent snapshots use the common `.wasm-git/write.lock`. +//! Native hosts keep its inode and release the kernel lock when the owner exits; +//! WASIp1 uses an exclusive-create lock that can require manual crash recovery. //! //! Immutable packs compress original envelopes without changing object IDs. //! Explicit GC preserves recovery roots after a verified full-store plan. @@ -36,16 +37,29 @@ mod pulls; #[path = "repository_signing.rs"] mod signing_storage; pub use partial_storage::{CloneFilter, PromiseSource, SelectOptions}; +pub(crate) use signing_storage::author as validate_author_identity; pub use signing_storage::cli as signing_cli; +pub(crate) use signing_storage::cli_formatted as signing_cli_formatted; pub use signing_storage::{AuthorSignature, SignatureFormat, SigningIdentity}; #[path = "repository_notes.rs"] mod notes_storage; #[path = "repository_pack.rs"] mod pack_storage; pub use network_storage::FetchOptions; +#[path = "repository_retention.rs"] +mod retention_storage; +pub use retention_storage::RetentionError; +#[path = "repository_chunk_receipts.rs"] +mod chunk_receipts; +#[path = "infrastructure/repository_record_store.rs"] +mod record_store; +#[path = "repository_scoped_transfer.rs"] +mod scoped_transfer_storage; +pub(crate) use crate::protocol::{ScopedExecution, ScopedReceipt}; #[path = "repository_transfer.rs"] mod transfer_storage; pub use notes_storage::NotesRequest; +pub(crate) use transfer_storage::ServiceGuard; #[path = "repository_history_tools.rs"] mod history_tools; #[path = "repository_merge_tool.rs"] @@ -415,6 +429,13 @@ pub struct Repository { pub root: PathBuf, metadata: PathBuf, common_metadata: PathBuf, + reference_recovery: ReferenceRecovery, +} + +#[derive(Debug, Clone)] +enum ReferenceRecovery { + Unrestricted, + Scoped(Option), } /// In-memory commit view; the native payload has an explicit binary layout. @@ -831,17 +852,7 @@ struct Snapshot { objects: BTreeMap, } -struct WriteLock { - path: PathBuf, - // Keep the file open until the entire mutation is finished. - _file: File, -} - -impl Drop for WriteLock { - fn drop(&mut self) { - let _ = fs::remove_file(&self.path); - } -} +type WriteLock = crate::platform_fs::ResourceLock; impl Repository { #[cfg(feature = "server")] @@ -860,6 +871,15 @@ impl Repository { let path = metadata.join(child); fs::create_dir(&path).map_err(|e| io_error("create repository directory", &path, e))?; } + #[cfg(any(unix, windows))] + for name in [ + "write.lock", + "index.lock", + "transfer.lock", + "transfer-state.lock", + ] { + write_new_file(&metadata.join(name), crate::platform_fs::NATIVE_LOCK_FORMAT)?; + } write_new_file(&metadata.join("HEAD"), &encode_reference("main", false)?)?; // Write the format marker last; incomplete initialization cannot be opened. write_new_file(&metadata.join("format"), FORMAT)?; @@ -868,10 +888,33 @@ impl Repository { root, common_metadata: metadata.clone(), metadata, + reference_recovery: ReferenceRecovery::Unrestricted, }) } pub fn open(root: impl AsRef) -> RepositoryResult { + Self::open_with_recovery(root, ReferenceRecovery::Unrestricted) + } + + /// Keep the journal boundary on every later writer-lock acquisition too. + /// `None` permits no reference recovery; `Some` permits only that scope. + pub(crate) fn open_for_recovery( + root: impl AsRef, + expected: Option<&ScopedExecution>, + ) -> RepositoryResult { + if let Some(scope) = expected { + crate::protocol::repository_name(&scope.repository)?; + crate::protocol::repository_component(&scope.actor)?; + require_id(&scope.session)?; + scope.binding.validate()?; + } + Self::open_with_recovery(root, ReferenceRecovery::Scoped(expected.cloned())) + } + + fn open_with_recovery( + root: impl AsRef, + reference_recovery: ReferenceRecovery, + ) -> RepositoryResult { let root = root.as_ref().to_path_buf(); require_directory(&root)?; let metadata = root.join(".wasm-git"); @@ -890,6 +933,7 @@ impl Repository { root, metadata, common_metadata, + reference_recovery, }; repo.recover_reference_transaction_on_open()?; repo.current_branch()?; @@ -1593,11 +1637,29 @@ impl Repository { } pub fn export_bundle(&self, destination: impl AsRef) -> RepositoryResult { + let result = self.export_bundle_result(destination)?; + usize::try_from(result.objects).map_err(|_| "bundle object count exceeds host size".into()) + } + + pub(crate) fn export_bundle_result( + &self, + destination: impl AsRef, + ) -> RepositoryResult { let _lock = self.lock()?; let snapshot = self.snapshot()?; let bundle = encode_bundle(&snapshot)?; + let result = crate::protocol::BundleResult { + version: 1, + head: snapshot.manifest.head.clone(), + tip: snapshot.manifest.tip().cloned(), + objects: u64::try_from(snapshot.objects.len()) + .map_err(|_| "bundle object count overflow")?, + bytes: u64::try_from(bundle.len()).map_err(|_| "bundle length overflow")?, + sha256: format!("{:x}", Sha256::digest(&bundle)), + }; + result.validate()?; crate::output::write_export_file(destination.as_ref(), &bundle)?; - Ok(snapshot.objects.len()) + Ok(result) } /// Import a verified self-contained bundle to one explicitly named branch. @@ -3385,40 +3447,13 @@ impl Repository { } fn lock_named(&self, name: &str) -> RepositoryResult { - let directory = if name == "write.lock" { + let directory = if matches!(name, "write.lock" | "transfer.lock" | "transfer-state.lock") { &self.common_metadata } else { &self.metadata }; let path = directory.join(name); - let file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .map_err(|e| { - if e.kind() == std::io::ErrorKind::AlreadyExists { - format!( - "repository is locked: {}; if a writer crashed, inspect and remove this lock manually", - path.display() - ) - } else { - io_error("lock repository", &path, e) - } - })?; - let mut lock = WriteLock { path, _file: file }; - lock._file - .write_all( - &[ - b"WGTLCK\0\x01".as_slice(), - &crate::platform_fs::process_id().to_be_bytes(), - ] - .concat(), - ) - .map_err(|e| format!("write repository lock: {e}"))?; - lock._file - .sync_all() - .map_err(|e| format!("sync repository lock: {e}"))?; - Ok(lock) + crate::platform_fs::acquire_lock(&path, &directory.join("tmp")) } /// Return the exact stored payload after full-store verification. @@ -3927,6 +3962,15 @@ impl Repository { } fn atomic_write(&self, destination: &Path, bytes: &[u8]) -> RepositoryResult<()> { + self.atomic_write_checked(destination, bytes, || Ok(())) + } + + fn atomic_write_checked( + &self, + destination: &Path, + bytes: &[u8], + before_publish: impl FnOnce() -> RepositoryResult<()>, + ) -> RepositoryResult<()> { // Refuse symbolic-link destinations even though rename would replace the // link itself: a repository containing links is not a valid store. match fs::symlink_metadata(destination) { @@ -3947,6 +3991,10 @@ impl Repository { }; let temp = staging.join("tmp").join(unique_name("ref")); write_new_file(&temp, bytes)?; + if let Err(error) = before_publish() { + let _ = fs::remove_file(&temp); + return Err(error); + } let result = fs::rename(&temp, destination) .map_err(|e| io_error("publish reference", destination, e)); if result.is_err() { @@ -6654,6 +6702,10 @@ fn io_error(action: &str, path: &Path, error: std::io::Error) -> String { /// Repository command dispatch. The first argument is the command, not argv[0]. pub fn run(args: &[String]) -> RepositoryResult { + run_formatted(args, false) +} + +pub(crate) fn run_formatted(args: &[String], machine: bool) -> RepositoryResult { // Handle help before interpreting paths or performing any filesystem action. // Prefix a literal path named --help/-h with ./ to disambiguate it. if crate::command_args::help_requested(args) { @@ -6797,8 +6849,12 @@ pub fn run(args: &[String]) -> RepositoryResult { Ok(format!("cloned {} into {}", args[1], repo.root.display())) } "bundle" if args.len() == 3 => { - let count = Repository::open(&args[1])?.export_bundle(&args[2])?; - Ok(format!("wrote {count} verified objects to {}", args[2])) + let result = Repository::open(&args[1])?.export_bundle_result(&args[2])?; + if machine { + serde_json::to_string(&result).map_err(|e| e.to_string()) + } else { + Ok(format!("wrote {} verified objects to {}", result.objects, args[2])) + } } "unbundle" if args.len() == 4 => { let id = Repository::open(&args[1])?.import_bundle(&args[2], &args[3])?; @@ -8245,7 +8301,7 @@ mod tests { let mut seen = Vec::new(); let report = repo .describe("HEAD", &DescribeOptions::default(), |name| { - assert!(repo.metadata.join("write.lock").is_file()); + assert!(repo.lock_named("write.lock").is_err()); seen.push(name.to_owned()); Ok(name != "omit-base") }) @@ -8272,7 +8328,7 @@ mod tests { "fixed predicate error" ); assert_eq!(stored_state(&repo), before); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } #[test] @@ -8395,7 +8451,7 @@ mod tests { let corrupt = stored_state(&repo); assert!(repo.describe("HEAD", &options, |_| Ok(true)).is_err()); assert_eq!(stored_state(&repo), corrupt); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } #[test] @@ -8479,7 +8535,7 @@ mod tests { let corrupt = stored_state(&repo); assert!(repo.archive_files("HEAD").is_err()); assert_eq!(stored_state(&repo), corrupt); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } #[test] @@ -8581,7 +8637,7 @@ mod tests { commit_id ); assert_eq!(before.objects, both.objects); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } fn query_tracking( @@ -8656,7 +8712,7 @@ mod tests { ); assert_eq!(fs::read(repo.metadata.join("index")).unwrap(), index); assert_eq!(fs::read(repo.root.join("editor.txt")).unwrap(), work); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } #[test] @@ -8924,13 +8980,9 @@ mod tests { assert!(repo.query_objects().is_err()); assert_eq!(stored_state(&repo), before); }; - fs::write(repo.metadata.join("write.lock"), b"external owner").unwrap(); + let guard = repo.lock_named("write.lock").unwrap(); assert_rejected(); - assert_eq!( - fs::read(repo.metadata.join("write.lock")).unwrap(), - b"external owner" - ); - fs::remove_file(repo.metadata.join("write.lock")).unwrap(); + drop(guard); let id = repo.store_object(WASM_KIND, &wasm(&[99, 1, 9])).unwrap(); let path = repo.metadata.join("objects").join(&id); let original = fs::read(&path).unwrap(); @@ -9238,8 +9290,8 @@ mod tests { assert_eq!(bare.resolve("HEAD").unwrap(), descendant); assert_eq!(bare.files_at("HEAD").unwrap().files, descendant_files); assert!(!bare.metadata.join("index").exists()); - assert!(!target.metadata.join("index.lock").exists()); - assert!(!target.metadata.join("write.lock").exists()); + assert!(target.lock_named("index.lock").is_ok()); + assert!(target.lock_named("write.lock").is_ok()); } #[test] @@ -9268,8 +9320,8 @@ mod tests { .contains("write.lock")); assert_eq!(complete_repository_bytes(&target), before); drop(writer_lock); - assert!(!target.metadata.join("index.lock").exists()); - assert!(!target.metadata.join("write.lock").exists()); + assert!(target.lock_named("index.lock").is_ok()); + assert!(target.lock_named("write.lock").is_ok()); } #[test] @@ -10434,7 +10486,7 @@ mod tests { .contains("locked")); assert_eq!(stored_state(&target), before); drop(index_lock); - assert!(!target.metadata.join("index.lock").exists()); + assert!(target.lock_named("index.lock").is_ok()); } #[test] @@ -11320,7 +11372,7 @@ mod tests { assert_eq!(batch[3].commit, original); assert_eq!(batch[2].bytes, original_bytes); assert_eq!(batch[3].bytes, original_bytes); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); repo.commit(&wasm(&[]), "advance after snapshot").unwrap(); // Both IDs and copies remain an immutable description of the state read. assert_eq!(batch[0].commit, current); @@ -11343,7 +11395,7 @@ mod tests { assert!(read_revisions(&repo.root, &["HEAD", "unknown"]) .unwrap_err() .contains("unknown revision")); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); assert_eq!( read_revisions(&repo.root, &["HEAD", "HEAD"]).unwrap().len(), 2 @@ -11377,7 +11429,7 @@ mod tests { .unwrap_err() .contains(expected_error)); assert_eq!(stored_state(&repo), before); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } } @@ -11407,7 +11459,7 @@ mod tests { let before = stored_state(&repo); let history = read_history(&repo.root, "HEAD").unwrap(); assert_eq!(stored_state(&repo), before); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); assert_eq!(history.tip, merged); assert_eq!(history.commits.len(), 4); assert_eq!(history.blobs.len(), 1); @@ -11456,7 +11508,7 @@ mod tests { .unwrap_err() .contains("non-commit")); assert_eq!(stored_state(&repo), before); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); assert_eq!(read_history(&repo.root, &root).unwrap().tip, root); } @@ -11501,7 +11553,7 @@ mod tests { .unwrap_err() .contains(expected_error)); assert_eq!(stored_state(&repo), before); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } } @@ -11707,7 +11759,7 @@ mod tests { assert!(repo.metadata.join("write.lock").exists()); drop(lock); repo.commit(&wasm(&[]), "allowed").unwrap(); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } fn function_wasm(left: i32, right: i32) -> Vec { @@ -12046,7 +12098,7 @@ mod tests { assert_eq!(outcome.report.as_ref().unwrap().status, "conflict"); assert_eq!(stored_state(&repo), before); assert_eq!(repo.fsck().unwrap().commits, 3); - assert!(!repo.metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); } #[test] diff --git a/src/repository_chunk_receipts.rs b/src/repository_chunk_receipts.rs new file mode 100644 index 0000000..a28cded --- /dev/null +++ b/src/repository_chunk_receipts.rs @@ -0,0 +1,1133 @@ +//! Durable per-slot decisions for scoped upload chunks. +use super::scoped_transfer_storage::{ScopedRecord, ScopedUploadError}; +use super::*; +use crate::protocol::{ + ScopedChunkCleanupReason, ScopedChunkData, ScopedChunkIdentity, ScopedChunkState, + ScopedChunkStatus, ScopedUploadState, TRANSFER_CHUNK, +}; + +const MAX_RECORD: u64 = 4096; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Decision { + version: u32, + session: String, + offset: u64, + operation_id: String, + payload_sha256: String, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Cleanup { + version: u32, + session: String, + reason: ScopedChunkCleanupReason, + cleaned: bool, +} + +fn read_record( + path: &Path, +) -> RepositoryResult> { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(io_error("inspect chunk record", path, error)), + }; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > MAX_RECORD { + return Err(format!( + "chunk record must be a bounded regular file: {}", + path.display() + )); + } + let bytes = read_regular(path)?; + let record: T = crate::binary::decode(&bytes)?; + if crate::binary::encode(&record)? != bytes { + return Err("noncanonical chunk record".into()); + } + Ok(Some(record)) +} + +impl Repository { + fn existing_chunk_directory(&self, session: &str) -> RepositoryResult> { + require_id(session)?; + let root = self.common_metadata.join("scoped-chunks"); + match fs::symlink_metadata(&root) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(io_error("inspect chunk directory", &root, error)), + Ok(_) => require_directory(&root)?, + } + let directory = root.join(session); + match fs::symlink_metadata(&directory) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(io_error("inspect chunk directory", &directory, error)), + Ok(_) => { + require_directory(&directory)?; + Ok(Some(directory)) + } + } + } + + fn ensure_chunk_directory(&self, session: &str) -> RepositoryResult { + require_id(session)?; + let root = self.common_metadata.join("scoped-chunks"); + match fs::create_dir(&root) { + Ok(()) => (), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + require_directory(&root)? + } + Err(error) => return Err(io_error("create chunk directory", &root, error)), + } + // Creation may have succeeded on an earlier attempt whose parent sync + // failed; fence even when the directory already exists. + sync_directory(&self.common_metadata)?; + let directory = root.join(session); + match fs::create_dir(&directory) { + Ok(()) => (), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + require_directory(&directory)? + } + Err(error) => { + return Err(io_error( + "create chunk session directory", + &directory, + error, + )) + } + } + sync_directory(&root)?; + Ok(directory) + } + + fn chunk_cleanup_record(&self, session: &str) -> RepositoryResult> { + let Some(directory) = self.existing_chunk_directory(session)? else { + return Ok(None); + }; + let Some(cleanup): Option = read_record(&directory.join("cleanup"))? else { + return Ok(None); + }; + if cleanup.version != 1 || cleanup.session != session { + return Err("invalid chunk cleanup record".into()); + } + Ok(Some(cleanup)) + } + + fn chunk_decision_at( + &self, + directory: &Path, + session: &str, + offset: u64, + ) -> RepositoryResult> { + let path = directory.join(format!("decision-{offset}")); + let Some(decision): Option = read_record(&path)? else { + return Ok(None); + }; + if decision.version != 1 + || decision.session != session + || decision.offset != offset + || !offset.is_multiple_of(TRANSFER_CHUNK as u64) + || offset >= crate::protocol::MAX_BUNDLE_BYTES + { + return Err("invalid chunk decision".into()); + } + require_id(&decision.operation_id)?; + require_id(&decision.payload_sha256)?; + Ok(Some(decision)) + } + + fn chunk_decision( + &self, + directory: &Path, + chunk: &ScopedChunkIdentity, + ) -> Result, ScopedUploadError> { + let Some(decision) = self + .chunk_decision_at(directory, &chunk.scope.session, chunk.offset) + .map_err(ScopedUploadError::unknown)? + else { + return Ok(None); + }; + if decision.operation_id != chunk.operation_id + || decision.payload_sha256 != chunk.payload_sha256 + { + return Err("scoped chunk identity conflict".into()); + } + Ok(Some(decision)) + } + + fn chunk_status(chunk: &ScopedChunkIdentity, state: ScopedChunkState) -> ScopedChunkStatus { + ScopedChunkStatus { + version: 1, + chunk: chunk.clone(), + state, + } + } + + fn terminal_cleanup_reason(state: &ScopedUploadState) -> Option { + match state { + ScopedUploadState::Canceled => Some(ScopedChunkCleanupReason::Canceled), + ScopedUploadState::Finished { .. } + | ScopedUploadState::FinishedV4 { .. } + | ScopedUploadState::Aborted { .. } => Some(ScopedChunkCleanupReason::Completed), + _ => None, + } + } + + pub(super) fn require_live_scoped_chunks_locked(&self, session: &str) -> RepositoryResult<()> { + if let Some(cleanup) = self.chunk_cleanup_record(session)? { + return Err(format!( + "scoped upload data is being cleaned or was cleaned: {:?}", + cleanup.reason + )); + } + Ok(()) + } + + pub(super) fn resume_scoped_cleanup_locked(&self, session: &str) -> RepositoryResult { + if let Some(cleanup) = self.chunk_cleanup_record(session)? { + self.cleanup_scoped_chunks_locked(session, cleanup.reason)?; + Ok(true) + } else { + Ok(false) + } + } + + pub(super) fn resume_all_scoped_cleanups_locked(&self) -> RepositoryResult<()> { + let root = self.common_metadata.join("scoped-chunks"); + match fs::symlink_metadata(&root) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(io_error("inspect chunk directory", &root, error)), + Ok(_) => require_directory(&root)?, + } + for entry in fs::read_dir(&root).map_err(|error| error.to_string())? { + let entry = entry.map_err(|error| error.to_string())?; + let session = entry + .file_name() + .into_string() + .map_err(|_| "invalid chunk session name")?; + require_id(&session)?; + require_directory(&entry.path())?; + self.resume_scoped_cleanup_locked(&session)?; + } + Ok(()) + } + + /// Both transfer-state.lock and transfer.lock are held by the caller. + pub(super) fn cleanup_scoped_chunks_locked( + &self, + session: &str, + reason: ScopedChunkCleanupReason, + ) -> RepositoryResult { + let directory = self.ensure_chunk_directory(session)?; + let path = directory.join("cleanup"); + let mut cleanup = match self.chunk_cleanup_record(session)? { + Some(cleanup) => { + // Finish a possibly uncertain tombstone publication before any unlink. + sync_directory(&directory)?; + cleanup + } + None => { + let cleanup = Cleanup { + version: 1, + session: session.into(), + reason, + cleaned: false, + }; + self.atomic_write(&path, &crate::binary::encode(&cleanup)?)?; + cleanup + } + }; + if cleanup.cleaned { + return Ok(cleanup.reason); + } + let mut payloads = Vec::new(); + for entry in fs::read_dir(&directory).map_err(|error| error.to_string())? { + let entry = entry.map_err(|error| error.to_string())?; + let name = entry + .file_name() + .into_string() + .map_err(|_| "invalid chunk entry")?; + if name == "cleanup" { + continue; + } + if let Some(offset) = name.strip_prefix("decision-") { + let offset = offset + .parse::() + .map_err(|_| "invalid chunk decision filename")?; + if name != format!("decision-{offset}") + || self + .chunk_decision_at(&directory, session, offset)? + .is_none() + { + return Err("invalid chunk decision filename".into()); + } + continue; + } + if let Some(offset) = name.strip_prefix("payload-") { + let offset = offset + .parse::() + .map_err(|_| "invalid chunk payload filename")?; + if name != format!("payload-{offset}") + || !offset.is_multiple_of(TRANSFER_CHUNK as u64) + || offset >= crate::protocol::MAX_BUNDLE_BYTES + { + return Err("invalid chunk payload filename".into()); + } + } else { + return Err("unexpected chunk session entry".into()); + } + let metadata = fs::symlink_metadata(entry.path()).map_err(|error| error.to_string())?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > TRANSFER_CHUNK as u64 + { + return Err("invalid chunk payload file".into()); + } + payloads.push(entry.path()); + if payloads.len() > 4096 { + return Err("chunk session contains too many payload files".into()); + } + } + for path in payloads { + fs::remove_file(path).map_err(|error| error.to_string())?; + } + sync_directory(&directory)?; + self.remove_upload_cache_locked(session)?; + cleanup.cleaned = true; + self.atomic_write(&path, &crate::binary::encode(&cleanup)?)?; + Ok(cleanup.reason) + } + + /// Called under transfer-state.lock then transfer.lock, including GC/TTL. + pub(super) fn expire_scoped_upload_locked(&self, session: &str) -> RepositoryResult { + let record = self.scoped_record(session)?; + let reason = match record.as_ref().map(|record| &record.state) { + Some(ScopedUploadState::Applying | ScopedUploadState::ApplyingV4 { .. }) => { + return Ok(false) + } + Some(ScopedUploadState::Canceled) => ScopedChunkCleanupReason::Canceled, + Some( + ScopedUploadState::Finished { .. } + | ScopedUploadState::FinishedV4 { .. } + | ScopedUploadState::Aborted { .. }, + ) => ScopedChunkCleanupReason::Completed, + Some(ScopedUploadState::Open) | None => ScopedChunkCleanupReason::Expired, + }; + self.cleanup_scoped_chunks_locked(session, reason)?; + Ok(true) + } + + fn validate_chunk_record_scope( + &self, + record: &ScopedRecord, + chunk: &ScopedChunkIdentity, + ) -> RepositoryResult<()> { + Self::check_scope( + record, + &chunk.scope.repository, + &chunk.scope.actor, + &chunk.scope.binding, + false, + ) + } + + fn materialize_chunk_locked( + &self, + directory: &Path, + chunk: &ScopedChunkIdentity, + ) -> RepositoryResult<()> { + let raw = directory.join(format!("payload-{}", chunk.offset)); + let metadata = fs::symlink_metadata(&raw) + .map_err(|error| io_error("inspect accepted chunk data", &raw, error))?; + if !metadata.is_file() + || metadata.file_type().is_symlink() + || metadata.len() > TRANSFER_CHUNK as u64 + { + return Err("invalid accepted chunk data".into()); + } + let bytes = read_regular(&raw)?; + chunk.validate_payload(&bytes)?; + let upload = match self + .existing_upload_directory_locked(&chunk.scope.session, chunk.scope.binding.total)? + { + Some(directory) => directory, + None => self + .prepare_upload_directory_locked(&chunk.scope.session, chunk.scope.binding.total)?, + }; + let target = upload.join(chunk.offset.to_string()); + match fs::symlink_metadata(&target) { + Ok(_) => { + if read_regular(&target)? != bytes { + return Err("accepted chunk conflicts with cached upload bytes".into()); + } + sync_directory(&upload) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + fs::hard_link(&raw, &target) + .map_err(|error| io_error("materialize accepted chunk", &target, error))?; + self.finish_upload_link_locked(&upload) + } + Err(error) => Err(io_error("inspect upload chunk", &target, error)), + } + } + + pub(super) fn recover_scoped_chunks_locked( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &crate::protocol::UploadBinding, + ) -> RepositoryResult<()> { + self.require_live_scoped_chunks_locked(session)?; + let Some(directory) = self.existing_chunk_directory(session)? else { + return Ok(()); + }; + let mut offset = 0; + while offset < binding.total { + if let Some(decision) = self.chunk_decision_at(&directory, session, offset)? { + sync_directory(&directory)?; + let chunk = ScopedChunkIdentity { + version: 1, + operation_id: decision.operation_id, + scope: ScopedExecution { + actor: actor.into(), + repository: repository.into(), + session: session.into(), + binding: binding.clone(), + }, + offset, + payload_sha256: decision.payload_sha256, + }; + chunk.validate()?; + self.materialize_chunk_locked(&directory, &chunk)?; + } + offset += TRANSFER_CHUNK as u64; + } + Ok(()) + } + + fn accepted_chunk_locked( + &self, + directory: &Path, + chunk: &ScopedChunkIdentity, + state: &ScopedUploadState, + ) -> Result { + sync_directory(directory).map_err(ScopedUploadError::unknown)?; + let terminal = Self::terminal_cleanup_reason(state); + if let Some(cleanup) = self + .chunk_cleanup_record(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + { + let reason = self + .cleanup_scoped_chunks_locked(&chunk.scope.session, cleanup.reason) + .map_err(ScopedUploadError::unknown)?; + return Ok(Self::chunk_status( + chunk, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { reason }, + }, + )); + } + if let Some(reason) = terminal { + let reason = self + .cleanup_scoped_chunks_locked(&chunk.scope.session, reason) + .map_err(ScopedUploadError::unknown)?; + return Ok(Self::chunk_status( + chunk, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { reason }, + }, + )); + } + if let Err(error) = self.materialize_chunk_locked(directory, chunk) { + if let Some(cleanup) = self + .chunk_cleanup_record(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + { + let reason = self + .cleanup_scoped_chunks_locked(&chunk.scope.session, cleanup.reason) + .map_err(ScopedUploadError::unknown)?; + return Ok(Self::chunk_status( + chunk, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { reason }, + }, + )); + } + return Err(ScopedUploadError::unknown(format!( + "accepted chunk requires recovery: {error}" + ))); + } + Ok(Self::chunk_status( + chunk, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available, + }, + )) + } + + pub(crate) fn scoped_chunk_query( + &self, + gate: &ServiceGuard, + chunk: &ScopedChunkIdentity, + ) -> Result { + chunk.validate()?; + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + let _state = self.lock_named("transfer-state.lock")?; + let _transfer = self.lock_named("transfer.lock")?; + let record = self + .scoped_record(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)?; + let record = record.as_ref(); + if let Some(record) = record { + self.validate_chunk_record_scope(record, chunk)?; + } + let Some(directory) = self + .existing_chunk_directory(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + else { + if let Some(reason) = + record.and_then(|record| Self::terminal_cleanup_reason(&record.state)) + { + self.cleanup_scoped_chunks_locked(&chunk.scope.session, reason) + .map_err(ScopedUploadError::unknown)?; + } + return Ok(Self::chunk_status(chunk, ScopedChunkState::Unobserved)); + }; + let Some(_decision) = self.chunk_decision(&directory, chunk)? else { + if !self + .resume_scoped_cleanup_locked(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + { + if let Some(reason) = + record.and_then(|record| Self::terminal_cleanup_reason(&record.state)) + { + self.cleanup_scoped_chunks_locked(&chunk.scope.session, reason) + .map_err(ScopedUploadError::unknown)?; + } + } + return Ok(Self::chunk_status(chunk, ScopedChunkState::Unobserved)); + }; + let record = record.ok_or_else(|| { + ScopedUploadError::unknown("chunk decision has no authoritative scoped session".into()) + })?; + self.accepted_chunk_locked(&directory, chunk, &record.state) + } + + pub(crate) fn scoped_chunk_write( + &self, + gate: &ServiceGuard, + chunk: &ScopedChunkIdentity, + bytes: &[u8], + before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result { + self.scoped_chunk_write_with_checkpoint(gate, chunk, bytes, before_publish, || Ok(())) + } + + fn scoped_chunk_write_with_checkpoint( + &self, + gate: &ServiceGuard, + chunk: &ScopedChunkIdentity, + bytes: &[u8], + mut before_publish: impl FnMut() -> RepositoryResult<()>, + after_decision: impl FnOnce() -> RepositoryResult<()>, + ) -> Result { + chunk.validate_payload(bytes)?; + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + let _state = self.lock_named("transfer-state.lock")?; + let _transfer = self.lock_named("transfer.lock")?; + let record = self + .scoped_record(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)?; + if let Some(record) = &record { + self.validate_chunk_record_scope(record, chunk)?; + } + if let Some(directory) = self + .existing_chunk_directory(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + { + if self.chunk_decision(&directory, chunk)?.is_some() { + let record = record.as_ref().ok_or_else(|| { + ScopedUploadError::unknown( + "chunk decision has no authoritative scoped session".into(), + ) + })?; + return self.accepted_chunk_locked(&directory, chunk, &record.state); + } + } + self.require_live_scoped_chunks_locked(&chunk.scope.session)?; + let newly_opened = self.ensure_scoped_open_locked( + &chunk.scope.repository, &chunk.scope.actor, &chunk.scope.session, + &chunk.scope.binding, &mut before_publish, false, + ).map_err(|mut error| { + if error.outcome_unknown { error.message = format!("scoped session admission may have been published; chunk decision was not attempted: {}", error.message); } + error + })?; + let record = self + .scoped_record(&chunk.scope.session) + .map_err(ScopedUploadError::unknown)? + .ok_or("missing scoped upload")?; + self.stage_and_decide_chunk_locked( + chunk, + bytes, + &record, + &mut before_publish, + after_decision, + ) + .map_err(|mut error| { + if newly_opened && !error.outcome_unknown { + error.message = format!( + "{}; scoped session remains open, and this chunk decision was not published", + error.message + ); + } + error + }) + } + + fn stage_and_decide_chunk_locked( + &self, + chunk: &ScopedChunkIdentity, + bytes: &[u8], + record: &ScopedRecord, + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + after_decision: impl FnOnce() -> RepositoryResult<()>, + ) -> Result { + let upload = + self.prepare_upload_directory_locked(&chunk.scope.session, chunk.scope.binding.total)?; + let cached = upload.join(chunk.offset.to_string()); + match fs::symlink_metadata(&cached) { + Ok(_) if read_regular(&cached)? != bytes => { + return Err("upload slot contains different bytes".into()) + } + Ok(_) => (), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), + Err(error) => return Err(error.to_string().into()), + } + let directory = self.ensure_chunk_directory(&chunk.scope.session)?; + let raw = directory.join(format!("payload-{}", chunk.offset)); + let raw_exists = match fs::symlink_metadata(&raw) { + Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => { + if metadata.len() > TRANSFER_CHUNK as u64 { + return Err("invalid staged chunk size".into()); + } + true + } + Ok(_) => return Err("invalid staged chunk file".into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(error) => return Err(error.to_string().into()), + }; + // This one bounded staging inode belongs to an undecided slot. A + // stopped writer may leave partial bytes, which can be rewritten only + // while no decision exists and both resource locks are held. + let mut options = OpenOptions::new(); + options.write(true).create_new(!raw_exists); + crate::platform_fs::protect_lock_open(&mut options); + let mut file = options + .open(&raw) + .map_err(|error| io_error("open staged chunk", &raw, error))?; + if !file + .metadata() + .map_err(|error| error.to_string())? + .is_file() + { + return Err("invalid staged chunk file".into()); + } + if !raw_exists || read_regular(&raw)? != bytes { + file.set_len(0).map_err(|error| error.to_string())?; + file.write_all(bytes).map_err(|error| error.to_string())?; + } + file.sync_all().map_err(|error| error.to_string())?; + drop(file); + sync_directory(&directory)?; + let decision = Decision { + version: 1, + session: chunk.scope.session.clone(), + offset: chunk.offset, + operation_id: chunk.operation_id.clone(), + payload_sha256: chunk.payload_sha256.clone(), + }; + let path = directory.join(format!("decision-{}", chunk.offset)); + let mut passed = false; + self.atomic_write_checked(&path, &crate::binary::encode(&decision)?, || { + before_publish()?; + passed = true; + Ok(()) + }) + .map_err(|message| ScopedUploadError { + message, + outcome_unknown: passed, + })?; + after_decision().map_err(ScopedUploadError::unknown)?; + self.accepted_chunk_locked(&directory, chunk, &record.state) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Operation, UploadBinding}; + use sha2::{Digest, Sha256}; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-chunks-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + struct ChildGuard(std::process::Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_none() { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + } + + fn fixture(payload: &[u8]) -> (Temp, Repository, ScopedChunkIdentity) { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let slice = &payload[..payload.len().min(TRANSFER_CHUNK)]; + let chunk = ScopedChunkIdentity { + version: 1, + operation_id: "a".repeat(64), + scope: ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: "b".repeat(64), + binding, + }, + offset: 0, + payload_sha256: format!("{:x}", Sha256::digest(slice)), + }; + (temp, repo, chunk) + } + + #[test] + fn undecided_staging_is_unobserved_and_original_can_retry() { + let payload = b"frozen chunk"; + let (_temp, repo, chunk) = fixture(payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Unobserved + ); + let mut checks = 0; + let error = repo + .scoped_chunk_write(&gate, &chunk, payload, || { + checks += 1; + if checks == 1 { + Ok(()) + } else { + Err("authorization expired".into()) + } + }) + .unwrap_err(); + assert_eq!(checks, 2); + assert!(!error.outcome_unknown); + assert!(error.message.contains("session remains open")); + let directory = repo + .common_metadata + .join("scoped-chunks") + .join(&chunk.scope.session); + assert!(directory.join("payload-0").is_file()); + assert!(!directory.join("decision-0").exists()); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Unobserved + ); + let status = repo + .scoped_chunk_write(&gate, &chunk, payload, || Ok(())) + .unwrap(); + assert_eq!( + status.state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available + } + ); + } + + #[test] + fn legacy_cache_is_not_a_chunk_decision_without_new_authorization() { + let payload = b"legacy chunk"; + let (_temp, repo, chunk) = fixture(payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_slice( + "project", + "alice", + &chunk.scope.session, + &chunk.scope.binding, + 0, + payload, + ) + .unwrap(); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Unobserved + ); + let error = repo + .scoped_chunk_write(&gate, &chunk, payload, || { + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Unobserved + ); + let mut checks = 0; + let status = repo + .scoped_chunk_write(&gate, &chunk, payload, || { + checks += 1; + Ok(()) + }) + .unwrap(); + assert_eq!(checks, 1); + assert_eq!( + status.state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available + } + ); + } + + #[test] + fn committed_chunk_recovers_after_materialization_failure_without_new_authority() { + let payload = b"frozen chunk"; + let (temp, repo, chunk) = fixture(payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + let cache = repo + .common_metadata + .join("tmp") + .join(format!("upload-{}/0", chunk.scope.session)); + let mut checks = 0; + let error = repo + .scoped_chunk_write(&gate, &chunk, payload, || { + checks += 1; + if checks == 2 { + fs::write(&cache, b"conflicting cache").unwrap(); + } + Ok(()) + }) + .unwrap_err(); + assert_eq!(checks, 2); + assert!(error.outcome_unknown); + let directory = repo + .common_metadata + .join("scoped-chunks") + .join(&chunk.scope.session); + assert!(directory.join("decision-0").is_file()); + assert_eq!(fs::read(directory.join("payload-0")).unwrap(), payload); + fs::remove_file(&cache).unwrap(); + drop(gate); + let reopened = Repository::open(&temp.0).unwrap(); + let gate = reopened.service_lock(std::time::Duration::ZERO).unwrap(); + assert_eq!( + reopened.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available + } + ); + assert_eq!(fs::read(&cache).unwrap(), payload); + reopened + .scoped_chunk_write(&gate, &chunk, payload, || { + panic!("accepted replay must not reauthorize") + }) + .unwrap(); + let mut conflict = chunk.clone(); + conflict.operation_id = "d".repeat(64); + assert!(reopened.scoped_chunk_query(&gate, &conflict).is_err()); + assert!(reopened + .scoped_chunk_write(&gate, &conflict, payload, || Ok(())) + .is_err()); + } + + #[test] + fn decision_checkpoint_child() { + let Some(root) = std::env::var_os("WASMGIT_CHUNK_TEST_ROOT") else { + return; + }; + let root = PathBuf::from(root); + let chunk: ScopedChunkIdentity = + crate::binary::decode(&fs::read(root.join("checkpoint-identity")).unwrap()).unwrap(); + let repo = Repository::open(&root).unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + let result = repo.scoped_chunk_write_with_checkpoint( + &gate, + &chunk, + b"process crash chunk", + || Ok(()), + || { + fs::write(root.join("checkpoint-ready"), b"ready") + .map_err(|error| error.to_string())?; + let mut byte = [0u8; 1]; + std::io::stdin() + .read_exact(&mut byte) + .map_err(|error| error.to_string())?; + Ok(()) + }, + ); + panic!("test child unexpectedly left its checkpoint: {result:?}"); + } + + #[test] + fn killed_process_after_durable_decision_recovers_original_chunk() { + let payload = b"process crash chunk"; + let (temp, repo, chunk) = fixture(payload); + fs::write( + temp.0.join("checkpoint-identity"), + crate::binary::encode(&chunk).unwrap(), + ) + .unwrap(); + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "repository::chunk_receipts::tests::decision_checkpoint_child", + "--nocapture", + ]) + .env("WASMGIT_CHUNK_TEST_ROOT", &temp.0) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let mut child = ChildGuard(child); + let ready = temp.0.join("checkpoint-ready"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !ready.is_file() { + if let Some(status) = child.0.try_wait().unwrap() { + let mut stderr = String::new(); + child + .0 + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + panic!("checkpoint child exited before decision ({status}): {stderr}"); + } + assert!( + std::time::Instant::now() < deadline, + "checkpoint child did not publish a decision" + ); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let directory = repo + .common_metadata + .join("scoped-chunks") + .join(&chunk.scope.session); + let cache = repo + .common_metadata + .join("tmp") + .join(format!("upload-{}/0", chunk.scope.session)); + assert!(directory.join("decision-0").is_file()); + assert_eq!(fs::read(directory.join("payload-0")).unwrap(), payload); + assert!(!cache.exists()); + assert!(repo.service_lock(std::time::Duration::ZERO).is_err()); + child.0.kill().unwrap(); + assert!(!child.0.wait().unwrap().success()); + + let reopened = Repository::open(&temp.0).unwrap(); + let gate = reopened.service_lock(std::time::Duration::ZERO).unwrap(); + assert_eq!( + reopened.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Available + } + ); + assert_eq!(fs::read(cache).unwrap(), payload); + } + + #[test] + fn cancellation_cleanup_recovers_and_never_recreates_accepted_or_late_chunks() { + let payload = vec![7; TRANSFER_CHUNK + 1]; + let (temp, repo, chunk) = fixture(&payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_chunk_write(&gate, &chunk, &payload[..TRANSFER_CHUNK], || Ok(())) + .unwrap(); + let directory = repo + .common_metadata + .join("scoped-chunks") + .join(&chunk.scope.session); + fs::write(directory.join("unexpected"), b"retain").unwrap(); + let error = repo + .scoped_upload_cancel_checked( + "project", + "alice", + &chunk.scope.session, + &chunk.scope.binding, + || Ok(()), + ) + .unwrap_err(); + assert!(error.outcome_unknown); + let cleanup = repo + .chunk_cleanup_record(&chunk.scope.session) + .unwrap() + .unwrap(); + assert_eq!(cleanup.reason, ScopedChunkCleanupReason::Canceled); + assert!(!cleanup.cleaned); + assert!(directory.join("payload-0").is_file()); + fs::remove_file(directory.join("unexpected")).unwrap(); + drop(gate); + let reopened = Repository::open(&temp.0).unwrap(); + let gate = reopened.service_lock(std::time::Duration::ZERO).unwrap(); + let cleaned = ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { + reason: ScopedChunkCleanupReason::Canceled, + }, + }; + assert_eq!( + reopened.scoped_chunk_query(&gate, &chunk).unwrap().state, + cleaned + ); + assert!(!directory.join("payload-0").exists()); + assert!(directory.join("decision-0").is_file()); + assert!(!reopened + .common_metadata + .join("tmp") + .join(format!("upload-{}", chunk.scope.session)) + .exists()); + assert_eq!( + reopened + .scoped_chunk_write(&gate, &chunk, &payload[..TRANSFER_CHUNK], || panic!( + "cleaned replay must not republish" + )) + .unwrap() + .state, + cleaned + ); + let mut late = chunk.clone(); + late.operation_id = "e".repeat(64); + late.offset = TRANSFER_CHUNK as u64; + late.payload_sha256 = format!("{:x}", Sha256::digest(&payload[TRANSFER_CHUNK..])); + assert_eq!( + reopened.scoped_chunk_query(&gate, &late).unwrap().state, + ScopedChunkState::Unobserved + ); + assert!(reopened + .scoped_chunk_write(&gate, &late, &payload[TRANSFER_CHUNK..], || Ok(())) + .is_err()); + assert!(!directory.join(format!("payload-{}", late.offset)).exists()); + } + + #[test] + fn expiry_preserves_decision_and_records_cleaned_reason() { + let payload = b"frozen chunk"; + let (_temp, repo, chunk) = fixture(payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_chunk_write(&gate, &chunk, payload, || Ok(())) + .unwrap(); + let meta = repo + .common_metadata + .join("tmp") + .join(format!("upload-{}/meta", chunk.scope.session)); + File::options() + .write(true) + .open(meta) + .unwrap() + .set_modified( + std::time::SystemTime::now() - std::time::Duration::from_secs(24 * 3600 + 1), + ) + .unwrap(); + repo.expire_transfers().unwrap(); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { + reason: ScopedChunkCleanupReason::Expired + } + } + ); + assert_eq!( + repo.scoped_chunk_write(&gate, &chunk, payload, || panic!( + "expired replay must not republish" + )) + .unwrap() + .state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { + reason: ScopedChunkCleanupReason::Expired + } + } + ); + } + + #[test] + fn terminal_operation_cleanup_preserves_completed_receipt() { + let payload = vec![9; TRANSFER_CHUNK + 1]; + let (_temp, repo, chunk) = fixture(&payload); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_chunk_write(&gate, &chunk, &payload[..TRANSFER_CHUNK], || Ok(())) + .unwrap(); + repo.scoped_upload_applying_checked( + &gate, + "project", + "alice", + &chunk.scope.session, + &chunk.scope.binding, + || Ok(()), + ) + .unwrap(); + assert!(matches!( + repo.scoped_upload_status( + &gate, + "project", + "alice", + &chunk.scope.session, + &chunk.scope.binding + ) + .unwrap() + .state, + Some(ScopedUploadState::Aborted { .. }) + )); + let mut unobserved = chunk.clone(); + unobserved.offset = TRANSFER_CHUNK as u64; + unobserved.operation_id = "f".repeat(64); + unobserved.payload_sha256 = format!("{:x}", Sha256::digest(&payload[TRANSFER_CHUNK..])); + assert_eq!( + repo.scoped_chunk_query(&gate, &unobserved).unwrap().state, + ScopedChunkState::Unobserved + ); + assert!(!repo + .common_metadata + .join("tmp") + .join(format!("upload-{}", chunk.scope.session)) + .exists()); + assert_eq!( + repo.scoped_chunk_query(&gate, &chunk).unwrap().state, + ScopedChunkState::Accepted { + data: ScopedChunkData::Cleaned { + reason: ScopedChunkCleanupReason::Completed + } + } + ); + } +} diff --git a/src/repository_plumbing.rs b/src/repository_plumbing.rs index 0403173..2c07a3d 100644 --- a/src/repository_plumbing.rs +++ b/src/repository_plumbing.rs @@ -133,6 +133,7 @@ impl Repository { } roots.extend(super::notes_storage::retention_roots(&snapshot)?); roots.extend(self.pull_roots(&snapshot.objects)?); + roots.extend(self.release_retention_roots()?); // Fetched remote-only tags are validated by snapshot(), but are not // exposed as tracking branches. They still protect recovery objects. let remotes = self.common_metadata.join("remotes"); diff --git a/src/repository_pool.rs b/src/repository_pool.rs index 5f5928d..6f820bd 100644 --- a/src/repository_pool.rs +++ b/src/repository_pool.rs @@ -132,11 +132,15 @@ impl Repository { } let mut snapshot = self.snapshot()?; let reachable = reachable_from_roots(replicated.iter().cloned(), &snapshot.objects)?; + // A verified pool copy does not replace a release holder's local + // obligation to serve the selected immutable bytes. + let retained = self.release_retention_blobs()?; let blobs: BTreeSet<_> = snapshot .objects .iter() .filter_map(|(id, o)| { - (matches!(o, Object::Wasm(_)) && reachable.contains(id)).then_some(id.clone()) + (matches!(o, Object::Wasm(_)) && reachable.contains(id) && !retained.contains(id)) + .then_some(id.clone()) }) .collect(); let mut state = self.partial_state()?; diff --git a/src/repository_ref_transactions.rs b/src/repository_ref_transactions.rs index 02be2e6..d65acea 100644 --- a/src/repository_ref_transactions.rs +++ b/src/repository_ref_transactions.rs @@ -6,6 +6,7 @@ mod head_transaction; use head_transaction::{ReferenceHead, ResolvedHeadEdit}; const JOURNAL: &str = "ref-transaction.bin"; +const SCOPED_JOURNAL_MAGIC: &[u8; 8] = b"WGTREF04"; const MAX_TRANSACTION_BYTES: u64 = 64 * 1024 * 1024; pub const MAX_REFERENCE_EDITS: usize = 4096; @@ -131,11 +132,70 @@ struct ReferencePlan { head: Option, } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ScopedReferenceJournal { + version: u32, + plan: ReferencePlan, + receipt: ScopedReceipt, +} + +impl ScopedReferenceJournal { + fn bytes(&self) -> RepositoryResult> { + if self.version != 4 { + return Err("invalid scoped reference journal version".into()); + } + self.plan.after()?; + self.receipt.validate()?; + let accepted: Vec<_> = if self.receipt.response.ok && !self.receipt.dry_run { + self.receipt + .updates + .iter() + .zip(&self.receipt.rejections) + .filter(|(_, reason)| reason.is_none()) + .map(|(update, _)| update) + .collect() + } else { + Vec::new() + }; + if accepted.len() != self.plan.changes.len() { + return Err("scoped journal reference count mismatch".into()); + } + for (update, change) in accepted.into_iter().zip(&self.plan.changes) { + let reference = format!( + "refs/{}/{}", + if matches!(update.namespace, crate::protocol::RefNamespace::Branch) { + "heads" + } else { + "tags" + }, + update.name + ); + if reference != change.reference + || update.expected != change.old + || update.new != change.new + { + return Err("scoped journal reference image mismatch".into()); + } + } + if self.plan.head.is_some() { + return Err("scoped receive cannot change HEAD directly".into()); + } + let mut bytes = SCOPED_JOURNAL_MAGIC.to_vec(); + bytes.extend(crate::binary::encode(self)?); + if bytes.len() as u64 > MAX_TRANSACTION_BYTES { + return Err("scoped reference transaction exceeds 64 MiB".into()); + } + Ok(bytes) + } +} + pub struct PreparedReferences<'a> { repo: &'a Repository, _lock: WriteLock, plan: ReferencePlan, rejections: Vec, + scoped: Option, } fn reference_parts(reference: &str) -> RepositoryResult<(&str, &str)> { @@ -518,6 +578,7 @@ impl Repository { _lock: lock, plan, rejections, + scoped: None, }) } @@ -786,14 +847,43 @@ impl Repository { return Err("reference transaction must be a bounded regular file".into()); } let bytes = read_regular(&path)?; - let plan: ReferencePlan = crate::binary::decode(&bytes) - .map_err(|error| format!("invalid reference transaction: {error}"))?; - if plan.bytes()? != bytes { - return Err("noncanonical reference transaction".into()); + let (plan, scoped) = if let Some(body) = bytes.strip_prefix(SCOPED_JOURNAL_MAGIC) { + let journal: ScopedReferenceJournal = crate::binary::decode(body) + .map_err(|error| format!("invalid scoped reference transaction: {error}"))?; + if journal.bytes()? != bytes { + return Err("noncanonical scoped reference transaction".into()); + } + (journal.plan, Some(journal.receipt)) + } else { + let plan: ReferencePlan = crate::binary::decode(&bytes) + .map_err(|error| format!("invalid reference transaction: {error}"))?; + if plan.bytes()? != bytes { + return Err("noncanonical reference transaction".into()); + } + (plan, None) + }; + if let ReferenceRecovery::Scoped(expected) = &self.reference_recovery { + match (expected, &scoped) { + (Some(expected), Some(receipt)) + if crate::binary::encode(expected)? + == crate::binary::encode(&receipt.scope)? => {} + _ => { + return Err( + "pending reference transaction requires recovery of its original scope" + .into(), + ) + } + } } let result = (|| { let after = self.validate_reference_plan(&plan)?; + if let Some(receipt) = &scoped { + self.scoped_check_journal(receipt)?; + } self.apply_reference_plan(&plan, &after, || Ok(()))?; + if let Some(receipt) = &scoped { + self.scoped_finish_from_journal(receipt)?; + } self.clear_reference_transaction() })(); result.map_err(|error| format!("committed reference transaction requires recovery; no later operation may proceed: {error}")) @@ -802,12 +892,20 @@ impl Repository { impl PreparedReferences<'_> { pub fn commit(self) -> RepositoryResult { + self.commit_checked(|| Ok(())) + } + + fn commit_checked( + self, + before_publish: impl FnOnce() -> RepositoryResult<()>, + ) -> RepositoryResult { let after = self.plan.after()?; let mut reports: Vec = self.plan.changes.iter().map(|change| json!({"reference":change.reference,"old":change.old,"new":change.new,"updated":change.old != change.new})).collect(); if let Some(head) = &self.plan.head { reports.push(head.report(&self.plan.before, &after)); } - if !self.plan.head.as_ref().is_some_and(ReferenceHead::changed) + if self.scoped.is_none() + && !self.plan.head.as_ref().is_some_and(ReferenceHead::changed) && self .plan .changes @@ -820,8 +918,40 @@ impl PreparedReferences<'_> { }); } self.repo.check_reference_preimages(&self.plan, &after)?; - self.repo.atomic_write(&self.repo.common_metadata.join(JOURNAL), &self.plan.bytes()?).map_err(|error| format!("reference commit decision may be durable; inspect or retry a locked query to recover: {error}"))?; - self.repo.apply_reference_plan(&self.plan, &after, || Ok(())).and_then(|()| self.repo.clear_reference_transaction()).map_err(|error| format!("reference transaction is committed and may be partially installed; a locked query will finish recovery: {error}"))?; + if let Some(receipt) = &self.scoped { + self.repo.scoped_check_journal(receipt)?; + } + let journal = if let Some(receipt) = &self.scoped { + ScopedReferenceJournal { + version: 4, + plan: self.plan.clone(), + receipt: receipt.clone(), + } + .bytes()? + } else { + self.plan.bytes()? + }; + let mut passed = false; + let result = self.repo.atomic_write_checked( + &self.repo.common_metadata.join(JOURNAL), + &journal, + || { + before_publish()?; + passed = true; + Ok(()) + }, + ); + if let Err(error) = result { + return Err(if passed { + format!("reference commit decision may be durable; inspect or retry a locked query to recover: {error}") + } else { + error + }); + } + self.repo.apply_reference_plan(&self.plan, &after, || Ok(())).and_then(|()| { + if let Some(receipt) = &self.scoped { self.repo.scoped_finish_from_journal(receipt)?; } + self.repo.clear_reference_transaction() + }).map_err(|error| format!("reference transaction is committed and may be partially installed; a locked query will finish recovery: {error}"))?; Ok(ReferenceCommitOutcome { updates: reports, rejections: self.rejections, @@ -830,6 +960,47 @@ impl PreparedReferences<'_> { } impl Repository { + pub(super) fn scoped_record_receipt_locked( + &self, + _lock: WriteLock, + receipt: ScopedReceipt, + ) -> RepositoryResult<(crate::protocol::Response, Vec)> { + if let Some(result) = self.scoped_finished_under_writer(&receipt.scope)? { + return Ok(result); + } + let result = (receipt.response.clone(), receipt.payload.clone()); + // No reference decision is being made. The writer lock has already + // rolled forward a prior committed journal; one record rename is the + // durable decision and does not require a full reference snapshot. + self.scoped_finish_from_journal(&receipt)?; + Ok(result) + } + + pub(crate) fn scoped_record_failure( + &self, + gate: &ServiceGuard, + scope: &ScopedExecution, + mut response: crate::protocol::Response, + ) -> RepositoryResult<(crate::protocol::Response, Vec)> { + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + let lock = self.lock()?; + if let Some(message) = &mut response.error { + if message.len() > 32 * 1024 { + crate::cli_error(&format!("scoped operation diagnostic: {message}")); + let mut end = 32 * 1024; + while !message.is_char_boundary(end) { + end -= 1; + } + message.truncate(end); + message.push('…'); + } + } + let receipt = ScopedReceipt::failure(scope, response)?; + self.scoped_record_receipt_locked(lock, receipt) + } + /// One durable decision publishes the whole leased receive batch. Hook /// rejection precedes installation; the hook sees a verified quarantine /// bundle, never an unverified object in the repository's public store. @@ -839,10 +1010,29 @@ impl Repository { updates: &[crate::protocol::RefUpdate], before_receive: impl FnOnce(&[u8]) -> RepositoryResult<()>, ) -> Result<(), ReceiveError> { - self.receive_batch_mode(bytes, updates, true, false, |bundle, _| { - before_receive(bundle)?; - Ok(vec![None; updates.len()]) - }) + self.receive_batch_checked_scoped(bytes, updates, None, before_receive, || Ok(())) + } + + pub(crate) fn receive_batch_checked_scoped( + &self, + bytes: &[u8], + updates: &[crate::protocol::RefUpdate], + scope: Option<&ScopedExecution>, + before_receive: impl FnOnce(&[u8]) -> RepositoryResult<()>, + before_commit: impl FnOnce() -> RepositoryResult<()>, + ) -> Result<(), ReceiveError> { + self.receive_batch_mode( + bytes, + updates, + true, + false, + scope, + |bundle, _| { + before_receive(bundle)?; + Ok(vec![None; updates.len()]) + }, + |_| before_commit(), + ) .map(|_| ()) } @@ -856,16 +1046,31 @@ impl Repository { dry_run: bool, check: impl FnOnce(&[u8], &[Option]) -> RepositoryResult>>, ) -> Result>, ReceiveError> { - self.receive_batch_mode(bytes, updates, false, dry_run, check) + self.receive_batch_selective_scoped(bytes, updates, dry_run, None, check, |_| Ok(())) + } + + pub(crate) fn receive_batch_selective_scoped( + &self, + bytes: &[u8], + updates: &[crate::protocol::RefUpdate], + dry_run: bool, + scope: Option<&ScopedExecution>, + check: impl FnOnce(&[u8], &[Option]) -> RepositoryResult>>, + before_commit: impl FnOnce(&[Option]) -> RepositoryResult<()>, + ) -> Result>, ReceiveError> { + self.receive_batch_mode(bytes, updates, false, dry_run, scope, check, before_commit) } + #[allow(clippy::too_many_arguments)] // Distinct authorization and publication hooks share one transaction. fn receive_batch_mode( &self, bytes: &[u8], updates: &[crate::protocol::RefUpdate], atomic: bool, dry_run: bool, + scope: Option<&ScopedExecution>, before_receive: impl FnOnce(&[u8], &[Option]) -> RepositoryResult>>, + before_commit: impl FnOnce(&[Option]) -> RepositoryResult<()>, ) -> Result>, ReceiveError> { let mut publishing = false; let result = (|| { @@ -996,7 +1201,7 @@ impl Repository { return Err(error.clone()); } } - let plan = ReferencePlan { + let mut plan = ReferencePlan { unix_seconds: reflog_timestamp()?, version: 3, message: if atomic { "receive-atomic" } else { "receive" }.into(), @@ -1016,21 +1221,34 @@ impl Repository { }; plan.after()?; plan.bytes()?; - if dry_run || plan.changes.is_empty() { + if (dry_run || plan.changes.is_empty()) && scope.is_none() { + before_commit(&reasons)?; return Ok(reasons); } - if let Some(incoming) = &incoming { - self.install_snapshot_objects(incoming)?; + let receipt = scope + .map(|scope| ScopedReceipt::success(scope, updates, &reasons, dry_run)) + .transpose()?; + if dry_run { + plan.changes.clear(); + } + if !dry_run && !plan.changes.is_empty() { + if let Some(incoming) = &incoming { + self.install_snapshot_objects(incoming)?; + } } self.validate_reference_plan(&plan)?; - publishing = true; PreparedReferences { repo: self, _lock: lock, plan, rejections: Vec::new(), + scoped: receipt, } - .commit()?; + .commit_checked(|| { + before_commit(&reasons)?; + publishing = true; + Ok(()) + })?; Ok(reasons) })(); receive_result(result, publishing) @@ -1045,10 +1263,28 @@ impl Repository { updates: &[crate::protocol::RefUpdate], check: impl FnOnce(&[u8]) -> RepositoryResult<()>, ) -> Result<(), ReceiveError> { - self.receive_batch_mode(bytes, updates, true, true, |quarantine, _| { - check(quarantine)?; - Ok(vec![None; updates.len()]) - }) + self.check_receive_batch_scoped(bytes, updates, None, check) + } + + pub(crate) fn check_receive_batch_scoped( + &self, + bytes: &[u8], + updates: &[crate::protocol::RefUpdate], + scope: Option<&ScopedExecution>, + check: impl FnOnce(&[u8]) -> RepositoryResult<()>, + ) -> Result<(), ReceiveError> { + self.receive_batch_mode( + bytes, + updates, + true, + true, + scope, + |quarantine, _| { + check(quarantine)?; + Ok(vec![None; updates.len()]) + }, + |_| Ok(()), + ) .map(|_| ()) } } @@ -1135,6 +1371,518 @@ mod tests { .unwrap(); } + #[test] + fn restricted_recovery_checks_journal_scope_on_open_and_every_later_lock() { + use crate::protocol::{Operation, ScopedUploadState, UploadBinding}; + let temp = Temp::new(); + let (repo, mut plan, after) = fixture(&temp); + let unscoped = plan.clone(); + let payload = b"frozen scoped upload"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let scope = ScopedExecution { + actor: "alice".into(), + repository: "repo".into(), + session: "a".repeat(64), + binding: binding.clone(), + }; + repo.scoped_upload_slice( + &scope.repository, + &scope.actor, + &scope.session, + &binding, + 0, + payload, + ) + .unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_applying( + &gate, + &scope.repository, + &scope.actor, + &scope.session, + &binding, + ) + .unwrap(); + drop(gate); + let mut wrong_actor = scope.clone(); + wrong_actor.actor = "bob".into(); + let mut wrong_repository = scope.clone(); + wrong_repository.repository = "other".into(); + let mut wrong_session = scope.clone(); + wrong_session.session = "b".repeat(64); + let mut wrong_binding = scope.clone(); + wrong_binding.binding = UploadBinding::for_payload( + Operation::Push { + branch: "other".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let foreign = [wrong_actor, wrong_repository, wrong_session, wrong_binding]; + let no_scope = Repository::open_for_recovery(&repo.root, None).unwrap(); + let wrong_scopes: Vec<_> = foreign + .iter() + .map(|scope| Repository::open_for_recovery(&repo.root, Some(scope)).unwrap()) + .collect(); + plan.version = 3; + plan.message = "receive-atomic".into(); + plan.changes.clear(); + let journal = ScopedReferenceJournal { + version: 4, + plan, + receipt: ScopedReceipt::aborted(&scope), + }; + repo.atomic_write( + &repo.common_metadata.join(JOURNAL), + &journal.bytes().unwrap(), + ) + .unwrap(); + + assert!(no_scope.lock().is_err()); + assert!(Repository::open_for_recovery(&repo.root, None).is_err()); + for (expected, reopened) in foreign.iter().zip(&wrong_scopes) { + assert!(reopened.lock().is_err()); + assert!(Repository::open_for_recovery(&repo.root, Some(expected)).is_err()); + } + assert!(matches!( + repo.scoped_record(&scope.session).unwrap().unwrap().state, + ScopedUploadState::ApplyingV4 { .. } + )); + assert!(repo.common_metadata.join(JOURNAL).exists()); + let recovered = Repository::open_for_recovery(&repo.root, Some(&scope)).unwrap(); + assert!(matches!( + recovered + .scoped_record(&scope.session) + .unwrap() + .unwrap() + .state, + ScopedUploadState::Aborted { .. } + )); + + persist(&repo, &unscoped); + assert!(no_scope.lock().is_err()); + assert!(recovered.lock().is_err()); + assert!(Repository::open_for_recovery(&repo.root, Some(&scope)).is_err()); + let ordinary = Repository::open(&repo.root).unwrap(); + assert_eq!(ordinary.snapshot().unwrap().manifest.refs, after.refs); + } + + #[test] + fn scoped_receipt_recovers_every_commit_and_receipt_boundary() { + use crate::protocol::{ + BatchPublication, Operation, RefNamespace, RefUpdate, ScopedUploadState, UploadBinding, + }; + for stop in 0..=5 { + let temp = Temp::new(); + let (repo, mut plan, _) = fixture(&temp); + plan.version = 3; + plan.message = "receive-atomic".into(); + let updates: Vec<_> = plan + .changes + .iter() + .map(|change| { + let (namespace, name) = + if let Some(name) = change.reference.strip_prefix("refs/heads/") { + (RefNamespace::Branch, name) + } else { + ( + RefNamespace::Tag, + change.reference.strip_prefix("refs/tags/").unwrap(), + ) + }; + RefUpdate { + namespace, + name: name.into(), + expected: change.old.clone(), + new: change.new.clone(), + force: false, + } + }) + .collect(); + let payload = crate::binary::encode(&BatchPublication { + updates: updates.clone(), + bundle: Vec::new(), + }) + .unwrap(); + let binding = UploadBinding::for_payload(Operation::PublishBatch {}, &payload).unwrap(); + let session = "7".repeat(64); + let scope = ScopedExecution { + actor: "alice".into(), + repository: "repo".into(), + session: session.clone(), + binding: binding.clone(), + }; + #[cfg(feature = "server")] + let install_policy = |generation: u64, digit: &str, alice: bool| { + let grant = serde_json::json!({"repository":"repo","read":true,"write":["refs/heads/*","refs/tags/*"],"force":true,"create":false}); + let policy = serde_json::json!({"version":3,"principals":[ + {"name":"alice","token_sha256":null,"grants":if alice { vec![grant.clone()] } else { vec![] }}, + {"name":"bob","token_sha256":null,"grants":[grant]} + ]}); + let request = serde_json::json!({"version":1,"operation_id":digit.repeat(64),"expected_generation":generation,"policy":policy}); + let input = temp.0.join("policy-request.json"); + fs::write(&input, serde_json::to_vec(&request).unwrap()).unwrap(); + crate::server::run(&[ + "server".into(), + "policy-set".into(), + temp.0.to_str().unwrap().into(), + input.to_str().unwrap().into(), + ]) + .unwrap(); + }; + #[cfg(feature = "server")] + install_policy(0, "a", true); + repo.scoped_upload_slice( + &scope.repository, + &scope.actor, + &session, + &binding, + 0, + &payload, + ) + .unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_applying(&gate, &scope.repository, &scope.actor, &session, &binding) + .unwrap(); + drop(gate); + let receipt = + ScopedReceipt::success(&scope, &updates, &vec![None; updates.len()], false) + .unwrap(); + let journal = ScopedReferenceJournal { + version: 4, + plan: plan.clone(), + receipt: receipt.clone(), + }; + let after = plan.after().unwrap(); + if stop > 0 { + let _writer = repo.lock_named("write.lock").unwrap(); + repo.atomic_write( + &repo.common_metadata.join(JOURNAL), + &journal.bytes().unwrap(), + ) + .unwrap(); + if stop == 1 { + // A committed old journal must remain recoverable while + // the old single-file ledger is first migrated. + let record = repo.scoped_record(&session).unwrap().unwrap(); + let old = super::super::scoped_transfer_storage::ScopedLedger { + version: 3, + records: BTreeMap::from([(session.clone(), record)]), + }; + repo.atomic_write( + &repo.common_metadata.join("scoped-uploads.bin"), + &crate::binary::encode(&old).unwrap(), + ) + .unwrap(); + } + if stop == 2 { + let mut writes = 0; + assert!(repo + .apply_reference_plan(&plan, &after, || { + writes += 1; + if writes == 1 { + Err("power loss".into()) + } else { + Ok(()) + } + }) + .is_err()); + } + if stop >= 3 { + repo.apply_reference_plan(&plan, &after, || Ok(())).unwrap(); + } + if stop >= 4 { + repo.scoped_finish_from_journal(&receipt).unwrap(); + } + if stop >= 5 { + repo.clear_reference_transaction().unwrap(); + } + } + #[cfg(feature = "server")] + { + install_policy(1, "b", false); + let request = |operation| crate::protocol::Request { + version: 1, + repository: scope.repository.clone(), + operation, + }; + // A different authorized actor opens the repository after the + // fence. Only an existing journal may be rolled forward. + crate::server::test_authorized_process( + &temp.0, + "bob", + request(Operation::Advertise {}), + &[], + ) + .unwrap(); + assert!(crate::server::test_authorized_process( + &temp.0, + "alice", + request(Operation::ApplyScopedUpload { + session: session.clone(), + binding: binding.clone() + }), + &[] + ) + .is_err()); + assert!(crate::server::test_authorized_process( + &temp.0, + "bob", + request(Operation::QueryScopedUpload { + session: session.clone(), + binding: binding.clone() + }), + &[] + ) + .is_err()); + install_policy(2, "c", true); + let (response, bytes) = crate::server::test_authorized_process( + &temp.0, + "alice", + request(Operation::QueryScopedUpload { + session: session.clone(), + binding: binding.clone(), + }), + &[], + ) + .unwrap(); + assert!(response.ok); + let checked: crate::protocol::ScopedUploadStatus = + crate::binary::decode(&bytes).unwrap(); + if stop == 0 { + assert!(matches!( + checked.state, + Some(ScopedUploadState::Aborted { .. }) + )); + } else { + assert!(matches!( + checked.state, + Some(ScopedUploadState::FinishedV4 { .. }) + )); + } + } + let reopened = Repository::open(&repo.root).unwrap(); + let gate = reopened.service_lock(std::time::Duration::ZERO).unwrap(); + let status = reopened + .scoped_upload_status(&gate, &scope.repository, &scope.actor, &session, &binding) + .unwrap(); + if stop == 0 { + assert!(matches!( + status.state, + Some(ScopedUploadState::Aborted { .. }) + )); + assert_eq!(reopened.snapshot().unwrap().manifest.refs, plan.before.refs); + } else { + assert!( + matches!(status.state, Some(ScopedUploadState::FinishedV4 { receipt }) if receipt.response.ok) + ); + let snapshot = reopened.snapshot().unwrap(); + assert_eq!(snapshot.manifest.refs, after.refs); + assert_eq!(snapshot.manifest.tags, after.tags); + assert!(!reopened.common_metadata.join(JOURNAL).exists()); + } + } + } + + #[test] + fn old_near_full_ledger_recovers_committed_receipt_growth() { + use super::super::scoped_transfer_storage::{ScopedLedger, ScopedRecord}; + use crate::protocol::{ + BatchPublication, Operation, RefNamespace, RefUpdate, Response, ScopedUploadState, + UploadBinding, + }; + + let temp = Temp::new(); + let (repo, mut plan, _) = fixture(&temp); + let change = plan.changes.first().unwrap().clone(); + let (namespace, name) = if let Some(name) = change.reference.strip_prefix("refs/heads/") { + (RefNamespace::Branch, name) + } else { + ( + RefNamespace::Tag, + change.reference.strip_prefix("refs/tags/").unwrap(), + ) + }; + let update = RefUpdate { + namespace, + name: name.into(), + expected: change.old, + new: change.new, + force: false, + }; + let payload = crate::binary::encode(&crate::protocol::OptionsPublication { + publication: BatchPublication { + updates: vec![update.clone()], + bundle: Vec::new(), + }, + options: Vec::new(), + }) + .unwrap(); + let binding = + UploadBinding::for_payload(Operation::PublishPartial { dry_run: false }, &payload) + .unwrap(); + let session = "7".repeat(64); + let scope = ScopedExecution { + actor: "alice".into(), + repository: "repo".into(), + session: session.clone(), + binding: binding.clone(), + }; + let receipt = + ScopedReceipt::success(&scope, &[update], &[Some("r".repeat(65_536))], false).unwrap(); + let applying = ScopedRecord { + actor: scope.actor.clone(), + binding: binding.clone(), + state: ScopedUploadState::ApplyingV4 { + repository: scope.repository.clone(), + }, + repository: Some(scope.repository.clone()), + }; + let previous = "8".repeat(64); + let previous_record = ScopedRecord { + actor: scope.actor.clone(), + binding, + state: ScopedUploadState::Finished { + response: Response { + version: 1, + ok: true, + publication_unknown: false, + error: None, + state: None, + tip: None, + }, + payload: vec![0x5a; MAX_TRANSACTION_BYTES as usize - 8192], + }, + repository: Some(scope.repository.clone()), + }; + let before_record = crate::binary::encode(&applying).unwrap().len(); + let mut finished = applying.clone(); + finished.state = ScopedUploadState::FinishedV4 { + receipt: Box::new(receipt.clone()), + }; + let after_record = crate::binary::encode(&finished).unwrap().len(); + let old = ScopedLedger { + version: 3, + records: BTreeMap::from([ + (session.clone(), applying), + (previous.clone(), previous_record), + ]), + }; + let old_bytes = crate::binary::encode(&old).unwrap(); + assert!(old_bytes.len() < MAX_TRANSACTION_BYTES as usize); + assert!(old_bytes.len() - before_record + after_record > MAX_TRANSACTION_BYTES as usize); + repo.atomic_write(&repo.common_metadata.join("scoped-uploads.bin"), &old_bytes) + .unwrap(); + drop(old_bytes); + drop(old); + plan.version = 3; + plan.message = "receive-atomic".into(); + plan.changes.clear(); + let journal = ScopedReferenceJournal { + version: 4, + plan, + receipt, + }; + repo.atomic_write( + &repo.common_metadata.join(JOURNAL), + &journal.bytes().unwrap(), + ) + .unwrap(); + let reopened = Repository::open(&repo.root).unwrap(); + assert!(matches!( + reopened.scoped_record(&session).unwrap().unwrap().state, + ScopedUploadState::FinishedV4 { .. } + )); + assert!( + matches!(reopened.scoped_record(&previous).unwrap().unwrap().state, + ScopedUploadState::Finished { payload, .. } if payload.len() == MAX_TRANSACTION_BYTES as usize - 8192) + ); + assert!(!reopened.common_metadata.join(JOURNAL).exists()); + } + + #[test] + fn scoped_recovery_refuses_foreign_identity_before_installing_refs() { + use crate::protocol::{ + BatchPublication, Operation, RefNamespace, RefUpdate, UploadBinding, + }; + let temp = Temp::new(); + let (repo, mut plan, _) = fixture(&temp); + plan.version = 3; + plan.message = "receive-atomic".into(); + let updates: Vec<_> = plan + .changes + .iter() + .map(|change| { + let (namespace, name) = + if let Some(name) = change.reference.strip_prefix("refs/heads/") { + (RefNamespace::Branch, name) + } else { + ( + RefNamespace::Tag, + change.reference.strip_prefix("refs/tags/").unwrap(), + ) + }; + RefUpdate { + namespace, + name: name.into(), + expected: change.old.clone(), + new: change.new.clone(), + force: false, + } + }) + .collect(); + let payload = crate::binary::encode(&BatchPublication { + updates: updates.clone(), + bundle: Vec::new(), + }) + .unwrap(); + let binding = UploadBinding::for_payload(Operation::PublishBatch {}, &payload).unwrap(); + let session = "8".repeat(64); + repo.scoped_upload_slice("project", "alice", &session, &binding, 0, &payload) + .unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_applying(&gate, "project", "alice", &session, &binding) + .unwrap(); + drop(gate); + let scope = ScopedExecution { + actor: "bob".into(), + repository: "project".into(), + session, + binding, + }; + let receipt = + ScopedReceipt::success(&scope, &updates, &vec![None; updates.len()], false).unwrap(); + let journal = ScopedReferenceJournal { + version: 4, + plan: plan.clone(), + receipt, + }; + repo.atomic_write( + &repo.common_metadata.join(JOURNAL), + &journal.bytes().unwrap(), + ) + .unwrap(); + assert!(Repository::open(&repo.root).is_err()); + assert_eq!( + repo.read_named_refs("refs", false).unwrap(), + plan.before.refs + ); + assert_eq!( + repo.read_named_refs("tags", true).unwrap(), + plan.before.tags + ); + } + #[test] fn bare_receive_recovers_each_durable_publication_prefix_including_head() { for stop in 0..=3 { @@ -1314,10 +2062,10 @@ mod tests { "abort me", ) .unwrap(); - assert!(repo.common_metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_err()); assert!(!repo.common_metadata.join(JOURNAL).exists()); drop(prepared); - assert!(!repo.common_metadata.join("write.lock").exists()); + assert!(repo.lock_named("write.lock").is_ok()); assert!(!repo .read_named_refs("tags", true) .unwrap() @@ -1670,12 +2418,12 @@ mod tests { fs::read(primary.common_metadata.join(JOURNAL)).unwrap(), plan.bytes().unwrap() ); - assert!(!primary.common_metadata.join("write.lock").exists()); + assert!(primary.lock_named("write.lock").is_ok()); } } #[test] - fn stale_writer_lock_is_preserved_until_explicit_removal_before_head_recovery() { + fn legacy_writer_lock_is_preserved_until_controlled_removal_before_head_recovery() { let temp = Temp::new(); let (primary, peer, origin, plan, _) = head_fixture(&temp, true); persist(&primary, &plan); diff --git a/src/repository_retention.rs b/src/repository_retention.rs new file mode 100644 index 0000000..07f1572 --- /dev/null +++ b/src/repository_retention.rs @@ -0,0 +1,1003 @@ +//! Durable release references. All transitions and maintenance consult this +//! file under the repository writer lock, including close-before-prepare. +use super::record_store::{self, Bucket, RecordStore, Seed}; +use super::*; +use crate::protocol::{ + RetainedFile, RetentionCommand, RetentionRecord, RetentionReply, RetentionState, +}; +use sha2::{Digest, Sha256}; + +const MAX_RECORDS: usize = 4096; +const MAX_FILES: usize = 128; + +#[derive(Debug)] +pub struct RetentionError { + pub message: String, + pub outcome_unknown: bool, +} +impl std::fmt::Display for RetentionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} +impl std::error::Error for RetentionError {} +impl From for RetentionError { + fn from(message: String) -> Self { + Self { + message, + outcome_unknown: false, + } + } +} +impl From<&str> for RetentionError { + fn from(message: &str) -> Self { + message.to_owned().into() + } +} +#[derive(Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Retentions { + version: u32, + records: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyRetentionRecord { + version: u32, + operation: String, + actor: String, + state: RetentionState, + commit: Option, + files: BTreeMap, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyRetentions { + version: u32, + records: BTreeMap, +} + +fn retention_bucket(state: &RetentionState) -> Bucket { + match state { + RetentionState::Prepared => Bucket::Active, + RetentionState::Promoted => Bucket::Pinned, + RetentionState::Closed => Bucket::Terminal, + } +} + +fn validate_retention_record(id: &str, bucket: Bucket, bytes: &[u8]) -> RepositoryResult<()> { + let record: RetentionRecord = crate::binary::decode(bytes)?; + if record.operation != id || retention_bucket(&record.state) != bucket { + return Err("invalid release retention record".into()); + } + record.validate() +} + +fn compare_retention_records( + _id: &str, + active: &[u8], + bucket: Bucket, + terminal: &[u8], +) -> RepositoryResult<()> { + let old: RetentionRecord = crate::binary::decode(active)?; + let mut new: RetentionRecord = crate::binary::decode(terminal)?; + if !matches!( + (bucket, &new.state), + (Bucket::Pinned, RetentionState::Promoted) | (Bucket::Terminal, RetentionState::Closed) + ) { + return Err("invalid release retention transition".into()); + } + new.state = RetentionState::Prepared; + if old != new { + return Err("conflicting release retention transition".into()); + } + Ok(()) +} + +impl Repository { + fn retention_store(&self) -> RepositoryResult> { + RecordStore::open(self, "release-retentions", |bytes| { + let Some(bytes) = bytes else { + return Ok(Vec::new()); + }; + let state = match crate::binary::decode::(bytes) { + Ok(state) if state.version == crate::protocol::RETENTION_VERSION => state, + _ => { + let legacy: LegacyRetentions = crate::binary::decode(bytes)?; + if legacy.version != 1 { + return Err("invalid release retention store version".into()); + } + let mut records = BTreeMap::new(); + for (id, record) in legacy.records { + if record.version != 1 { + return Err("invalid legacy release retention record".into()); + } + records.insert( + id, + RetentionRecord { + version: crate::protocol::RETENTION_VERSION, + operation: record.operation, + actor: record.actor, + state: record.state, + repository: None, + commit: record.commit, + files: record.files, + }, + ); + } + Retentions { + version: crate::protocol::RETENTION_VERSION, + records, + } + } + }; + if state.records.len() > MAX_RECORDS { + return Err("invalid release retention store version or size".into()); + } + let mut seeds = Vec::with_capacity(state.records.len()); + for (id, record) in state.records { + let bucket = retention_bucket(&record.state); + let payload = crate::binary::encode(&record)?; + validate_retention_record(&id, bucket, &payload)?; + seeds.push(Seed { + id, + bucket, + payload, + }); + } + Ok(seeds) + }) + } + + fn retention_record(&self, id: &str) -> RepositoryResult> { + self.retention_store()? + .get(id, validate_retention_record, compare_retention_records)? + .map(|(_, bytes)| crate::binary::decode(&bytes)) + .transpose() + } + + fn save_retention_record( + &self, + record: &RetentionRecord, + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), RetentionError> { + let bytes = crate::binary::encode(record)?; + self.retention_store()? + .write( + &record.operation, + retention_bucket(&record.state), + &bytes, + validate_retention_record, + compare_retention_records, + before_publish, + ) + .map_err(|error| RetentionError { + message: error.message, + outcome_unknown: error.outcome_unknown, + }) + } + + fn fence_retention(&self, state: &RetentionState) -> Result<(), RetentionError> { + self.retention_store()? + .fence(retention_bucket(state)) + .map_err(|message| RetentionError { + message, + outcome_unknown: true, + }) + } + + pub(super) fn retention_capacity_locked( + &self, + ) -> RepositoryResult { + self.retention_store()? + .capacity(validate_retention_record, compare_retention_records) + } + + // These helpers are called with the writer lock already held. + pub(super) fn release_retention_roots(&self) -> RepositoryResult> { + let store = self.retention_store()?; + let mut roots = Vec::new(); + for bucket in [Bucket::Active, Bucket::Pinned] { + store.for_each( + bucket, + validate_retention_record, + compare_retention_records, + |_, bytes| { + let record: RetentionRecord = crate::binary::decode(bytes)?; + if let Some(commit) = record.commit { + roots.push(commit); + } + Ok(()) + }, + )?; + } + Ok(roots) + } + pub(super) fn release_retention_blobs(&self) -> RepositoryResult> { + let store = self.retention_store()?; + let mut blobs = BTreeSet::new(); + for bucket in [Bucket::Active, Bucket::Pinned] { + store.for_each( + bucket, + validate_retention_record, + compare_retention_records, + |_, bytes| { + let record: RetentionRecord = crate::binary::decode(bytes)?; + blobs.extend(record.files.into_values().map(|f| f.blob)); + Ok(()) + }, + )?; + } + Ok(blobs) + } + + #[cfg(test)] + pub fn release_retention( + &self, + repository: &str, + actor: &str, + command: RetentionCommand, + ) -> Result { + self.release_retention_checked(repository, actor, command, || Ok(())) + } + + pub fn release_retention_checked( + &self, + repository: &str, + actor: &str, + command: RetentionCommand, + mut before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result { + crate::protocol::RetentionRequest { + version: 1, + command: command.clone(), + } + .validate()?; + crate::protocol::repository_name(repository)?; + if actor.is_empty() || actor.len() > 128 { + return Err("invalid authenticated actor".into()); + } + let _lock = self.lock()?; + let operation = match &command { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Query { operation } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } + | RetentionCommand::Read { operation, .. } => operation, + }; + require_id(operation)?; + let mut stored = self + .retention_record(operation) + .map_err(|message| RetentionError { + message, + outcome_unknown: true, + })?; + if let Some(record) = &stored { + let legacy_query = + record.repository.is_none() && matches!(&command, RetentionCommand::Query { .. }); + if record.actor != actor + || (!legacy_query && record.repository.as_deref() != Some(repository)) + { + return Err("release retention unavailable to this actor or repository".into()); + } + } + match command { + RetentionCommand::Query { operation } => { + if let Some(record) = &stored { + self.fence_retention(&record.state)?; + } + Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation: operation.clone(), + record: stored, + }) + } + RetentionCommand::Prepare { + operation, + commit, + mut paths, + } => { + require_id(&commit)?; + if paths.is_empty() || paths.len() > MAX_FILES { + return Err("release retention requires 1..=128 paths".into()); + } + paths.sort(); + if paths.windows(2).any(|p| p[0] == p[1]) { + return Err("duplicate release path".into()); + } + for path in &paths { + validate_tree_path(path)?; + if path.len() > 1024 { + return Err("release path too long".into()); + } + } + if let Some(record) = &stored { + if record.state == RetentionState::Closed { + return Err("release retention is closed".into()); + } + if record.commit.as_deref() != Some(&commit) + || !record.files.keys().eq(paths.iter()) + { + return Err("release operation identity conflict".into()); + } + self.fence_retention(&record.state)?; + return Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation: operation.clone(), + record: Some(record.clone()), + }); + } + let snapshot = self.snapshot()?; + let Some(Object::Commit(found)) = snapshot.objects.get(&commit) else { + return Err("release commit is not stored".into()); + }; + let Some(Object::Tree(tree)) = + found.tree.as_ref().and_then(|id| snapshot.objects.get(id)) + else { + return Err("release requires a named commit tree".into()); + }; + let mut files = BTreeMap::new(); + for path in paths { + let blob = tree + .entries + .get(&path) + .ok_or("release path absent from commit")?; + let Some(Object::Wasm(bytes)) = snapshot.objects.get(blob) else { + return Err( + "release file must be available locally before preparation".into() + ); + }; + files.insert( + path, + RetainedFile { + blob: blob.clone(), + sha256: format!("{:x}", Sha256::digest(bytes)), + size: bytes.len() as u64, + }, + ); + } + let record = RetentionRecord { + version: crate::protocol::RETENTION_VERSION, + operation: operation.clone(), + actor: actor.into(), + state: RetentionState::Prepared, + repository: Some(repository.into()), + commit: Some(commit), + files, + }; + let store = self.retention_store()?; + let (count, bytes) = + store.active_stats(validate_retention_record, compare_retention_records)?; + let size = store.encoded_len(&operation, &crate::binary::encode(&record)?)?; + if count >= record_store::MAX_ACTIVE_RECORDS + || bytes + .checked_add(size) + .is_none_or(|total| total > record_store::MAX_ACTIVE_BYTES) + { + return Err("release retention admission capacity exceeded".into()); + } + self.save_retention_record(&record, &mut before_publish)?; + Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation, + record: Some(record), + }) + } + RetentionCommand::Promote { operation } => { + let record = stored.as_mut().ok_or("release retention not prepared")?; + if record.state == RetentionState::Closed { + return Err("release retention is closed".into()); + } + if record.state == RetentionState::Prepared { + record.state = RetentionState::Promoted; + self.save_retention_record(record, &mut before_publish)?; + } else { + self.fence_retention(&record.state)?; + } + Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation: operation.clone(), + record: stored, + }) + } + RetentionCommand::Close { operation } => { + if let Some(record) = stored.as_mut() { + if record.state == RetentionState::Promoted { + return Err("promoted release retention cannot be closed".into()); + } + if record.state == RetentionState::Closed { + self.fence_retention(&record.state)?; + return Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation: operation.clone(), + record: Some(record.clone()), + }); + } + record.state = RetentionState::Closed; + } else { + stored = Some(RetentionRecord { + version: crate::protocol::RETENTION_VERSION, + operation: operation.clone(), + actor: actor.into(), + state: RetentionState::Closed, + repository: Some(repository.into()), + commit: None, + files: BTreeMap::new(), + }); + } + self.save_retention_record( + stored.as_ref().ok_or("missing retention record")?, + &mut before_publish, + )?; + Ok(RetentionReply::State { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + operation: operation.clone(), + record: stored, + }) + } + RetentionCommand::Read { + operation, + path, + offset, + } => { + let record = stored.as_ref().ok_or("release retention not found")?; + if record.state == RetentionState::Closed { + return Err("release retention is closed".into()); + } + let file = record + .files + .get(&path) + .ok_or("path not protected by release retention")? + .clone(); + let commit = record.commit.clone().ok_or("invalid release commit")?; + let snapshot = self.snapshot()?; + let Some(Object::Wasm(bytes)) = snapshot.objects.get(&file.blob) else { + return Err("protected file unavailable locally".into()); + }; + if bytes.len() as u64 != file.size + || format!("{:x}", Sha256::digest(bytes)) != file.sha256 + { + return Err("protected file checksum mismatch".into()); + } + let start = usize::try_from(offset).map_err(|_| "invalid release file offset")?; + if start >= bytes.len() { + return Err("invalid release file offset".into()); + } + self.fence_retention(&record.state)?; + Ok(RetentionReply::File { + version: crate::protocol::RETENTION_VERSION, + repository: repository.into(), + actor: actor.into(), + operation, + commit, + path, + file, + offset, + bytes: bytes[start + ..bytes + .len() + .min(start.saturating_add(crate::protocol::TRANSFER_CHUNK))] + .to_vec(), + }) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-retention-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn setup() -> (Temp, Repository, String, Vec) { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let bytes = b"\0asm\x01\0\0\0".to_vec(); + let tree = repo + .create_files_tree(&BTreeMap::from([ + ("a.wasm".into(), bytes.clone()), + ("b.wasm".into(), b"\0asm\x01\0\0\0\0\x02\x01x".to_vec()), + ])) + .unwrap(); + let commit = repo.create_commit_object(&tree, &[], "release").unwrap(); + (temp, repo, commit, bytes) + } + fn prepare(id: &str, commit: &str) -> RetentionCommand { + RetentionCommand::Prepare { + operation: id.into(), + commit: commit.into(), + paths: vec!["a.wasm".into()], + } + } + + #[test] + fn publication_checks_run_after_staging_and_only_for_new_decisions() { + let (_temp, repo, commit, bytes) = setup(); + let id = "a".repeat(64); + let error = repo + .release_retention_checked("project", "coordinator", prepare(&id, &commit), || { + assert!(repo.retention_record(&id).unwrap().is_none()); + assert!(fs::read_dir(repo.common_metadata.join("tmp")) + .unwrap() + .next() + .is_some()); + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(error.message, "authorization expired"); + assert!(repo.retention_record(&id).unwrap().is_none()); + + repo.release_retention("project", "coordinator", prepare(&id, &commit)) + .unwrap(); + let prepared = repo.retention_record(&id).unwrap(); + repo.release_retention_checked("project", "coordinator", prepare(&id, &commit), || { + panic!("exact prepare replay must not reauthorize an existing decision") + }) + .unwrap(); + repo.release_retention_checked( + "project", + "coordinator", + RetentionCommand::Query { + operation: id.clone(), + }, + || panic!("query does not publish"), + ) + .unwrap(); + let read = repo + .release_retention_checked( + "project", + "coordinator", + RetentionCommand::Read { + operation: id.clone(), + path: "a.wasm".into(), + offset: 0, + }, + || panic!("read does not publish"), + ) + .unwrap(); + assert!(matches!(read, RetentionReply::File { bytes: actual, .. } if actual == bytes)); + let error = repo + .release_retention_checked( + "project", + "coordinator", + RetentionCommand::Promote { + operation: id.clone(), + }, + || { + assert_eq!(repo.retention_record(&id).unwrap(), prepared); + Err("authorization expired".into()) + }, + ) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(repo.retention_record(&id).unwrap(), prepared); + + repo.release_retention_checked( + "project", + "coordinator", + RetentionCommand::Promote { + operation: id.clone(), + }, + || Ok(()), + ) + .unwrap(); + repo.release_retention_checked( + "project", + "coordinator", + RetentionCommand::Promote { operation: id }, + || panic!("promote replay must not publish"), + ) + .unwrap(); + + let closed = "b".repeat(64); + let before = repo.retention_record(&closed).unwrap(); + let error = repo + .release_retention_checked( + "project", + "coordinator", + RetentionCommand::Close { operation: closed }, + || Err("authorization expired".into()), + ) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(repo.retention_record(&"b".repeat(64)).unwrap(), before); + } + + #[test] + fn tombstones_and_promotion_survive_reopen_and_replays() { + let (temp, repo, commit, _) = setup(); + let closed = "1".repeat(64); + repo.release_retention( + "project", + "coordinator", + RetentionCommand::Close { + operation: closed.clone(), + }, + ) + .unwrap(); + let reopened = Repository::open(&temp.0).unwrap(); + assert!(reopened + .release_retention("project", "coordinator", prepare(&closed, &commit)) + .is_err()); + assert!(reopened + .release_retention( + "project", + "other", + RetentionCommand::Query { operation: closed } + ) + .is_err()); + let id = "2".repeat(64); + reopened + .release_retention("project", "coordinator", prepare(&id, &commit)) + .unwrap(); + assert!(reopened + .release_retention( + "other", + "coordinator", + RetentionCommand::Query { + operation: id.clone() + } + ) + .is_err()); + assert!(reopened + .release_retention( + "other", + "coordinator", + RetentionCommand::Close { + operation: id.clone() + } + ) + .is_err()); + reopened + .release_retention("project", "coordinator", prepare(&id, &commit)) + .unwrap(); + assert!(reopened + .release_retention( + "project", + "coordinator", + RetentionCommand::Prepare { + operation: id.clone(), + commit: commit.clone(), + paths: vec!["b.wasm".into()] + } + ) + .is_err()); + reopened + .release_retention( + "project", + "coordinator", + RetentionCommand::Promote { + operation: id.clone(), + }, + ) + .unwrap(); + assert!(Repository::open(&temp.0) + .unwrap() + .release_retention( + "project", + "coordinator", + RetentionCommand::Close { + operation: id.clone() + } + ) + .is_err()); + assert!(matches!( + reopened + .release_retention( + "project", + "coordinator", + RetentionCommand::Query { operation: id } + ) + .unwrap(), + RetentionReply::State { + record: Some(RetentionRecord { + state: RetentionState::Promoted, + .. + }), + .. + } + )); + } + + #[test] + fn writer_lock_orders_gc_and_pool_eviction_with_protected_bytes() { + let (_temp, repo, commit, bytes) = setup(); + let id = "3".repeat(64); + let guard = repo.lock().unwrap(); + assert!(repo + .release_retention("project", "coordinator", prepare(&id, &commit)) + .is_err()); + drop(guard); + repo.release_retention("project", "coordinator", prepare(&id, &commit)) + .unwrap(); + repo.garbage_collect_mode(&[], true, true).unwrap(); + let config = repo + .attach_pool(vec![PromiseSource { + location: "http://127.0.0.1:9419/pool".into(), + allow_insecure_http: false, + }]) + .unwrap(); + let _pool = repo.pool_lock().unwrap(); + assert_eq!( + repo.evict_pool_blobs(&config, &BTreeSet::from([commit.clone()])) + .unwrap(), + 1 + ); + match repo + .release_retention( + "project", + "coordinator", + RetentionCommand::Read { + operation: id.clone(), + path: "a.wasm".into(), + offset: 0, + }, + ) + .unwrap() + { + RetentionReply::File { bytes: actual, .. } => assert_eq!(actual, bytes), + _ => panic!("expected retained file"), + } + assert!(repo + .release_retention( + "project", + "coordinator", + RetentionCommand::Read { + operation: id.clone(), + path: "b.wasm".into(), + offset: 0 + } + ) + .is_err()); + repo.release_retention( + "project", + "coordinator", + RetentionCommand::Close { operation: id }, + ) + .unwrap(); + repo.garbage_collect_mode(&[], true, false).unwrap(); + assert!(!repo.snapshot().unwrap().objects.contains_key(&commit)); + } + + #[test] + fn legacy_unbound_retention_remains_protected_and_cannot_be_mutated() { + let (_temp, repo, commit, bytes) = setup(); + let id = "9".repeat(64); + // Start with a real old-format store, not a rollback of an already + // published new-format marker over unrelated authoritative records. + let snapshot = repo.snapshot().unwrap(); + let Object::Commit(found) = snapshot.objects.get(&commit).unwrap() else { + panic!("missing commit") + }; + let Object::Tree(tree) = snapshot.objects.get(found.tree.as_ref().unwrap()).unwrap() else { + panic!("missing tree") + }; + let files = BTreeMap::from([( + "a.wasm".into(), + RetainedFile { + blob: tree.entries["a.wasm"].clone(), + sha256: format!("{:x}", Sha256::digest(&bytes)), + size: bytes.len() as u64, + }, + )]); + let legacy = LegacyRetentions { + version: 1, + records: BTreeMap::from([( + id.clone(), + LegacyRetentionRecord { + version: 1, + operation: id.clone(), + actor: "coordinator".into(), + state: RetentionState::Prepared, + commit: Some(commit.clone()), + files, + }, + )]), + }; + repo.atomic_write( + &repo.common_metadata.join("release-retentions.bin"), + &crate::binary::encode(&legacy).unwrap(), + ) + .unwrap(); + let query = repo + .release_retention( + "project", + "coordinator", + RetentionCommand::Query { + operation: id.clone(), + }, + ) + .unwrap(); + assert!(matches!( + query, + RetentionReply::State { + record: Some(RetentionRecord { + repository: None, + .. + }), + .. + } + )); + assert!(repo + .release_retention( + "project", + "coordinator", + RetentionCommand::Close { operation: id } + ) + .is_err()); + repo.garbage_collect_mode(&[], true, true).unwrap(); + assert!(repo.snapshot().unwrap().objects.contains_key(&commit)); + } + + #[test] + fn concurrent_promote_and_close_have_one_durable_winner() { + let (_temp, repo, commit, _) = setup(); + let id = "4".repeat(64); + repo.release_retention("project", "coordinator", prepare(&id, &commit)) + .unwrap(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(3)); + let mut workers = Vec::new(); + for promote in [true, false] { + let barrier = barrier.clone(); + let repo = repo.clone(); + let id = id.clone(); + workers.push(std::thread::spawn(move || { + barrier.wait(); + for _ in 0..1000 { + let command = if promote { + RetentionCommand::Promote { + operation: id.clone(), + } + } else { + RetentionCommand::Close { + operation: id.clone(), + } + }; + match repo.release_retention("project", "coordinator", command) { + Err(e) if e.message.contains("resource is locked") => { + std::thread::sleep(std::time::Duration::from_millis(1)) + } + result => return result.is_ok(), + } + } + panic!("writer lock did not become available"); + })); + } + barrier.wait(); + let successes = workers + .into_iter() + .map(|worker| worker.join().unwrap()) + .filter(|success| *success) + .count(); + assert_eq!(successes, 1); + assert!(matches!( + repo.release_retention( + "project", + "coordinator", + RetentionCommand::Query { operation: id } + ) + .unwrap(), + RetentionReply::State { + record: Some(RetentionRecord { + state: RetentionState::Promoted | RetentionState::Closed, + .. + }), + .. + } + )); + } + + #[test] + fn active_watermark_allows_unknown_close_and_keeps_promoted_roots() { + let (temp, repo, commit, _) = setup(); + let initial = "1".repeat(64); + let RetentionReply::State { + record: Some(mut record), + .. + } = repo + .release_retention("project", "coordinator", prepare(&initial, &commit)) + .unwrap() + else { + panic!("missing prepared record") + }; + let store = repo.retention_store().unwrap(); + for index in 0..record_store::MAX_ACTIVE_RECORDS - 1 { + record.operation = format!("{index:064x}"); + store + .seed_fixture( + &record.operation, + Bucket::Active, + &crate::binary::encode(&record).unwrap(), + ) + .unwrap(); + } + let full = repo.capacity_status().unwrap(); + assert_eq!( + full.retentions.active_records, + record_store::MAX_ACTIVE_RECORDS + ); + assert_eq!( + full.retentions.total_records, + record_store::MAX_ACTIVE_RECORDS + ); + let next = "a".repeat(64); + assert!(repo + .release_retention("project", "coordinator", prepare(&next, &commit)) + .unwrap_err() + .message + .contains("admission capacity")); + let closed = "b".repeat(64); + repo.release_retention( + "project", + "coordinator", + RetentionCommand::Close { + operation: closed.clone(), + }, + ) + .unwrap(); + assert!(repo + .release_retention("project", "coordinator", prepare(&closed, &commit)) + .is_err()); + let promoted = format!("{:064x}", 0); + repo.release_retention( + "project", + "coordinator", + RetentionCommand::Promote { + operation: promoted.clone(), + }, + ) + .unwrap(); + repo.release_retention("project", "coordinator", prepare(&next, &commit)) + .unwrap(); + let after = repo.capacity_status().unwrap(); + assert_eq!( + after.retentions.active_records, + record_store::MAX_ACTIVE_RECORDS + ); + assert_eq!( + after.retentions.total_records, + record_store::MAX_ACTIVE_RECORDS + 2 + ); + assert!(after.retentions.total_bytes > after.retentions.active_bytes); + let reopened = Repository::open(&temp.0).unwrap(); + let _writer = reopened.lock().unwrap(); + assert!(reopened + .release_retention_roots() + .unwrap() + .contains(&commit)); + assert_eq!( + reopened.retention_record(&promoted).unwrap().unwrap().state, + RetentionState::Promoted + ); + assert_eq!( + reopened.retention_record(&closed).unwrap().unwrap().state, + RetentionState::Closed + ); + } +} diff --git a/src/repository_scoped_transfer.rs b/src/repository_scoped_transfer.rs new file mode 100644 index 0000000..80501f1 --- /dev/null +++ b/src/repository_scoped_transfer.rs @@ -0,0 +1,1734 @@ +//! Persistent ownership and outcome for server upload sessions. The service +//! gate serializes the complete RPC; this ledger also survives process exits. +use super::record_store::{self, Bucket, RecordStore, Seed}; +use super::*; +use crate::protocol::{Response, ScopedUploadState, ScopedUploadStatus, UploadBinding}; + +#[derive(Debug)] +pub(crate) struct ScopedUploadError { + pub(crate) message: String, + pub(crate) outcome_unknown: bool, +} + +impl From for ScopedUploadError { + fn from(message: String) -> Self { + Self { + message, + outcome_unknown: false, + } + } +} + +impl From<&str> for ScopedUploadError { + fn from(message: &str) -> Self { + message.to_owned().into() + } +} + +impl ScopedUploadError { + pub(super) fn unknown(message: String) -> Self { + Self { + message, + outcome_unknown: true, + } + } +} + +impl ScopedReceipt { + pub(crate) fn success( + scope: &ScopedExecution, + updates: &[crate::protocol::RefUpdate], + rejections: &[Option], + dry_run: bool, + ) -> RepositoryResult { + use crate::protocol::Operation; + if updates.len() != rejections.len() || updates.len() != scope.binding.targets.len() { + return Err("scoped receipt has an invalid update count".into()); + } + let expected_dry = matches!( + *scope.binding.operation, + Operation::CheckBatch {} | Operation::PublishPartial { dry_run: true } + ); + if dry_run != expected_dry { + return Err("scoped receipt dry-run mismatch".into()); + } + for (update, target) in updates.iter().zip(&scope.binding.targets) { + let reference = format!( + "refs/{}/{}", + if matches!(update.namespace, crate::protocol::RefNamespace::Branch) { + "heads" + } else { + "tags" + }, + update.name + ); + if reference != target.reference || update.force != target.force { + return Err("scoped receipt target mismatch".into()); + } + for id in update.expected.iter().chain(&update.new) { + require_id(id)?; + } + } + if rejections + .iter() + .flatten() + .any(|reason| reason.len() > 65_536) + { + return Err("scoped rejection exceeds bounds".into()); + } + let mut response = Response { + version: 1, + ok: true, + publication_unknown: false, + error: None, + state: None, + tip: None, + }; + let payload = match scope.binding.operation.as_ref() { + Operation::Push { expected, .. } + if updates.len() == 1 + && rejections[0].is_none() + && &updates[0].expected == expected + && updates[0].new.is_some() => + { + response.tip = updates[0].new.clone(); + Vec::new() + } + Operation::UpdateRef { expected, new, .. } + if updates.len() == 1 + && rejections[0].is_none() + && &updates[0].expected == expected + && &updates[0].new == new => + { + response.tip = updates[0].new.clone(); + Vec::new() + } + Operation::PublishBatch {} + | Operation::PublishOptions {} + | Operation::CheckBatch {} + if rejections.iter().all(Option::is_none) => + { + response.tip = Some(scope.binding.digest.clone()); + Vec::new() + } + Operation::PublishPartial { .. } => { + response.tip = Some(scope.binding.digest.clone()); + crate::binary::encode(&crate::protocol::PartialReceipt { + rejections: rejections.to_vec(), + })? + } + _ => return Err("invalid scoped success receipt".into()), + }; + Ok(Self { + version: 4, + scope: scope.clone(), + updates: updates.to_vec(), + rejections: rejections.to_vec(), + dry_run, + aborted: false, + response, + payload, + }) + } + + pub(crate) fn failure( + scope: &ScopedExecution, + mut response: Response, + ) -> RepositoryResult { + if response.ok || response.error.is_none() { + return Err("invalid scoped failure receipt".into()); + } + response.publication_unknown = false; + Ok(Self { + version: 4, + scope: scope.clone(), + updates: Vec::new(), + rejections: Vec::new(), + dry_run: false, + aborted: false, + response, + payload: Vec::new(), + }) + } + + pub(crate) fn aborted(scope: &ScopedExecution) -> Self { + Self { + version: 4, + scope: scope.clone(), + updates: Vec::new(), + rejections: Vec::new(), + dry_run: false, + aborted: true, + response: Response { + version: 1, + ok: false, + publication_unknown: false, + error: Some("operation aborted before native decision".into()), + state: None, + tip: None, + }, + payload: Vec::new(), + } + } + + pub fn validate(&self) -> RepositoryResult<()> { + require_id(&self.scope.session)?; + crate::protocol::repository_name(&self.scope.repository)?; + self.scope.binding.validate()?; + if self.version != 4 + || self.scope.actor.is_empty() + || self.scope.actor.len() > 128 + || self.response.version != 1 + || self.response.publication_unknown + || self.response.state.is_some() + || (!self.response.ok && self.response.tip.is_some()) + || self.payload.len() > crate::protocol::MAX_PACKET_BYTES + { + return Err("invalid scoped receipt identity or response".into()); + } + let expected = if self.aborted { + Self::aborted(&self.scope) + } else if self.response.ok { + Self::success(&self.scope, &self.updates, &self.rejections, self.dry_run)? + } else { + Self::failure(&self.scope, self.response.clone())? + }; + if crate::binary::encode(&expected)? != crate::binary::encode(self)? { + return Err("noncanonical scoped receipt".into()); + } + Ok(()) + } +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ScopedRecord { + pub(super) actor: String, + pub(super) binding: UploadBinding, + pub(super) state: ScopedUploadState, + pub(super) repository: Option, +} +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ScopedLedger { + pub(super) version: u32, + pub(super) records: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyScopedRecord { + actor: String, + binding: UploadBinding, + state: ScopedUploadState, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct LegacyScopedLedger { + version: u32, + records: BTreeMap, +} + +fn scoped_bucket(state: &ScopedUploadState) -> Bucket { + match state { + ScopedUploadState::Open + | ScopedUploadState::Applying + | ScopedUploadState::ApplyingV4 { .. } => Bucket::Active, + _ => Bucket::Terminal, + } +} + +fn validate_scoped_record(id: &str, bucket: Bucket, bytes: &[u8]) -> RepositoryResult<()> { + let record: ScopedRecord = crate::binary::decode(bytes)?; + require_id(id)?; + if scoped_bucket(&record.state) != bucket || record.actor.is_empty() || record.actor.len() > 128 + { + return Err("invalid scoped upload record".into()); + } + record.binding.validate()?; + if let Some(repository) = &record.repository { + crate::protocol::repository_name(repository)?; + } + if let ScopedUploadState::ApplyingV4 { repository } + | ScopedUploadState::Aborted { repository } = &record.state + { + crate::protocol::repository_name(repository)?; + if record.repository.as_ref() != Some(repository) { + return Err("scoped upload repository does not match its state".into()); + } + } + if let ScopedUploadState::FinishedV4 { receipt } = &record.state { + receipt.validate()?; + if receipt.aborted + || receipt.scope.session != id + || receipt.scope.actor != record.actor + || record.repository.as_ref() != Some(&receipt.scope.repository) + || crate::binary::encode(&receipt.scope.binding)? + != crate::binary::encode(&record.binding)? + { + return Err("scoped receipt does not match ledger identity".into()); + } + } + Ok(()) +} + +fn compare_scoped_records( + _id: &str, + active: &[u8], + bucket: Bucket, + terminal: &[u8], +) -> RepositoryResult<()> { + let old: ScopedRecord = crate::binary::decode(active)?; + let new: ScopedRecord = crate::binary::decode(terminal)?; + if bucket != Bucket::Terminal + || old.actor != new.actor + || old.repository != new.repository + || crate::binary::encode(&old.binding)? != crate::binary::encode(&new.binding)? + || !matches!( + (&old.state, &new.state), + (ScopedUploadState::Open, ScopedUploadState::Canceled) + | ( + ScopedUploadState::ApplyingV4 { .. }, + ScopedUploadState::Aborted { .. } | ScopedUploadState::FinishedV4 { .. } + ) + ) + { + return Err("conflicting scoped upload transition".into()); + } + Ok(()) +} + +impl Repository { + fn scoped_store(&self) -> RepositoryResult> { + RecordStore::open(self, "scoped-uploads", |bytes| { + let Some(bytes) = bytes else { + return Ok(Vec::new()); + }; + let ledger = match crate::binary::decode::(bytes) { + Ok(ledger) if ledger.version == 3 => ledger, + _ => { + let legacy: LegacyScopedLedger = crate::binary::decode(bytes)?; + if !matches!(legacy.version, 1 | 2) { + return Err("invalid scoped upload ledger version".into()); + } + let mut records = BTreeMap::new(); + for (id, record) in legacy.records { + if legacy.version == 1 + && matches!( + record.state, + ScopedUploadState::ApplyingV4 { .. } + | ScopedUploadState::Aborted { .. } + | ScopedUploadState::FinishedV4 { .. } + ) + { + return Err("v4 scoped state requires ledger version 2".into()); + } + let repository = match &record.state { + ScopedUploadState::ApplyingV4 { repository } + | ScopedUploadState::Aborted { repository } => Some(repository.clone()), + ScopedUploadState::FinishedV4 { receipt } => { + Some(receipt.scope.repository.clone()) + } + _ => None, + }; + records.insert( + id, + ScopedRecord { + actor: record.actor, + binding: record.binding, + state: record.state, + repository, + }, + ); + } + ScopedLedger { + version: 3, + records, + } + } + }; + if ledger.records.len() > 4096 { + return Err("invalid scoped upload ledger".into()); + } + let mut seeds = Vec::with_capacity(ledger.records.len()); + for (id, record) in ledger.records { + let bucket = scoped_bucket(&record.state); + let payload = crate::binary::encode(&record)?; + validate_scoped_record(&id, bucket, &payload)?; + seeds.push(Seed { + id, + bucket, + payload, + }); + } + Ok(seeds) + }) + } + + pub(super) fn scoped_record(&self, id: &str) -> RepositoryResult> { + self.scoped_store()? + .get(id, validate_scoped_record, compare_scoped_records)? + .map(|(_, bytes)| crate::binary::decode(&bytes)) + .transpose() + } + + #[cfg(test)] + fn scoped_ledger(&self) -> RepositoryResult { + let store = self.scoped_store()?; + let mut records = BTreeMap::new(); + for bucket in [Bucket::Active, Bucket::Terminal] { + store.for_each( + bucket, + validate_scoped_record, + compare_scoped_records, + |id, bytes| { + records.insert(id.into(), crate::binary::decode(bytes)?); + Ok(()) + }, + )?; + } + Ok(ScopedLedger { + version: 3, + records, + }) + } + + #[cfg(test)] + fn save_scoped_ledger(&self, ledger: &ScopedLedger) -> RepositoryResult<()> { + for (id, record) in &ledger.records { + self.save_scoped_record_checked(id, record, &mut || Ok(())) + .map_err(|error| error.message)?; + } + Ok(()) + } + + /// Snapshot admission usage and retained record totals under the writer and transfer locks. + pub fn capacity_status(&self) -> RepositoryResult { + let _writer = self.lock()?; + let _state = self.lock_named("transfer-state.lock")?; + let scoped = self + .scoped_store()? + .capacity(validate_scoped_record, compare_scoped_records)?; + let retentions = self.retention_capacity_locked()?; + let status = crate::protocol::RepositoryCapacity { + version: 1, + scoped, + retentions, + }; + status.validate()?; + Ok(status) + } + + fn save_scoped_record_checked( + &self, + id: &str, + record: &ScopedRecord, + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { + let bytes = crate::binary::encode(record)?; + self.scoped_store()? + .write( + id, + scoped_bucket(&record.state), + &bytes, + validate_scoped_record, + compare_scoped_records, + before_publish, + ) + .map_err(|error| ScopedUploadError { + message: error.message, + outcome_unknown: error.outcome_unknown, + }) + } + pub(super) fn check_scope( + record: &ScopedRecord, + repository: &str, + actor: &str, + binding: &UploadBinding, + allow_legacy_terminal: bool, + ) -> RepositoryResult<()> { + let legacy_terminal = allow_legacy_terminal + && record.repository.is_none() + && !matches!(record.state, ScopedUploadState::Open); + if (!legacy_terminal && record.repository.as_deref() != Some(repository)) + || record.actor != actor + || crate::binary::encode(&record.binding)? != crate::binary::encode(binding)? + { + return Err("scoped upload identity conflict".into()); + } + Ok(()) + } + + // The caller holds transfer-state.lock and has checked any cleanup or + // existing per-chunk decision relevant to its entry point. + pub(super) fn ensure_scoped_open_locked( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + existing_fence_unknown: bool, + ) -> Result { + if let Some(record) = self.scoped_record(session)? { + Self::check_scope(&record, repository, actor, binding, false)?; + if !matches!(record.state, ScopedUploadState::Open) { + return Err("scoped upload is not open".into()); + } + // A prior Open rename may have succeeded before its directory + // sync failed; fence it before confirming or extending the state. + self.scoped_store()? + .fence(Bucket::Active) + .map_err(|message| ScopedUploadError { + message, + outcome_unknown: existing_fence_unknown, + })?; + return Ok(false); + } + if self.scoped_upload_directory_exists(session)? { + return Err("upload session already exists outside this scope".into()); + } + let record = ScopedRecord { + actor: actor.into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + repository: Some(repository.into()), + }; + let store = self.scoped_store()?; + let (count, bytes) = store.active_stats(validate_scoped_record, compare_scoped_records)?; + let size = store.encoded_len(session, &crate::binary::encode(&record)?)?; + if count >= record_store::MAX_ACTIVE_RECORDS + || bytes + .checked_add(size) + .is_none_or(|total| total > record_store::MAX_ACTIVE_BYTES) + { + return Err("scoped upload admission capacity exceeded".into()); + } + self.save_scoped_record_checked(session, &record, before_publish)?; + Ok(true) + } + + fn check_receipt_state( + record: &ScopedRecord, + receipt: &ScopedReceipt, + ) -> RepositoryResult { + Self::check_scope( + record, + &receipt.scope.repository, + &receipt.scope.actor, + &receipt.scope.binding, + false, + )?; + match &record.state { + ScopedUploadState::ApplyingV4 { repository } + if repository == &receipt.scope.repository => + { + Ok(false) + } + ScopedUploadState::Aborted { repository } + if receipt.aborted && repository == &receipt.scope.repository => + { + Ok(true) + } + ScopedUploadState::FinishedV4 { receipt: existing } + if crate::binary::encode(existing.as_ref())? == crate::binary::encode(receipt)? => + { + Ok(true) + } + _ => Err("scoped upload state conflicts with durable journal".into()), + } + } + + // Validate the identity and state before recovery changes any reference. + pub(super) fn scoped_check_journal(&self, receipt: &ScopedReceipt) -> RepositoryResult<()> { + receipt.validate()?; + let _lock = self.lock_named("transfer-state.lock")?; + let mut record = self + .scoped_record(&receipt.scope.session)? + .ok_or("scoped upload not found")?; + if !Self::check_receipt_state(&record, receipt)? { + record.state = if receipt.aborted { + ScopedUploadState::Aborted { + repository: receipt.scope.repository.clone(), + } + } else { + ScopedUploadState::FinishedV4 { + receipt: Box::new(receipt.clone()), + } + }; + self.scoped_store()? + .encoded_len(&receipt.scope.session, &crate::binary::encode(&record)?)?; + } + Ok(()) + } + + #[cfg(test)] + pub(crate) fn scoped_upload_slice( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + offset: u64, + bytes: &[u8], + ) -> RepositoryResult<()> { + self.scoped_upload_slice_checked(repository, actor, session, binding, offset, bytes, || { + Ok(()) + }) + .map_err(|error| error.message) + } + + #[allow(clippy::too_many_arguments)] // Explicit legacy slice identity and decision callback. + pub(crate) fn scoped_upload_slice_checked( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + offset: u64, + bytes: &[u8], + mut before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { + require_id(session)?; + crate::protocol::repository_name(repository)?; + binding.validate_slice(offset, bytes.len())?; + let _lock = self.lock_named("transfer-state.lock")?; + self.require_live_scoped_chunks_locked(session)?; + let newly_opened = self.ensure_scoped_open_locked( + repository, + actor, + session, + binding, + &mut before_publish, + true, + )?; + self.repair_scoped_upload_directory(session, binding.total) + .map_err(|message| ScopedUploadError { + message, + outcome_unknown: newly_opened, + })?; + self.upload_slice_checked(session, binding.total, offset, bytes, &mut before_publish) + .map_err(|mut error| { + error.outcome_unknown |= newly_opened; + error + }) + } + + pub(crate) fn scoped_upload_read( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + ) -> RepositoryResult> { + require_id(session)?; + crate::protocol::repository_name(repository)?; + binding.validate()?; + let _lock = self.lock_named("transfer-state.lock")?; + let record = self + .scoped_record(session)? + .ok_or("scoped upload not found")?; + Self::check_scope(&record, repository, actor, binding, false)?; + if !matches!(record.state, ScopedUploadState::Open) { + return Err("scoped upload is not open".into()); + } + self.scoped_store()?.fence(Bucket::Active)?; + { + let _transfer = self.lock_named("transfer.lock")?; + self.recover_scoped_chunks_locked(repository, actor, session, binding)?; + } + let bytes = self.read_upload_staged(session)?; + binding.validate_payload(&bytes)?; + Ok(bytes) + } + + #[cfg(test)] + pub(crate) fn scoped_upload_applying( + &self, + gate: &ServiceGuard, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + ) -> RepositoryResult<()> { + self.scoped_upload_applying_checked(gate, repository, actor, session, binding, || Ok(())) + .map_err(|error| error.message) + } + + pub(crate) fn scoped_upload_applying_checked( + &self, + gate: &ServiceGuard, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + mut before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { + crate::protocol::repository_name(repository)?; + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + let _lock = self.lock_named("transfer-state.lock")?; + self.require_live_scoped_chunks_locked(session)?; + let mut record = self + .scoped_record(session)? + .ok_or("scoped upload not found")?; + Self::check_scope(&record, repository, actor, binding, false)?; + if !matches!(record.state, ScopedUploadState::Open) { + return Err("scoped upload is not open".into()); + } + record.state = ScopedUploadState::ApplyingV4 { + repository: repository.into(), + }; + self.save_scoped_record_checked(session, &record, &mut before_publish) + } + + // Called only while the repository writer lock and its v4 journal are held. + pub(super) fn scoped_finish_from_journal( + &self, + receipt: &ScopedReceipt, + ) -> RepositoryResult<()> { + receipt.validate()?; + let _lock = self.lock_named("transfer-state.lock")?; + let mut record = self + .scoped_record(&receipt.scope.session)? + .ok_or("scoped upload not found")?; + if Self::check_receipt_state(&record, receipt)? { + self.scoped_store()?.fence(scoped_bucket(&record.state))?; + return Ok(()); + } + record.state = if receipt.aborted { + ScopedUploadState::Aborted { + repository: receipt.scope.repository.clone(), + } + } else { + ScopedUploadState::FinishedV4 { + receipt: Box::new(receipt.clone()), + } + }; + self.save_scoped_record_checked(&receipt.scope.session, &record, &mut || Ok(())) + .map_err(|error| error.message) + } + + // The caller holds writer lock, after recovering any pending journal. + pub(super) fn scoped_finished_under_writer( + &self, + scope: &ScopedExecution, + ) -> RepositoryResult)>> { + let _lock = self.lock_named("transfer-state.lock")?; + let record = self + .scoped_record(&scope.session)? + .ok_or("scoped upload not found")?; + Self::check_scope( + &record, + &scope.repository, + &scope.actor, + &scope.binding, + false, + )?; + match &record.state { + ScopedUploadState::ApplyingV4 { repository } if repository == &scope.repository => { + Ok(None) + } + ScopedUploadState::Finished { response, payload } => { + Ok(Some((response.clone(), payload.clone()))) + } + ScopedUploadState::FinishedV4 { receipt } + if receipt.scope.repository == scope.repository => + { + Ok(Some((receipt.response.clone(), receipt.payload.clone()))) + } + _ => Err("scoped upload has no v4 operation in progress".into()), + } + } + + pub(super) fn scoped_upload_directory_exists(&self, session: &str) -> RepositoryResult { + let path = self + .common_metadata + .join("tmp") + .join(format!("upload-{session}")); + match fs::symlink_metadata(&path) { + Ok(_) => Ok(true), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(io_error("inspect scoped upload directory", &path, error)), + } + } + + pub(crate) fn scoped_upload_cleanup(&self, session: &str) -> RepositoryResult<()> { + require_id(session)?; + let _state = self.lock_named("transfer-state.lock")?; + let record = self.scoped_record(session)?; + let reason = match record.as_ref().map(|record| &record.state) { + Some( + ScopedUploadState::Finished { .. } + | ScopedUploadState::FinishedV4 { .. } + | ScopedUploadState::Aborted { .. }, + ) => crate::protocol::ScopedChunkCleanupReason::Completed, + Some(ScopedUploadState::Canceled) => { + crate::protocol::ScopedChunkCleanupReason::Canceled + } + _ => return Err("scoped upload is not terminal; cleanup is not authorized".into()), + }; + self.scoped_store()?.fence(Bucket::Terminal)?; + let _transfer = self.lock_named("transfer.lock")?; + self.cleanup_scoped_chunks_locked(session, reason)?; + Ok(()) + } + + #[cfg(test)] + pub(crate) fn scoped_upload_cancel( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + ) -> RepositoryResult<()> { + self.scoped_upload_cancel_checked(repository, actor, session, binding, || Ok(())) + .map_err(|error| error.message) + } + + pub(crate) fn scoped_upload_cancel_checked( + &self, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + mut before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { + require_id(session)?; + crate::protocol::repository_name(repository)?; + binding.validate()?; + let _lock = self.lock_named("transfer-state.lock")?; + let mut record = self + .scoped_record(session) + .map_err(ScopedUploadError::unknown)?; + let needs_publish = if let Some(record) = record.as_mut() { + Self::check_scope(record, repository, actor, binding, false)?; + match record.state { + ScopedUploadState::Open => { + record.state = ScopedUploadState::Canceled; + true + } + ScopedUploadState::Canceled => false, + _ => { + return Err( + "scoped upload outcome must be recovered before cancellation".into(), + ) + } + } + } else { + if self.scoped_upload_directory_exists(session)? { + return Err("upload session already exists outside this scope".into()); + } + record = Some(ScopedRecord { + actor: actor.into(), + binding: binding.clone(), + state: ScopedUploadState::Canceled, + repository: Some(repository.into()), + }); + true + }; + if needs_publish { + self.save_scoped_record_checked( + session, + record.as_ref().ok_or("missing cancellation record")?, + &mut before_publish, + )?; + } else { + // Never remove chunks until a previously published cancellation + // tombstone has a completed directory durability fence. + self.scoped_store()? + .fence(Bucket::Terminal) + .map_err(ScopedUploadError::unknown)?; + } + let _transfer = self + .lock_named("transfer.lock") + .map_err(ScopedUploadError::unknown)?; + self.cleanup_scoped_chunks_locked( + session, + crate::protocol::ScopedChunkCleanupReason::Canceled, + ) + .map_err(ScopedUploadError::unknown)?; + Ok(()) + } + + pub(crate) fn scoped_upload_status( + &self, + gate: &ServiceGuard, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + ) -> RepositoryResult { + self.scoped_upload_status_inner(gate, repository, actor, session, binding, true) + } + + /// Recover a permitted durable journal, but never invent a terminal decision. + pub(crate) fn scoped_upload_observe( + &self, + gate: &ServiceGuard, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + ) -> RepositoryResult { + self.scoped_upload_status_inner(gate, repository, actor, session, binding, false) + } + + fn scoped_upload_status_inner( + &self, + gate: &ServiceGuard, + repository: &str, + actor: &str, + session: &str, + binding: &UploadBinding, + abort_interrupted: bool, + ) -> RepositoryResult { + require_id(session)?; + crate::protocol::repository_name(repository)?; + binding.validate()?; + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + // The guard excludes every in-flight service worker. Acquiring the + // writer lock first rolls forward a pending v4 decision before reading + // the ledger. Only a v4 Applying with no journal can then be aborted. + let writer = self.lock()?; + let _lock = self.lock_named("transfer-state.lock")?; + let record = self.scoped_record(session)?; + let state = match record.as_ref() { + Some(record) => { + // Legacy records without repository identity are readable by + // the old status API, but cannot authorize restricted recovery. + Self::check_scope(record, repository, actor, binding, abort_interrupted)?; + match &record.state { + ScopedUploadState::ApplyingV4 { repository: actual } + | ScopedUploadState::Aborted { repository: actual } + if actual != repository => + { + return Err("scoped upload repository conflict".into()) + } + ScopedUploadState::FinishedV4 { receipt } + if receipt.scope.repository != repository => + { + return Err("scoped upload repository conflict".into()) + } + _ => (), + } + Some(record.state.clone()) + } + None => None, + }; + // State reads must not turn an uncertain earlier rename into a + // confirmed status until the ledger's directory is synchronized. + if let Some(record) = &record { + self.scoped_store()?.fence(scoped_bucket(&record.state))?; + } + drop(_lock); + if abort_interrupted && matches!(state, Some(ScopedUploadState::ApplyingV4 { .. })) { + let scope = ScopedExecution { + actor: actor.into(), + repository: repository.into(), + session: session.into(), + binding: binding.clone(), + }; + self.scoped_record_receipt_locked(writer, ScopedReceipt::aborted(&scope))?; + return Ok(ScopedUploadStatus { + version: crate::protocol::SCOPED_UPLOAD_STATUS_VERSION, + state: Some(ScopedUploadState::Aborted { + repository: repository.into(), + }), + }); + } + Ok(ScopedUploadStatus { + version: crate::protocol::SCOPED_UPLOAD_STATUS_VERSION, + state, + }) + } + + /// Close an interrupted v4 apply only after the writer lock establishes + /// there is no committed journal, while the service gate excludes workers. + pub(crate) fn scoped_upload_abort_checked( + &self, + gate: &ServiceGuard, + scope: &ScopedExecution, + mut before_publish: impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { + require_id(&scope.session)?; + crate::protocol::repository_name(&scope.repository)?; + scope.binding.validate()?; + if gate.common_metadata != self.common_metadata { + return Err("service guard belongs to another repository".into()); + } + let _writer = self.lock().map_err(ScopedUploadError::unknown)?; + let _state = self.lock_named("transfer-state.lock")?; + let mut record = self + .scoped_record(&scope.session) + .map_err(ScopedUploadError::unknown)? + .ok_or("scoped upload not found")?; + Self::check_scope( + &record, + &scope.repository, + &scope.actor, + &scope.binding, + false, + )?; + if !matches!(&record.state, ScopedUploadState::ApplyingV4 { repository } if repository == &scope.repository) + { + return Err("scoped upload is not an interrupted v4 apply".into()); + } + record.state = ScopedUploadState::Aborted { + repository: scope.repository.clone(), + }; + self.save_scoped_record_checked(&scope.session, &record, &mut before_publish) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Operation, ScopedUploadState, UploadTarget}; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "wasm-git-scoped-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&p).unwrap(); + Self(p) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn observing_interrupted_apply_does_not_abort_until_authorized_close() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let payload = b"frozen intent"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let scope = ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: "d".repeat(64), + binding, + }; + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_slice( + &scope.repository, + &scope.actor, + &scope.session, + &scope.binding, + 0, + payload, + ) + .unwrap(); + repo.scoped_upload_applying( + &gate, + &scope.repository, + &scope.actor, + &scope.session, + &scope.binding, + ) + .unwrap(); + let observe = || { + repo.scoped_upload_observe( + &gate, + &scope.repository, + &scope.actor, + &scope.session, + &scope.binding, + ) + .unwrap() + }; + assert!(matches!( + observe().state, + Some(ScopedUploadState::ApplyingV4 { .. }) + )); + let failure = repo + .scoped_upload_abort_checked(&gate, &scope, || Err("authorization expired".into())) + .unwrap_err(); + assert!(!failure.outcome_unknown); + assert!(matches!( + observe().state, + Some(ScopedUploadState::ApplyingV4 { .. }) + )); + repo.scoped_upload_abort_checked(&gate, &scope, || Ok(())) + .unwrap(); + assert!(matches!( + observe().state, + Some(ScopedUploadState::Aborted { .. }) + )); + } + + #[test] + fn applying_intent_checks_authority_at_publication_and_recovers_without_it() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + let payload = b"frozen intent"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let session = "c".repeat(64); + repo.scoped_upload_slice("project", "alice", &session, &binding, 0, payload) + .unwrap(); + let path = repo + .common_metadata + .join("scoped-uploads-records/active") + .join(&session); + let before = fs::read(&path).unwrap(); + let error = repo + .scoped_upload_applying_checked(&gate, "project", "alice", &session, &binding, || { + assert_eq!(fs::read(&path).unwrap(), before); + assert!(fs::read_dir(repo.common_metadata.join("tmp")) + .unwrap() + .any(|entry| { + entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("ref-") + })); + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(fs::read(&path).unwrap(), before); + assert!(matches!( + &repo.scoped_ledger().unwrap().records[&session].state, + ScopedUploadState::Open + )); + + repo.scoped_upload_applying_checked(&gate, "project", "alice", &session, &binding, || { + Ok(()) + }) + .unwrap(); + drop(gate); + let reopened = Repository::open(&temp.0).unwrap(); + let gate = reopened.service_lock(std::time::Duration::ZERO).unwrap(); + assert!(matches!( + reopened + .scoped_upload_status(&gate, "project", "alice", &session, &binding) + .unwrap() + .state, + Some(ScopedUploadState::Aborted { .. }) + )); + } + + #[test] + fn authorization_fences_new_upload_and_cancel_decisions_but_not_replays() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let payload = b"frozen chunk"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let session = "a".repeat(64); + let ledger_path = repo + .common_metadata + .join("scoped-uploads-records/active") + .join(&session); + let directory = repo + .common_metadata + .join("tmp") + .join(format!("upload-{session}")); + let error = repo + .scoped_upload_slice_checked("project", "alice", &session, &binding, 0, payload, || { + assert!(!ledger_path.exists()); + assert!(fs::read_dir(repo.common_metadata.join("tmp")) + .unwrap() + .next() + .is_some()); + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(error.message, "authorization expired"); + assert!(!ledger_path.exists()); + assert!(!directory.exists()); + + let mut checks = 0; + let error = repo + .scoped_upload_slice_checked("project", "alice", &session, &binding, 0, payload, || { + checks += 1; + if checks == 1 { + Ok(()) + } else { + Err("authorization expired".into()) + } + }) + .unwrap_err(); + assert_eq!(checks, 2); + assert!(error.outcome_unknown); + assert!(matches!( + &repo.scoped_ledger().unwrap().records[&session].state, + ScopedUploadState::Open + )); + assert!(!directory.join("0").exists()); + + let mut checks = 0; + repo.scoped_upload_slice_checked( + "project", + "alice", + &session, + &binding, + 0, + payload, + || { + checks += 1; + assert!(!directory.join("0").exists()); + Ok(()) + }, + ) + .unwrap(); + assert_eq!(checks, 1); + assert_eq!(fs::read(directory.join("0")).unwrap(), payload); + repo.scoped_upload_slice_checked( + "project", + "alice", + &session, + &binding, + 0, + payload, + || panic!("an exact slice replay must not publish again"), + ) + .unwrap(); + + let before = fs::read(&ledger_path).unwrap(); + let absent = "b".repeat(64); + let error = repo + .scoped_upload_cancel_checked("project", "alice", &absent, &binding, || { + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert_eq!(fs::read(&ledger_path).unwrap(), before); + let error = repo + .scoped_upload_cancel_checked("project", "alice", &session, &binding, || { + assert_eq!(fs::read(&ledger_path).unwrap(), before); + Err("authorization expired".into()) + }) + .unwrap_err(); + assert!(!error.outcome_unknown); + assert!(directory.join("0").exists()); + assert_eq!(fs::read(&ledger_path).unwrap(), before); + + fs::write(directory.join("foreign"), b"prevent cleanup").unwrap(); + let error = repo + .scoped_upload_cancel_checked("project", "alice", &session, &binding, || Ok(())) + .unwrap_err(); + assert!(error.outcome_unknown); + assert!(matches!( + &repo.scoped_ledger().unwrap().records[&session].state, + ScopedUploadState::Canceled + )); + let reopened = Repository::open(&temp.0).unwrap(); + let error = reopened + .scoped_upload_cancel_checked("project", "alice", &session, &binding, || { + panic!("canceled replay is cleanup of an existing decision") + }) + .unwrap_err(); + assert!(error.outcome_unknown); + fs::remove_file(directory.join("foreign")).unwrap(); + reopened + .scoped_upload_cancel_checked("project", "alice", &session, &binding, || { + panic!("canceled replay must not reauthorize cleanup") + }) + .unwrap(); + assert!(!directory.exists()); + assert!(matches!( + &reopened.scoped_ledger().unwrap().records[&session].state, + ScopedUploadState::Canceled + )); + } + + #[test] + fn session_owner_targets_cancel_and_unknown_outcome_survive_restart() { + let t = Temp::new(); + let repo = Repository::init(&t.0).unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + let id = "1".repeat(64); + let payload = b"a frozen bundle"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "a".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let other_binding = UploadBinding::for_payload( + Operation::Push { + branch: "b".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + repo.scoped_upload_slice("project", "alice", &id, &binding, 0, payload) + .unwrap(); + assert!(repo + .scoped_upload_slice("other", "alice", &id, &binding, 0, payload) + .is_err()); + assert!(repo + .scoped_upload_read("other", "alice", &id, &binding) + .is_err()); + assert!(repo + .scoped_upload_cancel("other", "alice", &id, &binding) + .is_err()); + assert!(repo + .scoped_upload_status(&gate, "other", "alice", &id, &binding) + .is_err()); + assert!(repo + .scoped_upload_slice("project", "bob", &id, &binding, 0, payload) + .is_err()); + assert!(repo + .scoped_upload_read("project", "bob", &id, &binding) + .is_err()); + assert!(repo + .scoped_upload_cancel("project", "bob", &id, &binding) + .is_err()); + assert!(repo + .scoped_upload_status(&gate, "project", "alice", &id, &other_binding) + .is_err()); + assert_eq!( + repo.scoped_upload_read("project", "alice", &id, &binding) + .unwrap(), + payload + ); + repo.scoped_upload_applying(&gate, "project", "alice", &id, &binding) + .unwrap(); + let reopened = Repository::open(&t.0).unwrap(); + assert!(reopened + .scoped_upload_status(&gate, "other", "alice", &id, &binding) + .is_err()); + assert!(matches!( + reopened + .scoped_upload_status(&gate, "project", "alice", &id, &binding) + .unwrap() + .state, + Some(ScopedUploadState::Aborted { .. }) + )); + assert!(reopened + .scoped_upload_read("project", "alice", &id, &binding) + .is_err()); + assert!(reopened + .scoped_upload_cancel("project", "alice", &id, &binding) + .is_err()); + let closed = "2".repeat(64); + reopened + .scoped_upload_cancel("project", "alice", &closed, &binding) + .unwrap(); + assert!(reopened + .scoped_upload_slice("project", "alice", &closed, &binding, 0, payload) + .is_err()); + let interrupted = "3".repeat(64); + let mut ledger = reopened.scoped_ledger().unwrap(); + ledger.records.insert( + interrupted.clone(), + ScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + repository: Some("project".into()), + }, + ); + reopened.save_scoped_ledger(&ledger).unwrap(); + fs::create_dir( + reopened + .common_metadata + .join("tmp") + .join(format!("upload-{interrupted}")), + ) + .unwrap(); + Repository::open(&t.0) + .unwrap() + .scoped_upload_slice("project", "alice", &interrupted, &binding, 0, payload) + .unwrap(); + assert_eq!( + reopened + .scoped_upload_read("project", "alice", &interrupted, &binding) + .unwrap(), + payload + ); + let legacy = "4".repeat(64); + reopened + .scoped_upload_slice("project", "alice", &legacy, &binding, 0, payload) + .unwrap(); + let mut ledger = reopened.scoped_ledger().unwrap(); + ledger.records.get_mut(&legacy).unwrap().state = ScopedUploadState::Applying; + reopened.save_scoped_ledger(&ledger).unwrap(); + assert!(matches!( + reopened + .scoped_upload_status(&gate, "project", "alice", &legacy, &binding) + .unwrap() + .state, + Some(ScopedUploadState::Applying) + )); + } + + #[test] + fn legacy_applying_is_not_reinterpreted_when_ledger_upgrades() { + let t = Temp::new(); + let repo = Repository::init(&t.0).unwrap(); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + let payload = b"legacy"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "a".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let old = "a".repeat(64); + let old_open = "c".repeat(64); + let ledger = LegacyScopedLedger { + version: 1, + records: BTreeMap::from([ + ( + old.clone(), + LegacyScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Applying, + }, + ), + ( + old_open.clone(), + LegacyScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + }, + ), + ]), + }; + repo.atomic_write( + &repo.common_metadata.join("scoped-uploads.bin"), + &crate::binary::encode(&ledger).unwrap(), + ) + .unwrap(); + let state = repo + .scoped_upload_status(&gate, "project", "alice", &old, &binding) + .unwrap(); + assert_eq!(state.version, crate::protocol::SCOPED_UPLOAD_STATUS_VERSION); + assert!(matches!(state.state, Some(ScopedUploadState::Applying))); + assert!(repo + .scoped_upload_slice("project", "alice", &old_open, &binding, 0, payload) + .is_err()); + assert!(repo + .scoped_upload_cancel("project", "alice", &old_open, &binding) + .is_err()); + let new = "b".repeat(64); + repo.scoped_upload_slice("project", "alice", &new, &binding, 0, payload) + .unwrap(); + assert_eq!(repo.scoped_ledger().unwrap().version, 3); + assert!(matches!( + repo.scoped_upload_status(&gate, "project", "alice", &old, &binding) + .unwrap() + .state, + Some(ScopedUploadState::Applying) + )); + } + + #[test] + fn active_watermark_never_blocks_tombstones_or_reuses_terminal_ids() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let payload = b"watermark"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let record = ScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + repository: Some("project".into()), + }; + let store = repo.scoped_store().unwrap(); + let encoded = crate::binary::encode(&record).unwrap(); + for index in 0..record_store::MAX_ACTIVE_RECORDS { + store + .seed_fixture(&format!("{index:064x}"), Bucket::Active, &encoded) + .unwrap(); + } + let full = repo.capacity_status().unwrap(); + assert_eq!(full.scoped.active_records, record_store::MAX_ACTIVE_RECORDS); + assert_eq!(full.scoped.total_records, record_store::MAX_ACTIVE_RECORDS); + assert!(full.scoped.active_bytes > 0); + let next = "a".repeat(64); + assert!(repo + .scoped_upload_slice("project", "alice", &next, &binding, 0, payload) + .unwrap_err() + .contains("admission capacity")); + let canceled = "b".repeat(64); + repo.scoped_upload_cancel("project", "alice", &canceled, &binding) + .unwrap(); + assert!(repo + .scoped_upload_slice("project", "alice", &canceled, &binding, 0, payload) + .is_err()); + let first = format!("{:064x}", 0); + repo.scoped_upload_cancel("project", "alice", &first, &binding) + .unwrap(); + repo.scoped_upload_slice("project", "alice", &next, &binding, 0, payload) + .unwrap(); + let after = repo.capacity_status().unwrap(); + assert_eq!( + after.scoped.active_records, + record_store::MAX_ACTIVE_RECORDS + ); + assert_eq!( + after.scoped.total_records, + record_store::MAX_ACTIVE_RECORDS + 2 + ); + assert!(after.scoped.total_bytes > after.scoped.active_bytes); + let reopened = Repository::open(&temp.0).unwrap(); + assert!(matches!( + reopened.scoped_record(&canceled).unwrap().unwrap().state, + ScopedUploadState::Canceled + )); + assert!(matches!( + reopened.scoped_record(&first).unwrap().unwrap().state, + ScopedUploadState::Canceled + )); + } + + #[test] + fn active_byte_watermark_rejects_admission_but_not_cancellation() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let payload = b"x"; + let binding = UploadBinding { + version: 1, + digest: format!("{:x}", Sha256::digest(payload)), + total: 1, + operation: Box::new(Operation::PublishBatch {}), + targets: vec![ + UploadTarget { + reference: format!("refs/heads/{}", "a".repeat(128)), + force: false, + }; + 4096 + ], + }; + binding.validate().unwrap(); + let record = ScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + repository: Some("project".into()), + }; + let encoded = crate::binary::encode(&record).unwrap(); + let store = repo.scoped_store().unwrap(); + let size = store.encoded_len(&format!("{:064x}", 0), &encoded).unwrap(); + let count = record_store::MAX_ACTIVE_BYTES / size; + assert!(count > 0 && count < record_store::MAX_ACTIVE_RECORDS); + for index in 0..count { + store + .seed_fixture(&format!("{index:064x}"), Bucket::Active, &encoded) + .unwrap(); + } + let next = "a".repeat(64); + let full = repo.capacity_status().unwrap(); + assert!(full.scoped.active_bytes + size > full.scoped.max_active_bytes); + assert!(repo + .scoped_upload_slice("project", "alice", &next, &binding, 0, payload) + .unwrap_err() + .contains("admission capacity")); + let closed = "b".repeat(64); + repo.scoped_upload_cancel("project", "alice", &closed, &binding) + .unwrap(); + assert!( + repo.capacity_status().unwrap().scoped.total_bytes > record_store::MAX_ACTIVE_BYTES + ); + repo.scoped_upload_cancel("project", "alice", &format!("{:064x}", 0), &binding) + .unwrap(); + repo.scoped_upload_slice("project", "alice", &next, &binding, 0, payload) + .unwrap(); + assert!(matches!( + repo.scoped_record(&closed).unwrap().unwrap().state, + ScopedUploadState::Canceled + )); + } + + #[test] + fn interrupted_terminal_publication_reconciles_only_matching_identity() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + b"identity", + ) + .unwrap(); + let store = repo.scoped_store().unwrap(); + let id = "d".repeat(64); + let active = ScopedRecord { + actor: "alice".into(), + binding: binding.clone(), + state: ScopedUploadState::Open, + repository: Some("project".into()), + }; + let mut terminal = active.clone(); + terminal.state = ScopedUploadState::Canceled; + store + .seed_fixture( + &id, + Bucket::Active, + &crate::binary::encode(&active).unwrap(), + ) + .unwrap(); + store + .seed_fixture( + &id, + Bucket::Terminal, + &crate::binary::encode(&terminal).unwrap(), + ) + .unwrap(); + assert!(matches!( + repo.scoped_record(&id).unwrap().unwrap().state, + ScopedUploadState::Canceled + )); + assert!(!repo + .common_metadata + .join("scoped-uploads-records/active") + .join(&id) + .exists()); + + let conflict = "e".repeat(64); + terminal.actor = "mallory".into(); + store + .seed_fixture( + &conflict, + Bucket::Active, + &crate::binary::encode(&active).unwrap(), + ) + .unwrap(); + store + .seed_fixture( + &conflict, + Bucket::Terminal, + &crate::binary::encode(&terminal).unwrap(), + ) + .unwrap(); + assert!(repo.scoped_record(&conflict).is_err()); + assert!(repo + .common_metadata + .join("scoped-uploads-records/active") + .join(&conflict) + .exists()); + } + + #[test] + fn missing_marker_preserves_existing_record_directory() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + b"frozen", + ) + .unwrap(); + let id = "f".repeat(64); + repo.scoped_upload_cancel("project", "alice", &id, &binding) + .unwrap(); + let terminal = repo + .common_metadata + .join("scoped-uploads-records/terminal") + .join(&id); + fs::remove_file(repo.common_metadata.join("scoped-uploads.bin")).unwrap(); + assert!(repo.scoped_record(&id).is_err()); + assert!(terminal.exists()); + } + + #[test] + fn oversized_failure_finishes_without_reference_journal() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let payload = b"frozen"; + let binding = UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let session = "c".repeat(64); + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_upload_slice("project", "alice", &session, &binding, 0, payload) + .unwrap(); + repo.scoped_upload_applying(&gate, "project", "alice", &session, &binding) + .unwrap(); + let scope = ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: session.clone(), + binding: binding.clone(), + }; + let response = Response { + version: 1, + ok: false, + publication_unknown: true, + error: Some("错".repeat(12_000)), + state: None, + tip: None, + }; + let (reply, _) = repo.scoped_record_failure(&gate, &scope, response).unwrap(); + assert!(!reply.publication_unknown); + assert!(reply.error.as_ref().unwrap().len() <= 32 * 1024 + 3); + crate::protocol::write_packet(&mut Vec::new(), &reply, &[]).unwrap(); + assert!(!repo.common_metadata.join("ref-transaction.bin").exists()); + assert!(matches!( + repo.scoped_upload_status(&gate, "project", "alice", &session, &binding) + .unwrap() + .state, + Some(ScopedUploadState::FinishedV4 { .. }) + )); + } +} diff --git a/src/repository_signing.rs b/src/repository_signing.rs index 935a801..bfd7093 100644 --- a/src/repository_signing.rs +++ b/src/repository_signing.rs @@ -26,7 +26,7 @@ struct TrustedAuthors { authors: BTreeMap>, external_keys: BTreeMap<[u8; 32], Vec>, } -fn author(name: &str) -> RepositoryResult<()> { +pub(crate) fn author(name: &str) -> RepositoryResult<()> { if name.is_empty() || name.len() > 1024 || name.chars().any(char::is_control) { Err("invalid author identity".into()) } else { @@ -188,15 +188,8 @@ fn edit_trust( let mut lock = path.as_os_str().to_owned(); lock.push(".lock"); let lock = PathBuf::from(lock); - let guard = OpenOptions::new() - .create_new(true) - .write(true) - .open(&lock) - .map_err(|e| e.to_string())?; - let guard = WriteLock { - path: lock.clone(), - _file: guard, - }; + let parent = lock.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(Path::new(".")); + let guard = crate::platform_fs::acquire_lock(&lock, parent)?; let mut trusted = match fs::symlink_metadata(path) { Ok(_) => crate::binary::decode::(&read_regular(path)?)?, Err(e) if e.kind() == std::io::ErrorKind::NotFound => TrustedAuthors { @@ -314,6 +307,15 @@ impl Repository { identity: &SigningIdentity, format: SignatureFormat, ) -> RepositoryResult { + self.sign_head_result(expected, identity, format) + .map(|result| result.commit) + } + fn sign_head_result( + &self, + expected: &str, + identity: &SigningIdentity, + format: SignatureFormat, + ) -> RepositoryResult { let _lock = self.lock()?; let snapshot = self.snapshot()?; if snapshot.manifest.tip().map(String::as_str) != Some(expected) { @@ -328,8 +330,16 @@ impl Repository { let mut commit = old.clone(); sign(&mut commit, identity, format)?; let id = self.store_object(COMMIT_KIND, &encode_commit(&commit)?)?; + let result = crate::protocol::SignCommitResult { + version: 1, + head: snapshot.manifest.head.clone(), + previous: expected.into(), + commit: id.clone(), + author: identity.author.clone(), + }; + result.validate()?; self.write_ref(&snapshot.manifest.head, &id)?; - Ok(id) + Ok(result) } pub fn verify_author(&self, revision: &str, trust: Option<&Path>) -> RepositoryResult { let info = self.read_commit(revision)?; @@ -435,6 +445,10 @@ enum SigningCommand { }, } pub fn cli(args: &[String]) -> RepositoryResult { + cli_formatted(args, false) +} + +pub(crate) fn cli_formatted(args: &[String], machine: bool) -> RepositoryResult { use clap::Parser; let args = match Args::try_parse_from( std::iter::once("wasm-git".to_owned()).chain(args.iter().cloned()), @@ -531,15 +545,22 @@ pub fn cli(args: &[String]) -> RepositoryResult { key, timestamp, format, - } => Repository::open(repository)?.sign_head_format( - &expected, - &SigningIdentity { - author, - key, - timestamp: timestamp.map_or_else(now, Ok)?, - }, - format, - ), + } => { + let result = Repository::open(repository)?.sign_head_result( + &expected, + &SigningIdentity { + author, + key, + timestamp: timestamp.map_or_else(now, Ok)?, + }, + format, + )?; + if machine { + serde_json::to_string(&result).map_err(|e| e.to_string()) + } else { + Ok(result.commit) + } + } SigningCommand::VerifyCommit { repository, revision, diff --git a/src/repository_transfer.rs b/src/repository_transfer.rs index 007b349..168edc6 100644 --- a/src/repository_transfer.rs +++ b/src/repository_transfer.rs @@ -1,5 +1,6 @@ //! Bounded-frame transfer of a frozen, checksummed bundle. Chunks are immutable; //! no uploaded byte becomes an object or a reference until final verification. +use super::scoped_transfer_storage::ScopedUploadError; use super::*; use crate::protocol::{MAX_BUNDLE_BYTES, TRANSFER_CHUNK}; use std::io::{Seek, SeekFrom}; @@ -15,8 +16,74 @@ const MAX_UPLOADS: usize = 32; const MAX_STAGED_BYTES: u64 = 8 * 1024 * 1024 * 1024; const TRANSFER_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 3600); +pub(crate) struct ServiceGuard { + _file: File, + pub(super) common_metadata: PathBuf, +} + impl Repository { - pub(crate) fn service_lock(&self, timeout: std::time::Duration) -> RepositoryResult { + fn install_upload_metadata(&self, directory: &Path, total: u64) -> RepositoryResult<()> { + let temp = self + .common_metadata + .join("tmp") + .join(unique_name("upload-meta")); + write_new_file( + &temp, + &crate::binary::encode(&Upload { version: 1, total })?, + )?; + let result = fs::hard_link(&temp, directory.join("meta")).map_err(|e| e.to_string()); + let _ = fs::remove_file(temp); + result?; + sync_directory(directory) + } + + // A crash between creating the staging directory and publishing its + // metadata leaves an empty directory. Only a matching durable scoped + // ledger may invoke this recovery. + pub(super) fn repair_scoped_upload_directory( + &self, + id: &str, + total: u64, + ) -> RepositoryResult<()> { + require_id(id)?; + let _lock = self.lock_named("transfer.lock")?; + self.repair_scoped_upload_directory_locked(id, total) + } + + pub(super) fn repair_scoped_upload_directory_locked( + &self, + id: &str, + total: u64, + ) -> RepositoryResult<()> { + let directory = self + .common_metadata + .join("tmp") + .join(format!("upload-{id}")); + match fs::symlink_metadata(&directory) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e.to_string()), + Ok(_) => require_directory(&directory)?, + } + match fs::symlink_metadata(directory.join("meta")) { + Ok(_) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if fs::read_dir(&directory) + .map_err(|e| e.to_string())? + .next() + .is_some() + { + return Err("incomplete upload directory contains unexpected files".into()); + } + self.install_upload_metadata(&directory, total) + } + Err(e) => Err(e.to_string()), + } + } + + pub(crate) fn service_lock( + &self, + timeout: std::time::Duration, + ) -> RepositoryResult { // Lock the immutable format inode: read-only service requests must not // create metadata or require a writable repository filesystem. let path = self.common_metadata.join("format"); @@ -24,7 +91,12 @@ impl Repository { let deadline = std::time::Instant::now() + timeout; loop { match crate::platform_fs::try_service_lock(&file) { - Ok(()) => return Ok(file), + Ok(()) => { + return Ok(ServiceGuard { + _file: file, + common_metadata: self.common_metadata.clone(), + }) + } Err(std::fs::TryLockError::WouldBlock) if std::time::Instant::now() < deadline => { std::thread::sleep(std::time::Duration::from_millis(2)) } @@ -33,7 +105,7 @@ impl Repository { } } - // Called under transfer.lock: reservation uses declared totals, so sparse + // Called under transfer-state.lock then transfer.lock: reservation uses declared totals, so sparse // uploads cannot overcommit the quota. Last successful chunk refreshes TTL. fn upload_reservations(&self) -> RepositoryResult<(usize, u64)> { let mut count = 0; @@ -48,13 +120,51 @@ impl Repository { continue; } require_directory(&entry.path())?; + if self.resume_scoped_cleanup_locked(id)? { + continue; + } let meta = entry.path().join("meta"); + match fs::symlink_metadata(&meta) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let record = self + .scoped_record(id)? + .ok_or("incomplete upload has no scoped owner")?; + match &record.state { + crate::protocol::ScopedUploadState::Open => { + if fs::read_dir(entry.path()) + .map_err(|error| error.to_string())? + .next() + .is_some() + { + return Err( + "incomplete upload directory contains unexpected files".into(), + ); + } + self.install_upload_metadata(&entry.path(), record.binding.total)?; + } + crate::protocol::ScopedUploadState::Applying + | crate::protocol::ScopedUploadState::ApplyingV4 { .. } => { + return Err( + "incomplete applying upload requires original operation recovery" + .into(), + ); + } + _ => { + self.expire_scoped_upload_locked(id)?; + continue; + } + } + } + Err(error) => return Err(io_error("inspect upload metadata", &meta, error)), + Ok(_) => (), + } let modified = fs::symlink_metadata(&meta) .map_err(|e| e.to_string())? .modified() .map_err(|e| e.to_string())?; - if modified.elapsed().is_ok_and(|age| age > TRANSFER_TTL) { - self.remove_upload_locked(id)?; + if modified.elapsed().is_ok_and(|age| age > TRANSFER_TTL) + && self.expire_scoped_upload_locked(id)? + { continue; } let upload: Upload = crate::binary::decode(&read_regular(&meta)?)?; @@ -70,7 +180,9 @@ impl Repository { } pub(crate) fn expire_transfers(&self) -> RepositoryResult<()> { + let _state = self.lock_named("transfer-state.lock")?; let _lock = self.lock_named("transfer.lock")?; + self.resume_all_scoped_cleanups_locked()?; self.upload_reservations()?; for entry in fs::read_dir(self.common_metadata.join("tmp")).map_err(|e| e.to_string())? { let entry = entry.map_err(|e| e.to_string())?; @@ -210,6 +322,7 @@ impl Repository { Ok((state, payload)) } + #[cfg(test)] pub fn upload_slice( &self, id: &str, @@ -217,6 +330,19 @@ impl Repository { offset: u64, bytes: &[u8], ) -> RepositoryResult<()> { + let _state = self.lock_named("transfer-state.lock")?; + self.upload_slice_checked(id, total, offset, bytes, &mut || Ok(())) + .map_err(|error| error.message) + } + + pub(super) fn upload_slice_checked( + &self, + id: &str, + total: u64, + offset: u64, + bytes: &[u8], + before_publish: &mut impl FnMut() -> RepositoryResult<()>, + ) -> Result<(), ScopedUploadError> { require_id(id)?; if total == 0 || total > MAX_BUNDLE_BYTES @@ -227,7 +353,65 @@ impl Repository { return Err("invalid upload slice bounds".into()); } let _lock = self.lock_named("transfer.lock")?; + let directory = self.prepare_upload_directory_locked(id, total)?; + let path = directory.join(offset.to_string()); + match fs::symlink_metadata(&path) { + Ok(_) => { + if read_regular(&path)? == bytes { + // The previous link may have succeeded while its parent + // sync failed. Reconfirm durability without republishing. + sync_directory(&directory).map_err(ScopedUploadError::unknown)?; + return Ok(()); + } else { + return Err("upload retry contains different bytes".into()); + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), + Err(e) => return Err(e.to_string().into()), + } + let temp = self.common_metadata.join("tmp").join(unique_name("upload")); + write_new_file(&temp, bytes)?; + if let Err(error) = before_publish() { + return Err(match fs::remove_file(&temp) { + Ok(()) => error, + Err(cleanup) => format!( + "{error}; cannot remove staged upload {}: {cleanup}", + temp.display() + ), + } + .into()); + } + let result = fs::hard_link(&temp, &path); + let cleanup = fs::remove_file(&temp); + if let Err(error) = result { + return Err(match cleanup { + Ok(()) => error.to_string(), + Err(cleanup) => format!( + "{error}; cannot remove staged upload {}: {cleanup}", + temp.display() + ), + } + .into()); + } + cleanup.map_err(|error| { + ScopedUploadError::unknown(format!( + "upload slice was published but staged upload {} could not be removed: {error}", + temp.display() + )) + })?; + self.finish_upload_link_locked(&directory) + .map_err(ScopedUploadError::unknown) + } + + pub(super) fn prepare_upload_directory_locked( + &self, + id: &str, + total: u64, + ) -> RepositoryResult { + self.require_live_scoped_chunks_locked(id)?; + self.repair_scoped_upload_directory_locked(id, total)?; let (count, reserved) = self.upload_reservations()?; + self.require_live_scoped_chunks_locked(id)?; let directory = self .common_metadata .join("tmp") @@ -239,12 +423,7 @@ impl Repository { return Err("staged upload quota exceeded; complete or cancel an upload".into()); } fs::create_dir(&directory).map_err(|e| e.to_string())?; - write_new_file( - &directory.join("meta"), - &crate::binary::encode(&Upload { version: 1, total }) - .map_err(|e| e.to_string())?, - )?; - sync_directory(&directory)?; + self.install_upload_metadata(&directory, total)?; } Err(e) => return Err(e.to_string()), } @@ -253,33 +432,50 @@ impl Repository { if meta.version != 1 || meta.total != total { return Err("upload metadata changed".into()); } - let path = directory.join(offset.to_string()); - match fs::symlink_metadata(&path) { - Ok(_) => { - if read_regular(&path)? == bytes { - return Ok(()); - } else { - return Err("upload retry contains different bytes".into()); - } - } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => (), - Err(e) => return Err(e.to_string()), + Ok(directory) + } + + pub(super) fn existing_upload_directory_locked( + &self, + id: &str, + total: u64, + ) -> RepositoryResult> { + let directory = self + .common_metadata + .join("tmp") + .join(format!("upload-{id}")); + match fs::symlink_metadata(&directory) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(io_error("inspect upload directory", &directory, error)), + Ok(_) => require_directory(&directory)?, } - let temp = self.common_metadata.join("tmp").join(unique_name("upload")); - write_new_file(&temp, bytes)?; - let result = fs::hard_link(&temp, &path).map_err(|e| e.to_string()); - let _ = fs::remove_file(temp); - result?; + self.repair_scoped_upload_directory_locked(id, total)?; + let meta: Upload = crate::binary::decode(&read_regular(&directory.join("meta"))?)?; + if meta.version != 1 || meta.total != total { + return Err("upload metadata changed".into()); + } + Ok(Some(directory)) + } + + pub(super) fn finish_upload_link_locked(&self, directory: &Path) -> RepositoryResult<()> { File::options() .write(true) .open(directory.join("meta")) .map_err(|e| e.to_string())? .set_modified(std::time::SystemTime::now()) .map_err(|e| e.to_string())?; - sync_directory(&directory) + sync_directory(directory) } pub fn read_upload(&self, id: &str) -> RepositoryResult> { + let result = self.read_upload_staged(id)?; + if object_id(&result) != id { + return Err("uploaded bundle checksum mismatch".into()); + } + Ok(result) + } + + pub(super) fn read_upload_staged(&self, id: &str) -> RepositoryResult> { require_id(id)?; let _lock = self.lock_named("transfer.lock")?; let directory = self @@ -303,24 +499,33 @@ impl Repository { result.extend_from_slice(&bytes); offset += bytes.len() as u64; } - if object_id(&result) != id { - return Err("uploaded bundle checksum mismatch".into()); - } + // An earlier chunk publication may have returned an unknown outcome. + // All source files were synced before linking; fence their names. + sync_directory(&directory)?; Ok(result) } + #[cfg(test)] pub fn remove_upload(&self, id: &str) -> RepositoryResult<()> { require_id(id)?; + let _state = self.lock_named("transfer-state.lock")?; let _lock = self.lock_named("transfer.lock")?; - self.remove_upload_locked(id) + self.cleanup_scoped_chunks_locked(id, crate::protocol::ScopedChunkCleanupReason::Expired)?; + Ok(()) } - fn remove_upload_locked(&self, id: &str) -> RepositoryResult<()> { + pub(super) fn remove_upload_cache_locked(&self, id: &str) -> RepositoryResult<()> { let directory = self .common_metadata .join("tmp") .join(format!("upload-{id}")); - require_directory(&directory)?; + match fs::symlink_metadata(&directory) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return sync_directory(&self.common_metadata.join("tmp")); + } + Err(error) => return Err(io_error("inspect upload cache", &directory, error)), + Ok(_) => require_directory(&directory)?, + } // Delete only the metadata and precisely named regular chunks owned by // this transfer; an unexpected entry prevents recursive deletion. let mut paths = Vec::new(); @@ -429,6 +634,46 @@ mod tests { .exists()); } + #[test] + fn slice_failure_after_hard_link_is_unknown_and_exact_retry_recovers() { + let temp = Temp::new(); + let repo = Repository::init(&temp.0).unwrap(); + let _state = repo.lock_named("transfer-state.lock").unwrap(); + let bytes = b"frozen payload"; + let id = object_id(bytes); + let directory = repo + .common_metadata + .join("tmp") + .join(format!("upload-{id}")); + let metadata = directory.join("meta"); + let error = repo + .upload_slice_checked(&id, bytes.len() as u64, 0, bytes, &mut || { + assert!(metadata.is_file()); + assert!(!directory.join("0").exists()); + // Simulate an I/O obstruction after the decision is ready but + // before post-publication metadata refresh and directory sync. + fs::remove_file(&metadata).unwrap(); + Ok(()) + }) + .unwrap_err(); + assert!(error.outcome_unknown); + assert_eq!(fs::read(directory.join("0")).unwrap(), bytes); + write_new_file( + &metadata, + &crate::binary::encode(&Upload { + version: 1, + total: bytes.len() as u64, + }) + .unwrap(), + ) + .unwrap(); + repo.upload_slice_checked(&id, bytes.len() as u64, 0, bytes, &mut || { + panic!("exact slice replay must not authorize a new decision") + }) + .unwrap(); + assert_eq!(repo.read_upload(&id).unwrap(), bytes); + } + #[test] fn uploads_are_immutable_complete_and_hash_checked_before_use() { let t = Temp::new(); diff --git a/src/repository_worktrees.rs b/src/repository_worktrees.rs index 1f8d5e1..cc21723 100644 --- a/src/repository_worktrees.rs +++ b/src/repository_worktrees.rs @@ -339,6 +339,11 @@ impl Repository { let metadata = target.join(".wasm-git"); fs::create_dir(&metadata).map_err(|error| error.to_string())?; fs::create_dir(metadata.join("tmp")).map_err(|error| error.to_string())?; + #[cfg(any(unix, windows))] + write_new_file( + &metadata.join("index.lock"), + crate::platform_fs::NATIVE_LOCK_FORMAT, + )?; write_new_file(&metadata.join("HEAD"), &encode_reference(branch, false)?)?; let head_log = vec![ReflogEntry { unix_seconds: reflog_timestamp()?, @@ -640,6 +645,7 @@ pub(super) fn reference_head_origin( root, metadata, common_metadata: common, + reference_recovery: ReferenceRecovery::Unrestricted, }) } diff --git a/src/server.rs b/src/server.rs index e5288bd..ad085cd 100644 --- a/src/server.rs +++ b/src/server.rs @@ -10,16 +10,20 @@ use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; -const USAGE: &str = "server --root DIR [--listen 127.0.0.1:9419] [--token-file FILE | --policy FILE] [--allow-write | --read-only] [--allow-force] [--signed-authors BINARY_TRUST_FILE] [--protection BINARY_PROTECTION_FILE] [--merge-author NAME --merge-signing-key KEY --merge-signing-format native|ssh|openpgp] [--pre-receive PROGRAM] [--update PROGRAM] [--post-receive PROGRAM] [--post-update PROGRAM] [--max-connections N]; server --stdio --root DIR [--policy FILE --principal NAME] [--read-only] [--allow-force]; server compile-policy INPUT_JSON NEW_BINARY_FILE; server compile-protection INPUT_JSON NEW_BINARY_FILE; server audit-log BINARY_LOG"; +const USAGE: &str = "server --root DIR [--listen 127.0.0.1:9419] [--token-file FILE | --policy BOOTSTRAP_FILE] [--require-operation-credentials] [--allow-write | --read-only] [--allow-force] [--signed-authors BINARY_TRUST_FILE] [--protection BINARY_PROTECTION_FILE] [--merge-author NAME --merge-signing-key KEY --merge-signing-format native|ssh|openpgp] [--pre-receive PROGRAM] [--update PROGRAM] [--post-receive PROGRAM] [--post-update PROGRAM] [--max-connections N]; server --stdio --root DIR [--policy BOOTSTRAP_FILE --principal NAME] [--read-only] [--allow-force]; server policy-set ROOT REQUEST_JSON; server policy-query ROOT REQUEST_JSON; server policy-migrate ROOT REQUEST_JSON; server operation-credential-issue ROOT REQUEST_JSON; server operation-credential-query ROOT REQUEST_JSON; server policy-status ROOT; server compile-policy INPUT_JSON NEW_BINARY_FILE; server compile-protection INPUT_JSON NEW_BINARY_FILE; server audit-log BINARY_LOG; server operation-recover ROOT REQUEST_JSON; server operation-context ROOT REQUEST_JSON; server audit-query ROOT REQUEST_JSON; server capacity-query ROOT REQUEST_JSON"; const MAX_HEADER: usize = 16 * 1024; const TIMEOUT: Duration = Duration::from_secs(15); +#[path = "server_admin_identity.rs"] +mod admin_identity; #[path = "server_policy.rs"] mod policy; #[path = "server_pulls.rs"] mod pulls; #[path = "server_receive.rs"] mod receive; +#[path = "server_recovery.rs"] +mod recovery; #[derive(Clone)] struct Settings { @@ -29,7 +33,10 @@ struct Settings { token: Option>, write: bool, force: bool, - policy: Option>, + policy_enabled: bool, + policy: Option>, + require_operation_credentials: bool, + operation_credential: Option, actor: String, pre_receive: Option, update_hook: Option, @@ -73,8 +80,12 @@ fn repository_name(name: &str) -> Result<(), String> { // Namespace directories may contain repositories, but a repository's working // files must never become an alternative server root or a fork destination. fn repository_parent(settings: &Settings, name: &str, create: bool) -> Result { + repository_parent_in(&settings.root, name, create) +} + +fn repository_parent_in(root: &Path, name: &str, create: bool) -> Result { repository_name(name)?; - let mut parent = settings.root.clone(); + let mut parent = root.to_path_buf(); let components: Vec<_> = name.split('/').collect(); for component in &components[..components.len() - 1] { namespace_directory(&parent)?; @@ -101,7 +112,11 @@ fn namespace_directory(path: &Path) -> Result<(), String> { } fn repository_path(settings: &Settings, name: &str) -> Result { - let parent = repository_parent(settings, name, false)?; + repository_path_in(&settings.root, name) +} + +fn repository_path_in(root: &Path, name: &str) -> Result { + let parent = repository_parent_in(root, name, false)?; real_path(&parent.join(name.rsplit('/').next().unwrap()), true) } @@ -111,7 +126,8 @@ fn authorize( operation: &Operation, payload: &[u8], ) -> Result<(), String> { - let check = |reference: Option<&str>, force: bool| -> Result<(), String> { + let mut limit = credential_limit(settings); + let mut check = |reference: Option<&str>, force: bool| -> Result<(), String> { if reference.is_some_and(|r| { settings .protection @@ -127,7 +143,13 @@ fn authorize( return Err("server does not allow forced updates".into()); } if let Some(policy) = &settings.policy { - policy.authorize(&settings.actor, repository, reference, force, false)?; + limit = limit.intersect(policy.authorization_limit( + &settings.actor, + repository, + reference, + force, + false, + )?); } Ok(()) }; @@ -184,35 +206,114 @@ fn authorize( // under the same repository lock as lease validation. Ok(()) } - Operation::ApplyUpload { operation, .. } => { - check(Some("*"), false)?; - // Batch operands arrive in the verified upload. Reauthorize that - // exact payload before applying it in process_locked. + Operation::ApplyUpload { .. } + | Operation::UploadSlice { .. } + | Operation::CancelUpload { .. } => Err("legacy unscoped uploads are disabled".into()), + Operation::ScopedUploadSlice { binding, .. } + | Operation::ApplyScopedUpload { binding, .. } + | Operation::CancelScopedUpload { binding, .. } => { + binding.validate()?; + for target in &binding.targets { + check(Some(&target.reference), target.force)?; + } + Ok(()) + } + Operation::QueryScopedUpload { binding, .. } => binding.validate(), + Operation::QueryChunk { chunk } => chunk.validate_scope(repository, &settings.actor), + Operation::UploadChunk { chunk } => { + chunk.validate_scope(repository, &settings.actor)?; + for target in &chunk.scope.binding.targets { + check(Some(&target.reference), target.force)?; + } + Ok(()) + } + Operation::ReleaseRetention { command } => { if matches!( - **operation, - Operation::PublishBatch {} - | Operation::PublishOptions {} - | Operation::CheckBatch {} - | Operation::PublishPartial { .. } - ) { - Ok(()) - } else { - authorize(settings, repository, operation, &[]) + command, + protocol::RetentionCommand::Prepare { .. } + | protocol::RetentionCommand::Promote { .. } + | protocol::RetentionCommand::Close { .. } + ) && !settings.write + { + return Err("server is read-only".into()); } + limit = limit.intersect( + settings + .policy + .as_ref() + .ok_or("release retention requires an explicit principal policy")? + .retention_limit(&settings.actor, repository)?, + ); + Ok(()) } - Operation::UploadSlice { .. } | Operation::CancelUpload { .. } => check(Some("*"), false), Operation::Fork { destination } => { if !settings.write { return Err("server is read-only".into()); } repository_name(destination)?; if let Some(policy) = &settings.policy { - policy.authorize(&settings.actor, destination, None, false, true)?; + limit = limit.intersect(policy.authorization_limit( + &settings.actor, + destination, + None, + false, + true, + )?); } Ok(()) } _ => Ok(()), + }?; + limit.require_current() +} + +fn credential_limit(settings: &Settings) -> policy::AuthorizationLimit { + settings + .operation_credential + .as_ref() + .map_or_else(policy::AuthorizationLimit::unbounded, |receipt| { + policy::AuthorizationLimit::until(receipt.expires_at) + }) +} + +// Pull merges have already passed branch protection through their own review +// path, so the final check here revalidates grants without rerouting protection. +fn authorize_updates( + settings: &Settings, + repository: &str, + updates: &[protocol::RefUpdate], + reasons: &[Option], +) -> Result<(), String> { + if updates.len() != reasons.len() { + return Err("reference authorization decisions do not match updates".into()); + } + let mut limit = credential_limit(settings); + if let Some(policy) = &settings.policy { + limit = limit.intersect(policy.authorization_limit( + &settings.actor, + repository, + None, + false, + false, + )?); + for (update, rejection) in updates.iter().zip(reasons) { + if rejection.is_none() { + let namespace = if matches!(update.namespace, RefNamespace::Branch) { + "heads" + } else { + "tags" + }; + limit = limit.intersect(policy.authorization_limit( + &settings.actor, + repository, + Some(&format!("refs/{namespace}/{}", update.name)), + update.force, + false, + )?); + } + } } + limit.require_current() } fn process( @@ -220,28 +321,134 @@ fn process( request: Request, payload: &[u8], ) -> Result<(Response, Vec), String> { + if settings.require_operation_credentials && settings.operation_credential.is_none() { + return Err("operation credential required".into()); + } + if settings.require_operation_credentials + && matches!(&request.operation, Operation::ScopedUploadSlice { .. }) + { + return Err("strict uploads require an original-operation chunk request".into()); + } + if let Some(credential) = &settings.operation_credential { + if credential.actor != settings.actor { + return Err("operation credential actor mismatch".into()); + } + credential.validate_rpc(&request, payload)?; + } + if let Operation::UploadChunk { chunk } | Operation::QueryChunk { chunk } = &request.operation { + chunk.validate_scope(&request.repository, &settings.actor)?; + if settings.operation_credential.is_none() { + return Err("chunk operations require an operation credential".into()); + } + if let Operation::UploadChunk { .. } = &request.operation { + chunk.validate_payload(payload)?; + } else if !payload.is_empty() { + return Err("chunk query requires an empty payload".into()); + } + } repository_name(&request.repository)?; authorize(settings, &request.repository, &request.operation, payload)?; - let root = repository_path(settings, &request.repository)?; - let repository = Repository::open(root)?; - // OS-owned locks survive neither a crash nor an SSH process exit. Queue - // competing service operations instead of leaking local fail-fast locks to - // network readers. Local writer locks and ref leases remain authoritative. - let _gate = repository.service_lock(TIMEOUT)?; - process_locked(settings, request, payload) + if let Operation::UploadChunk { chunk } | Operation::QueryChunk { chunk } = &request.operation { + policy::validate_original_chunk(&settings.root, chunk)?; + } + let attempt = match ( + &settings.operation_credential, + recovery::observation_scope(&request.operation), + ) { + (Some(credential), Some(scope)) if credential.effect_key.is_some() => Some(( + credential.operation_id.clone(), + policy::audit_start(&settings.root, credential, &request, payload)?, + scope, + )), + _ => None, + }; + let mut observed = protocol::AuditEvidenceObservation::Unknown; + let result = (|| { + let root = repository_path(settings, &request.repository)?; + let expected = if attempt.is_some() { + match &request.operation { + Operation::UploadChunk { chunk } => Some(chunk.scope.clone()), + Operation::ScopedUploadSlice { + session, binding, .. + } + | Operation::ApplyScopedUpload { session, binding } + | Operation::CancelScopedUpload { session, binding } => { + Some(protocol::ScopedExecution { + actor: settings.actor.clone(), + repository: request.repository.clone(), + session: session.clone(), + binding: binding.clone(), + }) + } + _ => None, + } + } else { + None + }; + let repository = if settings.require_operation_credentials { + Repository::open_for_recovery(root, expected.as_ref())? + } else { + Repository::open(root)? + }; + // Root authorization gate -> service gate -> repository writer. An + // audit attempt precedes even journal recovery performed on open. + let gate = repository.service_lock(TIMEOUT)?; + authorize(settings, &request.repository, &request.operation, payload)?; + let original = request.clone(); + let result = process_locked(settings, request, payload, &gate, None, &repository); + if attempt.is_some() + && result + .as_ref() + .is_ok_and(|(response, _)| response.ok && !response.publication_unknown) + { + match recovery::observe_native(&repository, &gate, &settings.actor, &original) { + Ok(evidence) => observed = evidence, + Err(cause) => { + crate::cli_error(&format!("original operation result observation: {cause}")); + return Ok((Response { version: 1, ok: false, publication_unknown: true, + error: Some("native result observation is unavailable; query the original operation".into()), state: None, tip: None }, Vec::new())); + } + } + } + result + })(); + if let Some((operation_id, attempt_id, scope)) = attempt { + // A rejected retry does not prove the original operation failed. + let observation = protocol::AuditObservation { + version: 1, + scope, + evidence: observed, + }; + if let Err(cause) = policy::audit_observe( + &settings.root, + &protocol::AuditTarget::Operation { + operation_id, + attempt_id, + }, + &observation, + ) { + crate::cli_error(&format!("original operation audit observation: {cause}")); + return Ok((Response { version: 1, ok: false, publication_unknown: true, + error: Some("operation observation is unconfirmed; query or recover the original operation".into()), state: None, tip: None }, Vec::new())); + } + } + result } fn process_locked( settings: &Settings, request: Request, payload: &[u8], + gate: &crate::repository::ServiceGuard, + scope: Option<&crate::repository::ScopedExecution>, + repository: &Repository, ) -> Result<(Response, Vec), String> { if request.version != 1 { return Err("unsupported RPC version".into()); } repository_name(&request.repository)?; - let root = repository_path(settings, &request.repository)?; - let repository = Repository::open(root)?; + let original_operation = request.operation.clone(); + let before_publish = || authorize(settings, &request.repository, &original_operation, payload); let mut response = Response { version: 1, ok: true, @@ -251,10 +458,322 @@ fn process_locked( tip: None, }; let bytes = match request.operation { + Operation::UploadChunk { chunk } | Operation::QueryChunk { chunk } => { + let writes = matches!(&original_operation, Operation::UploadChunk { .. }); + let result = if writes { + repository.scoped_chunk_write(gate, &chunk, payload, before_publish) + } else { + repository.scoped_chunk_query(gate, &chunk) + }; + match result { + Ok(status) => { + let encoded = status.validate_for(&chunk).and_then(|()| { + if writes + && !matches!(status.state, protocol::ScopedChunkState::Accepted { .. }) + { + return Err("chunk acknowledgement has no accepted decision".into()); + } + crate::binary::encode(&status) + }); + match encoded { + Ok(bytes) => bytes, + Err(error) => { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: writes, + error: Some(error), + state: None, + tip: None, + }, + Vec::new(), + )) + } + } + } + Err(error) => { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: error.outcome_unknown, + error: Some(error.message), + state: None, + tip: None, + }, + Vec::new(), + )) + } + } + } + Operation::ReleaseRetention { command } => { + if !payload.is_empty() { + return Err("release retention requires an empty payload".into()); + } + match repository.release_retention_checked( + &request.repository, + &settings.actor, + command, + before_publish, + ) { + Ok(reply) => crate::binary::encode(&reply)?, + Err(error) => { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: error.outcome_unknown, + error: Some(error.message), + state: None, + tip: None, + }, + Vec::new(), + )) + } + } + } + Operation::ScopedUploadSlice { + session, + binding, + offset, + } => { + if let Err(error) = repository.scoped_upload_slice_checked( + &request.repository, + &settings.actor, + &session, + &binding, + offset, + payload, + before_publish, + ) { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: error.outcome_unknown, + error: Some(error.message), + state: None, + tip: None, + }, + Vec::new(), + )); + } + Vec::new() + } + Operation::QueryScopedUpload { session, binding } => { + if !payload.is_empty() { + return Err("upload query requires an empty payload".into()); + } + let status = if settings.require_operation_credentials { + repository.scoped_upload_observe( + gate, + &request.repository, + &settings.actor, + &session, + &binding, + )? + } else { + repository.scoped_upload_status( + gate, + &request.repository, + &settings.actor, + &session, + &binding, + )? + }; + crate::binary::encode(&status)? + } + Operation::CancelScopedUpload { session, binding } => { + if !payload.is_empty() { + return Err("upload cancellation requires an empty payload".into()); + } + if let Err(error) = repository.scoped_upload_cancel_checked( + &request.repository, + &settings.actor, + &session, + &binding, + before_publish, + ) { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: error.outcome_unknown, + error: Some(error.message), + state: None, + tip: None, + }, + Vec::new(), + )); + } + Vec::new() + } + Operation::ApplyScopedUpload { session, binding } => { + if !payload.is_empty() { + return Err("upload application requires an empty payload".into()); + } + let status = if settings.require_operation_credentials { + repository.scoped_upload_observe( + gate, + &request.repository, + &settings.actor, + &session, + &binding, + )? + } else { + repository.scoped_upload_status( + gate, + &request.repository, + &settings.actor, + &session, + &binding, + )? + }; + match status.state { + Some(protocol::ScopedUploadState::Finished { response, payload }) => { + return Ok((response, payload)) + } + Some(protocol::ScopedUploadState::FinishedV4 { receipt }) => { + return Ok((receipt.response, receipt.payload)) + } + Some( + protocol::ScopedUploadState::Applying + | protocol::ScopedUploadState::ApplyingV4 { .. }, + ) => { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: true, + error: Some( + "scoped upload outcome is unknown; recover the original operation" + .into(), + ), + state: None, + tip: None, + }, + Vec::new(), + )) + } + Some(protocol::ScopedUploadState::Canceled) => { + return Err("scoped upload is canceled".into()) + } + Some(protocol::ScopedUploadState::Aborted { .. }) => { + return Err("scoped upload was aborted before its native decision".into()) + } + _ => (), + } + let bytes = repository.scoped_upload_read( + &request.repository, + &settings.actor, + &session, + &binding, + )?; + authorize(settings, &request.repository, &binding.operation, &bytes)?; + if let Err(error) = repository.scoped_upload_applying_checked( + gate, + &request.repository, + &settings.actor, + &session, + &binding, + before_publish, + ) { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: error.outcome_unknown, + error: Some(error.message), + state: None, + tip: None, + }, + Vec::new(), + )); + } + let execution = crate::repository::ScopedExecution { + actor: settings.actor.clone(), + repository: request.repository.clone(), + session: session.clone(), + binding: binding.clone(), + }; + let result = process_locked( + settings, + Request { + version: request.version, + repository: request.repository, + operation: *binding.operation.clone(), + }, + &bytes, + gate, + Some(&execution), + repository, + ); + // An error after entering application may follow a committed ref + // update; retain an unknown outcome rather than claiming failure. + let (reply, _reply_bytes) = result.unwrap_or_else(|error| { + ( + Response { + version: 1, + ok: false, + publication_unknown: true, + error: Some(error), + state: None, + tip: None, + }, + Vec::new(), + ) + }); + let durable = if reply.ok { + match repository.scoped_upload_status( + gate, + &execution.repository, + &settings.actor, + &session, + &binding, + ) { + Ok(protocol::ScopedUploadStatus { + state: Some(protocol::ScopedUploadState::Finished { response, payload }), + .. + }) => Ok((response, payload)), + Ok(protocol::ScopedUploadStatus { + state: Some(protocol::ScopedUploadState::FinishedV4 { receipt }), + .. + }) => Ok((receipt.response, receipt.payload)), + Ok(_) => Err("scoped success has no durable receipt".into()), + Err(error) => Err(error), + } + } else { + repository.scoped_record_failure(gate, &execution, reply) + }; + match durable { + Ok(result) => { + if let Err(error) = repository.scoped_upload_cleanup(&session) { + crate::cli_error(&format!("scoped upload cleanup: {error}")); + } + return Ok(result); + } + Err(error) => { + return Ok(( + Response { + version: 1, + ok: false, + publication_unknown: true, + error: Some(format!( + "scoped upload outcome is unknown; query the original session: {error}" + )), + state: None, + tip: None, + }, + Vec::new(), + )) + } + } + } Operation::PullRequest {} => { let command: crate::pull::PullCommand = crate::binary::decode(payload)?; let mutates = command.mutates(); - match pulls::run(settings, &request.repository, &repository, command) { + match pulls::run(settings, &request.repository, repository, command) { Ok(reply) => { use sha2::Digest; response.tip = Some(format!("{:x}", sha2::Sha256::digest(payload))); @@ -352,74 +871,10 @@ fn process_locked( response.state = state; bytes } - Operation::UploadSlice { - transfer, - total, - offset, - } => { - if !settings.write { - return Err("server is read-only".into()); - } - repository.upload_slice(&transfer, total, offset, payload)?; - Vec::new() - } - Operation::CancelUpload { transfer } => { - if !settings.write { - return Err("server is read-only".into()); - } - if !payload.is_empty() { - return Err("cancel upload requires an empty payload".into()); - } - repository.remove_upload(&transfer)?; - Vec::new() - } - Operation::ApplyUpload { - transfer, - operation, - } => { - if !settings.write { - return Err("server is read-only".into()); - } - if !payload.is_empty() - || !matches!( - &*operation, - Operation::Push { .. } - | Operation::UpdateRef { .. } - | Operation::PublishBatch {} - | Operation::PublishOptions {} - | Operation::CheckBatch {} - | Operation::PublishPartial { .. } - ) - { - return Err("uploaded payload can only apply one reference mutation".into()); - } - let bytes = match repository.read_upload(&transfer) { - Ok(bytes) => bytes, - Err(error) => { - // Incomplete uploads remain resumable. A complete upload - // with a bad digest can never succeed and must be removed. - if error.contains("checksum mismatch") { - repository.remove_upload(&transfer)?; - } - return Err(error); - } - }; - let result = - authorize(settings, &request.repository, &operation, &bytes).and_then(|()| { - process_locked( - settings, - Request { - version: request.version, - repository: request.repository, - operation: *operation, - }, - &bytes, - ) - }); - if let Err(error) = repository.remove_upload(&transfer) { - crate::cli_error(&format!("upload cleanup: {error}")); - } - return result; + Operation::UploadSlice { .. } + | Operation::ApplyUpload { .. } + | Operation::CancelUpload { .. } => { + return Err("legacy unscoped uploads are disabled".into()) } Operation::Fork { destination } => { if !settings.write { @@ -429,7 +884,7 @@ fn process_locked( return Err("fork requires an empty payload".into()); } repository_name(&destination)?; - match receive::fork(settings, &request.repository, &repository, &destination) { + match receive::fork(settings, &request.repository, repository, &destination) { Ok(()) => response.tip = Some(format!("fork-created:{destination}")), Err(error) => return Ok((receive_error_response(error), Vec::new())), } @@ -473,10 +928,11 @@ fn process_locked( match receive::publish( settings, &request.repository, - &repository, + repository, &completed, &updates, &[], + scope, ) { Ok(()) => response.tip = Some(tip), Err(error) => return Ok((receive_error_response(error), Vec::new())), @@ -509,10 +965,11 @@ fn process_locked( match receive::publish( settings, &request.repository, - &repository, + repository, payload, &updates, &[], + scope, ) { Ok(()) => response.tip = new, Err(error) => return Ok((receive_error_response(error), Vec::new())), @@ -524,10 +981,11 @@ fn process_locked( match receive::publish_selective( settings, &request.repository, - &repository, + repository, &batch, &options, dry_run, + scope, ) { Ok(rejections) => { response.tip = Some(format!( @@ -544,20 +1002,26 @@ fn process_locked( | Operation::CheckBatch {}) => { let (batch, options) = protocol::publication_payload(&operation, payload)?; let result = if matches!(operation, Operation::CheckBatch {}) { - repository.check_receive_batch(&batch.bundle, &batch.updates, |bundle| { - if let Some(path) = &settings.signed_authors { - repository.verify_receive_authors(bundle, &batch.updates, path)?; - } - Ok(()) - }) + repository.check_receive_batch_scoped( + &batch.bundle, + &batch.updates, + scope, + |bundle| { + if let Some(path) = &settings.signed_authors { + repository.verify_receive_authors(bundle, &batch.updates, path)?; + } + Ok(()) + }, + ) } else { receive::publish( settings, &request.repository, - &repository, + repository, &batch.bundle, &batch.updates, &options, + scope, ) }; match result { @@ -606,23 +1070,86 @@ fn response_packet(response: &Response, payload: &[u8]) -> Result, Strin Ok(bytes) } -fn rpc(settings: &Settings, bytes: &[u8]) -> Result, String> { - let outcome = protocol::read_complete_packet::(bytes) - .and_then(|(request, payload)| process(settings, request, &payload)); - let (response, payload) = outcome.unwrap_or_else(|error| { - ( - Response { - version: 1, - ok: false, - publication_unknown: false, - error: Some(error), - state: None, - tip: None, - }, - Vec::new(), - ) - }); - response_packet(&response, &payload) +struct PreparedReply { + request: Option<(Request, Vec)>, + response: Response, + bytes: Vec, +} + +impl PreparedReply { + fn new( + settings: &Settings, + request: Result<(Request, Vec), String>, + ) -> Result { + let (request, outcome) = match request { + Ok((request, payload)) => { + let outcome = process(settings, request.clone(), &payload); + (Some((request, payload)), outcome) + } + Err(error) => (None, Err(error)), + }; + let (response, payload) = outcome.unwrap_or_else(|error| { + ( + Response { + version: 1, + ok: false, + publication_unknown: settings.require_operation_credentials + && settings + .operation_credential + .as_ref() + .is_some_and(|c| c.effect_key.is_some()), + error: Some(error), + state: None, + tip: None, + }, + Vec::new(), + ) + }); + let bytes = response_packet(&response, &payload)?; + Ok(Self { + request, + response, + bytes, + }) + } + + /// This is the last check before the first protected output write. Once + /// that write begins, the single already-authorized transfer may finish. + fn for_delivery(self, settings: &Settings) -> Result, String> { + if let Some((request, payload)) = &self.request { + if let Err(cause) = + authorize(settings, &request.repository, &request.operation, payload) + { + crate::cli_error(&format!("authorization before delivery: {cause}")); + let mutates = match &request.operation { + Operation::Advertise {} + | Operation::Fetch {} + | Operation::FetchSlice { .. } + | Operation::RefsPage { .. } + | Operation::ObjectSlice { .. } + | Operation::QueryScopedUpload { .. } + | Operation::CheckBatch {} + | Operation::QueryChunk { .. } + | Operation::PublishPartial { dry_run: true } => false, + Operation::ReleaseRetention { command } => !matches!( + command, + protocol::RetentionCommand::Query { .. } + | protocol::RetentionCommand::Read { .. } + ), + Operation::PullRequest {} => { + crate::binary::decode::(payload) + .is_ok_and(|p| p.mutates()) + } + _ => true, + }; + return response_packet(&Response { version: 1, ok: false, + publication_unknown: self.response.publication_unknown || (self.response.ok && mutates), + error: Some("authorization unavailable before delivery; query the original operation with current authorization".into()), + state: None, tip: None }, &[]); + } + } + Ok(self.bytes) + } } fn equal_secret(left: &[u8], right: &[u8]) -> bool { @@ -799,6 +1326,34 @@ fn finish_http(stream: &mut DeadlineStream) -> usize { consumed } +fn http_authentication( + stream: &mut impl Write, + result: Result, String>, +) -> Result, String> { + match result { + Ok(Some(authenticated)) => Ok(Some(authenticated)), + Ok(None) => { + http_response( + stream, + "401 Unauthorized", + b"authentication required", + false, + )?; + Ok(None) + } + Err(cause) => { + crate::cli_error(&format!("operation credential authentication: {cause}")); + http_response( + stream, + "503 Service Unavailable", + b"authorization unavailable", + false, + )?; + Ok(None) + } + } +} + fn http_request(stream: &mut DeadlineStream, settings: &Settings) -> Result<(), String> { let headers = match read_headers(stream) { Ok(headers) => headers, @@ -819,22 +1374,49 @@ fn http_request(stream: &mut DeadlineStream, settings: &Settings) -> Result<(), } } let mut authenticated = settings.clone(); - if let Some(policy) = &settings.policy { + let initial = match policy::request_guard(&settings.root, settings.policy_enabled) { + Ok(guard) => guard, + Err(_) => { + return http_response( + stream, + "503 Service Unavailable", + b"authorization unavailable", + false, + ) + } + }; + if initial.operation_credentials + && (!settings.require_operation_credentials || !initial.chunk_receipts) + { + return http_response( + stream, + "503 Service Unavailable", + b"this root requires the strict credential entry point", + false, + ); + } + if let Some(policy) = &initial.policy { let token = headers .get("authorization") .and_then(|h| h.strip_prefix("Bearer ")) .unwrap_or(""); - let Some(actor) = policy.authenticate(token.as_bytes()) else { - return http_response( - stream, - "401 Unauthorized", - b"authentication required", - false, - ); + let Some((actor, credential)) = http_authentication( + stream, + policy::authenticate( + &settings.root, + policy, + initial.generation, + token.as_bytes(), + settings.require_operation_credentials, + ), + )? + else { + return Ok(()); }; authenticated.actor = actor; + authenticated.operation_credential = credential; } - let settings = &authenticated; + drop(initial); let Some(length_text) = headers.get("content-length") else { return http_response( stream, @@ -883,16 +1465,64 @@ fn http_request(stream: &mut DeadlineStream, settings: &Settings) -> Result<(), false, ); } + // Authentication before reading the body is only an early rejection. The + // actual request uses a fresh snapshot and retains the gate through output. + let guard = match policy::request_guard(&settings.root, settings.policy_enabled) { + Ok(guard) => guard, + Err(_) => { + return http_response( + stream, + "503 Service Unavailable", + b"authorization unavailable", + false, + ) + } + }; + if guard.operation_credentials + && (!settings.require_operation_credentials || !guard.chunk_receipts) + { + return http_response( + stream, + "503 Service Unavailable", + b"this root requires the strict credential entry point", + false, + ); + } + authenticated.policy = guard.policy.clone(); + if let Some(policy) = &authenticated.policy { + let token = headers + .get("authorization") + .and_then(|h| h.strip_prefix("Bearer ")) + .unwrap_or(""); + let Some((actor, credential)) = http_authentication( + stream, + policy::authenticate( + &settings.root, + policy, + guard.generation, + token.as_bytes(), + settings.require_operation_credentials, + ), + )? + else { + return Ok(()); + }; + authenticated.actor = actor; + authenticated.operation_credential = credential; + } + let settings = &authenticated; let started = Instant::now(); - let bytes = rpc(settings, &body); + let reply = PreparedReply::new(settings, protocol::read_complete_packet::(&body)); // Verification/fsync may exceed the network budget on a slow host. A // completed publication still needs its acknowledgement; only the time // spent processing this fully buffered request is excluded from I/O time. stream .exclude_processing(started.elapsed()) .map_err(|e| e.to_string())?; - let bytes = bytes?; - http_response(stream, "200 OK", &bytes, true) + let bytes = reply?.for_delivery(settings)?; + let result = http_response(stream, "200 OK", &bytes, true); + drop(guard); + result } fn read_token_file(path: &Path) -> Result, String> { @@ -929,6 +1559,104 @@ pub fn run(args: &[String]) -> Result { return Ok(USAGE.into()); } if let [_, command, input, output] = args { + if matches!( + command.as_str(), + "policy-set" + | "policy-query" + | "policy-migrate" + | "operation-credential-issue" + | "operation-credential-query" + | "operation-recover" + | "audit-query" + | "operation-context" + | "capacity-query" + ) { + let root = real_path(Path::new(input), true)?; + let request_path = real_path(Path::new(output), false)?; + if fs::metadata(&request_path) + .map_err(|e| e.to_string())? + .len() + > 16 * 1024 * 1024 + { + return Err("policy update request exceeds 16 MiB".into()); + } + let bytes = fs::read(request_path).map_err(|e| e.to_string())?; + protocol::validate_node_safe_json(&bytes)?; + if command == "operation-recover" { + let request: protocol::OperationRecoveryRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&recovery::run(&root, &request)?) + .map_err(|e| e.to_string()); + } + if command == "audit-query" { + admin_identity::authorize_recovery_root(&root)?; + let request: protocol::AuditQueryRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + let reply = policy::audit_query(&root, &request)?; + reply.validate_for(&request)?; + return serde_json::to_string(&reply).map_err(|e| e.to_string()); + } + if command == "operation-context" { + admin_identity::authorize_recovery_root(&root)?; + let request: protocol::OperationCredentialQuery = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + request.validate()?; + let reply = protocol::OperationContextReply { + version: 1, + operation_id: request.operation_id.clone(), + original: policy::operation_context(&root, &request.operation_id)?, + }; + reply.validate_for(&request)?; + return serde_json::to_string(&reply).map_err(|e| e.to_string()); + } + if command == "capacity-query" { + admin_identity::authorize_recovery_root(&root)?; + let request: protocol::CapacityQueryRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + request.validate()?; + let _guard = policy::request_guard(&root, true)?; + let repository = Repository::open_for_recovery( + repository_path_in(&root, &request.repository)?, + None, + )?; + let capacity = repository.capacity_status()?; + let reply = protocol::CapacityQueryReply { + version: 1, + repository: request.repository.clone(), + capacity, + }; + reply.validate_for(&request)?; + return serde_json::to_string(&reply).map_err(|e| e.to_string()); + } + if command == "operation-credential-issue" { + let request: protocol::OperationCredentialRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&policy::issue_credential(&root, &request)?) + .map_err(|e| e.to_string()); + } + if command == "operation-credential-query" { + let request: protocol::OperationCredentialQuery = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&policy::query_credential(&root, &request)?) + .map_err(|e| e.to_string()); + } + if command == "policy-set" { + let request: protocol::PolicyUpdateRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&policy::set(&root, &request)?) + .map_err(|e| e.to_string()); + } + if command == "policy-migrate" { + let request: protocol::PolicyMigrationRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&policy::migrate(&root, &request)?) + .map_err(|e| e.to_string()); + } + let request: protocol::PolicyQueryRequest = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + return serde_json::to_string(&policy::query(&root, &request)?) + .map_err(|e| e.to_string()); + } if command == "compile-policy" { return policy::compile(Path::new(input), Path::new(output)); } @@ -940,6 +1668,10 @@ pub fn run(args: &[String]) -> Result { } } if let [_, command, path] = args { + if command == "policy-status" { + let root = real_path(Path::new(path), true)?; + return serde_json::to_string(&policy::status(&root)?).map_err(|e| e.to_string()); + } if command == "audit-log" { return receive::read_audit(Path::new(path)); } @@ -961,6 +1693,7 @@ pub fn run(args: &[String]) -> Result { let mut listen_selected = false; let mut token_file = None; let mut stdio = false; + let mut require_operation_credentials = false; let mut write = false; let mut force = false; let mut max_connections = None; @@ -968,6 +1701,7 @@ pub fn run(args: &[String]) -> Result { while index < args.len() { match args[index].as_str() { "--stdio" => stdio = true, + "--require-operation-credentials" => require_operation_credentials = true, "--read-only" => read_only = true, "--allow-write" => write = true, "--allow-force" => force = true, @@ -1046,24 +1780,39 @@ pub fn run(args: &[String]) -> Result { if read_only && (write || force) { return Err("--read-only conflicts with write/force flags".into()); } - let policy = policy_file - .map(|p| policy::Policy::load(&p).map(Arc::new)) - .transpose()?; - if policy.is_some() && token.is_some() { + let policy_enabled = policy_file.is_some(); + if require_operation_credentials && (!policy_enabled || stdio) { + return Err("operation credentials require an HTTP policy entry point".into()); + } + if policy_enabled && token.is_some() { return Err("choose --policy or --token-file".into()); } - if principal.is_some() && (!stdio || policy.is_none()) { + if principal.is_some() && (!stdio || !policy_enabled) { return Err("--principal requires SSH stdio and --policy".into()); } - if stdio && policy.is_some() && principal.is_none() { + if stdio && policy_enabled && principal.is_none() { return Err("SSH policy requires a trusted forced-command --principal".into()); } - if let Some(name) = &principal { - if !policy.as_ref().unwrap().principal_exists(name) { - return Err("unknown SSH principal".into()); + if let Some(path) = &policy_file { + policy::bootstrap(&root, path)?; + } + { + let guard = policy::request_guard(&root, policy_enabled)?; + if guard.operation_credentials && (!require_operation_credentials || !guard.chunk_receipts) + { + return Err("this root requires the strict credential entry point".into()); + } + if let Some(name) = &principal { + if !guard + .policy + .as_ref() + .is_some_and(|policy| policy.principal_exists(name)) + { + return Err("unknown SSH principal".into()); + } } } - if !stdio && write && token.is_none() && policy.is_none() { + if !stdio && write && token.is_none() && !policy_enabled { return Err("HTTP --allow-write requires --token-file or --policy".into()); } let settings = Arc::new(Settings { @@ -1091,7 +1840,10 @@ pub fn run(args: &[String]) -> Result { token, write: !read_only && (stdio || write), force, - policy, + policy_enabled, + policy: None, + require_operation_credentials, + operation_credential: None, actor: principal.unwrap_or_else(|| if stdio { "ssh".into() } else { "token".into() }), pre_receive, update_hook, @@ -1106,26 +1858,25 @@ pub fn run(args: &[String]) -> Result { if input.read(&mut extra).map_err(|e| e.to_string())? != 0 { return Err("trailing bytes after stdio request".into()); } - let result = process(&settings, request, &payload); - let (response, payload) = result.unwrap_or_else(|error| { - ( - Response { - version: 1, - ok: false, - publication_unknown: false, - error: Some(error), - state: None, - tip: None, - }, - Vec::new(), - ) - }); + let guard = policy::request_guard(&settings.root, settings.policy_enabled)?; + if guard.operation_credentials { + return Err("this root requires the strict credential entry point".into()); + } + let mut authenticated = (*settings).clone(); + authenticated.policy = guard.policy.clone(); + if let Some(policy) = &authenticated.policy { + if !policy.principal_exists(&authenticated.actor) { + return Err("unknown SSH principal".into()); + } + } + let reply = PreparedReply::new(&authenticated, Ok((request, payload)))?; let mut output = std::io::stdout().lock(); - let bytes = response_packet(&response, &payload)?; + let bytes = reply.for_delivery(&authenticated)?; output .write_all(&bytes) .map_err(|e| format!("write stdio response: {e}"))?; output.flush().map_err(|e| e.to_string())?; + drop(guard); return Ok(String::new()); } let listener = TcpListener::bind(&listen).map_err(|e| format!("listen: {e}"))?; @@ -1183,10 +1934,168 @@ pub fn run(args: &[String]) -> Result { Ok(String::new()) } +#[cfg(test)] +pub(crate) fn test_authorized_process( + root: &Path, + actor: &str, + request: Request, + payload: &[u8], +) -> Result<(Response, Vec), String> { + let root = real_path(root, true)?; + let guard = policy::request_guard(&root, true)?; + let settings = Settings { + protection: None, + merge_signer: None, + root, + token: None, + write: true, + force: true, + policy_enabled: true, + policy: guard.policy.clone(), + require_operation_credentials: false, + operation_credential: None, + actor: actor.into(), + pre_receive: None, + update_hook: None, + signed_authors: None, + post_receive: None, + post_update: None, + }; + let result = process(&settings, request, payload); + drop(guard); + result +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn credential_store_failure_is_unavailable_not_invalid_credentials() { + let absent = std::env::temp_dir().join(format!( + "wasm-git-absent-credential-root-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + assert!(!absent.exists()); + let policy = protocol::ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + let failure = policy::authenticate(&absent, &policy, 0, b"token", true); + assert!(failure.is_err()); + let mut bytes = Vec::new(); + assert!(http_authentication(&mut bytes, failure).unwrap().is_none()); + assert!(bytes.starts_with(b"HTTP/1.1 503 Service Unavailable")); + assert!(!String::from_utf8_lossy(&bytes).contains("store is not initialized")); + bytes.clear(); + assert!(http_authentication(&mut bytes, Ok(None)).unwrap().is_none()); + assert!(bytes.starts_with(b"HTTP/1.1 401 Unauthorized")); + } + + #[test] + fn first_delivery_removes_expired_data_without_reclassifying_committed_or_unknown_writes() { + let policy = protocol::ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: vec![protocol::PolicyPrincipal { + name: "alice".into(), + token_sha256: None, + grants: vec![protocol::PolicyGrant { + repository: "project".into(), + read: true, + write: vec!["refs/heads/*".into()], + force: false, + create: false, + release_retention: true, + expires_at: None, + }], + }], + }; + let mut settings = Settings { + protection: None, + merge_signer: None, + root: PathBuf::new(), + token: None, + write: true, + force: false, + policy_enabled: true, + policy: Some(Arc::new(policy)), + require_operation_credentials: true, + operation_credential: None, + actor: "alice".into(), + pre_receive: None, + update_hook: None, + signed_authors: None, + post_receive: None, + post_update: None, + }; + for (operation, mutation) in [ + (Operation::Fetch {}, false), + ( + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Close { + operation: "a".repeat(64), + }, + }, + true, + ), + ] { + let request = Request { + version: 1, + repository: "project".into(), + operation, + }; + let issuance = protocol::OperationCredentialRequest { + version: 1, + operation_id: "b".repeat(64), + policy_generation: 1, + actor: "alice".into(), + token_sha256: "c".repeat(64), + request: request.clone(), + payload_sha256: format!("{:x}", ::digest([])), + expires_at: protocol::NODE_SAFE_INTEGER_MAX, + }; + settings.operation_credential = Some(issuance.receipt().unwrap()); + let ready = |ok, unknown| { + let response = Response { + version: 1, + ok, + publication_unknown: unknown, + error: None, + state: None, + tip: Some("private-tip".into()), + }; + PreparedReply { + request: Some((request.clone(), Vec::new())), + bytes: response_packet(&response, b"private-bytes").unwrap(), + response, + } + }; + let allowed = ready(true, false).for_delivery(&settings).unwrap(); + assert_eq!( + protocol::read_complete_packet::(&allowed) + .unwrap() + .1, + b"private-bytes" + ); + // The result was prepared while valid, but no output has started. + settings.operation_credential.as_mut().unwrap().expires_at = 1; + for (ok, unknown) in [(true, false), (false, true), (false, false)] { + let (response, payload) = protocol::read_complete_packet::( + &ready(ok, unknown).for_delivery(&settings).unwrap(), + ) + .unwrap(); + assert!(!response.ok); + assert!(payload.is_empty()); + assert!(response.tip.is_none()); + assert_eq!(response.publication_unknown, unknown || (ok && mutation)); + } + } + } + #[test] fn http_framing_rejects_ambiguity_and_oversized_headers() { for request in [ @@ -1308,7 +2217,10 @@ mod tests { token: Some(b"required-token".to_vec()), write: false, force: false, + policy_enabled: false, policy: None, + require_operation_credentials: false, + operation_credential: None, actor: "test".into(), pre_receive: None, update_hook: None, diff --git a/src/server_admin_identity.rs b/src/server_admin_identity.rs new file mode 100644 index 0000000..99c67ab --- /dev/null +++ b/src/server_admin_identity.rs @@ -0,0 +1,272 @@ +//! Operating-system identities for local administrative actions. + +use crate::protocol::AuditOperator; +use std::path::Path; + +#[cfg(unix)] +fn unix_operator(uid: libc::uid_t) -> Result { + let operator = AuditOperator { + version: 1, + identity: format!("unix:uid:{uid}"), + }; + operator.validate()?; + Ok(operator) +} + +#[cfg(unix)] +pub(super) fn current_operator() -> Result { + // SAFETY: geteuid has no preconditions and reports the process's effective UID. + unix_operator(unsafe { libc::geteuid() }) +} + +#[cfg(windows)] +pub(super) fn current_operator() -> Result { + use std::io; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use std::ptr; + use windows_sys::Win32::Foundation::{LocalFree, ERROR_INSUFFICIENT_BUFFER}; + use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW; + use windows_sys::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TOKEN_USER}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + + struct LocalWide(*mut u16); + impl Drop for LocalWide { + fn drop(&mut self) { + // SAFETY: ConvertSidToStringSidW allocated this buffer with LocalAlloc. + unsafe { LocalFree(self.0.cast()) }; + } + } + + let mut raw_token = ptr::null_mut(); + // SAFETY: GetCurrentProcess returns a valid pseudo-handle and raw_token is writable. + if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw_token) } == 0 { + return Err(format!( + "cannot open process token: {}", + io::Error::last_os_error() + )); + } + if raw_token.is_null() { + return Err("process token handle is null".into()); + } + // SAFETY: successful OpenProcessToken returns an owned, non-null handle. + let token = unsafe { OwnedHandle::from_raw_handle(raw_token) }; + + let mut needed = 0u32; + // SAFETY: the initial zero-length query only writes the required size. + let query = unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenUser, + ptr::null_mut(), + 0, + &mut needed, + ) + }; + let cause = io::Error::last_os_error(); + if query != 0 { + return Err("process token user size query unexpectedly succeeded without a buffer".into()); + } + if cause.raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER as i32) { + return Err(format!("cannot query process token user size: {cause}")); + } + if needed < std::mem::size_of::() as u32 || needed > 64 * 1024 { + return Err("invalid process token user size".into()); + } + // TOKEN_USER contains pointers, so allocate with pointer alignment. + let words = (needed as usize).div_ceil(std::mem::size_of::()); + let mut buffer = vec![0usize; words]; + // SAFETY: buffer is aligned and contains at least `needed` writable bytes. + if unsafe { + GetTokenInformation( + token.as_raw_handle(), + TokenUser, + buffer.as_mut_ptr().cast(), + needed, + &mut needed, + ) + } == 0 + { + return Err(format!( + "cannot read process token user: {}", + io::Error::last_os_error() + )); + } + // SAFETY: the successful query populated a TOKEN_USER and its SID in buffer. + let user = unsafe { &*buffer.as_ptr().cast::() }; + let mut sid = ptr::null_mut(); + // SAFETY: user.User.Sid is the SID supplied by the successful token query. + if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid) } == 0 { + return Err(format!( + "cannot convert process token SID: {}", + io::Error::last_os_error() + )); + } + if sid.is_null() { + return Err("process token SID string is null".into()); + } + let sid = LocalWide(sid); + let mut length = 0usize; + // SAFETY: ConvertSidToStringSidW returned a null-terminated UTF-16 string. + while unsafe { *sid.0.add(length) } != 0 { + length += 1; + } + // SAFETY: length was measured up to the string terminator in that allocation. + let wide = unsafe { std::slice::from_raw_parts(sid.0, length) }; + let text = + String::from_utf16(wide).map_err(|error| format!("invalid process token SID: {error}"))?; + let operator = AuditOperator { + version: 1, + identity: format!("windows:sid:{text}"), + }; + operator.validate()?; + Ok(operator) +} + +#[cfg(not(any(unix, windows)))] +pub(super) fn current_operator() -> Result { + Err("local operator identity is unavailable on this platform".into()) +} + +#[cfg(target_os = "linux")] +fn check_recovery_owner(uid: u32, owner: u32) -> Result<(), String> { + if uid != 0 && uid != owner { + return Err("recovery requires root or the server root owner".into()); + } + Ok(()) +} + +#[cfg(target_os = "linux")] +pub(super) fn authorize_recovery_root(root: &Path) -> Result { + use std::os::unix::fs::MetadataExt; + use std::path::Component; + + if !root.is_absolute() || root.components().any(|part| part == Component::ParentDir) { + return Err("recovery root must be an absolute path without '..'".into()); + } + let inspect = |path: &Path| { + let metadata = std::fs::symlink_metadata(path) + .map_err(|error| format!("cannot inspect recovery path {}: {error}", path.display()))?; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err(format!( + "recovery path is not a real directory: {}", + path.display() + )); + } + Ok(metadata) + }; + // Capture the UID once so the authorization and audit identity agree. + // SAFETY: geteuid has no preconditions. + let uid = unsafe { libc::geteuid() }; + let metadata = inspect(root)?; + let owner = metadata.uid(); + check_recovery_owner(uid, owner)?; + if metadata.mode() & 0o022 != 0 { + return Err("recovery root must not be group- or other-writable".into()); + } + for ancestor in root.ancestors().skip(1) { + let metadata = inspect(ancestor)?; + if metadata.uid() != 0 && metadata.uid() != uid && metadata.uid() != owner { + return Err(format!( + "recovery ancestor has an untrusted owner: {}", + ancestor.display() + )); + } + // A sticky directory protects each trusted-owned child entry against + // replacement by other users; each child is inspected in this loop. + if metadata.mode() & 0o022 != 0 && metadata.mode() & 0o1000 == 0 { + return Err(format!( + "recovery ancestor is writable by other users: {}", + ancestor.display() + )); + } + } + unix_operator(uid) +} + +#[cfg(not(target_os = "linux"))] +pub(super) fn authorize_recovery_root(_root: &Path) -> Result { + Err("local recovery authorization is only available on Linux".into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(unix)] + #[test] + fn operator_is_the_effective_uid() { + // SAFETY: geteuid has no preconditions. + let uid = unsafe { libc::geteuid() }; + assert_eq!( + current_operator().unwrap().identity, + format!("unix:uid:{uid}") + ); + } + + #[cfg(windows)] + #[test] + fn operator_is_a_windows_sid() { + let operator = current_operator().unwrap(); + assert!(operator.identity.starts_with("windows:sid:S-")); + operator.validate().unwrap(); + } + + #[cfg(not(target_os = "linux"))] + #[test] + fn recovery_is_unavailable_on_other_platforms() { + assert!(authorize_recovery_root(Path::new(".")).is_err()); + } + + #[cfg(target_os = "linux")] + #[test] + fn recovery_requires_root_or_directory_owner() { + assert!(check_recovery_owner(0, 1000).is_ok()); + assert!(check_recovery_owner(1000, 1000).is_ok()); + assert!(check_recovery_owner(1000, 1001).is_err()); + } + + #[cfg(target_os = "linux")] + #[test] + fn recovery_checks_root_ancestors_and_symlinks() { + use std::fs; + use std::os::unix::fs::{symlink, DirBuilderExt, PermissionsExt}; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + let base = std::env::temp_dir().join(format!( + "wasm-git-recovery-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::DirBuilder::new().mode(0o700).create(&base).unwrap(); + let temp = Temp(base); + let parent = temp.0.join("parent"); + let root = parent.join("root"); + fs::DirBuilder::new().mode(0o700).create(&parent).unwrap(); + fs::DirBuilder::new().mode(0o700).create(&root).unwrap(); + + assert_eq!( + authorize_recovery_root(&root).unwrap().identity, + current_operator().unwrap().identity + ); + fs::set_permissions(&root, fs::Permissions::from_mode(0o720)).unwrap(); + assert!(authorize_recovery_root(&root).is_err()); + fs::set_permissions(&root, fs::Permissions::from_mode(0o702)).unwrap(); + assert!(authorize_recovery_root(&root).is_err()); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + + fs::set_permissions(&parent, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(authorize_recovery_root(&root).is_err()); + fs::set_permissions(&parent, fs::Permissions::from_mode(0o1777)).unwrap(); + assert!(authorize_recovery_root(&root).is_ok()); + symlink(&root, temp.0.join("link")).unwrap(); + assert!(authorize_recovery_root(&temp.0.join("link")).is_err()); + } +} diff --git a/src/server_policy.rs b/src/server_policy.rs index 65d6548..c904bec 100644 --- a/src/server_policy.rs +++ b/src/server_policy.rs @@ -1,30 +1,397 @@ -//! Hosting authorization configuration is compiled once from an administrator's -//! external JSON input. The runtime file and audit records are native binary. +//! Root-scoped authority. The stable gate protects both the current policy and +//! every served operation; an update takes the exclusive side as its fence. use super::*; +use crate::protocol::{ + PolicyMigrationReceipt, PolicyMigrationRequest, PolicyQueryReply, PolicyQueryRequest, + PolicyStatus, PolicyUpdateOutcome, PolicyUpdateReceipt, PolicyUpdateRequest, ServerPolicy, +}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -#[derive(Clone, Serialize, Deserialize)] +#[path = "infrastructure/database/policy_ledger.rs"] +mod ledger; + +const GATE_FILE: &str = ".wasm-git-authorization.lock"; +const MAX_POLICY_BYTES: u64 = 16 * 1024 * 1024; +const MAX_LEGACY_RECEIPTS: usize = 4096; + +#[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub(super) struct Policy { +struct LegacyStore { version: u32, - principals: Vec, + generation: u64, + policy: Option, + receipts: BTreeMap, } -#[derive(Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Principal { - name: String, - token_sha256: Option, - grants: Vec, + +impl LegacyStore { + fn validate(&self) -> Result<(), String> { + if self.version != 1 + || self.generation > protocol::NODE_SAFE_INTEGER_MAX + || (self.generation == 0) != self.policy.is_none() + { + return Err("invalid authorization store version or generation".into()); + } + if let Some(policy) = &self.policy { + policy.validate()?; + } + if self.receipts.len() > MAX_LEGACY_RECEIPTS { + return Err("policy receipt capacity exceeded".into()); + } + let mut generations = std::collections::BTreeSet::new(); + for (id, receipt) in &self.receipts { + receipt.validate()?; + if id != &receipt.operation_id + || receipt.generation > self.generation + || (receipt.outcome == PolicyUpdateOutcome::Applied + && !generations.insert(receipt.generation)) + || (receipt.outcome == PolicyUpdateOutcome::Applied + && receipt.generation == self.generation + && receipt.policy_sha256 + != self + .policy + .as_ref() + .ok_or("missing current policy")? + .digest()?) + { + return Err("invalid policy receipt ledger".into()); + } + } + if generations.len() as u64 != self.generation + || generations + .iter() + .enumerate() + .any(|(index, generation)| *generation != index as u64 + 1) + { + return Err("policy applied receipt history is incomplete".into()); + } + Ok(()) + } } -#[derive(Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Grant { - repository: String, - read: bool, - write: Vec, - force: bool, - create: bool, + +pub(super) struct Guard { + _gate: fs::File, + pub policy: Option>, + pub generation: u64, + pub operation_credentials: bool, + pub chunk_receipts: bool, +} + +fn gate(root: &Path, exclusive: bool) -> Result { + let path = root.join(GATE_FILE); + let mut options = fs::OpenOptions::new(); + options.read(true).write(true).create(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let file = options + .open(&path) + .map_err(|e| format!("open authorization gate: {e}"))?; + real_path(&path, false)?; + let deadline = Instant::now() + TIMEOUT; + loop { + let result = if exclusive { + file.try_lock() + } else { + file.try_lock_shared() + }; + match result { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(2)); + } + Err(e) => return Err(format!("authorization gate busy: {e}")), + } + } +} + +/// A bootstrap file is used only for an uninitialized root. Existing roots +/// always use their own durable store, never a stale process-local snapshot. +pub(super) fn bootstrap(root: &Path, input: &Path) -> Result<(), String> { + let _gate = gate(root, true)?; + let current = ledger::current(root)?; + if current.as_ref().is_none_or(|store| store.policy.is_none()) { + let policy = load_compiled(input)?; + ledger::bootstrap_audited(root, policy, &admin_identity::current_operator()?)?; + } + Ok(()) +} + +pub(super) fn request_guard(root: &Path, policy_enabled: bool) -> Result { + let gate = gate(root, false)?; + let store = ledger::current(root)?; + let generation = store.as_ref().map_or(0, |store| store.generation); + let operation_credentials = store + .as_ref() + .is_some_and(|store| store.operation_credentials); + let chunk_receipts = store.as_ref().is_some_and(|store| store.chunk_receipts); + let policy = match (policy_enabled, store) { + (true, Some(store)) => Some(Arc::new( + store + .policy + .ok_or("authorization store is not initialized")?, + )), + (true, None) => return Err("authorization store is not initialized".into()), + (false, Some(_)) => return Err("this root requires its authorization policy".into()), + (false, None) => None, + }; + Ok(Guard { + _gate: gate, + policy, + generation, + operation_credentials, + chunk_receipts, + }) +} + +pub(super) fn set( + root: &Path, + request: &PolicyUpdateRequest, +) -> Result { + request.validate()?; + let _gate = gate(root, true)?; + ledger::set_audited(root, request, &admin_identity::current_operator()?) +} + +pub(super) fn status(root: &Path) -> Result { + let _gate = gate(root, false)?; + ledger::status(root) +} + +pub(super) fn query(root: &Path, request: &PolicyQueryRequest) -> Result { + let _gate = gate(root, false)?; + ledger::query(root, request) +} + +pub(super) fn issue_credential( + root: &Path, + request: &protocol::OperationCredentialRequest, +) -> Result { + let receipt = request.receipt()?; + let _gate = gate(root, true)?; + if matches!( + &request.request.operation, + Operation::ScopedUploadSlice { .. } + ) { + // Preserve historical replay without issuing a new way around the + // original-operation chunk journal. Its execution is also disabled. + return match ledger::credential_query(root, &receipt.operation_id)? { + Some(prior) if prior == receipt => Ok(prior), + _ => Err("strict uploads require an original-operation chunk request".into()), + }; + } + // The transaction checks expiry at first issuance's INSERT decision point; + // historical replay returns the original receipt without renewing it. + ledger::credential_issue_audited(root, request, &admin_identity::current_operator()?) +} + +/// Caller owns the root authorization gate for the complete native attempt. +pub(super) fn audit_start( + root: &Path, + credential: &protocol::OperationCredentialReceipt, + request: &Request, + payload: &[u8], +) -> Result { + ledger::audit_start_operation( + root, + credential, + request, + &format!("{:x}", Sha256::digest(payload)), + ) +} + +pub(super) fn audit_observe( + root: &Path, + target: &protocol::AuditTarget, + observation: &protocol::AuditObservation, +) -> Result<(), String> { + ledger::audit_observe(root, target, observation) +} + +pub(super) fn recovery_begin( + root: &Path, + request: &protocol::OperationRecoveryRequest, + operator: &protocol::AuditOperator, +) -> Result<(fs::File, u64), String> { + request.validate()?; + let guard = gate(root, true)?; + let original = ledger::credential_query(root, &request.original.operation_id)? + .ok_or("original credential issuance is unavailable")?; + original.validate_request(&request.original)?; + let attempt = ledger::audit_begin_recovery( + root, + &request.recovery_id, + &request.original, + request.action, + operator, + )?; + Ok((guard, attempt)) +} + +pub(super) fn audit_query( + root: &Path, + request: &protocol::AuditQueryRequest, +) -> Result { + let _gate = gate(root, false)?; + ledger::audit_query(root, request) +} + +pub(super) fn audit_reconcile_many( + root: &Path, + recovery_id: &str, + attempt_id: u64, + targets: &[protocol::AuditTarget], + observation: &protocol::AuditObservation, +) -> Result<(), String> { + ledger::audit_reconcile_many(root, recovery_id, attempt_id, targets, observation) +} + +pub(super) fn operation_context( + root: &Path, + operation_id: &str, +) -> Result, String> { + let _gate = gate(root, false)?; + ledger::audit_operation_context(root, operation_id) +} + +/// The caller retains the root's shared guard. Original issuance is identity +/// evidence, not proof of execution, and is readable after expiry/revocation. +pub(super) fn validate_original_chunk( + root: &Path, + chunk: &protocol::ScopedChunkIdentity, +) -> Result<(), String> { + let credential = ledger::credential_query(root, &chunk.operation_id).map_err(|cause| { + crate::cli_error(&format!("original chunk authority: {cause}")); + "original chunk authority unavailable".to_owned() + })?; + if credential + .as_ref() + .is_some_and(|credential| chunk.validate_credential(credential).is_ok()) + { + Ok(()) + } else { + Err("original chunk is unavailable to this actor or scope".into()) + } +} + +pub(super) fn query_credential( + root: &Path, + request: &protocol::OperationCredentialQuery, +) -> Result { + request.validate()?; + let _gate = gate(root, false)?; + Ok(protocol::OperationCredentialQueryReply { + version: 1, + operation_id: request.operation_id.clone(), + receipt: ledger::credential_query(root, &request.operation_id)?, + }) +} + +/// The root guard is held by the transport throughout authentication, use and +/// output. A credential narrows the current principal policy; it never grants +/// rights by itself or falls back to a principal token after a failed match. +pub(super) type Authentication = (String, Option); + +pub(super) fn authenticate( + root: &Path, + policy: &ServerPolicy, + generation: u64, + token: &[u8], + strict: bool, +) -> Result, String> { + // An absent/malformed Bearer value cannot become an identity even if a + // trusted issuer accidentally stores the digest of such a value. + if token.is_empty() || token.len() > 4096 || token.iter().any(|byte| !(33..=126).contains(byte)) + { + return Ok(None); + } + let digest = format!("{:x}", Sha256::digest(token)); + if let Some(receipt) = ledger::credential_by_token(root, &digest)? { + if receipt.policy_generation != generation + || !policy.principal_exists(&receipt.actor) + || now()? >= receipt.expires_at + { + return Ok(None); + } + return Ok(Some((receipt.actor.clone(), Some(receipt)))); + } + if strict { + return Ok(None); + } + Ok(policy.authenticate(token).map(|actor| (actor, None))) +} + +/// Explicit maintenance-window migration. Old participants that do not honor +/// this gate must be stopped before invoking it. +pub(super) fn migrate( + root: &Path, + request: &PolicyMigrationRequest, +) -> Result { + request.validate()?; + let _gate = gate(root, true)?; + let path = root.join(".wasm-git-authorization.bin"); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("inspect policy migration source: {error}"))?; + if !metadata.is_file() || metadata.file_type().is_symlink() { + return Err("policy migration source must be a regular file".into()); + } + let mut file = + fs::File::open(&path).map_err(|error| format!("open policy migration source: {error}"))?; + let mut header = [0u8; 16]; + file.read_exact(&mut header[..8]) + .map_err(|error| format!("read policy migration source: {error}"))?; + if &header[..8] != b"WGTM\0\0\0\x01" { + file.read_exact(&mut header[8..]) + .map_err(|error| format!("read policy migration source: {error}"))?; + if &header == b"SQLite format 3\0" { + return ledger::migration_receipt(root, request); + } + return Err("unsupported legacy policy migration source".into()); + } + if metadata.len() > MAX_POLICY_BYTES { + return Err("unsupported legacy policy migration source".into()); + } + drop(file); + let bytes = fs::read(&path).map_err(|error| format!("read legacy policy: {error}"))?; + if format!("{:x}", Sha256::digest(&bytes)) != request.source_sha256 { + return Err("legacy policy source digest mismatch".into()); + } + let legacy: LegacyStore = crate::binary::decode(&bytes)?; + legacy.validate()?; + let receipt = PolicyMigrationReceipt { + version: 1, + source_sha256: request.source_sha256.clone(), + source_version: 1, + target_version: 2, + generation: legacy.generation, + policy_sha256: legacy + .policy + .as_ref() + .map(ServerPolicy::digest) + .transpose()?, + receipts: legacy.receipts.len() as u64, + }; + receipt.validate_request(request)?; + ledger::migrate( + root, + legacy.policy.as_ref(), + legacy.generation, + &legacy.receipts, + &receipt, + )?; + Ok(receipt) +} + +fn load_compiled(path: &Path) -> Result { + let path = real_path(path, false)?; + if fs::metadata(&path).map_err(|e| e.to_string())?.len() > MAX_POLICY_BYTES { + return Err("policy exceeds 16 MiB".into()); + } + let policy: ServerPolicy = crate::binary::decode(&fs::read(path).map_err(|e| e.to_string())?)?; + policy.validate()?; + Ok(policy) } fn matches(pattern: &str, value: &str) -> bool { @@ -33,55 +400,51 @@ fn matches(pattern: &str, value: &str) -> bool { .map_or(pattern == value, |prefix| value.starts_with(prefix)) } -impl Policy { - fn validate(&self) -> Result<(), String> { - if self.version != 1 || self.principals.len() > 4096 { - return Err("invalid policy version or principal count".into()); - } - let mut names = std::collections::BTreeSet::new(); - let mut tokens = std::collections::BTreeSet::new(); - for principal in &self.principals { - protocol::repository_component(&principal.name)?; - if !names.insert(&principal.name) { - return Err("duplicate policy principal".into()); - } - if let Some(hash) = &principal.token_sha256 { - crate::binary::oid(hash)?; - if !tokens.insert(hash) { - return Err("duplicate policy credential".into()); - } - } - for grant in &principal.grants { - let prefix = grant - .repository - .strip_suffix('*') - .unwrap_or(&grant.repository); - if grant.repository != "*" { - protocol::repository_name(prefix.strip_suffix('/').unwrap_or(prefix))?; - } - for reference in &grant.write { - let prefix = reference.strip_suffix('*').unwrap_or(reference); - if !(prefix.starts_with("refs/heads/") || prefix.starts_with("refs/tags/")) - || prefix.contains('*') - || prefix.contains("..") - || prefix.bytes().any(|b| b <= 32 || b >= 127) - { - return Err("policy write rules require refs/heads/ or refs/tags/ prefixes and an optional final '*'".into()); - } - } - } - } - Ok(()) +fn now() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|t| t.as_secs()) + .map_err(|_| "authorization clock unavailable".into()) +} + +/// None is unbounded; an absent matching grant is represented by Result, not +/// by None. Alternatives take the longest bound and required permissions the +/// shortest, so a batch compares one combined limit against one clock reading. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct AuthorizationLimit(Option); + +impl AuthorizationLimit { + pub(super) fn unbounded() -> Self { + Self(None) } - pub(super) fn load(path: &Path) -> Result { - let path = real_path(path, false)?; - if fs::metadata(&path).map_err(|e| e.to_string())?.len() > 16 * 1024 * 1024 { - return Err("policy exceeds 16 MiB".into()); + pub(super) fn until(expiry: u64) -> Self { + Self(Some(expiry)) + } + pub(super) fn intersect(self, other: Self) -> Self { + Self(match (self.0, other.0) { + (None, value) | (value, None) => value, + (Some(left), Some(right)) => Some(left.min(right)), + }) + } + + fn alternative(self, other: Self) -> Self { + Self(match (self.0, other.0) { + (None, _) | (_, None) => None, + (Some(left), Some(right)) => Some(left.max(right)), + }) + } + + pub(super) fn require_current(self) -> Result<(), String> { + let current = now()?; + if self.0.is_none_or(|expiry| current < expiry) { + Ok(()) + } else { + Err("authorization denied for this repository or reference".into()) } - let policy: Self = crate::binary::decode(&fs::read(path).map_err(|e| e.to_string())?)?; - policy.validate()?; - Ok(policy) } +} + +impl ServerPolicy { pub(super) fn authenticate(&self, token: &[u8]) -> Option { let hash = format!("{:x}", Sha256::digest(token)); let mut name = None; @@ -99,52 +462,78 @@ impl Policy { pub(super) fn principal_exists(&self, name: &str) -> bool { self.principals.iter().any(|p| p.name == name) } - pub(super) fn authorize( + pub(super) fn retention_limit( + &self, + actor: &str, + repo: &str, + ) -> Result { + self.principals + .iter() + .filter(|p| p.name == actor) + .flat_map(|p| &p.grants) + .filter(|g| matches(&g.repository, repo) && g.read && g.release_retention) + .map(|g| AuthorizationLimit(g.expires_at)) + .reduce(AuthorizationLimit::alternative) + .ok_or_else(|| "release retention authorization denied".into()) + } + pub(super) fn authorization_limit( &self, actor: &str, repo: &str, reference: Option<&str>, force: bool, create: bool, - ) -> Result<(), String> { - let allowed = self + ) -> Result { + let mut limit: Option = None; + for grant in self .principals .iter() .filter(|p| p.name == actor) .flat_map(|p| &p.grants) - .any(|g| { - matches(&g.repository, repo) - && if create { - g.create - } else { - g.read - && (!force || g.force) - && reference.is_none_or(|r| { - if r == "*" { - !g.write.is_empty() - } else { - g.write.iter().any(|p| matches(p, r)) - } - }) - } - }); - if allowed { - Ok(()) - } else { - Err("authorization denied for this repository or reference".into()) + { + let allowed = matches(&grant.repository, repo) + && if create { + grant.create + } else { + grant.read + && (!force || grant.force) + && reference.is_none_or(|r| { + if r == "*" { + !grant.write.is_empty() + } else { + grant.write.iter().any(|p| matches(p, r)) + } + }) + }; + if allowed { + let candidate = AuthorizationLimit(grant.expires_at); + limit = Some(limit.map_or(candidate, |prior| prior.alternative(candidate))); + } } + limit.ok_or_else(|| "authorization denied for this repository or reference".into()) + } + + pub(super) fn authorize( + &self, + actor: &str, + repo: &str, + reference: Option<&str>, + force: bool, + create: bool, + ) -> Result<(), String> { + self.authorization_limit(actor, repo, reference, force, create)? + .require_current() } } pub(super) fn compile(input: &Path, output: &Path) -> Result { let input = real_path(input, false)?; - if fs::metadata(&input).map_err(|e| e.to_string())?.len() > 16 * 1024 * 1024 { + if fs::metadata(&input).map_err(|e| e.to_string())?.len() > MAX_POLICY_BYTES { return Err("policy input exceeds 16 MiB".into()); } - let policy: Policy = serde_json::from_slice(&fs::read(input).map_err(|e| e.to_string())?) + let policy: ServerPolicy = serde_json::from_slice(&fs::read(input).map_err(|e| e.to_string())?) .map_err(|e| e.to_string())?; policy.validate()?; - let bytes = crate::binary::encode(&policy)?; let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -153,8 +542,282 @@ pub(super) fn compile(input: &Path, output: &Path) -> Result { options.mode(0o600); } let mut file = options.open(output).map_err(|e| e.to_string())?; - file.write_all(&bytes) + file.write_all(&crate::binary::encode(&policy)?) .and_then(|_| file.sync_all()) .map_err(|e| e.to_string())?; Ok(format!("compiled {} principals", policy.principals.len())) } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + + #[test] + fn missing_or_malformed_bearer_never_queries_a_credential() { + let policy = ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + for token in [ + Vec::new(), + b" ".to_vec(), + b"token with spaces".to_vec(), + vec![b'x'; 4097], + vec![0xff], + ] { + assert!( + authenticate(Path::new("absent-root"), &policy, 1, &token, true) + .unwrap() + .is_none() + ); + } + } + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "wasm-git-policy-migration-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&root).unwrap(); + Self(root) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn missing_applied_receipts_are_rejected() { + let policy = ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + let digest = policy.digest().unwrap(); + let receipt = PolicyUpdateReceipt { + version: 1, + operation_id: "2".repeat(64), + expected_generation: 1, + outcome: PolicyUpdateOutcome::Applied, + generation: 2, + policy_sha256: digest, + }; + let store = LegacyStore { + version: 1, + generation: 2, + policy: Some(policy), + receipts: BTreeMap::from([(receipt.operation_id.clone(), receipt)]), + }; + assert!(store + .validate() + .unwrap_err() + .contains("history is incomplete")); + } + + #[test] + fn alternative_grants_and_required_permissions_combine_expiry_once() { + use crate::protocol::{PolicyGrant, PolicyPrincipal}; + let grant = |expiry, reference: &str| PolicyGrant { + repository: "project".into(), + read: true, + write: vec![reference.into()], + force: false, + create: false, + release_retention: false, + expires_at: expiry, + }; + let policy = ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: vec![PolicyPrincipal { + name: "alice".into(), + token_sha256: None, + grants: vec![ + grant(Some(10), "refs/heads/a"), + grant(Some(20), "refs/heads/a"), + grant(Some(15), "refs/heads/b"), + ], + }], + }; + let a = policy + .authorization_limit("alice", "project", Some("refs/heads/a"), false, false) + .unwrap(); + let b = policy + .authorization_limit("alice", "project", Some("refs/heads/b"), false, false) + .unwrap(); + assert_eq!(a, AuthorizationLimit(Some(20))); + assert_eq!(a.intersect(b), AuthorizationLimit(Some(15))); + assert_eq!(AuthorizationLimit(None).intersect(a), a); + assert!(a.require_current().is_err()); + assert!(policy + .authorization_limit("alice", "project", Some("refs/heads/c"), false, false) + .is_err()); + } + + #[test] + fn migration_preserves_every_receipt_and_replays_after_later_updates() { + let root = Temp::new(); + let policy = ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + let digest = policy.digest().unwrap(); + let applied = PolicyUpdateReceipt { + version: 1, + operation_id: "a".repeat(64), + expected_generation: 0, + outcome: PolicyUpdateOutcome::Applied, + generation: 1, + policy_sha256: digest.clone(), + }; + let conflict = PolicyUpdateReceipt { + version: 1, + operation_id: "b".repeat(64), + expected_generation: 0, + outcome: PolicyUpdateOutcome::GenerationConflict, + generation: 1, + policy_sha256: digest, + }; + let legacy = LegacyStore { + version: 1, + generation: 1, + policy: Some(policy.clone()), + receipts: BTreeMap::from([ + (applied.operation_id.clone(), applied.clone()), + (conflict.operation_id.clone(), conflict.clone()), + ]), + }; + let bytes = crate::binary::encode(&legacy).unwrap(); + let path = root.0.join(".wasm-git-authorization.bin"); + fs::write(&path, &bytes).unwrap(); + assert!(status(&root.0) + .unwrap_err() + .contains("maintenance-window migration")); + let mut request = PolicyMigrationRequest { + version: 1, + source_sha256: "0".repeat(64), + }; + assert!(migrate(&root.0, &request).is_err()); + assert_eq!(fs::read(&path).unwrap(), bytes); + request.source_sha256 = format!("{:x}", Sha256::digest(&bytes)); + let migrated = migrate(&root.0, &request).unwrap(); + assert_eq!(migrated.generation, 1); + assert_eq!(migrated.receipts, 2); + let actual = query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: conflict.operation_id.clone(), + }, + ) + .unwrap() + .receipt + .unwrap(); + assert_eq!( + crate::binary::encode(&actual).unwrap(), + crate::binary::encode(&conflict).unwrap() + ); + set( + &root.0, + &PolicyUpdateRequest { + version: 1, + operation_id: "c".repeat(64), + expected_generation: 1, + policy, + }, + ) + .unwrap(); + assert_eq!(status(&root.0).unwrap().generation, 2); + let replay = migrate(&root.0, &request).unwrap(); + assert_eq!( + crate::binary::encode(&replay).unwrap(), + crate::binary::encode(&migrated).unwrap() + ); + request.source_sha256 = "f".repeat(64); + assert!(migrate(&root.0, &request).is_err()); + } + + #[test] + fn migration_preserves_conflicts_before_first_policy() { + let root = Temp::new(); + let policy = ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + let conflict = PolicyUpdateReceipt { + version: 1, + operation_id: "d".repeat(64), + expected_generation: 1, + outcome: PolicyUpdateOutcome::GenerationConflict, + generation: 0, + policy_sha256: policy.digest().unwrap(), + }; + let legacy = LegacyStore { + version: 1, + generation: 0, + policy: None, + receipts: BTreeMap::from([(conflict.operation_id.clone(), conflict.clone())]), + }; + let bytes = crate::binary::encode(&legacy).unwrap(); + fs::write(root.0.join(".wasm-git-authorization.bin"), &bytes).unwrap(); + let request = PolicyMigrationRequest { + version: 1, + source_sha256: format!("{:x}", Sha256::digest(&bytes)), + }; + let migrated = migrate(&root.0, &request).unwrap(); + assert_eq!(migrated.generation, 0); + assert_eq!(migrated.policy_sha256, None); + assert!(status(&root.0).is_err()); + assert!(query( + &root.0, + &PolicyQueryRequest { + version: 1, + operation_id: conflict.operation_id.clone() + } + ) + .unwrap() + .receipt + .is_some()); + set( + &root.0, + &PolicyUpdateRequest { + version: 1, + operation_id: "e".repeat(64), + expected_generation: 0, + policy, + }, + ) + .unwrap(); + assert_eq!(migrate(&root.0, &request).unwrap().generation, 0); + } + + #[test] + fn migration_refuses_incomplete_history_without_replacing_source() { + let root = Temp::new(); + let legacy = LegacyStore { + version: 1, + generation: 1, + policy: Some(ServerPolicy { + version: protocol::SERVER_POLICY_VERSION, + principals: Vec::new(), + }), + receipts: BTreeMap::new(), + }; + let bytes = crate::binary::encode(&legacy).unwrap(); + let path = root.0.join(".wasm-git-authorization.bin"); + fs::write(&path, &bytes).unwrap(); + let request = PolicyMigrationRequest { + version: 1, + source_sha256: format!("{:x}", Sha256::digest(&bytes)), + }; + assert!(migrate(&root.0, &request) + .unwrap_err() + .contains("history is incomplete")); + assert_eq!(fs::read(path).unwrap(), bytes); + } +} diff --git a/src/server_pulls.rs b/src/server_pulls.rs index c705127..89bc890 100644 --- a/src/server_pulls.rs +++ b/src/server_pulls.rs @@ -374,7 +374,8 @@ pub(super) fn run( new: Some(prepared.merge.as_ref().unwrap().commit.clone()), force: false, }]; - if let Err(error) = receive::publish(settings, name, repo, &bundle, &updates, &[]) { + if let Err(error) = receive::publish(settings, name, repo, &bundle, &updates, &[], None) + { if error.publication_unknown { return Err(format!( "pull merge publication outcome is unknown: {}; use pr recover", diff --git a/src/server_receive.rs b/src/server_receive.rs index 144edb7..524e26a 100644 --- a/src/server_receive.rs +++ b/src/server_receive.rs @@ -26,6 +26,12 @@ fn audit( outcome: &str, options: &[String], ) -> Result<(), String> { + // Strict operations use the durable original-operation audit index and + // native scoped receipts. This legacy append log is not a second result + // source and cannot turn a completed strict decision into an unaudited one. + if settings.require_operation_credentials { + return Ok(()); + } audit_with_rejections(settings, repo, updates, transaction, outcome, options, &[]) } @@ -240,6 +246,7 @@ pub(super) fn publish( bytes: &[u8], updates: &[RefUpdate], options: &[String], + scope: Option<&crate::repository::ScopedExecution>, ) -> Result<(), ReceiveError> { let transaction = format!( "{}-{}-{}", @@ -256,41 +263,47 @@ pub(super) fn publish( publication_unknown: false, } })?; - let result = repo.receive_batch_checked(bytes, updates, |bundle| { - if let Some(path) = &settings.signed_authors { - repo.verify_receive_authors(bundle, updates, path)?; - } - if settings.pre_receive.is_some() || settings.update_hook.is_some() { - let input = HookInput::new(repo, updates, bundle)?; - let context = HookContext { - settings, - repo, - input: &input, - options, - transaction: &transaction, - deadline: Instant::now() + TIMEOUT, - }; - if let Some(path) = &settings.pre_receive { - hook(path, &context, "pre-receive", &[])?; + let result = repo.receive_batch_checked_scoped( + bytes, + updates, + scope, + |bundle| { + if let Some(path) = &settings.signed_authors { + repo.verify_receive_authors(bundle, updates, path)?; } - if let Some(path) = &settings.update_hook { - let zero = "0".repeat(64); - for update in updates { - hook( - path, - &context, - "update", - &[ - reference(update), - update.expected.as_ref().unwrap_or(&zero).clone(), - update.new.as_ref().unwrap_or(&zero).clone(), - ], - )?; + if settings.pre_receive.is_some() || settings.update_hook.is_some() { + let input = HookInput::new(repo, updates, bundle)?; + let context = HookContext { + settings, + repo, + input: &input, + options, + transaction: &transaction, + deadline: Instant::now() + TIMEOUT, + }; + if let Some(path) = &settings.pre_receive { + hook(path, &context, "pre-receive", &[])?; + } + if let Some(path) = &settings.update_hook { + let zero = "0".repeat(64); + for update in updates { + hook( + path, + &context, + "update", + &[ + reference(update), + update.expected.as_ref().unwrap_or(&zero).clone(), + update.new.as_ref().unwrap_or(&zero).clone(), + ], + )?; + } } } - } - Ok(()) - }); + Ok(()) + }, + || authorize_updates(settings, name, updates, &vec![None; updates.len()]), + ); let outcome = match &result { Ok(()) => "accepted", Err(e) if e.publication_unknown => "unknown", @@ -368,6 +381,7 @@ pub(super) fn publish_selective( batch: &protocol::BatchPublication, options: &[String], dry_run: bool, + scope: Option<&crate::repository::ScopedExecution>, ) -> Result>, ReceiveError> { let transaction = format!( "receive-{}-{}-{}", @@ -387,8 +401,12 @@ pub(super) fn publish_selective( } })?; } - let result = - repo.receive_batch_selective(&batch.bundle, updates, dry_run, |bundle, reasons| { + let result = repo.receive_batch_selective_scoped( + &batch.bundle, + updates, + dry_run, + scope, + |bundle, reasons| { let mut rejections = reasons.to_vec(); for (update, rejection) in updates.iter().zip(&mut rejections) { if rejection.is_none() { @@ -451,7 +469,9 @@ pub(super) fn publish_selective( } } Ok(rejections) - }); + }, + |rejections| authorize_updates(settings, name, updates, rejections), + ); if !dry_run { let outcome = match &result { Ok(reasons) if reasons.iter().all(Option::is_none) => "accepted", @@ -524,6 +544,14 @@ pub(super) fn fork( let _cleanup = Quarantine(staging.clone()); let checkout = staging.join("repository"); Repository::fork_local(source.root_path(), &checkout)?; + authorize( + settings, + source_name, + &Operation::Fork { + destination: destination.into(), + }, + &[], + )?; // Reserve the name without replacing an existing repository. A client // cannot open this empty reservation before the atomic directory rename. fs::create_dir(&target).map_err(|e| e.to_string())?; diff --git a/src/server_recovery.rs b/src/server_recovery.rs new file mode 100644 index 0000000..4bb2894 --- /dev/null +++ b/src/server_recovery.rs @@ -0,0 +1,455 @@ +//! A local, OS-authenticated maintenance boundary. No upload payload, retained +//! file read or new publish decision is accepted through this entry point. +use super::*; +use protocol::{ + AuditEvidenceObservation, AuditObservation, AuditObservationScope, AuditTarget, + OperationRecoveryReply, OperationRecoveryRequest, RecoveryAuditAction, RecoveryState, + RecoveryUploadState, RetentionCommand, RetentionReply, RetentionState, ScopedChunkIdentity, + ScopedChunkStatus, ScopedUploadState, ScopedUploadStatus, +}; +use sha2::{Digest, Sha256}; + +pub(super) fn observation_scope(operation: &Operation) -> Option { + match operation { + Operation::UploadChunk { .. } | Operation::QueryChunk { .. } => { + Some(AuditObservationScope::Chunk) + } + Operation::ScopedUploadSlice { .. } + | Operation::ApplyScopedUpload { .. } + | Operation::CancelScopedUpload { .. } + | Operation::QueryScopedUpload { .. } => Some(AuditObservationScope::UploadSession), + Operation::ReleaseRetention { .. } => Some(AuditObservationScope::Retention), + _ => None, + } +} + +fn observed(value: &T) -> Result { + Ok(AuditEvidenceObservation::Observed { + sha256: format!("{:x}", Sha256::digest(crate::binary::encode(value)?)), + }) +} + +fn chunk_evidence( + status: &ScopedChunkStatus, + chunk: &ScopedChunkIdentity, +) -> Result { + status.validate_for(chunk)?; + if matches!(status.state, protocol::ScopedChunkState::Unobserved) { + Ok(AuditEvidenceObservation::Unobserved) + } else { + observed(status) + } +} + +fn upload_evidence( + status: &ScopedUploadStatus, + repository: &str, + session: &str, + binding: &protocol::UploadBinding, +) -> Result { + status.validate_for(repository, session, binding)?; + match &status.state { + None => Ok(AuditEvidenceObservation::Unobserved), + Some( + ScopedUploadState::Applying + | ScopedUploadState::ApplyingV4 { .. } + | ScopedUploadState::Finished { .. }, + ) => Ok(AuditEvidenceObservation::Unknown), + _ => observed(status), + } +} + +fn retention_evidence( + reply: &RetentionReply, + repository: &str, + actor: &str, + original: &RetentionCommand, +) -> Result { + let operation = match original { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } => operation, + _ => return Err("audit scope is not a retention mutation".into()), + }; + let query = RetentionCommand::Query { + operation: operation.clone(), + }; + reply.validate_for(repository, &query)?; + match reply { + RetentionReply::State { record: None, .. } => Ok(AuditEvidenceObservation::Unobserved), + RetentionReply::State { + record: Some(record), + .. + } => { + if record.actor != actor || record.repository.as_deref() != Some(repository) { + return Err("retention observation cannot prove the original scope".into()); + } + if let RetentionCommand::Prepare { commit, paths, .. } = original { + if record.commit.is_some() + && (record.commit.as_ref() != Some(commit) + || record + .files + .keys() + .collect::>() + != paths.iter().collect()) + { + return Err( + "original retention preparation does not match the durable scope".into(), + ); + } + } + observed(reply) + } + _ => Err("unexpected retention observation".into()), + } +} + +pub(super) fn observe_native( + repository: &Repository, + gate: &crate::repository::ServiceGuard, + actor: &str, + request: &Request, +) -> Result { + match &request.operation { + Operation::UploadChunk { chunk } => { + let status = repository + .scoped_chunk_query(gate, chunk) + .map_err(|e| e.message)?; + chunk_evidence(&status, chunk) + } + Operation::ScopedUploadSlice { + session, binding, .. + } + | Operation::ApplyScopedUpload { session, binding } + | Operation::CancelScopedUpload { session, binding } => { + let status = repository.scoped_upload_observe( + gate, + &request.repository, + actor, + session, + binding, + )?; + upload_evidence(&status, &request.repository, session, binding) + } + Operation::ReleaseRetention { command } => { + let operation = match command { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } => operation, + _ => return Err("audit scope is not a retention mutation".into()), + }; + let query = RetentionCommand::Query { + operation: operation.clone(), + }; + let reply = repository + .release_retention_checked(&request.repository, actor, query, || Ok(())) + .map_err(|e| e.message)?; + retention_evidence(&reply, &request.repository, actor, command) + } + _ => Err("unsupported original operation observation".into()), + } +} + +pub(super) fn run( + root: &Path, + request: &OperationRecoveryRequest, +) -> Result { + request.validate()?; + let operator = admin_identity::authorize_recovery_root(root)?; + // Exclusive root fencing drains earlier HTTP operations. The immutable + // original credential supplies identity, never renewed action authority. + let (_gate, attempt_id) = policy::recovery_begin(root, request, &operator)?; + let scope = observation_scope(&request.original.request.operation) + .ok_or("unsupported recovery scope")?; + let target = AuditTarget::Recovery { + recovery_id: request.recovery_id.clone(), + attempt_id, + }; + let result = native_state(root, request).and_then(|(state, evidence)| { + let reply = OperationRecoveryReply { + version: 1, + recovery_id: request.recovery_id.clone(), + attempt_id, + original_operation_id: request.original.operation_id.clone(), + actor: request.original.actor.clone(), + repository: request.original.request.repository.clone(), + operator, + action: request.action, + state, + }; + reply.validate_for(request)?; + Ok((reply, evidence)) + }); + let evidence = result + .as_ref() + .map_or(AuditEvidenceObservation::Unknown, |(_, evidence)| { + evidence.clone() + }); + let observation = AuditObservation { + version: 1, + scope, + evidence, + }; + if let Err(cause) = policy::audit_observe(root, &target, &observation) { + return Err(format!( + "recovery observation is unconfirmed; query the same original operation: {cause}" + )); + } + let (reply, _) = result.map_err(|cause| { + format!("recovery outcome is unknown; query the original operation: {cause}") + })?; + if !request.reconcile.is_empty() { + policy::audit_reconcile_many(root, &request.recovery_id, attempt_id, &request.reconcile, &observation) + .map_err(|cause| format!("recovery was observed but audit reconciliation is unconfirmed; query the audit index: {cause}"))?; + } + Ok(reply) +} + +fn native_state( + root: &Path, + request: &OperationRecoveryRequest, +) -> Result<(RecoveryState, AuditEvidenceObservation), String> { + let original = &request.original; + let name = &original.request.repository; + let actor = &original.actor; + let (scope, chunk) = match &original.request.operation { + Operation::UploadChunk { chunk } => (Some(chunk.scope.clone()), Some(chunk)), + Operation::ScopedUploadSlice { + session, binding, .. + } + | Operation::ApplyScopedUpload { session, binding } + | Operation::CancelScopedUpload { session, binding } => ( + Some(crate::repository::ScopedExecution { + actor: actor.clone(), + repository: name.clone(), + session: session.clone(), + binding: binding.clone(), + }), + None, + ), + Operation::ReleaseRetention { .. } => (None, None), + _ => return Err("unsupported recovery action".into()), + }; + let path = repository_path_in(root, name)?; + let repository = Repository::open_for_recovery(&path, scope.as_ref())?; + let gate = repository.service_lock(TIMEOUT)?; + if let Operation::ReleaseRetention { command } = &original.request.operation { + return retention(root, &repository, name, actor, command, request.action); + } + let scope = scope.ok_or("unsupported recovery scope")?; + let session = &scope.session; + let binding = &scope.binding; + let mut status = repository.scoped_upload_observe(&gate, name, actor, session, binding)?; + if request.action == RecoveryAuditAction::Close { + match &status.state { + None | Some(ScopedUploadState::Open) => { + repository + .scoped_upload_cancel_checked(name, actor, session, binding, || { + admin_identity::authorize_recovery_root(root).map(|_| ()) + }) + .map_err(|error| error.message)?; + status = repository.scoped_upload_observe(&gate, name, actor, session, binding)?; + } + Some(ScopedUploadState::ApplyingV4 { .. }) => { + repository + .scoped_upload_abort_checked(&gate, &scope, || { + admin_identity::authorize_recovery_root(root).map(|_| ()) + }) + .map_err(|error| error.message)?; + status = repository.scoped_upload_observe(&gate, name, actor, session, binding)?; + } + Some(ScopedUploadState::Applying) => { + return Err( + "original upload decision is unresolved; no terminal result can be asserted" + .into(), + ); + } + _ => (), + } + } + // Cleanup uses only an already durable terminal fact. It cannot introduce + // a new reference update, even when the original actor has been revoked. + if matches!( + &status.state, + Some( + ScopedUploadState::Canceled + | ScopedUploadState::Aborted { .. } + | ScopedUploadState::Finished { .. } + | ScopedUploadState::FinishedV4 { .. } + ) + ) { + repository.scoped_upload_cleanup(session)?; + } + let chunk = chunk + .map(|identity| { + repository + .scoped_chunk_query(&gate, identity) + .map_err(|error| error.message) + }) + .transpose()?; + let evidence = match (&chunk, &original.request.operation) { + (Some(status), Operation::UploadChunk { chunk }) => chunk_evidence(status, chunk)?, + _ => upload_evidence(&status, name, session, binding)?, + }; + let state = match status.state { + None => RecoveryUploadState::Unobserved, + Some(ScopedUploadState::Open) => RecoveryUploadState::Open, + Some(ScopedUploadState::Canceled) => RecoveryUploadState::Canceled, + Some(ScopedUploadState::Aborted { .. }) => RecoveryUploadState::Aborted, + Some(ScopedUploadState::Applying | ScopedUploadState::ApplyingV4 { .. }) => { + RecoveryUploadState::Unknown + } + Some(ScopedUploadState::Finished { .. }) => RecoveryUploadState::LegacyFinished, + Some(ScopedUploadState::FinishedV4 { receipt }) => { + receipt.validate()?; + RecoveryUploadState::Finished { receipt } + } + }; + Ok(( + RecoveryState::Upload { + session: session.clone(), + state, + chunk, + }, + evidence, + )) +} + +fn retention( + root: &Path, + repository: &Repository, + name: &str, + actor: &str, + original: &RetentionCommand, + action: RecoveryAuditAction, +) -> Result<(RecoveryState, AuditEvidenceObservation), String> { + let operation = match original { + RetentionCommand::Prepare { operation, .. } + | RetentionCommand::Promote { operation } + | RetentionCommand::Close { operation } => operation, + _ => return Err("retention recovery cannot read program bytes".into()), + }; + let query = RetentionCommand::Query { + operation: operation.clone(), + }; + let mut reply = repository + .release_retention_checked(name, actor, query.clone(), || Ok(())) + .map_err(|e| e.message)?; + reply.validate_for(name, &query)?; + retention_evidence(&reply, name, actor, original)?; + if action == RecoveryAuditAction::Close + && !matches!(&reply, RetentionReply::State { record: Some(record), .. } if record.state == RetentionState::Promoted) + { + reply = repository + .release_retention_checked( + name, + actor, + RetentionCommand::Close { + operation: operation.clone(), + }, + || admin_identity::authorize_recovery_root(root).map(|_| ()), + ) + .map_err(|e| e.message)?; + } + let evidence = retention_evidence(&reply, name, actor, original)?; + match reply { + RetentionReply::State { record, .. } => Ok(( + RecoveryState::Retention { + operation: operation.clone(), + record, + }, + evidence, + )), + _ => Err("unexpected retention recovery result".into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + + struct Temp(PathBuf); + impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-recovery-observation-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + } + impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn recovery_chunk_observation_uses_the_same_native_status_as_rpc() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let payload = b"frozen chunk"; + let binding = protocol::UploadBinding::for_payload( + Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }, + payload, + ) + .unwrap(); + let chunk = ScopedChunkIdentity { + version: 1, + operation_id: "1".repeat(64), + scope: crate::repository::ScopedExecution { + actor: "alice".into(), + repository: "project".into(), + session: "2".repeat(64), + binding, + }, + offset: 0, + payload_sha256: format!("{:x}", Sha256::digest(payload)), + }; + let rpc = Request { + version: 1, + repository: "project".into(), + operation: Operation::UploadChunk { + chunk: chunk.clone(), + }, + }; + let request = OperationRecoveryRequest { + version: 1, + recovery_id: "3".repeat(64), + original: protocol::OperationCredentialRequest { + version: 1, + operation_id: chunk.operation_id.clone(), + policy_generation: 1, + actor: "alice".into(), + token_sha256: "4".repeat(64), + request: rpc.clone(), + payload_sha256: chunk.payload_sha256.clone(), + expires_at: 100, + }, + action: RecoveryAuditAction::Inspect, + reconcile: vec![], + }; + let (_, evidence) = native_state(&temp.0, &request).unwrap(); + assert_eq!(evidence, AuditEvidenceObservation::Unobserved); + + let gate = repo.service_lock(std::time::Duration::ZERO).unwrap(); + repo.scoped_chunk_write(&gate, &chunk, payload, || Ok(())) + .unwrap(); + let rpc_evidence = observe_native(&repo, &gate, "alice", &rpc).unwrap(); + drop(gate); + let (_, recovery_evidence) = native_state(&temp.0, &request).unwrap(); + assert!(matches!( + recovery_evidence, + AuditEvidenceObservation::Observed { .. } + )); + assert_eq!(recovery_evidence, rpc_evidence); + } +} diff --git a/tests/bisect_cli.rs b/tests/bisect_cli.rs index bf1a7ff..027b030 100644 --- a/tests/bisect_cli.rs +++ b/tests/bisect_cli.rs @@ -527,11 +527,12 @@ fn verified_snapshot_and_writer_lock_are_required_but_reset_skips_object_decode( let t = Temp::new(); let c = linear(&t); t.bisect(&["start", &c[6], &c[0]]); - t.write(".wasm-git/write.lock", b"existing external writer\n"); + let held = fs::OpenOptions::new().read(true).write(true).open(t.path(".wasm-git/write.lock")).unwrap(); + held.try_lock().unwrap(); for action in ["status", "good", "reset"] { t.reject(&[action]); } - fs::remove_file(t.path(".wasm-git/write.lock")).unwrap(); + drop(held); let object = t.path(&format!(".wasm-git/objects/{}", c[6])); let original = fs::read(&object).unwrap(); fs::write(&object, b"corrupt committed object").unwrap(); diff --git a/tests/custom_reader_cli.rs b/tests/custom_reader_cli.rs index 885a8ac..e005156 100644 --- a/tests/custom_reader_cli.rs +++ b/tests/custom_reader_cli.rs @@ -436,7 +436,7 @@ fn threshold_and_padded_short_names_stay_original_while_raw_transport_stays_exac assert_eq!(event["edit"]["old_hex"], hex(&old.bytes[a.start..a.end])); assert_eq!(event["edit"]["new_hex"], hex(&new.bytes[b.start..b.end])); } - assert!(!Path::new(&repo).join(".wasm-git/write.lock").exists()); + assert!(Path::new(&repo).join(".wasm-git/write.lock").is_file()); assert_eq!(std::fs::read(old_path).unwrap(), old.bytes); assert_eq!(std::fs::read(new_path).unwrap(), new.bytes); } diff --git a/tests/fixtures/policy-v1.bin b/tests/fixtures/policy-v1.bin new file mode 100644 index 0000000..0d4d6c7 Binary files /dev/null and b/tests/fixtures/policy-v1.bin differ diff --git a/tests/index_listing_cli.rs b/tests/index_listing_cli.rs index 69ee6bc..f57242a 100644 --- a/tests/index_listing_cli.rs +++ b/tests/index_listing_cli.rs @@ -499,10 +499,11 @@ fn unnamed_history_and_malformed_or_unmatched_queries_fail_before_emitting_any_r ] { t.reject(&args); } - fs::write(t.0.join(".wasm-git/index.lock"), b"held").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(t.0.join(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); t.reject(&["--eol"]); t.reject(&["--others", "--directory"]); - fs::remove_file(t.0.join(".wasm-git/index.lock")).unwrap(); + drop(held); } #[test] diff --git a/tests/index_resolve_undo_cli.rs b/tests/index_resolve_undo_cli.rs index f47850a..b1655a7 100644 --- a/tests/index_resolve_undo_cli.rs +++ b/tests/index_resolve_undo_cli.rs @@ -487,10 +487,11 @@ fn malformed_batches_dry_runs_locks_and_clear_controls_preserve_all_other_state( &["update-index", t.root(), "--unresolve", "--stdin", "-z"], Some(b"a.wasm\0../bad\0"), ); - fs::write(t.path(".wasm-git/index.lock"), b"other writer").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(t.path(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); t.reject(&["update-index", t.root(), "--unresolve", "a.wasm"], None); t.reject(&["update-index", t.root(), "--clear-resolve-undo"], None); - fs::remove_file(t.path(".wasm-git/index.lock")).unwrap(); + drop(held); let stages = ok(&["ls-files", t.root(), "--stage"], None); let work = fs::read(t.path("a.wasm")).unwrap(); ok(&["update-index", t.root(), "--clear-resolve-undo"], None); @@ -993,7 +994,8 @@ fn conflict_restore_rejects_invalid_combinations_intents_and_index_locks_before_ t.write("intent.wasm", &wasm(4)); ok(&["add", t.root(), "-N", "intent.wasm"], None); t.reject(&["restore", t.root(), "--merge", "--", "."], None); - fs::write(t.path(".wasm-git/index.lock"), b"another writer").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(t.path(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); t.reject(&["restore", t.root(), "--merge", "--", "a.wasm"], None); } diff --git a/tests/infrastructure/audit_faults.rs b/tests/infrastructure/audit_faults.rs new file mode 100644 index 0000000..fae2516 --- /dev/null +++ b/tests/infrastructure/audit_faults.rs @@ -0,0 +1,14 @@ +//! Real SQLite fault injection at the holder's audit persistence boundary. +use std::path::Path; + +pub fn fail_observations(root: &Path) { + let connection = rusqlite::Connection::open(root.join(".wasm-git-authorization.bin")).unwrap(); + connection.execute_batch("CREATE TRIGGER test_observation_failure BEFORE UPDATE OF observation ON audit_index BEGIN SELECT RAISE(ABORT, 'injected observation failure'); END").unwrap(); +} + +pub fn restore_observations(root: &Path) { + let connection = rusqlite::Connection::open(root.join(".wasm-git-authorization.bin")).unwrap(); + connection + .execute_batch("DROP TRIGGER test_observation_failure") + .unwrap(); +} diff --git a/tests/integration_results_cli.rs b/tests/integration_results_cli.rs new file mode 100644 index 0000000..be42e95 --- /dev/null +++ b/tests/integration_results_cli.rs @@ -0,0 +1,263 @@ +//! The integration consumes native machine results, not CLI prose. +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::io::Write; +use std::path::PathBuf; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use wasm_git::repository::Repository; + +static NEXT: AtomicU64 = AtomicU64::new(0); +const WASM: &[u8] = b"\0asm\x01\0\0\0\0\x02\x01x"; + +struct Temp(PathBuf); +impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-integration-results-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + fn path(&self, name: &str) -> String { + self.0.join(name).to_str().unwrap().into() + } + fn root(&self) -> &str { + self.0.to_str().unwrap() + } +} +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn invoke(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(args) + .output() + .unwrap() +} +fn success(args: &[&str]) -> String { + let output = invoke(args); + assert!( + output.status.success(), + "{args:?}: {} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} +fn invoke_with_input(args: &[&str], input: &str) -> Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(input.as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() +} +fn validate_request(input: &str) -> bool { + invoke_with_input(&["--format", "json", "integration-validate"], input) + .status + .success() +} +fn validate(prefix: &str, raw_response: &str) -> bool { + validate_request(&format!("{prefix},\"response\":{raw_response}}}")) +} + +#[test] +fn actual_tree_sign_and_bundle_results_validate_and_match_published_bytes() { + let t = Temp::new(); + success(&["init", t.root()]); + fs::write(t.path("module.wasm"), WASM).unwrap(); + success(&["add", t.root(), "module.wasm"]); + + let commit_raw = success(&["--format", "json", "commit", t.root(), "-m", "initial"]); + let commit_expected = + r#"{"kind":"tree_commit_cli_reply","head":"main","previous":null,"process_exit":0"#; + assert!(validate(commit_expected, &commit_raw)); + let commit: Value = serde_json::from_str(&commit_raw).unwrap(); + let commit_value = &commit["result"]["value"]; + assert_eq!(commit_value["version"], 1); + let first = commit_value["commit"].as_str().unwrap(); + let repo = Repository::open(t.root()).unwrap(); + assert_eq!(repo.files_at(first).unwrap().files["module.wasm"], WASM); + assert!(repo.read_commit(first).unwrap().commit.parents.is_empty()); + + let key = t.path("author.key"); + let public = t.path("author.pub"); + success(&["keygen", &key, &public]); + let sign_raw = success(&[ + "--format", + "json", + "sign-commit", + t.root(), + first, + "--author", + "Alice", + "--key", + &key, + "--timestamp", + "42", + ]); + let sign_expected = format!( + r#"{{"kind":"sign_commit_cli_reply","head":"main","previous":"{first}","author":"Alice","process_exit":0"# + ); + assert!(validate(&sign_expected, &sign_raw)); + let signed: Value = serde_json::from_str(&sign_raw).unwrap(); + let signed_id = signed["result"]["value"]["commit"].as_str().unwrap(); + assert_ne!(first, signed_id); + assert_eq!( + repo.read_commit(signed_id) + .unwrap() + .commit + .signature + .unwrap() + .author, + "Alice" + ); + assert_eq!(repo.files_at(signed_id).unwrap().files["module.wasm"], WASM); + + let bundle = t.path("out.bundle"); + let bundle_raw = success(&["--format", "json", "bundle", t.root(), &bundle]); + let bundle_expected = format!( + r#"{{"kind":"bundle_cli_reply","head":"main","tip":"{signed_id}","process_exit":0"# + ); + assert!(validate(&bundle_expected, &bundle_raw)); + let result: Value = serde_json::from_str(&bundle_raw).unwrap(); + let result = &result["result"]["value"]; + let actual_bytes = fs::read(&bundle).unwrap(); + assert_eq!(result["bytes"].as_u64().unwrap(), actual_bytes.len() as u64); + assert_eq!( + result["objects"].as_u64().unwrap(), + repo.fsck().unwrap().objects as u64 + ); + assert_eq!( + result["sha256"], + format!("{:x}", Sha256::digest(&actual_bytes)) + ); + assert_eq!( + Repository::bundle_state(&actual_bytes) + .unwrap() + .tip() + .unwrap(), + signed_id + ); + let binding_request = + r#"{"version":1,"operation":{"Push":{"branch":"main","expected":null,"force":false}}}"#; + let binding_output = invoke_with_input( + &["--format", "json", "upload-binding", &bundle], + binding_request, + ); + assert!(binding_output.status.success()); + let binding_raw = std::str::from_utf8(&binding_output.stdout).unwrap(); + let binding_expected = format!( + r#"{{"kind":"upload_binding_cli_reply","request":{binding_request},"process_exit":0"# + ); + assert!(validate(&binding_expected, binding_raw)); + let binding: Value = serde_json::from_str(binding_raw).unwrap(); + let mut pair = json!({"kind":"bundle_upload_binding", "bundle":result, "binding":binding["result"]["value"]}); + assert!(validate_request(&pair.to_string())); + pair["binding"]["digest"] = json!("0".repeat(64)); + assert!(!validate_request(&pair.to_string())); + + assert!(!validate( + &commit_expected.replace("main", "other"), + &commit_raw + )); + assert!(!validate(&sign_expected.replace("Alice", "Bob"), &sign_raw)); + assert!(!validate( + &bundle_expected.replace(signed_id, first), + &bundle_raw + )); + let mut invalid_commit = commit.clone(); + invalid_commit["result"]["value"]["commit"] = json!("not-an-oid"); + assert!(!validate(commit_expected, &invalid_commit.to_string())); + let mut invalid_bundle: Value = serde_json::from_str(&bundle_raw).unwrap(); + invalid_bundle["result"]["value"]["sha256"] = json!("invalid"); + assert!(!validate(&bundle_expected, &invalid_bundle.to_string())); + invalid_bundle["result"]["value"] + .as_object_mut() + .unwrap() + .remove("tip"); + assert!(!validate(&bundle_expected, &invalid_bundle.to_string())); + assert!(!validate( + &bundle_expected.replace("\"process_exit\":0", "\"process_exit\":1"), + &bundle_raw + )); + + let failed = invoke(&[ + "--format", + "json", + "sign-commit", + t.root(), + first, + "--author", + "Alice", + "--key", + &key, + "--timestamp", + "42", + ]); + assert!(!failed.status.success()); + assert!(validate( + &sign_expected.replace("\"process_exit\":0", "\"process_exit\":1"), + std::str::from_utf8(&failed.stdout).unwrap() + )); + let plain_bundle = t.path("plain.bundle"); + assert!(success(&["bundle", t.root(), &plain_bundle]).starts_with("wrote ")); + let plain_sign = success(&[ + "sign-commit", + t.root(), + signed_id, + "--author", + "Alice", + "--key", + &key, + "--timestamp", + "43", + ]); + assert_eq!(plain_sign.trim().len(), 64); +} + +#[test] +fn empty_and_detached_snapshots_keep_native_head_identity() { + let t = Temp::new(); + success(&["init", t.root()]); + let empty_bundle = t.path("empty.bundle"); + let empty = success(&["--format", "json", "bundle", t.root(), &empty_bundle]); + assert!(validate( + r#"{"kind":"bundle_cli_reply","head":"main","tip":null,"process_exit":0"#, + &empty + )); + fs::write(t.path("module.wasm"), WASM).unwrap(); + success(&["add", t.root(), "module.wasm"]); + // The existing text output remains available for native callers. + let plain = success(&["commit", t.root(), "-m", "initial"]); + assert!(plain.starts_with("main ")); + let first = plain.split_whitespace().nth(1).unwrap(); + success(&["checkout", t.root(), "--detach", first]); + fs::write(t.path("module.wasm"), b"\0asm\x01\0\0\0").unwrap(); + success(&["add", t.root(), "module.wasm"]); + let raw = success(&["--format", "json", "commit", t.root(), "-m", "detached"]); + let expected = format!( + r#"{{"kind":"tree_commit_cli_reply","head":"{first}","previous":"{first}","process_exit":0"# + ); + assert!(validate(&expected, &raw)); + let record: Value = serde_json::from_str(&raw).unwrap(); + let next = record["result"]["value"]["commit"].as_str().unwrap(); + let detached_bundle = t.path("detached.bundle"); + let raw_bundle = success(&["--format", "json", "bundle", t.root(), &detached_bundle]); + let expected_bundle = + format!(r#"{{"kind":"bundle_cli_reply","head":"{next}","tip":"{next}","process_exit":0"#); + assert!(validate(&expected_bundle, &raw_bundle)); +} diff --git a/tests/maintenance_cli.rs b/tests/maintenance_cli.rs index 26bbaa9..e4e9fd9 100644 --- a/tests/maintenance_cli.rs +++ b/tests/maintenance_cli.rs @@ -126,9 +126,10 @@ fn cleanup_ignored_only_exclusions_path_scopes_and_worktree_lock_are_exact() { fs::write(root.join(name), name).unwrap(); } let before = snapshot(root); - fs::write(root.join(".wasm-git/index.lock"), b"held").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(root.join(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); assert!(!execute(&["clean", path(root), "-f", "-x"]).status.success()); - fs::remove_file(root.join(".wasm-git/index.lock")).unwrap(); + drop(held); assert_eq!(snapshot(root), before); json(&["clean", path(root), "-f", "-X", "-e", "b.log"]); assert!(!root.join("a.log").exists()); diff --git a/tests/path_transitions_cli.rs b/tests/path_transitions_cli.rs index 56daa5a..3c5b8c6 100644 --- a/tests/path_transitions_cli.rs +++ b/tests/path_transitions_cli.rs @@ -228,14 +228,16 @@ fn index_lock_and_ref_lock_leave_whole_prefix_exchange_unchanged() { let t = Temp::new(); t.history(); ok(&["switch", t.root(), "before"]); - t.write(".wasm-git/index.lock", b"held index lock"); + let held = fs::OpenOptions::new().read(true).write(true).open(t.0.join(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); no_change(&t, &["switch", t.root(), "after"]); no_change(&t, &["reset", t.root(), "--hard", "after"]); - fs::remove_file(t.0.join(".wasm-git/index.lock")).unwrap(); - t.write(".wasm-git/write.lock", b"held repository lock"); + drop(held); + let held = fs::OpenOptions::new().read(true).write(true).open(t.0.join(".wasm-git/write.lock")).unwrap(); + held.try_lock().unwrap(); no_change(&t, &["switch", t.root(), "after"]); no_change(&t, &["reset", t.root(), "--hard", "after"]); - fs::remove_file(t.0.join(".wasm-git/write.lock")).unwrap(); + drop(held); ok(&["switch", t.root(), "after"]); t.assert_after(); } diff --git a/tests/pending_cli.rs b/tests/pending_cli.rs index 9d6aff6..c7edbb5 100644 --- a/tests/pending_cli.rs +++ b/tests/pending_cli.rs @@ -619,11 +619,12 @@ fn invalid_control_forms_help_and_locks_do_not_change_pending_or_tracked_bytes() rejected(&t, &args); } for lock in ["index.lock", "write.lock"] { - t.write(&format!(".wasm-git/{lock}"), b"occupied"); + let held = fs::OpenOptions::new().read(true).write(true).open(t.path(&format!(".wasm-git/{lock}"))).unwrap(); + held.try_lock().unwrap(); rejected(&t, &["merge", t.root(), "--abort"]); rejected(&t, &["merge", t.root(), "--continue", "--resolved-index"]); rejected(&t, &["merge", t.root(), "--quit"]); - fs::remove_file(t.path(&format!(".wasm-git/{lock}"))).unwrap(); + drop(held); } let before = snapshot(&t.repo); ok(&["merge", t.root(), "--continue", "--help"]); diff --git a/tests/plumbing_cli.rs b/tests/plumbing_cli.rs index be1ecc6..4986080 100644 --- a/tests/plumbing_cli.rs +++ b/tests/plumbing_cli.rs @@ -604,14 +604,15 @@ fn index_info_binary_framing_and_batch_errors_keep_index_and_work_bytes_unchange } ok(&["update-index", r, "--index-info"], Some(b"0 0\ta.wasm\n")); assert_eq!(ok(&["ls-files", r], None), ""); - fs::write(root.join(".wasm-git/index.lock"), b"held").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(root.join(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); fail( &["update-index", r, "--index-info"], Some(format!("100644 {one}\ta.wasm\n").as_bytes()), ); assert_eq!( fs::read(root.join(".wasm-git/index.lock")).unwrap(), - b"held" + b"WGTLCK\0\x02" ); } @@ -963,13 +964,14 @@ fn malformed_options_help_literal_messages_and_locks_have_no_side_effects() { serde_json::from_str(&ok(&["cat-file", path(root), "-p", &id], None)).unwrap(); assert_eq!(value["message"], "--help"); let before = files(root); - fs::write(root.join(".wasm-git/write.lock"), b"held").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(root.join(".wasm-git/write.lock")).unwrap(); + held.try_lock().unwrap(); fail( &["hash-object", path(root), "-w", "--stdin"], Some(&wasm(9)), ); assert_eq!(files(root), before); - fs::remove_file(root.join(".wasm-git/write.lock")).unwrap(); + drop(held); fail(&["rev-list", path(root), "--invented"], None); fail(&["read-tree", path(root), "--empty", &tree], None); assert_eq!(files(root), before); diff --git a/tests/policy_migration_cli.rs b/tests/policy_migration_cli.rs new file mode 100644 index 0000000..0307a88 --- /dev/null +++ b/tests/policy_migration_cli.rs @@ -0,0 +1,170 @@ +#![cfg(all(feature = "client", feature = "server"))] +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::Write, + path::{Path, PathBuf}, + process::{Command, Stdio}, +}; +use wasm_git::protocol::{ + CommandEnvelope, PolicyMigrationReceipt, PolicyMigrationRequest, PolicyQueryReply, + PolicyQueryRequest, PolicyStatus, PolicyUpdateOutcome, PolicyUpdateReceipt, + PolicyUpdateRequest, ServerPolicy, SERVER_POLICY_VERSION, +}; + +struct Temp(PathBuf); +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn request_file(root: &Path, name: &str, request: &impl serde::Serialize) -> PathBuf { + let path = root.join(name); + fs::write(&path, serde_json::to_vec(request).unwrap()).unwrap(); + path +} +fn call(command: &str, root: &Path, request: Option<&Path>) -> std::process::Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + child.args(["--format", "json", command]).arg(root); + if let Some(request) = request { + child.arg(request); + } + child.output().unwrap() +} +fn validate(request: &PolicyMigrationRequest, response: &[u8], accepted: bool) { + let value = json!({"kind":"policy_migration_cli_reply", "request":request, "process_exit":0, + "response":serde_json::from_slice::(response).unwrap()}); + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(["--format", "json", "integration-validate"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(&serde_json::to_vec(&value).unwrap()) + .unwrap(); + let result = child.wait_with_output().unwrap(); + assert_eq!( + result.status.success(), + accepted, + "{}", + String::from_utf8_lossy(&result.stdout) + ); +} + +#[test] +fn actual_v1_native_ledger_migrates_without_forgetting_original_decisions() { + // Produced by the pinned auth-fence-v1 server through two real policy-set calls. + let legacy = include_bytes!("fixtures/policy-v1.bin"); + let source_sha256 = format!("{:x}", Sha256::digest(legacy)); + assert_eq!( + source_sha256, + "13e3efb311e04223a598be44b27ef725b9342f64480d15a1400c17c473cafcbe" + ); + let temporary = Temp( + std::env::temp_dir().join(format!("wasm-git-policy-migration-{}", std::process::id())), + ); + fs::create_dir(&temporary.0).unwrap(); + let root = &temporary.0; + let ledger = root.join(".wasm-git-authorization.bin"); + fs::write(&ledger, legacy).unwrap(); + assert!( + !call("policy-status", root, None).status.success(), + "Legacy data must not be silently reset" + ); + let wrong = PolicyMigrationRequest { + version: 1, + source_sha256: "0".repeat(64), + }; + let wrong_path = request_file(root, "wrong.json", &wrong); + assert!(!call("policy-migrate", root, Some(&wrong_path)) + .status + .success()); + assert_eq!(fs::read(&ledger).unwrap(), legacy); + + let request = PolicyMigrationRequest { + version: 1, + source_sha256, + }; + let path = request_file(root, "migration.json", &request); + let result = call("policy-migrate", root, Some(&path)); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stdout) + ); + let envelope: CommandEnvelope = + serde_json::from_slice(&result.stdout).unwrap(); + let receipt = envelope.validate_for("policy-migrate", 0).unwrap().unwrap(); + receipt.validate_request(&request).unwrap(); + assert_eq!(receipt.generation, 1); + assert_eq!(receipt.receipts, 2); + validate(&request, &result.stdout, true); + validate(&wrong, &result.stdout, false); + + let policy = ServerPolicy { + version: SERVER_POLICY_VERSION, + principals: Vec::new(), + }; + for (id, expected_generation, expected_outcome) in [ + ('a', 0, PolicyUpdateOutcome::Applied), + ('b', 7, PolicyUpdateOutcome::GenerationConflict), + ] { + let original = PolicyUpdateRequest { + version: 1, + operation_id: id.to_string().repeat(64), + expected_generation, + policy: policy.clone(), + }; + let query = PolicyQueryRequest { + version: 1, + operation_id: original.operation_id.clone(), + }; + let query_path = request_file(root, "query.json", &query); + let queried = call("policy-query", root, Some(&query_path)); + assert!(queried.status.success()); + let envelope: CommandEnvelope = + serde_json::from_slice(&queried.stdout).unwrap(); + let reply = envelope.validate_for("policy-query", 0).unwrap().unwrap(); + reply.validate_update(&original).unwrap(); + assert_eq!(reply.receipt.as_ref().unwrap().outcome, expected_outcome); + } + let next = PolicyUpdateRequest { + version: 1, + operation_id: "c".repeat(64), + expected_generation: 1, + policy, + }; + let next_path = request_file(root, "next.json", &next); + let committed = call("policy-set", root, Some(&next_path)); + assert!(committed.status.success()); + let envelope: CommandEnvelope = + serde_json::from_slice(&committed.stdout).unwrap(); + let applied = envelope.validate_for("policy-set", 0).unwrap().unwrap(); + applied.validate_update(&next).unwrap(); + assert_eq!(applied.generation, 2); + assert_eq!(applied.outcome, PolicyUpdateOutcome::Applied); + // Retrying a migration after later policy changes reports the original migration. + let replay = call("policy-migrate", root, Some(&path)); + assert!(replay.status.success()); + assert_eq!(replay.stdout, result.stdout); + assert!(!call("policy-migrate", root, Some(&wrong_path)) + .status + .success()); + let status = call("policy-status", root, None); + let envelope: CommandEnvelope = serde_json::from_slice(&status.stdout).unwrap(); + assert_eq!( + envelope + .validate_for("policy-status", 0) + .unwrap() + .unwrap() + .generation, + 2 + ); +} diff --git a/tests/porcelain_cli.rs b/tests/porcelain_cli.rs index 3507809..d1d3bbf 100644 --- a/tests/porcelain_cli.rs +++ b/tests/porcelain_cli.rs @@ -687,7 +687,7 @@ fn metadata_staging_directory_symlink_is_rejected_before_any_write() { ); assert_eq!(fs::read(outside.path("module.wasm")).unwrap(), C); assert_eq!(fs::read_dir(&outside.0).unwrap().count(), 1); - assert!(!Path::new(&temp.path(".wasm-git/index.lock")).exists()); + assert!(Path::new(&temp.path(".wasm-git/index.lock")).is_file()); } #[test] diff --git a/tests/query_cli.rs b/tests/query_cli.rs index 3058eee..bc20b59 100644 --- a/tests/query_cli.rs +++ b/tests/query_cli.rs @@ -1143,6 +1143,7 @@ fn explicit_branch_and_filtered_reference_queries_never_hide_repository_corrupti (".wasm-git/write.lock", b"other writer".as_slice()), (".wasm-git/upstreams.bin", b"{broken upstream".as_slice()), ] { + let original = fs::read(t.path(path)).ok(); t.write(path, bytes); for command in ["branch", "for-each-ref"] { t.reject(&[ @@ -1153,7 +1154,11 @@ fn explicit_branch_and_filtered_reference_queries_never_hide_repository_corrupti "no-match", ]); } - fs::remove_file(t.path(path)).unwrap(); + if let Some(original) = original { + t.write(path, &original); + } else { + fs::remove_file(t.path(path)).unwrap(); + } } t.write( &format!(".wasm-git/objects/{}", h.tip), diff --git a/tests/rebase_pending_cli.rs b/tests/rebase_pending_cli.rs index b304deb..6e590f0 100644 --- a/tests/rebase_pending_cli.rs +++ b/tests/rebase_pending_cli.rs @@ -675,11 +675,12 @@ fn pending_controls_locks_partial_status_and_history_guards_are_consistent() { t.stage("a.wasm", UNKNOWN); ok(&["reset", t.root(), "--", "a.wasm"]); ok(&["restore", t.root(), "--", "a.wasm"]); - fs::write(t.path(".wasm-git/index.lock"), b"external index owner").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(t.path(".wasm-git/index.lock")).unwrap(); + held.try_lock().unwrap(); rejected(&t, &["rebase", t.root(), "--skip"]); rejected(&t, &["rebase", t.root(), "--abort"]); rejected(&t, &["rebase", t.root(), "--quit"]); - fs::remove_file(t.path(".wasm-git/index.lock")).unwrap(); + drop(held); fs::write(t.path(".wasm-git/index"), b"corrupt").unwrap(); let partial = value(&["status", t.root()]); assert_eq!(partial["index_available"], false); diff --git a/tests/ref_transactions_cli.rs b/tests/ref_transactions_cli.rs index 7796199..655a248 100644 --- a/tests/ref_transactions_cli.rs +++ b/tests/ref_transactions_cli.rs @@ -41,8 +41,17 @@ fn execute(args: &[&str], input: &[u8]) -> Output { .stderr(Stdio::piped()) .spawn() .unwrap(); - child.stdin.take().unwrap().write_all(input).unwrap(); - child.wait_with_output().unwrap() + let write_result = child.stdin.take().unwrap().write_all(input); + let output = child.wait_with_output().unwrap(); + if let Err(error) = write_result { + assert!( + error.kind() == std::io::ErrorKind::BrokenPipe && !output.status.success(), + "{args:?}: write stdin: {error}; exit: {}; stderr: {}", + output.status, + String::from_utf8_lossy(&output.stderr) + ); + } + output } fn ok(args: &[&str]) -> String { let output = execute(args, &[]); @@ -320,7 +329,7 @@ fn prepare_acknowledgement_holds_writer_lock_until_commit_and_never_publishes_ea "{}", String::from_utf8_lossy(&output.stderr) ); - assert!(!root.join(".wasm-git/write.lock").exists()); + assert!(root.join(".wasm-git/write.lock").is_file()); assert_eq!(ok(&["rev-parse", p(&root), "held"]), second); } @@ -762,7 +771,7 @@ fn partial_prepare_holds_the_shared_lock_and_reports_rejections_only_after_commi "{}", String::from_utf8_lossy(&output.stderr) ); - assert!(!root.join(".wasm-git/write.lock").exists()); + assert!(root.join(".wasm-git/write.lock").is_file()); assert!(!root.join(".wasm-git/ref-transaction.bin").exists()); assert_eq!( root.join(".wasm-git/tags/accepted").exists(), diff --git a/tests/replay_resolution_cli.rs b/tests/replay_resolution_cli.rs index 49ce6ae..ca4a1d4 100644 --- a/tests/replay_resolution_cli.rs +++ b/tests/replay_resolution_cli.rs @@ -498,7 +498,8 @@ fn missing_invalid_or_locked_index_and_unborn_head_never_publish_a_resolution() ); for name in ["index.lock", "write.lock"] { let lock = t.path(&format!(".wasm-git/{name}")); - fs::write(&lock, b"held fixed lock").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(&lock).unwrap(); + held.try_lock().unwrap(); unchanged( &t, &[ @@ -510,7 +511,7 @@ fn missing_invalid_or_locked_index_and_unborn_head_never_publish_a_resolution() &head, ], ); - fs::remove_file(lock).unwrap(); + drop(held); } let index = t.path(".wasm-git/index"); let original = fs::read(&index).unwrap(); diff --git a/tests/server_chunk_receipts.rs b/tests/server_chunk_receipts.rs new file mode 100644 index 0000000..df0e7fd --- /dev/null +++ b/tests/server_chunk_receipts.rs @@ -0,0 +1,1564 @@ +#![cfg(all(feature = "client", feature = "server", unix))] +//! Real strict HTTP/CLI tests for scoped chunk outcomes. + +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::{BufRead, BufReader, Read, Write}, + net::{Shutdown, TcpListener, TcpStream}, + path::{Path, PathBuf}, + process::{Child, Command, Output, Stdio}, + sync::{ + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use wasm_git::{ + binary, + protocol::{ + self, Operation, OperationCredentialRequest, RefNamespace, Request, Response, + ScopedChunkIdentity, ScopedChunkState, ScopedChunkStatus, UploadBinding, + }, + repository::Repository, +}; + +const WASM: &[u8] = b"\0asm\x01\0\0\0"; +#[path = "infrastructure/audit_faults.rs"] +mod audit_faults; +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Https { + child: Child, + address: String, + certificate: PathBuf, +} +impl Https { + fn start(root: &Path, backend: &str) -> Self { + let certificate = root.join("test-ca.pem"); + let key = root.join("test-key.pem"); + let mut openssl = Command::new("openssl"); + openssl + .args([ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "1", + "-subj", + "/CN=localhost", + "-addext", + "subjectAltName=IP:127.0.0.1,DNS:localhost", + "-keyout", + ]) + .arg(&key) + .arg("-out") + .arg(&certificate); + let output = bounded_output(openssl, None); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let mut child = Command::new("python3") + .arg("-u") + .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/https_proxy.py")) + .arg(&certificate) + .arg(&key) + .arg(backend) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + let stdout = child.stdout.take().unwrap(); + let (send, receive) = mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut address = String::new(); + let result = BufReader::new(stdout) + .read_line(&mut address) + .map(|_| address); + let _ = send.send(result); + }); + let address = match receive.recv_timeout(Duration::from_secs(10)) { + Ok(Ok(address)) if !address.trim().is_empty() => address.trim().to_owned(), + error => { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + panic!("TLS proxy startup failed: {error:?}"); + } + }; + reader.join().unwrap(); + Self { + child, + address, + certificate, + } + } + + fn rpc(&self, token: &str, request: &Request, payload: &[u8]) -> Wire { + let mut curl = Command::new("curl"); + curl.args([ + "-q", + "--noproxy", + "*", + "--silent", + "--show-error", + "--max-time", + "25", + "--include", + "--cacert", + ]) + .arg(&self.certificate) + .args([ + "--header", + &format!("Authorization: Bearer {token}"), + "--header", + "Expect:", + "--data-binary", + "@-", + ]) + .arg(format!("https://{}/v1/wasm-git", self.address)); + let output = bounded_output(curl, Some(&packet(request, payload))); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let offset = output + .stdout + .windows(4) + .position(|v| v == b"\r\n\r\n") + .unwrap() + + 4; + let status = std::str::from_utf8(&output.stdout[..offset]) + .unwrap() + .lines() + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); + Wire { + status, + body: output.stdout[offset..].to_vec(), + } + } +} +impl Drop for Https { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn recovery( + root: &Path, + recovery_id: u64, + original: &OperationCredentialRequest, + close: bool, + reconcile: Vec, +) -> Value { + let input = json!({"version":1,"recovery_id":id(recovery_id),"original":original, + "action":if close {"Close"} else {"Inspect"},"reconcile":reconcile}); + let result = success(command(root, "operation-recover", &input)); + validate( + json!({"kind":"operation_recovery_cli_reply","request":input,"process_exit":0,"response":result}), + ); + result["result"]["value"].clone() +} + +fn audit_rows(root: &Path) -> Vec { + let mut items = Vec::new(); + let mut after = 0; + let mut high_water = None; + loop { + let input = json!({"version":1,"after":after,"high_water":high_water,"limit":2}); + let result = success(command(root, "audit-query", &input)); + validate( + json!({"kind":"audit_query_cli_reply","request":input,"process_exit":0,"response":result}), + ); + let value = &result["result"]["value"]; + high_water = value["high_water"].as_u64(); + items.extend(value["items"].as_array().unwrap().iter().cloned()); + match value["next_after"].as_u64() { + Some(next) => { + assert!(next > after); + after = next; + } + None => break, + } + assert!(items.len() < 1000, "audit pagination did not terminate"); + } + items +} + +#[test] +#[cfg(target_os = "linux")] +fn https_revoked_actor_recovery_closes_only_original_scope_and_keeps_chunk_evidence() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let head = repo.commit(WASM, "base").unwrap(); + Repository::init(temp.0.join("other")).unwrap(); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + let https = Https::start(&temp.0, &server.address); + let bytes = vec![42; 4096]; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head), + force: false, + }, + &bytes, + ) + .unwrap(); + let original_chunk = chunk(301, "alice", "project", &id(401), &binding, 0, &bytes); + let upload = issuance( + 301, + "alice", + "recover-alice", + upload_request(&original_chunk), + &bytes, + now() + 120, + ); + issue(&temp.0, &upload); + // Do not retain the application's receipt: recovery must find the durable fact. + assert_eq!( + https.rpc("recover-alice", &upload.request, &bytes).status, + 200 + ); + let bob_query = issuance( + 302, + "bob", + "recover-bob", + query_request(&original_chunk), + &[], + now() + 120, + ); + assert!(!command(&temp.0, "operation-credential-issue", &bob_query) + .status + .success()); + set_policy(&temp.0, 1, false, false); + https.rpc("recover-alice", &upload.request, &bytes).denied(); + let state = recovery(&temp.0, 501, &upload, false, vec![]); + assert_eq!(state["state"]["Upload"]["state"], "Open"); + assert_eq!( + state["state"]["Upload"]["chunk"]["state"], + json!({"Accepted":{"data":"Available"}}) + ); + assert!(state["operator"]["identity"] + .as_str() + .unwrap() + .starts_with("unix:uid:")); + for field in ["actor", "repository", "binding"] { + let mut changed = serde_json::to_value(&upload).unwrap(); + match field { + "actor" => changed["actor"] = json!("bob"), + "repository" => changed["request"]["repository"] = json!("other"), + _ => { + changed["request"]["operation"]["UploadChunk"]["chunk"]["scope"]["binding"] + ["digest"] = json!(id(999)) + } + } + assert!(!command( + &temp.0, + "operation-recover", + &json!({"version":1,"recovery_id":id(502),"original":changed,"action":"Close"}) + ) + .status + .success()); + } + let closed = recovery(&temp.0, 503, &upload, true, vec![]); + assert_eq!(closed["state"]["Upload"]["state"], "Canceled"); + assert_eq!( + closed["state"]["Upload"]["chunk"]["state"], + json!({"Accepted":{"data":{"Cleaned":{"reason":"Canceled"}}}}) + ); + drop(https); + drop(server); + let _restarted = Server::start(&temp.0); + assert_eq!( + recovery(&temp.0, 503, &upload, true, vec![])["state"], + closed["state"] + ); + let rows = audit_rows(&temp.0); + assert!(rows.iter().any( + |row| row["item"]["Policy"]["attribution"]["Recorded"]["operator"]["identity"].is_string() + )); + assert!(rows + .iter() + .any(|row| row["item"]["RecoveryAttempt"]["original_operation_id"] == id(301))); + let input = json!({"version":1,"repository":"other"}); + let capacity = success(command(&temp.0, "capacity-query", &input)); + validate( + json!({"kind":"capacity_query_cli_reply","request":input,"process_exit":0,"response":capacity}), + ); + assert_eq!( + capacity["result"]["value"]["capacity"]["scoped"]["total_records"], + 0 + ); +} + +#[test] +#[cfg(target_os = "linux")] +fn close_before_first_chunk_fences_late_effect_and_audit_failures_are_reconciled() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let head = repo.commit(WASM, "base").unwrap(); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + let https = Https::start(&temp.0, &server.address); + let bytes = vec![42; 4096]; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head), + force: false, + }, + &bytes, + ) + .unwrap(); + let original = chunk(601, "alice", "project", &id(701), &binding, 0, &bytes); + let first = issuance( + 601, + "alice", + "late-chunk", + upload_request(&original), + &bytes, + now() + 120, + ); + issue(&temp.0, &first); + let closed = recovery(&temp.0, 801, &first, true, vec![]); + assert_eq!(closed["state"]["Upload"]["state"], "Canceled"); + https.rpc("late-chunk", &first.request, &bytes).denied(); + assert_eq!( + recovery(&temp.0, 802, &first, false, vec![])["state"]["Upload"]["chunk"]["state"], + "Unobserved" + ); + + let original = chunk(602, "alice", "project", &id(702), &binding, 0, &bytes); + let second = issuance( + 602, + "alice", + "audit-failure", + upload_request(&original), + &bytes, + now() + 120, + ); + issue(&temp.0, &second); + audit_faults::fail_observations(&temp.0); + let response = https + .rpc("audit-failure", &second.request, &bytes) + .packet() + .0; + assert!(!response.ok && response.publication_unknown, "{response:?}"); + audit_faults::restore_observations(&temp.0); + drop(https); + drop(server); + let rows = audit_rows(&temp.0); + let pending = rows + .iter() + .find(|row| { + row["item"]["OperationAttempt"]["operation_id"] == id(602) + && row["item"]["OperationAttempt"]["observation"].is_null() + }) + .unwrap(); + let attempt = pending["sequence"].as_u64().unwrap(); + let result = recovery( + &temp.0, + 803, + &second, + true, + vec![json!({"Operation":{"operation_id":id(602),"attempt_id":attempt}})], + ); + assert_eq!( + result["state"]["Upload"]["chunk"]["state"], + json!({"Accepted":{"data":{"Cleaned":{"reason":"Canceled"}}}}) + ); + let rows = audit_rows(&temp.0); + let repaired = rows.iter().find(|row| row["sequence"] == attempt).unwrap(); + assert!( + repaired["item"]["OperationAttempt"]["observation"]["source"]["RecoveryAttempt"] + .is_object() + ); + let repeated = recovery( + &temp.0, + 803, + &second, + true, + vec![json!({"Operation":{"operation_id":id(602),"attempt_id":attempt}})], + ); + assert_eq!(repeated["state"], result["state"]); + let input = json!({"version":1,"operation_id":id(602)}); + let context = success(command(&temp.0, "operation-context", &input)); + validate( + json!({"kind":"operation_context_cli_reply","request":input,"process_exit":0,"response":context}), + ); + assert_eq!( + context["result"]["value"]["original"], + serde_json::to_value(second).unwrap() + ); +} + +#[test] +#[cfg(target_os = "linux")] +fn retention_recovery_never_promotes_or_releases_an_already_committed_reference() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let tree = repo + .create_files_tree(&std::collections::BTreeMap::from([( + "main.wasm".into(), + WASM.to_vec(), + )])) + .unwrap(); + let commit = repo.create_commit_object(&tree, &[], "release").unwrap(); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + let https = Https::start(&temp.0, &server.address); + let prepare = issuance( + 901, + "alice", + "retention-prepare", + request( + "project", + json!({"ReleaseRetention":{"command":{ + "Prepare":{"operation":id(902),"commit":commit,"paths":["main.wasm"]}}} }), + ), + &[], + now() + 120, + ); + issue(&temp.0, &prepare); + assert!( + https + .rpc("retention-prepare", &prepare.request, &[]) + .packet() + .0 + .ok + ); + let promote = issuance( + 903, + "alice", + "retention-promote", + request( + "project", + json!({"ReleaseRetention":{"command":{ + "Promote":{"operation":id(902)}}} }), + ), + &[], + now() + 120, + ); + issue(&temp.0, &promote); + assert!( + https + .rpc("retention-promote", &promote.request, &[]) + .packet() + .0 + .ok + ); + let unseen = issuance( + 904, + "alice", + "unseen-retention", + request( + "project", + json!({"ReleaseRetention":{"command":{ + "Prepare":{"operation":id(905),"commit":commit,"paths":["main.wasm"]}}} }), + ), + &[], + now() + 120, + ); + issue(&temp.0, &unseen); + assert_eq!( + recovery(&temp.0, 906, &unseen, true, vec![])["state"]["Retention"]["record"]["state"], + "Closed" + ); + https.rpc("unseen-retention", &unseen.request, &[]).denied(); + set_policy(&temp.0, 1, false, false); + let result = recovery(&temp.0, 907, &prepare, true, vec![]); + assert_eq!(result["state"]["Retention"]["record"]["state"], "Promoted"); + assert_eq!(result["state"]["Retention"]["record"]["commit"], commit); + repo.garbage_collect_mode(&[], true, true).unwrap(); + repo.read_commit(&commit).unwrap(); + repo.query_tree(&commit).unwrap(); + let invalid = json!({"version":1,"recovery_id":id(908),"original":prepare,"action":"Promote"}); + assert!(!command(&temp.0, "operation-recover", &invalid) + .status + .success()); +} + +struct Temp(PathBuf); +impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-chunk-receipts-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + use std::os::unix::fs::DirBuilderExt; + fs::DirBuilder::new().mode(0o700).create(&path).unwrap(); + Self(path) + } +} +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn id(value: u64) -> String { + format!("{value:064x}") +} +fn hash(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() +} + +fn wait_until(expiry: u64) { + let deadline = Instant::now() + Duration::from_secs(25); + while now() < expiry { + assert!( + Instant::now() < deadline, + "clock did not reach credential expiry" + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn bounded_output(mut command: Command, input: Option<&[u8]>) -> Output { + command.stdout(Stdio::piped()).stderr(Stdio::piped()); + command.stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }); + let mut child = command.spawn().unwrap(); + if let Some(input) = input { + if let Err(error) = child.stdin.take().unwrap().write_all(input) { + let _ = child.kill(); + let _ = child.wait(); + panic!("write command input: {error}"); + } + } + let deadline = Instant::now() + Duration::from_secs(35); + loop { + match child.try_wait() { + Ok(Some(_)) => return child.wait_with_output().unwrap(), + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)), + result => { + let _ = child.kill(); + let output = child.wait_with_output().unwrap(); + panic!( + "command did not finish ({result:?}): {}", + String::from_utf8_lossy(&output.stderr) + ); + } + } + } +} + +fn command(root: &Path, name: &str, input: &impl serde::Serialize) -> Output { + let path = root.join(format!( + "request-{}.json", + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::write(&path, serde_json::to_vec(input).unwrap()).unwrap(); + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + process.args(["--format", "json", name]).arg(root).arg(path); + bounded_output(process, None) +} + +fn success(output: Output) -> Value { + assert!( + output.status.success(), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn validate(value: Value) { + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git")); + process.args(["--format", "json", "integration-validate"]); + let output = bounded_output(process, Some(&serde_json::to_vec(&value).unwrap())); + assert!( + output.status.success(), + "validator: {}", + String::from_utf8_lossy(&output.stdout) + ); +} + +fn reject_validation(input: &[u8]) { + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git")); + process.args(["--format", "json", "integration-validate"]); + let output = bounded_output(process, Some(input)); + assert!( + !output.status.success(), + "invalid input passed validation: {}", + String::from_utf8_lossy(input) + ); +} + +fn set_policy(root: &Path, generation: u64, alice_exists: bool, alice_can_write: bool) { + let grant = json!({"repository":"*", "read":true, "write":["refs/heads/*"], + "force":false, "create":false, "release_retention":true}); + let mut principals = + vec![json!({"name":"bob", "token_sha256":hash(b"bob-legacy"), "grants":[grant.clone()]})]; + if alice_exists { + let mut alice_grant = grant; + if !alice_can_write { + alice_grant["write"] = json!([]); + } + principals.push( + json!({"name":"alice", "token_sha256":hash(b"alice-legacy"), "grants":[alice_grant]}), + ); + } + let policy = json!({"version":3, "principals":principals}); + let result = success(command( + root, + "policy-set", + &json!({"version":1, + "operation_id":id(9000 + generation), "expected_generation":generation, "policy":policy}), + )); + assert_eq!(result["result"]["value"]["outcome"], "applied"); +} + +fn request(repository: &str, operation: Value) -> Request { + serde_json::from_value(json!({"version":1, "repository":repository, "operation":operation})) + .unwrap() +} + +fn issuance( + number: u64, + actor: &str, + token: &str, + request: Request, + payload: &[u8], + expiry: u64, +) -> OperationCredentialRequest { + OperationCredentialRequest { + version: 1, + operation_id: id(number), + policy_generation: 1, + actor: actor.into(), + token_sha256: hash(token.as_bytes()), + request, + payload_sha256: hash(payload), + expires_at: expiry, + } +} + +fn issue(root: &Path, request: &OperationCredentialRequest) { + let result = success(command(root, "operation-credential-issue", request)); + validate( + json!({"kind":"operation_credential_issue_cli_reply", "request":request, + "process_exit":0, "response":result}), + ); +} + +struct Server { + child: Child, + address: String, +} +impl Server { + fn start(root: &Path) -> Self { + let mut command = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + command.args([ + "--root", + root.to_str().unwrap(), + "--listen", + "127.0.0.1:0", + "--allow-write", + "--policy", + root.join("unused-bootstrap").to_str().unwrap(), + "--require-operation-credentials", + ]); + let mut child = command + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + let output = child.stdout.take().unwrap(); + let (send, receive) = mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut line = String::new(); + let result = BufReader::new(output).read_line(&mut line).map(|_| line); + let _ = send.send(result); + }); + let line = match receive.recv_timeout(Duration::from_secs(15)) { + Ok(Ok(line)) => line, + other => { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + panic!("server readiness failed: {other:?}"); + } + }; + reader.join().unwrap(); + let parsed: Value = match serde_json::from_str(&line) { + Ok(value) => value, + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + panic!("invalid server readiness {line:?}: {error}"); + } + }; + let address = match parsed["listen"].as_str() { + Some(address) => address.to_owned(), + None => { + let _ = child.kill(); + let _ = child.wait(); + panic!("missing listen address in readiness: {parsed}"); + } + }; + Self { child, address } + } +} +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +struct Wire { + status: u16, + body: Vec, +} +impl Wire { + fn packet(self) -> (Response, Vec) { + assert_eq!(self.status, 200, "{}", String::from_utf8_lossy(&self.body)); + protocol::read_complete_packet(&self.body).unwrap() + } + fn denied(self) { + if self.status == 200 { + let (response, _) = protocol::read_complete_packet::(&self.body).unwrap(); + assert!(!response.ok, "unexpected successful response: {response:?}"); + } else { + assert!( + matches!(self.status, 401 | 403), + "unexpected HTTP {}: {}", + self.status, + String::from_utf8_lossy(&self.body) + ); + } + } +} + +fn packet(request: &Request, payload: &[u8]) -> Vec { + let mut packet = Vec::new(); + protocol::write_packet(&mut packet, request, payload).unwrap(); + packet +} + +fn connect(address: &str, token: &str, request: &Request, payload: &[u8]) -> TcpStream { + let packet = packet(request, payload); + let mut stream = TcpStream::connect(address).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(25))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(15))) + .unwrap(); + write!(stream, "POST /v1/wasm-git HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {token}\r\nContent-Length: {}\r\n\r\n", packet.len()).unwrap(); + stream.write_all(&packet).unwrap(); + stream.shutdown(Shutdown::Write).unwrap(); + stream +} + +fn rpc(address: &str, token: &str, request: &Request, payload: &[u8]) -> Wire { + let mut stream = connect(address, token, request, payload); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).unwrap(); + let offset = bytes + .windows(4) + .position(|b| b == b"\r\n\r\n") + .expect("HTTP headers") + + 4; + let status = std::str::from_utf8(&bytes[..offset]) + .unwrap() + .lines() + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); + Wire { + status, + body: bytes[offset..].to_vec(), + } +} + +fn assert_unauthenticated_token(address: &str, token: &str) { + let mut stream = TcpStream::connect(address).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(15))) + .unwrap(); + write!(stream, "POST /v1/wasm-git HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {token}\r\nContent-Length: 0\r\n\r\n").unwrap(); + stream.shutdown(Shutdown::Write).unwrap(); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).unwrap(); + assert!( + bytes.starts_with(b"HTTP/1.1 401"), + "{}", + String::from_utf8_lossy(&bytes) + ); +} + +// Consume only HTTP headers and deliberately discard the binary receipt. The +// server has completed the request, but the caller has no application result. +fn lose_reply(address: &str, token: &str, request: &Request, payload: &[u8]) { + let mut stream = connect(address, token, request, payload); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + assert!(headers.len() < 8192, "oversized HTTP headers"); + let mut byte = [0]; + stream.read_exact(&mut byte).unwrap(); + headers.push(byte[0]); + } + assert!(headers.starts_with(b"HTTP/1.1 200")); + drop(stream); +} + +fn chunk( + number: u64, + actor: &str, + repository: &str, + session: &str, + binding: &UploadBinding, + offset: u64, + payload: &[u8], +) -> Value { + json!({"version":1, "operation_id":id(number), "scope":{ + "actor":actor, "repository":repository, "session":session, "binding":binding + }, "offset":offset, "payload_sha256":hash(payload)}) +} + +fn upload_request(chunk: &Value) -> Request { + request( + chunk["scope"]["repository"].as_str().unwrap(), + json!({"UploadChunk":{"chunk":chunk}}), + ) +} + +fn query_request(chunk: &Value) -> Request { + request( + chunk["scope"]["repository"].as_str().unwrap(), + json!({"QueryChunk":{"chunk":chunk}}), + ) +} + +fn chunk_cli(address: &str, repository: &str, token: &str, command: Value) -> Value { + let input = json!({"version":1, "command":command}); + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git")); + process.args([ + "--format", + "json", + "scoped-upload-rpc", + &format!("http://{address}/{repository}"), + ]); + process.env("WASM_GIT_REMOTE_TOKEN", token); + let result = success(bounded_output( + process, + Some(&serde_json::to_vec(&input).unwrap()), + )); + validate( + json!({"kind":"upload_cli_reply", "repository":repository, "request":input, + "process_exit":0, "response":result}), + ); + result["result"]["value"]["Chunk"]["status"].clone() +} + +fn query_cli(address: &str, repository: &str, token: &str, chunk: &Value) -> Value { + chunk_cli( + address, + repository, + token, + json!({"QueryChunk":{"chunk":chunk}}), + ) +} + +fn assert_status(actual: Value, chunk: &Value, state: Value) { + assert_eq!(actual, json!({"version":1, "chunk":chunk, "state":state})); +} + +fn assert_claim_denied( + root: &Path, + address: &str, + chunk: &Value, + actor: &str, + number: u64, +) -> (u16, String) { + let token = format!("wrong-claim-{number}"); + let request = query_request(chunk); + issue( + root, + &issuance(number, actor, &token, request.clone(), &[], now() + 120), + ); + let reply = rpc(address, &token, &request, &[]); + if reply.status == 200 { + let (response, payload) = reply.packet(); + assert!( + !response.ok && !response.publication_unknown && payload.is_empty(), + "{response:?}" + ); + (200, response.error.unwrap_or_default()) + } else { + assert!( + matches!(reply.status, 401 | 403), + "unexpected HTTP {}", + reply.status + ); + (reply.status, String::from_utf8(reply.body).unwrap()) + } +} + +fn fake_chunk_reply(input: &Value, payload: Vec, outcome_unknown: bool) -> Output { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap(); + let worker = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(15); + let mut stream = loop { + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) + if error.kind() == std::io::ErrorKind::WouldBlock + && Instant::now() < deadline => + { + std::thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("fake HTTP server failed to accept: {error}"), + } + }; + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(15))) + .unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + assert!(headers.len() < 8192, "oversized HTTP request headers"); + let mut byte = [0]; + stream.read_exact(&mut byte).unwrap(); + headers.push(byte[0]); + } + let length: usize = std::str::from_utf8(&headers) + .unwrap() + .lines() + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .expect("content length") + .1 + .trim() + .parse() + .unwrap(); + assert!(length <= protocol::MAX_PACKET_BYTES); + let mut request = vec![0; length]; + stream.read_exact(&mut request).unwrap(); + let (request, _): (Request, Vec) = protocol::read_complete_packet(&request).unwrap(); + assert!(matches!(request.operation, Operation::UploadChunk { .. })); + let response = Response { + version: 1, + ok: !outcome_unknown, + publication_unknown: outcome_unknown, + error: outcome_unknown.then(|| "authorization unavailable before delivery".into()), + state: None, + tip: None, + }; + let mut body = Vec::new(); + protocol::write_packet(&mut body, &response, &payload).unwrap(); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .unwrap(); + stream.write_all(&body).unwrap(); + }); + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git")); + process.args([ + "--format", + "json", + "scoped-upload-rpc", + &format!("http://{address}/project"), + ]); + process.env("WASM_GIT_REMOTE_TOKEN", "fake-token"); + let result = bounded_output(process, Some(&serde_json::to_vec(input).unwrap())); + worker.join().unwrap(); + result +} + +#[test] +fn chunk_cli_reports_unknown_after_invalid_or_uncertain_acknowledgement() { + let bytes = b"original chunk"; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: None, + force: false, + }, + bytes, + ) + .unwrap(); + let identity = chunk(41, "alice", "project", &id(104), &binding, 0, bytes); + let input = json!({"version":1, "command":{"Chunk":{"chunk":identity, "bytes":bytes}}}); + let status = ScopedChunkStatus { + version: 1, + chunk: serde_json::from_value::(identity).unwrap(), + state: ScopedChunkState::Unobserved, + }; + for (payload, outcome_unknown) in [ + (vec![0xff], false), + (binary::encode(&status).unwrap(), false), + (Vec::new(), true), + ] { + let output = fake_chunk_reply(&input, payload, outcome_unknown); + assert!( + !output.status.success(), + "invalid acknowledgement was accepted" + ); + let message = format!( + "{} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) + .to_lowercase(); + assert!( + message.contains("unknown") && message.contains("query"), + "{message}" + ); + } +} + +#[test] +fn chunk_validator_rejects_unknown_duplicate_and_mismatched_fields() { + let bytes = b"chunk"; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: None, + force: false, + }, + bytes, + ) + .unwrap(); + let identity = chunk(51, "alice", "project", &id(105), &binding, 0, bytes); + let valid = json!({"kind":"chunk_identity", "chunk":identity}); + validate(valid.clone()); + let mut unknown = valid.clone(); + unknown["chunk"]["scope"]["extra"] = json!(true); + reject_validation(&serde_json::to_vec(&unknown).unwrap()); + let serialized = serde_json::to_string(&valid).unwrap(); + let duplicate = serialized.replacen( + "\"operation_id\":", + &format!("\"operation_id\":\"{}\",\"operation_id\":", id(51)), + 1, + ); + assert_ne!(duplicate, serialized); + reject_validation(duplicate.as_bytes()); + let mut wrong = identity.clone(); + wrong["scope"]["actor"] = json!("bob"); + let bad_status = json!({"kind":"chunk_status", "chunk":identity, + "status":{"version":1, "chunk":wrong, "state":"Unobserved"}}); + reject_validation(&serde_json::to_vec(&bad_status).unwrap()); +} + +#[test] +fn lost_chunk_reply_can_be_queried_after_expiry_and_cancel() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let head = repo.commit(WASM, "base").unwrap(); + Repository::init(temp.0.join("other")).unwrap(); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + + let bytes = vec![42; protocol::TRANSFER_CHUNK + 17]; + let operation = Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head), + force: false, + }; + let binding = UploadBinding::for_payload(operation, &bytes).unwrap(); + let session = id(100); + let first = chunk( + 1, + "alice", + "project", + &session, + &binding, + 0, + &bytes[..protocol::TRANSFER_CHUNK], + ); + let first_request = upload_request(&first); + let expiry = now() + 10; + // Neither a replacement original operation id nor another payload digest + // may mint a credential for this identity. + assert!(!command( + &temp.0, + "operation-credential-issue", + &issuance( + 9, + "alice", + "wrong-id", + first_request.clone(), + &bytes[..protocol::TRANSFER_CHUNK], + now() + 120 + ) + ) + .status + .success()); + assert!(!command( + &temp.0, + "operation-credential-issue", + &issuance( + 1, + "alice", + "wrong-payload", + first_request.clone(), + b"different bytes", + now() + 120 + ) + ) + .status + .success()); + issue( + &temp.0, + &issuance( + 1, + "alice", + "first-upload", + first_request.clone(), + &bytes[..protocol::TRANSFER_CHUNK], + expiry, + ), + ); + let mut replacement = first.clone(); + replacement["operation_id"] = json!(id(8)); + assert!(!command( + &temp.0, + "operation-credential-issue", + &issuance( + 8, + "alice", + "replacement-id", + upload_request(&replacement), + &bytes[..protocol::TRANSFER_CHUNK], + now() + 120 + ) + ) + .status + .success()); + let mut changed_bytes = bytes[..protocol::TRANSFER_CHUNK].to_vec(); + changed_bytes[0] ^= 1; + replacement["payload_sha256"] = json!(hash(&changed_bytes)); + assert!(!command( + &temp.0, + "operation-credential-issue", + &issuance( + 8, + "alice", + "replacement-bytes", + upload_request(&replacement), + &changed_bytes, + now() + 120 + ) + ) + .status + .success()); + lose_reply( + &server.address, + "first-upload", + &first_request, + &bytes[..protocol::TRANSFER_CHUNK], + ); + + // This operation was issued but never sent. Unobserved is not a terminal + // decision and must remain distinct from an accepted or cleaned chunk. + let second = chunk( + 2, + "alice", + "project", + &session, + &binding, + protocol::TRANSFER_CHUNK as u64, + &bytes[protocol::TRANSFER_CHUNK..], + ); + let second_request = upload_request(&second); + issue( + &temp.0, + &issuance( + 2, + "alice", + "second-upload", + second_request.clone(), + &bytes[protocol::TRANSFER_CHUNK..], + now() + 120, + ), + ); + let second_query = query_request(&second); + issue( + &temp.0, + &issuance(201, "alice", "second-query", second_query, &[], now() + 120), + ); + assert_status( + query_cli(&server.address, "project", "second-query", &second), + &second, + json!("Unobserved"), + ); + + let legacy = request( + "project", + json!({"ScopedUploadSlice":{ + "session":session, "binding":binding, "offset":0}}), + ); + assert!(!command( + &temp.0, + "operation-credential-issue", + &issuance( + 3, + "alice", + "legacy-slice", + legacy.clone(), + &bytes[..protocol::TRANSFER_CHUNK], + now() + 120 + ) + ) + .status + .success()); + rpc( + &server.address, + "second-upload", + &legacy, + &bytes[..protocol::TRANSFER_CHUNK], + ) + .denied(); + + wait_until(expiry); + assert_unauthenticated_token(&server.address, "first-upload"); + drop(server); + let server = Server::start(&temp.0); + let query = query_request(&first); + issue( + &temp.0, + &issuance(200, "alice", "first-query", query, &[], now() + 120), + ); + assert_status( + query_cli(&server.address, "project", "first-query", &first), + &first, + json!({"Accepted":{"data":"Available"}}), + ); + + let mut altered = first.clone(); + altered["operation_id"] = json!(id(700)); + altered["scope"]["actor"] = json!("bob"); + let absent = assert_claim_denied(&temp.0, &server.address, &altered, "bob", 210); + altered = first.clone(); + altered["scope"]["actor"] = json!("bob"); + let other_actor = assert_claim_denied(&temp.0, &server.address, &altered, "bob", 211); + assert_eq!( + absent, other_actor, + "query must not disclose another actor's original operation" + ); + altered = first.clone(); + altered["scope"]["repository"] = json!("other"); + assert_claim_denied(&temp.0, &server.address, &altered, "alice", 212); + altered = first.clone(); + altered["payload_sha256"] = json!(id(701)); + assert_claim_denied(&temp.0, &server.address, &altered, "alice", 213); + altered = first.clone(); + altered["scope"]["binding"]["digest"] = json!(id(702)); + assert_claim_denied(&temp.0, &server.address, &altered, "alice", 214); + altered = first.clone(); + altered["scope"]["session"] = json!(id(703)); + assert_claim_denied(&temp.0, &server.address, &altered, "alice", 215); + altered = first.clone(); + altered["offset"] = json!(protocol::TRANSFER_CHUNK as u64); + assert_claim_denied(&temp.0, &server.address, &altered, "alice", 216); + + let cancel = request( + "project", + json!({"CancelScopedUpload":{"session":session, "binding":binding}}), + ); + issue( + &temp.0, + &issuance( + 300, + "alice", + "cancel-upload", + cancel.clone(), + &[], + now() + 120, + ), + ); + let response = rpc(&server.address, "cancel-upload", &cancel, &[]) + .packet() + .0; + assert!(response.ok, "{response:?}"); + assert_status( + query_cli(&server.address, "project", "first-query", &first), + &first, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Canceled"}}}}), + ); + // The second original credential is still valid, but a delayed original + // request cannot recreate data in a canceled upload. + rpc( + &server.address, + "second-upload", + &second_request, + &bytes[protocol::TRANSFER_CHUNK..], + ) + .denied(); + assert_status( + query_cli(&server.address, "project", "second-query", &second), + &second, + json!("Unobserved"), + ); + assert_status( + query_cli(&server.address, "project", "first-query", &first), + &first, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Canceled"}}}}), + ); + + // A query requires current authorization, but a new query credential can + // still recover the original generation-one, expired operation afterward. + set_policy(&temp.0, 1, false, false); + assert_unauthenticated_token(&server.address, "first-query"); + set_policy(&temp.0, 2, true, true); + assert_unauthenticated_token(&server.address, "first-query"); + let mut renewed_query = issuance( + 301, + "alice", + "generation-three-query", + query_request(&first), + &[], + now() + 120, + ); + renewed_query.policy_generation = 3; + issue(&temp.0, &renewed_query); + assert_status( + query_cli(&server.address, "project", "generation-three-query", &first), + &first, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Canceled"}}}}), + ); +} + +#[test] +fn completed_apply_keeps_chunk_tombstone_and_prevents_rewrite() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let base = repo.commit(WASM, "base").unwrap(); + let fork = Repository::fork_local(temp.0.join("project"), temp.0.join("fork")).unwrap(); + let mut next = WASM.to_vec(); + next.extend([0, 3, 1, b'x', 1]); + let head = fork.commit(&next, "feature").unwrap(); + let bytes = fork + .network_bundle(std::slice::from_ref(&head), std::slice::from_ref(&base)) + .unwrap() + .1; + assert!(bytes.len() <= protocol::TRANSFER_CHUNK); + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head.clone()), + force: false, + }, + &bytes, + ) + .unwrap(); + let session = id(101); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + + let original = chunk(11, "alice", "project", &session, &binding, 0, &bytes); + let upload = upload_request(&original); + issue( + &temp.0, + &issuance( + 11, + "alice", + "completed-upload", + upload.clone(), + &bytes, + now() + 120, + ), + ); + assert_status( + chunk_cli( + &server.address, + "project", + "completed-upload", + json!({"Chunk":{"chunk":original, "bytes":bytes}}), + ), + &original, + json!({"Accepted":{"data":"Available"}}), + ); + let query = query_request(&original); + issue( + &temp.0, + &issuance(202, "alice", "completed-query", query, &[], now() + 120), + ); + assert_status( + query_cli(&server.address, "project", "completed-query", &original), + &original, + json!({"Accepted":{"data":"Available"}}), + ); + + let apply = request( + "project", + json!({"ApplyScopedUpload":{"session":session, "binding":binding}}), + ); + let original_apply = issuance(12, "alice", "apply-upload", apply.clone(), &[], now() + 120); + issue(&temp.0, &original_apply); + let response = rpc(&server.address, "apply-upload", &apply, &[]).packet().0; + assert!(response.ok, "{response:?}"); + assert_eq!(repo.resolve("topic").unwrap(), head); + assert_status( + query_cli(&server.address, "project", "completed-query", &original), + &original, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Completed"}}}}), + ); + // Idempotent replay returns the original cleaned fact and never recreates + // the transferred bytes. + let (response, payload) = rpc(&server.address, "completed-upload", &upload, &bytes).packet(); + assert!(response.ok, "{response:?}"); + let replay: ScopedChunkStatus = binary::decode(&payload).unwrap(); + assert_status( + serde_json::to_value(replay).unwrap(), + &original, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Completed"}}}}), + ); + assert_status( + query_cli(&server.address, "project", "completed-query", &original), + &original, + json!({"Accepted":{"data":{"Cleaned":{"reason":"Completed"}}}}), + ); + #[cfg(target_os = "linux")] + { + set_policy(&temp.0, 1, false, false); + let result = recovery(&temp.0, 990, &original_apply, true, vec![]); + assert_eq!( + result["state"]["Upload"]["state"]["Finished"]["receipt"]["response"]["ok"], + true + ); + assert_eq!(repo.resolve("topic").unwrap(), head); + } +} + +#[test] +fn current_read_grant_can_query_own_chunk_but_not_write_another() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let head = repo.commit(WASM, "base").unwrap(); + set_policy(&temp.0, 0, true, true); + let server = Server::start(&temp.0); + let bytes = b"a scoped upload chunk"; + let binding = UploadBinding::for_payload( + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head), + force: false, + }, + bytes, + ) + .unwrap(); + let session = id(102); + let original = chunk(31, "alice", "project", &session, &binding, 0, bytes); + let upload = upload_request(&original); + issue( + &temp.0, + &issuance( + 31, + "alice", + "read-test-upload", + upload.clone(), + bytes, + now() + 120, + ), + ); + let response = rpc(&server.address, "read-test-upload", &upload, bytes) + .packet() + .0; + assert!(response.ok, "{response:?}"); + + set_policy(&temp.0, 1, true, false); + assert_unauthenticated_token(&server.address, "read-test-upload"); + let query = query_request(&original); + let mut credential = issuance(32, "alice", "read-test-query", query, &[], now() + 120); + credential.policy_generation = 2; + issue(&temp.0, &credential); + assert_status( + query_cli(&server.address, "project", "read-test-query", &original), + &original, + json!({"Accepted":{"data":"Available"}}), + ); + + let scope_query = request( + "project", + json!({"QueryScopedUpload":{"session":session, "binding":binding}}), + ); + let mut credential = issuance( + 34, + "alice", + "read-test-scope", + scope_query.clone(), + &[], + now() + 120, + ); + credential.policy_generation = 2; + issue(&temp.0, &credential); + let response = rpc(&server.address, "read-test-scope", &scope_query, &[]) + .packet() + .0; + assert!(response.ok, "{response:?}"); + + let next = chunk(33, "alice", "project", &id(103), &binding, 0, bytes); + let next_upload = upload_request(&next); + let mut credential = issuance( + 33, + "alice", + "read-test-denied", + next_upload.clone(), + bytes, + now() + 120, + ); + credential.policy_generation = 2; + issue(&temp.0, &credential); + rpc(&server.address, "read-test-denied", &next_upload, bytes).denied(); + assert_status( + query_cli(&server.address, "project", "read-test-query", &original), + &original, + json!({"Accepted":{"data":"Available"}}), + ); +} diff --git a/tests/server_hosting_cli.rs b/tests/server_hosting_cli.rs index 8fe8f3e..407298f 100644 --- a/tests/server_hosting_cli.rs +++ b/tests/server_hosting_cli.rs @@ -311,19 +311,33 @@ fn negotiation_compresses_history_sends_no_known_objects_and_hides_unreachable_h } #[test] -fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_explicit() { +fn corrupt_scoped_upload_is_canceled_and_reservations_are_bounded() { let t = Temp::new(); Repository::init(t.0.join("project")).unwrap(); let server = Server::start(&t.0, &["--allow-write"]); let bytes = vec![0; protocol::TRANSFER_CHUNK]; let id = "1".repeat(64); + let binding = protocol::UploadBinding { + version: 1, + digest: id.clone(), + total: bytes.len() as u64, + operation: Box::new(Operation::Push { + branch: "main".into(), + expected: None, + force: false, + }), + targets: vec![protocol::UploadTarget { + reference: "refs/heads/main".into(), + force: false, + }], + }; assert!( server .rpc( "project", - Operation::UploadSlice { - transfer: id.clone(), - total: bytes.len() as u64, + Operation::ScopedUploadSlice { + session: id.clone(), + binding: binding.clone(), offset: 0 }, &bytes @@ -334,19 +348,28 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ let result = server .rpc( "project", - Operation::ApplyUpload { - transfer: id.clone(), - operation: Box::new(Operation::Push { - branch: "main".into(), - expected: None, - force: false, - }), + Operation::ApplyScopedUpload { + session: id.clone(), + binding: binding.clone(), }, &[], ) .0; assert!(!result.ok); assert!(result.error.unwrap().contains("checksum")); + assert!( + server + .rpc( + "project", + Operation::CancelScopedUpload { + session: id.clone(), + binding: binding.clone() + }, + &[] + ) + .0 + .ok + ); assert!(!t .0 .join(format!("project/.wasm-git/tmp/upload-{id}")) @@ -354,14 +377,18 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ let a = "2".repeat(64); let b = "3".repeat(64); let c = "4".repeat(64); + let mut large = binding.clone(); + large.total = protocol::MAX_BUNDLE_BYTES; + let mut small = binding.clone(); + small.total = 1; for id in [&a, &b] { assert!( server .rpc( "project", - Operation::UploadSlice { - transfer: id.clone(), - total: protocol::MAX_BUNDLE_BYTES, + Operation::ScopedUploadSlice { + session: id.clone(), + binding: large.clone(), offset: 0 }, &bytes @@ -373,9 +400,9 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ let full = server .rpc( "project", - Operation::UploadSlice { - transfer: c.clone(), - total: 1, + Operation::ScopedUploadSlice { + session: c.clone(), + binding: small.clone(), offset: 0, }, &[1], @@ -385,7 +412,14 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ assert!(full.error.unwrap().contains("quota")); assert!( server - .rpc("project", Operation::CancelUpload { transfer: a }, &[]) + .rpc( + "project", + Operation::CancelScopedUpload { + session: a, + binding: large + }, + &[] + ) .0 .ok ); @@ -393,9 +427,9 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ server .rpc( "project", - Operation::UploadSlice { - transfer: c, - total: 1, + Operation::ScopedUploadSlice { + session: c, + binding: small, offset: 0 }, &[1] @@ -405,6 +439,253 @@ fn terminal_upload_corruption_is_removed_reservations_are_bounded_and_cancel_is_ ); } +#[test] +fn authenticated_retention_rpc_and_cli_preserve_fixed_bytes_and_tombstones() { + let t = Temp::new(); + let repo = Repository::init(t.0.join("project")).unwrap(); + let tree = repo + .create_files_tree(&std::collections::BTreeMap::from([( + "module.wasm".into(), + WASM.to_vec(), + )])) + .unwrap(); + let commit = repo.create_commit_object(&tree, &[], "release").unwrap(); + let policy_input = t.0.join("policy.json"); + let policy = t.0.join("policy.bin"); + fs::write(&policy_input, json!({"version":3,"principals":[ + {"name":"publisher","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"project","read":true,"write":[],"force":false,"create":false,"release_retention":true}]}, + {"name":"other","token_sha256":format!("{:x}",Sha256::digest(b"other")),"grants":[{"repository":"project","read":true,"write":[],"force":false,"create":false,"release_retention":true}]}, + {"name":"reader","token_sha256":format!("{:x}",Sha256::digest(b"reader")),"grants":[{"repository":"project","read":true,"write":[],"force":false,"create":false}]} + ]}).to_string()).unwrap(); + success( + Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "compile-policy", + policy_input.to_str().unwrap(), + policy.to_str().unwrap(), + ]) + .output() + .unwrap(), + ); + let server = Server::start( + &t.0, + &["--allow-write", "--policy", policy.to_str().unwrap()], + ); + let id = "b".repeat(64); + let command = protocol::RetentionCommand::Prepare { + operation: id.clone(), + commit: commit.clone(), + paths: vec!["module.wasm".into()], + }; + let op = || Operation::ReleaseRetention { + command: command.clone(), + }; + let (result, bytes) = server.rpc("project", op(), &[]); + assert!(result.ok, "{result:?}"); + let reply: protocol::RetentionReply = binary::decode(&bytes).unwrap(); + reply.validate_for("project", &command).unwrap(); + assert!(!rpc(&server.address, "other", "project", op(), &[]).0.ok); + assert!(!rpc(&server.address, "reader", "project", op(), &[]).0.ok); + repo.garbage_collect_mode(&[], true, true).unwrap(); + let read = protocol::RetentionCommand::Read { + operation: id.clone(), + path: "module.wasm".into(), + offset: 0, + }; + let (result, bytes) = server.rpc( + "project", + Operation::ReleaseRetention { + command: read.clone(), + }, + &[], + ); + assert!(result.ok, "{result:?}"); + let reply: protocol::RetentionReply = binary::decode(&bytes).unwrap(); + reply.validate_for("project", &read).unwrap(); + assert!(matches!(reply, protocol::RetentionReply::File { bytes, .. } if bytes == WASM)); + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(["--format", "json", "retention-rpc", &server.url("project")]) + .env("WASM_GIT_REMOTE_TOKEN", "hosting-test") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all( + &serde_json::to_vec(&protocol::RetentionRequest { + version: 1, + command: protocol::RetentionCommand::Query { + operation: id.clone(), + }, + }) + .unwrap(), + ) + .unwrap(); + let output = child.wait_with_output().unwrap(); + let raw = success(output); + let value: serde_json::Value = serde_json::from_str(&raw).unwrap(); + assert_eq!(value["protocol"], "wasm-git.command"); + assert_eq!(value["result"]["value"]["State"]["record"]["operation"], id); + let request = serde_json::to_string(&protocol::RetentionRequest { version: 1, command: protocol::RetentionCommand::Query { operation: id.clone() } }).unwrap(); + for (exit, expected) in [(0, true), (1, false)] { + let validation = format!(r#"{{"kind":"retention_cli_reply","repository":"project","request":{request},"process_exit":{exit},"response":{raw}}}"#); + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")).args(["--format", "json", "integration-validate"]).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + child.stdin.take().unwrap().write_all(validation.as_bytes()).unwrap(); + assert_eq!(child.wait_with_output().unwrap().status.success(), expected); + } + assert!( + server + .rpc( + "project", + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Promote { + operation: id.clone() + } + }, + &[] + ) + .0 + .ok + ); + assert!( + !server + .rpc( + "project", + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Close { operation: id } + }, + &[] + ) + .0 + .ok + ); + let closed = "c".repeat(64); + assert!( + server + .rpc( + "project", + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Close { + operation: closed.clone() + } + }, + &[] + ) + .0 + .ok + ); + drop(server); + let server = Server::start( + &t.0, + &["--allow-write", "--policy", policy.to_str().unwrap()], + ); + assert!( + !server + .rpc( + "project", + Operation::ReleaseRetention { + command: protocol::RetentionCommand::Prepare { + operation: closed, + commit, + paths: vec!["module.wasm".into()] + } + }, + &[] + ) + .0 + .ok + ); +} + +#[test] +fn shared_common_metadata_does_not_cross_logical_repository_scopes() { + let t = Temp::new(); + let repo = Repository::init(t.0.join("project")).unwrap(); + let commit = repo.commit_files_on_branch(&std::collections::BTreeMap::from([("module.wasm".into(), WASM.to_vec())]), "initial", &[], "main", None, None).unwrap(); + repo.add_linked_worktree(&t.0.join("alias"), "alias-branch", Some(&commit), None).unwrap(); + let input = t.0.join("policy.json"); + let policy = t.0.join("policy.bin"); + fs::write(&input, json!({"version":3,"principals":[{"name":"owner","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"*","read":true,"write":["refs/heads/*"],"force":false,"create":false,"release_retention":true}]}]}).to_string()).unwrap(); + success(Command::new(env!("CARGO_BIN_EXE_wasm-git-server")).args(["compile-policy", input.to_str().unwrap(), policy.to_str().unwrap()]).output().unwrap()); + let server = Server::start(&t.0, &["--allow-write", "--policy", policy.to_str().unwrap()]); + let bytes = b"frozen upload"; + let binding = protocol::UploadBinding::for_payload(Operation::Push { branch: "topic".into(), expected: None, force: false }, bytes).unwrap(); + let session = "d".repeat(64); + let chunk = || Operation::ScopedUploadSlice { session: session.clone(), binding: binding.clone(), offset: 0 }; + let apply = || Operation::ApplyScopedUpload { session: session.clone(), binding: binding.clone() }; + let cancel = || Operation::CancelScopedUpload { session: session.clone(), binding: binding.clone() }; + let query = || Operation::QueryScopedUpload { session: session.clone(), binding: binding.clone() }; + assert!(server.rpc("project", chunk(), bytes).0.ok); + assert!(!server.rpc("alias", chunk(), bytes).0.ok); + assert!(!server.rpc("alias", apply(), &[]).0.ok); + assert!(!server.rpc("alias", cancel(), &[]).0.ok); + assert!(!server.rpc("alias", query(), &[]).0.ok); + assert!(server.rpc("project", query(), &[]).0.ok); + assert!(server.rpc("project", cancel(), &[]).0.ok); + assert!(!server.rpc("project", chunk(), bytes).0.ok); + let operation = "e".repeat(64); + let prepare = protocol::RetentionCommand::Prepare { operation: operation.clone(), commit, paths: vec!["module.wasm".into()] }; + assert!(server.rpc("project", Operation::ReleaseRetention { command: prepare }, &[]).0.ok); + assert!(!server.rpc("alias", Operation::ReleaseRetention { command: protocol::RetentionCommand::Query { operation: operation.clone() } }, &[]).0.ok); + assert!(!server.rpc("alias", Operation::ReleaseRetention { command: protocol::RetentionCommand::Read { operation: operation.clone(), path: "module.wasm".into(), offset: 0 } }, &[]).0.ok); + assert!(!server.rpc("alias", Operation::ReleaseRetention { command: protocol::RetentionCommand::Close { operation: operation.clone() } }, &[]).0.ok); + assert!(server.rpc("project", Operation::ReleaseRetention { command: protocol::RetentionCommand::Query { operation } }, &[]).0.ok); +} + +#[test] +fn native_integration_validator_rejects_duplicate_unknown_and_unsafe_json() { + fn validate(input: &str) -> std::process::Output { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(["--format", "json", "integration-validate"]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + child.wait_with_output().unwrap() + } + let id = "a".repeat(64); + let request = format!(r#"{{"version":1,"command":{{"Query":{{"operation":"{id}"}}}}}}"#); + let valid = format!(r#"{{"kind":"retention_reply","repository":"project","request":{request},"reply":{{"State":{{"version":2,"repository":"project","operation":"{id}","record":null}}}}}}"#); + assert!(validate(&valid).status.success()); + let duplicate_version = format!(r#"{{"kind":"retention_request","request":{{"version":1,"version":1,"command":{{"Query":{{"operation":"{id}"}}}}}}}}"#); + assert!(!validate(&duplicate_version).status.success()); + let duplicate_repository = valid.replacen("\"repository\":\"project\"", "\"repository\":\"project\",\"repository\":\"other\"", 1); + assert!(!validate(&duplicate_repository).status.success()); + let unknown = valid.replace("\"record\":null", "\"record\":null,\"ignored\":true"); + assert!(!validate(&unknown).status.success()); + let file = format!(r#"{{"blob":"{id}","sha256":"{id}","size":8}}"#); + let record = format!(r#"{{"version":2,"operation":"{id}","actor":"publisher","state":"Prepared","repository":"project","commit":"{id}","files":{{"m.wasm":{file}}}}}"#); + let mapped = valid.replace("\"record\":null", &format!("\"record\":{record}")); + assert!(validate(&mapped).status.success()); + let duplicate_map = mapped.replace(&format!(r#""m.wasm":{file}"#), &format!(r#""m.wasm":{file},"m.wasm":{file}"#)); + assert!(!validate(&duplicate_map).status.success()); + let raw_response = format!(r#"{{"protocol":"wasm-git.command","version":1,"command":"retention-rpc","ok":true,"exit_code":0,"result":{{"kind":"data","value":{{"State":{{"version":2,"repository":"project","operation":"{id}","record":null}}}}}},"error":null}}"#); + let embedded = format!(r#"{{"kind":"retention_cli_reply","repository":"project","request":{request},"process_exit":0,"response":{raw_response}}}"#); + assert!(validate(&embedded).status.success()); + assert!(!validate(&embedded.replacen("\"protocol\":\"wasm-git.command\",\"version\":1", "\"protocol\":\"wasm-git.command\",\"version\":1,\"version\":1", 1)).status.success()); + let safe = format!(r#"{{"kind":"retention_request","request":{{"version":1,"command":{{"Read":{{"operation":"{id}","path":"m.wasm","offset":9007199254740991}}}}}}}}"#); + assert!(validate(&safe).status.success()); + assert!(!validate(&safe.replace("9007199254740991", "9007199254740992")).status.success()); + let raw_capabilities = success(Command::new(env!("CARGO_BIN_EXE_wasm-git")).args(["--format", "json", "integration-capabilities"]).output().unwrap()); + let capabilities: serde_json::Value = serde_json::from_str(&raw_capabilities).unwrap(); + assert_eq!(capabilities["result"]["value"]["node_safe_integer_max"], 9_007_199_254_740_991_u64); + assert_eq!(capabilities["result"]["value"]["authorization_natural_expiry"], false); + assert_eq!(capabilities["result"]["value"]["authorization_revocation_fence"], cfg!(all(target_os = "linux", target_arch = "x86_64", any(target_env = "gnu", target_env = "musl")))); + let input = json!({"kind":"capabilities","capabilities":capabilities["result"]["value"]}).to_string(); + assert!(validate(&input).status.success()); + let input = format!(r#"{{"kind":"capabilities_cli_reply","process_exit":0,"response":{raw_capabilities}}}"#); + assert!(validate(&input).status.success()); + assert!(!validate(&input.replace("\"process_exit\":0", "\"process_exit\":1")).status.success()); + let failed = Command::new(env!("CARGO_BIN_EXE_wasm-git")).args(["--format", "json", "integration-capabilities", "unexpected"]).output().unwrap(); + let exit = failed.status.code().unwrap(); + assert_ne!(exit, 0); + let raw_failure = String::from_utf8(failed.stdout).unwrap(); + let failed_input = format!(r#"{{"kind":"capabilities_cli_reply","process_exit":{exit},"response":{raw_failure}}}"#); + assert!(validate(&failed_input).status.success()); + assert!(!validate(&failed_input.replace(&format!("\"process_exit\":{exit}"), "\"process_exit\":0")).status.success()); +} + #[test] fn atomic_receive_rejects_every_ref_on_one_bad_lease_and_cli_publishes_multiple_refs() { let t = Temp::new(); @@ -475,7 +756,7 @@ fn policy_enforces_principals_repo_ref_force_and_fork_scopes_over_http_and_stdio } let input = t.0.join("policy-input.json"); let output = t.0.join("policy.bin"); - fs::write(&input,serde_json::to_vec(&json!({"version":1,"principals":[{"name":"alice","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"alice.*","read":true,"write":["refs/heads/topic*"],"force":false,"create":true}]}]})).unwrap()).unwrap(); + fs::write(&input,serde_json::to_vec(&json!({"version":3,"principals":[{"name":"alice","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"alice.*","read":true,"write":["refs/heads/topic*"],"force":false,"create":true}]}]})).unwrap()).unwrap(); success( Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) .args([ @@ -1193,7 +1474,7 @@ fn hierarchical_repositories_clone_and_fork_under_exact_policy_boundaries() { let repo = Repository::init(t.0.join("team/project")).unwrap(); let tip = repo.commit(WASM, "base").unwrap(); let config = t.0.join("policy.json"); - fs::write(&config, json!({"version":1,"principals":[{"name":"test","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"team/*","read":true,"write":["refs/heads/*"],"force":false,"create":true}]}]}).to_string()).unwrap(); + fs::write(&config, json!({"version":3,"principals":[{"name":"test","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"team/*","read":true,"write":["refs/heads/*"],"force":false,"create":true}]}]}).to_string()).unwrap(); let policy = t.0.join("policy.bin"); success( Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) @@ -1438,13 +1719,18 @@ fn partial_receive_uses_one_quarantine_and_reports_only_accepted_refs_to_post_ho assert!(!repo.root.join("hooks.log").exists()); // Exercise the nonrecursive uploaded-operation codec as well as the direct RPC. let transfer = format!("{:x}", Sha256::digest(&payload)); + let binding = protocol::UploadBinding::for_payload( + Operation::PublishPartial { dry_run: false }, + &payload, + ) + .unwrap(); assert!( server .rpc( "project", - Operation::UploadSlice { - transfer: transfer.clone(), - total: payload.len() as u64, + Operation::ScopedUploadSlice { + session: transfer.clone(), + binding: binding.clone(), offset: 0 }, &payload @@ -1454,9 +1740,9 @@ fn partial_receive_uses_one_quarantine_and_reports_only_accepted_refs_to_post_ho ); let (reply, bytes) = server.rpc( "project", - Operation::ApplyUpload { - transfer, - operation: Box::new(Operation::PublishPartial { dry_run: false }), + Operation::ApplyScopedUpload { + session: transfer, + binding, }, &[], ); @@ -1521,7 +1807,7 @@ fn partial_receive_keeps_authorization_and_prefix_failures_per_reference() { let tip = repo.commit(WASM, "root").unwrap(); repo.create_branch("allowed-parent", &tip).unwrap(); let config = t.0.join("policy.json"); - fs::write(&config, json!({"version":1,"principals":[{"name":"test","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"project","read":true,"write":["refs/heads/allowed*"],"force":false,"create":false}]}]}).to_string()).unwrap(); + fs::write(&config, json!({"version":3,"principals":[{"name":"test","token_sha256":format!("{:x}",Sha256::digest(b"hosting-test")),"grants":[{"repository":"project","read":true,"write":["refs/heads/allowed*"],"force":false,"create":false}]}]}).to_string()).unwrap(); let policy = t.0.join("policy.bin"); success( Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) diff --git a/tests/server_operation_credentials.rs b/tests/server_operation_credentials.rs new file mode 100644 index 0000000..ddbc4b4 --- /dev/null +++ b/tests/server_operation_credentials.rs @@ -0,0 +1,475 @@ +#![cfg(all(feature = "client", feature = "server", unix))] +//! Real CLI and HTTP coverage for immutable, request-bound credentials. + +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + fs, + io::{BufRead, BufReader, Read, Write}, + net::{Shutdown, TcpStream}, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + process::{Child, Command, Output, Stdio}, + sync::{atomic::{AtomicU64, Ordering}, mpsc}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use wasm_git::{ + binary, + protocol::{ + self, CommandEnvelope, Operation, OperationCredentialQuery, + OperationCredentialQueryReply, OperationCredentialReceipt, OperationCredentialRequest, + RefNamespace, Request, Response, RetentionCommand, RetentionReply, ScopedUploadState, + ScopedUploadStatus, UploadBinding, + }, + repository::Repository, +}; + +const WASM: &[u8] = b"\0asm\x01\0\0\0"; +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Temp(PathBuf); +impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!("wasm-git-operation-credentials-{}-{}", + std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + fs::create_dir(&path).unwrap(); + Self(path) + } +} +impl Drop for Temp { + fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } +} + +fn hash(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } +fn id(value: u64) -> String { format!("{value:064x}") } +fn now() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() } + +fn wait_until(expiry: u64) { + let deadline = Instant::now() + Duration::from_secs(20); + while now() < expiry { + assert!(Instant::now() < deadline, "clock did not reach credential expiry"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +fn wait_for(path: &Path) { + let deadline = Instant::now() + Duration::from_secs(12); + while !path.exists() { + assert!(Instant::now() < deadline, "timed out waiting for {}", path.display()); + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn bounded_output(mut command: Command, input: Option<&[u8]>) -> Output { + command.stdout(Stdio::piped()).stderr(Stdio::piped()); + command.stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() }); + let mut child = command.spawn().unwrap(); + if let Some(input) = input { + if let Err(error) = child.stdin.take().unwrap().write_all(input) { + let _ = child.kill(); + let _ = child.wait(); + panic!("write command input: {error}"); + } + } + let deadline = Instant::now() + Duration::from_secs(30); + loop { + match child.try_wait() { + Ok(Some(_)) => return child.wait_with_output().unwrap(), + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)), + result => { + let _ = child.kill(); + let output = child.wait_with_output().unwrap(); + panic!("command did not finish ({result:?}): {}", String::from_utf8_lossy(&output.stderr)); + } + } + } +} + +fn command(root: &Path, name: &str, input: &impl serde::Serialize) -> Output { + let path = root.join(format!("request-{}.json", NEXT.fetch_add(1, Ordering::Relaxed))); + fs::write(&path, serde_json::to_vec(input).unwrap()).unwrap(); + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + process.args(["--format", "json", name]).arg(root).arg(path); + bounded_output(process, None) +} + +fn success(output: Output) -> Value { + assert!(output.status.success(), "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn validate(value: Value, expected: bool) { + let mut process = Command::new(env!("CARGO_BIN_EXE_wasm-git")); + process.args(["--format", "json", "integration-validate"]); + let result = bounded_output(process, Some(&serde_json::to_vec(&value).unwrap())); + assert_eq!(result.status.success(), expected, "{}", String::from_utf8_lossy(&result.stdout)); +} + +fn policy(alice_exists: bool, alice_allowed: bool) -> Value { + let grant = json!({"repository":"*", "read":true, "write":["refs/heads/*"], + "force":false, "create":false, "release_retention":true}); + let mut principals = vec![json!({"name":"bob", "token_sha256":hash(b"bob-legacy"), "grants":[grant.clone()]})]; + if alice_exists { + principals.push(json!({"name":"alice", "token_sha256":hash(b"alice-legacy"), + "grants":if alice_allowed { vec![grant] } else { vec![] }})); + } + json!({"version":3, "principals":principals}) +} + +fn set_policy(root: &Path, generation: u64, value: Value) { + let result = success(command(root, "policy-set", &json!({"version":1, + "operation_id":id(1000 + generation), "expected_generation":generation, "policy":value}))); + assert_eq!(result["result"]["value"]["outcome"], "applied"); +} + +fn request(repository: &str, operation: Operation) -> Request { + Request { version: 1, repository: repository.into(), operation } +} + +fn issuance(number: u64, actor: &str, token: &str, request: Request, + payload: &[u8], expiry: u64) -> OperationCredentialRequest { + OperationCredentialRequest { version: 1, operation_id: id(number), actor: actor.into(), + token_sha256: hash(token.as_bytes()), request, payload_sha256: hash(payload), + expires_at: expiry, policy_generation: 1 } +} + +fn issue(root: &Path, request: &OperationCredentialRequest) -> OperationCredentialReceipt { + let result = success(command(root, "operation-credential-issue", request)); + let envelope: CommandEnvelope = serde_json::from_value(result.clone()).unwrap(); + let receipt = envelope.validate_for("operation-credential-issue", 0).unwrap().unwrap().clone(); + receipt.validate_request(request).unwrap(); + validate(json!({"kind":"operation_credential_issue_cli_reply", "request":request, + "process_exit":0, "response":result}), true); + receipt +} + +fn query_credential(root: &Path, original: &OperationCredentialRequest) -> OperationCredentialReceipt { + let query = OperationCredentialQuery { version: 1, operation_id: original.operation_id.clone() }; + let result = success(command(root, "operation-credential-query", &query)); + let envelope: CommandEnvelope = serde_json::from_value(result.clone()).unwrap(); + let reply = envelope.validate_for("operation-credential-query", 0).unwrap().unwrap(); + reply.validate_request(original).unwrap(); + validate(json!({"kind":"operation_credential_query_cli_reply", "request":original, + "process_exit":0, "response":result}), true); + reply.receipt.clone().expect("credential receipt must remain queryable") +} + +struct Server { child: Child, address: String } +impl Server { + fn start(root: &Path, strict: bool, hook: Option<&Path>) -> Self { + let mut command = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + command.args(["--root", root.to_str().unwrap(), "--listen", "127.0.0.1:0", + "--allow-write", "--policy", root.join("unused-bootstrap").to_str().unwrap()]); + if strict { command.arg("--require-operation-credentials"); } + if let Some(hook) = hook { command.arg("--pre-receive").arg(hook); } + let mut child = command.stdout(Stdio::piped()).stderr(Stdio::inherit()).spawn().unwrap(); + let output = child.stdout.take().unwrap(); + let (send, receive) = mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut line = String::new(); + let result = BufReader::new(output).read_line(&mut line).map(|_| line); + let _ = send.send(result); + }); + let line = match receive.recv_timeout(Duration::from_secs(15)) { + Ok(Ok(line)) => line, + other => { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + panic!("server readiness failed: {other:?}"); + } + }; + reader.join().unwrap(); + let parsed: Value = match serde_json::from_str(&line) { + Ok(value) => value, + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + panic!("invalid server readiness {line:?}: {error}"); + } + }; + let address = match parsed["listen"].as_str() { + Some(address) => address.to_owned(), + None => { + let _ = child.kill(); + let _ = child.wait(); + panic!("missing listen address in readiness: {parsed}"); + } + }; + Self { child, address } + } +} +impl Drop for Server { + fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); } +} + +struct Wire { status: u16, body: Vec } +impl Wire { + fn packet(self) -> (Response, Vec) { + assert_eq!(self.status, 200, "{}", String::from_utf8_lossy(&self.body)); + protocol::read_complete_packet(&self.body).unwrap() + } + fn denied(self) { + if self.status == 200 { + let (response, _) = protocol::read_complete_packet::(&self.body).unwrap(); + assert!(!response.ok, "unexpected successful response: {response:?}"); + } else { + assert!(matches!(self.status, 401 | 403 | 503), "unexpected HTTP {}", self.status); + } + } +} + +fn rpc(address: &str, token: &str, request: &Request, payload: &[u8]) -> Wire { + let mut packet = Vec::new(); + protocol::write_packet(&mut packet, request, payload).unwrap(); + let mut stream = TcpStream::connect(address).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(25))).unwrap(); + stream.set_write_timeout(Some(Duration::from_secs(15))).unwrap(); + write!(stream, "POST /v1/wasm-git HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {token}\r\nContent-Length: {}\r\n\r\n", packet.len()).unwrap(); + stream.write_all(&packet).unwrap(); + stream.shutdown(Shutdown::Write).unwrap(); + let mut bytes = Vec::new(); + stream.read_to_end(&mut bytes).unwrap(); + let offset = bytes.windows(4).position(|b| b == b"\r\n\r\n").expect("HTTP headers") + 4; + let status = std::str::from_utf8(&bytes[..offset]).unwrap().lines().next().unwrap() + .split_whitespace().nth(1).unwrap().parse().unwrap(); + Wire { status, body: bytes[offset..].to_vec() } +} + +struct HookGuard { root: PathBuf } +impl HookGuard { + fn install(root: &Path) -> (PathBuf, Self) { + let hook = root.join("receive-hook.sh"); + fs::write(&hook, b"#!/bin/sh\ntouch \"$WASM_GIT_REPOSITORY/../hook-started\"\nfor i in $(seq 1 900); do if test -f \"$WASM_GIT_REPOSITORY/../hook-release\"; then touch \"$WASM_GIT_REPOSITORY/../hook-finished\"; exit 0; fi; sleep 0.02; done\nexit 1\n").unwrap(); + fs::set_permissions(&hook, fs::Permissions::from_mode(0o700)).unwrap(); + (hook, Self { root: root.into() }) + } + fn release(&self) { fs::write(self.root.join("hook-release"), b"release").unwrap(); } +} +impl Drop for HookGuard { + fn drop(&mut self) { + if self.root.join("hook-started").exists() { + let _ = fs::write(self.root.join("hook-release"), b"release"); + let deadline = Instant::now() + Duration::from_secs(3); + while !self.root.join("hook-finished").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + } + } +} + +fn scoped_fixture() -> (Temp, Repository, Vec, UploadBinding, String) { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let base = repo.commit(WASM, "base").unwrap(); + let fork = Repository::fork_local(temp.0.join("project"), temp.0.join("fork")).unwrap(); + let mut next = WASM.to_vec(); + next.extend([0, 3, 1, b'x', 1]); + let head = fork.commit(&next, "feature").unwrap(); + let bytes = fork.network_bundle(std::slice::from_ref(&head), std::slice::from_ref(&base)).unwrap().1; + let operation = Operation::UpdateRef { namespace: RefNamespace::Branch, name: "topic".into(), + expected: None, new: Some(head.clone()), force: false }; + let binding = UploadBinding::for_payload(operation, &bytes).unwrap(); + set_policy(&temp.0, 0, policy(true, true)); + (temp, repo, bytes, binding, head) +} + +#[test] +fn strict_activation_binds_request_payload_actor_and_current_policy() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + repo.commit(WASM, "base").unwrap(); + let tree = repo.create_files_tree(&BTreeMap::from([("module.wasm".into(), WASM.to_vec())])).unwrap(); + let commit = repo.create_commit_object(&tree, &[], "release").unwrap(); + set_policy(&temp.0, 0, policy(true, true)); + + let mut missing_policy = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + missing_policy.args(["--root", temp.0.to_str().unwrap(), "--require-operation-credentials", "--allow-write"]); + let missing_policy = bounded_output(missing_policy, None); + assert!(!missing_policy.status.success()); + let mut strict_stdio = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + strict_stdio.args(["--stdio", "--root", temp.0.to_str().unwrap(), "--policy", + temp.0.join("unused-bootstrap").to_str().unwrap(), "--principal", "alice", + "--require-operation-credentials"]); + let strict_stdio = bounded_output(strict_stdio, None); + assert!(!strict_stdio.status.success()); + assert!(String::from_utf8_lossy(&strict_stdio.stderr).contains("operation credentials require an HTTP policy entry point")); + + let legacy = Server::start(&temp.0, false, None); + let strict = Server::start(&temp.0, true, None); + let advertise = request("project", Operation::Advertise {}); + assert!(rpc(&legacy.address, "alice-legacy", &advertise, &[]).packet().0.ok); + // A legacy request may already have passed header authentication while + // still waiting for its body. Activation must fence that request too. + let mut pending_packet = Vec::new(); + protocol::write_packet(&mut pending_packet, &advertise, &[]).unwrap(); + let mut pending = TcpStream::connect(&legacy.address).unwrap(); + pending.set_read_timeout(Some(Duration::from_secs(15))).unwrap(); + pending.set_write_timeout(Some(Duration::from_secs(15))).unwrap(); + write!(pending, "POST /v1/wasm-git HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer alice-legacy\r\nExpect: 100-continue\r\nContent-Length: {}\r\n\r\n", pending_packet.len()).unwrap(); + let mut interim = Vec::new(); + while !interim.ends_with(b"\r\n\r\n") { + assert!(interim.len() < 1024, "oversized interim response"); + let mut byte = [0]; + pending.read_exact(&mut byte).unwrap(); + interim.push(byte[0]); + } + assert!(interim.starts_with(b"HTTP/1.1 100")); + let read = issuance(1, "alice", "alice-read-credential", advertise.clone(), &[], now() + 120); + let first = issue(&temp.0, &read); + pending.write_all(&pending_packet).unwrap(); + pending.shutdown(Shutdown::Write).unwrap(); + let mut rejected = Vec::new(); + pending.read_to_end(&mut rejected).unwrap(); + assert!(rejected.starts_with(b"HTTP/1.1 503"), "{}", String::from_utf8_lossy(&rejected)); + assert_eq!(query_credential(&temp.0, &read), first); + assert_eq!(issue(&temp.0, &read), first); + let mut altered = read.clone(); + altered.expires_at += 1; + assert!(!command(&temp.0, "operation-credential-issue", &altered).status.success()); + assert_eq!(rpc(&legacy.address, "alice-legacy", &advertise, &[]).status, 503); + let mut legacy_restart = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + legacy_restart.args(["--root", temp.0.to_str().unwrap(), "--policy", + temp.0.join("unused-bootstrap").to_str().unwrap()]); + let legacy_restart = bounded_output(legacy_restart, None); + assert!(!legacy_restart.status.success()); + assert!(String::from_utf8_lossy(&legacy_restart.stderr).contains("strict credential entry point")); + let mut legacy_stdio = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + legacy_stdio.args(["--stdio", "--root", temp.0.to_str().unwrap(), "--policy", + temp.0.join("unused-bootstrap").to_str().unwrap(), "--principal", "alice"]); + let legacy_stdio = bounded_output(legacy_stdio, None); + assert!(!legacy_stdio.status.success()); + assert!(String::from_utf8_lossy(&legacy_stdio.stderr).contains("strict credential entry point")); + rpc(&strict.address, "alice-legacy", &advertise, &[]).denied(); + assert!(rpc(&strict.address, "alice-read-credential", &advertise, &[]).packet().0.ok); + rpc(&strict.address, "alice-read-credential", &request("other", Operation::Advertise {}), &[]).denied(); + rpc(&strict.address, "alice-read-credential", &request("project", Operation::Fetch {}), &[]).denied(); + rpc(&strict.address, "alice-read-credential", &advertise, b"changed payload").denied(); + + let retention_id = id(77); + let prepare = request("project", Operation::ReleaseRetention { command: RetentionCommand::Prepare { + operation: retention_id.clone(), commit, paths: vec!["module.wasm".into()] } }); + let permit = issuance(2, "alice", "alice-retention", prepare.clone(), &[], now() + 120); + let receipt = issue(&temp.0, &permit); + assert!(receipt.effect_key.is_some()); + assert!(rpc(&strict.address, "alice-retention", &prepare, &[]).packet().0.ok); + let mut renewed = permit.clone(); + renewed.operation_id = id(3); + renewed.token_sha256 = hash(b"different-token"); + renewed.expires_at += 1; + assert!(!command(&temp.0, "operation-credential-issue", &renewed).status.success()); + let retention_query = request("project", Operation::ReleaseRetention { command: + RetentionCommand::Query { operation: retention_id } }); + let bob = issuance(4, "bob", "bob-query", retention_query.clone(), &[], now() + 120); + issue(&temp.0, &bob); + rpc(&strict.address, "bob-query", &retention_query, &[]).denied(); + let alice = issuance(5, "alice", "alice-query", retention_query.clone(), &[], now() + 120); + issue(&temp.0, &alice); + let (response, payload) = rpc(&strict.address, "alice-query", &retention_query, &[]).packet(); + assert!(response.ok, "{response:?}"); + let reply: RetentionReply = binary::decode(&payload).unwrap(); + assert!(matches!(reply, RetentionReply::State { record: Some(record), .. } if record.actor == "alice")); + + let raw_write = issuance(6, "alice", "raw-write", request("project", Operation::UpdateRef { + namespace: RefNamespace::Branch, name: "topic".into(), expected: None, new: None, force: false }), &[], now() + 120); + assert!(!command(&temp.0, "operation-credential-issue", &raw_write).status.success()); + set_policy(&temp.0, 1, policy(true, false)); + assert_eq!(rpc(&strict.address, "alice-read-credential", &advertise, &[]).status, 401); + set_policy(&temp.0, 2, policy(true, true)); + // Restoring the same grants cannot resurrect credentials from generation 1. + assert_eq!(rpc(&strict.address, "alice-read-credential", &advertise, &[]).status, 401); + assert_eq!(rpc(&strict.address, "alice-retention", &prepare, &[]).status, 401); + let stale = issuance(7, "alice", "stale-generation", advertise.clone(), &[], now() + 120); + assert!(!command(&temp.0, "operation-credential-issue", &stale).status.success()); + let mut fresh = issuance(8, "alice", "generation-three-read", advertise.clone(), &[], now() + 120); + fresh.policy_generation = 3; + issue(&temp.0, &fresh); + assert!(rpc(&strict.address, "generation-three-read", &advertise, &[]).packet().0.ok); + let mut renewed_after_regrant = permit.clone(); + renewed_after_regrant.operation_id = id(9); + renewed_after_regrant.token_sha256 = hash(b"regrant-write-token"); + renewed_after_regrant.expires_at += 2; + renewed_after_regrant.policy_generation = 3; + assert_eq!(renewed_after_regrant.receipt().unwrap().effect_key, receipt.effect_key); + assert!(!command(&temp.0, "operation-credential-issue", &renewed_after_regrant).status.success()); + set_policy(&temp.0, 3, policy(false, false)); + assert_eq!(rpc(&strict.address, "generation-three-read", &advertise, &[]).status, 401); + assert_eq!(query_credential(&temp.0, &read), first); + assert_eq!(query_credential(&temp.0, &permit), receipt); + assert_eq!(issue(&temp.0, &read), first); +} + +#[test] +fn scoped_apply_keeps_its_result_after_credential_expiry() { + let (temp, repo, bytes, binding, head) = scoped_fixture(); + let server = Server::start(&temp.0, true, None); + let session = id(200); + let slice = request("project", Operation::UploadChunk { chunk: protocol::ScopedChunkIdentity { + version: 1, operation_id: id(20), scope: protocol::ScopedExecution { actor: "alice".into(), repository: "project".into(), + session: session.clone(), binding: binding.clone() }, offset: 0, payload_sha256: hash(&bytes) } }); + let upload = issuance(20, "alice", "slice-token", slice.clone(), &bytes, now() + 120); + issue(&temp.0, &upload); + let mut changed = bytes.clone(); + changed[0] ^= 1; + rpc(&server.address, "slice-token", &slice, &changed).denied(); + assert!(rpc(&server.address, "slice-token", &slice, &bytes).packet().0.ok); + + let apply = request("project", Operation::ApplyScopedUpload { session: session.clone(), binding: binding.clone() }); + let expiry = now() + 5; + let issued = issuance(21, "alice", "apply-token", apply.clone(), &[], expiry); + let original = issue(&temp.0, &issued); + let response = rpc(&server.address, "apply-token", &apply, &[]).packet().0; + assert!(response.ok, "{response:?}"); + assert_eq!(repo.resolve("topic").unwrap(), head); + wait_until(expiry); + rpc(&server.address, "apply-token", &apply, &[]).denied(); + assert_eq!(query_credential(&temp.0, &issued), original); + assert_eq!(issue(&temp.0, &issued), original); + + let query = request("project", Operation::QueryScopedUpload { session: session.clone(), binding: binding.clone() }); + let fresh = issuance(22, "alice", "fresh-query", query.clone(), &[], now() + 120); + issue(&temp.0, &fresh); + let (response, payload) = rpc(&server.address, "fresh-query", &query, &[]).packet(); + assert!(response.ok, "{response:?}"); + let status: ScopedUploadStatus = binary::decode(&payload).unwrap(); + status.validate_for("project", &session, &binding).unwrap(); + assert!(matches!(status.state, Some(ScopedUploadState::FinishedV4 { receipt }) + if receipt.response.ok && receipt.scope.actor == "alice" && receipt.scope.session == session)); +} + +#[test] +fn scoped_apply_expiring_during_hook_does_not_publish_reference() { + let (temp, repo, bytes, binding, _) = scoped_fixture(); + let (hook, hook_guard) = HookGuard::install(&temp.0); + let server = Server::start(&temp.0, true, Some(&hook)); + let session = id(300); + let slice = request("project", Operation::UploadChunk { chunk: protocol::ScopedChunkIdentity { + version: 1, operation_id: id(30), scope: protocol::ScopedExecution { actor: "alice".into(), repository: "project".into(), + session: session.clone(), binding: binding.clone() }, offset: 0, payload_sha256: hash(&bytes) } }); + issue(&temp.0, &issuance(30, "alice", "hook-slice", slice.clone(), &bytes, now() + 120)); + assert!(rpc(&server.address, "hook-slice", &slice, &bytes).packet().0.ok); + let apply = request("project", Operation::ApplyScopedUpload { session: session.clone(), binding: binding.clone() }); + let expiry = now() + 8; + let issued = issuance(31, "alice", "hook-apply", apply.clone(), &[], expiry); + let original = issue(&temp.0, &issued); + let address = server.address.clone(); + let worker = std::thread::spawn(move || rpc(&address, "hook-apply", &apply, &[])); + wait_for(&temp.0.join("hook-started")); + wait_until(expiry); + hook_guard.release(); + let response = worker.join().unwrap().packet().0; + assert!(!response.ok, "{response:?}"); + assert!(repo.resolve("topic").is_err()); + assert_eq!(query_credential(&temp.0, &issued), original); + + let query = request("project", Operation::QueryScopedUpload { session: session.clone(), binding: binding.clone() }); + issue(&temp.0, &issuance(32, "alice", "hook-query", query.clone(), &[], now() + 120)); + let (response, payload) = rpc(&server.address, "hook-query", &query, &[]).packet(); + assert!(response.ok, "{response:?}"); + let status: ScopedUploadStatus = binary::decode(&payload).unwrap(); + status.validate_for("project", &session, &binding).unwrap(); + assert!(matches!(&status.state, Some(ScopedUploadState::FinishedV4 { receipt }) if !receipt.response.ok) + || matches!(&status.state, Some(ScopedUploadState::Aborted { .. }))); +} diff --git a/tests/server_policy_fence.rs b/tests/server_policy_fence.rs new file mode 100644 index 0000000..a657632 --- /dev/null +++ b/tests/server_policy_fence.rs @@ -0,0 +1,597 @@ +#![cfg(all(feature = "client", feature = "server", unix))] +//! Native policy decisions and the cross-process fence use real servers/stdio. +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::{BufRead, BufReader, Read, Write}, + net::{Shutdown, TcpStream}, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, + process::{Child, Command, Output, Stdio}, + sync::atomic::{AtomicU64, Ordering}, + time::{Duration, Instant}, +}; +use wasm_git::{ + protocol::{self, Operation, RefNamespace, Request, Response}, + repository::Repository, +}; + +static NEXT: AtomicU64 = AtomicU64::new(0); +const WASM: &[u8] = b"\0asm\x01\0\0\0"; +struct Temp(PathBuf); +impl Temp { + fn new() -> Self { + let path = std::env::temp_dir().join(format!( + "wasm-git-policy-fence-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } +} +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} +fn success(output: Output) -> Value { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + serde_json::from_slice(&output.stdout).unwrap() +} +fn policy(write: bool, read: bool) -> Value { + json!({"version":3,"principals":[{"name":"alice","token_sha256":format!("{:x}",Sha256::digest(b"alice")), + "grants":[{"repository":"project","read":read,"write":if write { vec!["refs/heads/*"] } else { vec![] }, + "force":false,"create":false}]}]}) +} +fn update(id: char, generation: u64, policy: Value) -> Value { + json!({"version":1,"operation_id":id.to_string().repeat(64),"expected_generation":generation,"policy":policy}) +} +fn input(root: &Path, name: &str, value: &Value) -> PathBuf { + let path = root.join(name); + fs::write(&path, serde_json::to_vec(value).unwrap()).unwrap(); + path +} +fn server_command(command: &str, root: &Path, input: &Path) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + cmd.args([ + "--format", + "json", + command, + root.to_str().unwrap(), + input.to_str().unwrap(), + ]); + cmd +} +fn validate(value: Value) { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args(["--format", "json", "integration-validate"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(&serde_json::to_vec(&value).unwrap()) + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); +} +fn set(root: &Path, name: &str, request: &Value) -> Value { + let file = input(root, name, request); + let output = success(server_command("policy-set", root, &file).output().unwrap()); + validate( + json!({"kind":"policy_update_cli_reply","request":request,"process_exit":0,"response":output}), + ); + output +} +fn query(root: &Path, request: &Value) -> Value { + let file = input( + root, + "query.json", + &json!({"version":1,"operation_id":request["operation_id"]}), + ); + let output = success( + server_command("policy-query", root, &file) + .output() + .unwrap(), + ); + validate( + json!({"kind":"policy_query_cli_reply","request":request,"process_exit":0,"response":output}), + ); + output +} +struct Server { + child: Child, + address: String, +} +impl Server { + fn start(root: &Path, hook: Option<&Path>) -> Self { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + cmd.args([ + "--root", + root.to_str().unwrap(), + "--listen", + "127.0.0.1:0", + "--allow-write", + "--policy", + root.join("unused-bootstrap").to_str().unwrap(), + ]); + if let Some(hook) = hook { + cmd.arg("--pre-receive").arg(hook); + } + let mut child = cmd + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + let mut line = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut line) + .unwrap(); + let value: Value = serde_json::from_str(&line).unwrap(); + Self { + child, + address: value["listen"].as_str().unwrap().into(), + } + } +} +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} +fn packet(op: Operation) -> Vec { + let mut bytes = Vec::new(); + protocol::write_packet( + &mut bytes, + &Request { + version: 1, + repository: "project".into(), + operation: op, + }, + &[], + ) + .unwrap(); + bytes +} +fn rpc(address: &str, op: Operation) -> Response { + let body = packet(op); + let mut stream = TcpStream::connect(address).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(20))) + .unwrap(); + write!(stream, "POST /v1/wasm-git HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer alice\r\nContent-Length: {}\r\n\r\n", body.len()).unwrap(); + stream.write_all(&body).unwrap(); + stream.shutdown(Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + stream.read_to_end(&mut reply).unwrap(); + let offset = reply.windows(4).position(|v| v == b"\r\n\r\n").unwrap() + 4; + protocol::read_complete_packet::(&reply[offset..]) + .unwrap() + .0 +} +fn reference(name: &str, tip: &str) -> Operation { + Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: name.into(), + expected: None, + new: Some(tip.into()), + force: false, + } +} +fn wait_for(path: &Path) { + let deadline = Instant::now() + Duration::from_secs(10); + while !path.exists() { + assert!( + Instant::now() < deadline, + "timed out waiting for {}", + path.display() + ); + std::thread::sleep(Duration::from_millis(10)); + } +} +fn hook(root: &Path) -> PathBuf { + let path = root.join("hook.sh"); + fs::write(&path, b"#!/bin/sh\ntouch \"$WASM_GIT_REPOSITORY/../hook-started\"\nfor i in $(seq 1 500); do if test -f \"$WASM_GIT_REPOSITORY/../hook-release\"; then touch \"$WASM_GIT_REPOSITORY/../hook-finished\"; exit 0; fi; sleep 0.02; done\nexit 1\n").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + path +} + +#[test] +fn fence_drains_existing_http_and_blocks_all_instances_and_stdio() { + eprintln!("tested client: {}", env!("CARGO_BIN_EXE_wasm-git")); + eprintln!("tested server: {}", env!("CARGO_BIN_EXE_wasm-git-server")); + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let tip = repo.commit(WASM, "base").unwrap(); + let first = update('a', 0, policy(true, true)); + assert_eq!( + set(&temp.0, "first.json", &first)["result"]["value"]["outcome"], + "applied" + ); + let hook = hook(&temp.0); + let one = Server::start(&temp.0, Some(&hook)); + let two = Server::start(&temp.0, None); + let address = one.address.clone(); + let old_tip = tip.clone(); + let active = std::thread::spawn(move || rpc(&address, reference("in-flight", &old_tip))); + wait_for(&temp.0.join("hook-started")); + let revoked = update('b', 1, policy(false, true)); + let file = input(&temp.0, "revoke.json", &revoked); + let mut pending = server_command("policy-set", &temp.0, &file) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + std::thread::sleep(Duration::from_millis(200)); + assert!(pending.try_wait().unwrap().is_none()); + fs::write(temp.0.join("hook-release"), b"release").unwrap(); + assert!(active.join().unwrap().ok); + let receipt = success(pending.wait_with_output().unwrap()); + assert_eq!(receipt["result"]["value"]["outcome"], "applied"); + validate( + json!({"kind":"policy_update_cli_reply","request":revoked,"process_exit":0,"response":receipt}), + ); + assert!(!rpc(&two.address, reference("after-fence", &tip)).ok); + assert!(!rpc(&one.address, reference("also-denied", &tip)).ok); + assert!(Repository::open(temp.0.join("project")) + .unwrap() + .resolve("after-fence") + .is_err()); + + let mut ssh = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "--stdio", + "--root", + temp.0.to_str().unwrap(), + "--policy", + temp.0.join("unused-bootstrap").to_str().unwrap(), + "--principal", + "alice", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + ssh.stdin + .take() + .unwrap() + .write_all(&packet(reference("stdio-denied", &tip))) + .unwrap(); + let output = ssh.wait_with_output().unwrap(); + assert!(output.status.success()); + assert!( + !protocol::read_complete_packet::(&output.stdout) + .unwrap() + .0 + .ok + ); + + // Replaying an old decision after a newer generation must not install it. + let third = update('c', 2, policy(false, false)); + set(&temp.0, "third.json", &third); + assert_eq!( + query(&temp.0, &revoked)["result"]["value"]["receipt"]["generation"], + 2 + ); + let replay = set(&temp.0, "replay.json", &revoked); + assert_eq!(replay["result"]["value"]["generation"], 2); + let conflict = update('b', 2, policy(true, true)); + let file = input(&temp.0, "conflict.json", &conflict); + assert!(!server_command("policy-set", &temp.0, &file) + .output() + .unwrap() + .status + .success()); + let mut status = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")); + let status = success( + status + .args([ + "--format", + "json", + "policy-status", + temp.0.to_str().unwrap(), + ]) + .output() + .unwrap(), + ); + assert_eq!(status["result"]["value"]["generation"], 3); + validate(json!({"kind":"policy_status_cli_reply","process_exit":0,"response":status})); + assert!(!rpc(&two.address, Operation::Advertise {}).ok); + + let token = temp.0.join("admin-token"); + fs::write(&token, b"admin").unwrap(); + let bypass = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "--root", + temp.0.to_str().unwrap(), + "--token-file", + token.to_str().unwrap(), + "--allow-write", + ]) + .output() + .unwrap(); + assert!(!bypass.status.success()); +} + +#[test] +fn generation_conflict_is_a_durable_identity_bound_decision() { + let temp = Temp::new(); + let stale = update('d', 1, policy(true, true)); + let rejected = set(&temp.0, "stale.json", &stale); + assert_eq!( + rejected["result"]["value"]["outcome"], + "generation_conflict" + ); + assert_eq!(rejected["result"]["value"]["generation"], 0); + assert_eq!( + query(&temp.0, &stale)["result"]["value"]["receipt"]["outcome"], + "generation_conflict" + ); + let changed = update('d', 0, policy(true, true)); + let file = input(&temp.0, "changed.json", &changed); + assert!(!server_command("policy-set", &temp.0, &file) + .output() + .unwrap() + .status + .success()); + let initial = update('e', 0, policy(false, true)); + assert_eq!( + set(&temp.0, "initial.json", &initial)["result"]["value"]["outcome"], + "applied" + ); + assert_eq!( + set(&temp.0, "retry.json", &stale)["result"]["value"], + rejected["result"]["value"] + ); +} + +#[test] +fn bootstrap_receipt_survives_lost_readiness_and_later_revisions() { + let temp = Temp::new(); + let initial_policy = policy(true, true); + let input = input(&temp.0, "bootstrap.json", &initial_policy); + let compiled = temp.0.join("bootstrap.bin"); + let output = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "compile-policy", + input.to_str().unwrap(), + compiled.to_str().unwrap(), + ]) + .output() + .unwrap(); + assert!(output.status.success()); + let operation = format!("{:x}", Sha256::digest(fs::read(&compiled).unwrap())); + let original = json!({"version":1,"operation_id":operation,"expected_generation":0,"policy":initial_policy}); + // EOF after initialization models a lost server readiness/reply. + let output = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "--stdio", + "--root", + temp.0.to_str().unwrap(), + "--policy", + compiled.to_str().unwrap(), + "--principal", + "alice", + ]) + .stdin(Stdio::null()) + .output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!( + query(&temp.0, &original)["result"]["value"]["receipt"]["outcome"], + "applied" + ); + set(&temp.0, "next.json", &update('f', 1, policy(false, true))); + assert_eq!( + query(&temp.0, &original)["result"]["value"]["receipt"]["generation"], + 1 + ); +} + +#[test] +fn fence_waits_for_stdio_response_output() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let mut module = WASM.to_vec(); + let size = 2 * 1024 * 1024; + module.push(0); + let mut n = size + 2; + loop { + let byte = (n & 127) as u8; + n >>= 7; + module.push(byte | if n != 0 { 128 } else { 0 }); + if n == 0 { + break; + } + } + module.extend_from_slice(b"\x01x"); + let mut random = 0x1234_5678u32; + for _ in 0..size { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + module.push(random as u8); + } + repo.commit(&module, "large").unwrap(); + set(&temp.0, "first.json", &update('a', 0, policy(true, true))); + let mut ssh = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args([ + "--stdio", + "--root", + temp.0.to_str().unwrap(), + "--policy", + temp.0.join("unused-bootstrap").to_str().unwrap(), + "--principal", + "alice", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + ssh.stdin + .take() + .unwrap() + .write_all(&packet(Operation::Fetch {})) + .unwrap(); + let mut output = ssh.stdout.take().unwrap(); + let mut first_byte = [0u8; 1]; + output.read_exact(&mut first_byte).unwrap(); + let revoked = update('b', 1, policy(false, false)); + let file = input(&temp.0, "revoke.json", &revoked); + let mut pending = server_command("policy-set", &temp.0, &file) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + std::thread::sleep(Duration::from_millis(200)); + assert!(pending.try_wait().unwrap().is_none()); + let mut response = first_byte.to_vec(); + output.read_to_end(&mut response).unwrap(); + assert!(ssh.wait().unwrap().success()); + assert!( + protocol::read_complete_packet::(&response) + .unwrap() + .0 + .ok + ); + let receipt = success(pending.wait_with_output().unwrap()); + validate( + json!({"kind":"policy_update_cli_reply","request":revoked,"process_exit":0,"response":receipt}), + ); +} + +#[test] +fn crashed_worker_cannot_publish_after_fence() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let tip = repo.commit(WASM, "base").unwrap(); + set(&temp.0, "first.json", &update('a', 0, policy(true, true))); + let hook = hook(&temp.0); + let mut one = Server::start(&temp.0, Some(&hook)); + let two = Server::start(&temp.0, None); + let address = one.address.clone(); + let thread = std::thread::spawn(move || { + let body = packet(reference("crashed", &tip)); + let mut stream = TcpStream::connect(address).unwrap(); + write!(stream, "POST /v1/wasm-git HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer alice\r\nContent-Length: {}\r\n\r\n", body.len()).unwrap(); + stream.write_all(&body).unwrap(); + let mut response = Vec::new(); + let _ = stream.read_to_end(&mut response); + }); + wait_for(&temp.0.join("hook-started")); + for name in ["index.lock", "write.lock"] { + let held = fs::OpenOptions::new().read(true).write(true) + .open(temp.0.join("project/.wasm-git").join(name)).unwrap(); + assert!(held.try_lock().is_err(), "{name} must exclude another process"); + } + one.child.kill().unwrap(); + one.child.wait().unwrap(); + fs::write(temp.0.join("hook-release"), b"release").unwrap(); + wait_for(&temp.0.join("hook-finished")); + thread.join().unwrap(); + let error = Repository::open(temp.0.join("project")) + .and_then(|r| r.resolve("crashed")) + .unwrap_err(); + assert!(!error.contains("locked")); + assert!(rpc(&two.address, reference("after-crash", &repo.resolve("HEAD").unwrap())).ok); + set(&temp.0, "revoke.json", &update('b', 1, policy(false, true))); + assert!( + !rpc( + &two.address, + reference("crashed", &repo.resolve("HEAD").unwrap()) + ) + .ok + ); +} + +#[test] +fn killed_stdio_receive_releases_repository_and_index_locks() { + struct Process(Child); + impl Drop for Process { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_none() { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + } + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let tip = repo.commit(WASM, "base").unwrap(); + set(&temp.0, "first.json", &update('a', 0, policy(true, true))); + let hook = hook(&temp.0); + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args(["--stdio", "--root", temp.0.to_str().unwrap(), "--policy", temp.0.join("unused-bootstrap").to_str().unwrap(), "--principal", "alice", "--pre-receive", hook.to_str().unwrap()]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + child.stdin.take().unwrap().write_all(&packet(reference("stdio-crashed", &tip))).unwrap(); + let mut process = Process(child); + wait_for(&temp.0.join("hook-started")); + for name in ["index.lock", "write.lock"] { + let held = fs::OpenOptions::new().read(true).write(true) + .open(temp.0.join("project/.wasm-git").join(name)).unwrap(); + assert!(held.try_lock().is_err(), "{name} must exclude another process"); + } + process.0.kill().unwrap(); + assert!(!process.0.wait().unwrap().success()); + fs::write(temp.0.join("hook-release"), b"release").unwrap(); + wait_for(&temp.0.join("hook-finished")); + let error = Repository::open(temp.0.join("project")).and_then(|repo| repo.resolve("stdio-crashed")).unwrap_err(); + assert!(!error.contains("locked")); + + let mut retry = Command::new(env!("CARGO_BIN_EXE_wasm-git-server")) + .args(["--stdio", "--root", temp.0.to_str().unwrap(), "--policy", temp.0.join("unused-bootstrap").to_str().unwrap(), "--principal", "alice"]) + .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + retry.stdin.take().unwrap().write_all(&packet(reference("stdio-after-crash", &tip))).unwrap(); + let output = retry.wait_with_output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(protocol::read_complete_packet::(&output.stdout).unwrap().0.ok); +} + +#[test] +fn grant_expiring_during_hook_is_checked_before_reference_journal() { + let temp = Temp::new(); + let repo = Repository::init(temp.0.join("project")).unwrap(); + let tip = repo.commit(WASM, "base").unwrap(); + let expiry = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + + 2; + let mut expiring = policy(true, true); + expiring["principals"][0]["grants"][0]["expires_at"] = json!(expiry); + set(&temp.0, "first.json", &update('a', 0, expiring)); + let hook = hook(&temp.0); + let server = Server::start(&temp.0, Some(&hook)); + let address = server.address.clone(); + let thread = std::thread::spawn(move || rpc(&address, reference("expired", &tip))); + wait_for(&temp.0.join("hook-started")); + while std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + < expiry + { + std::thread::sleep(Duration::from_millis(20)); + } + fs::write(temp.0.join("hook-release"), b"release").unwrap(); + let response = thread.join().unwrap(); + assert!(!response.ok); + assert!(!response.publication_unknown); + assert!(response.error.unwrap().contains("authorization unavailable before delivery")); + assert!(Repository::open(temp.0.join("project")) + .unwrap() + .resolve("expired") + .is_err()); +} diff --git a/tests/server_pulls.rs b/tests/server_pulls.rs index 8b9affa..4067586 100644 --- a/tests/server_pulls.rs +++ b/tests/server_pulls.rs @@ -71,7 +71,7 @@ impl Server { let policy = compile( root, "policy", - json!({"version":1,"principals":[ + json!({"version":3,"principals":[ {"name":"alice","token_sha256":format!("{:x}",Sha256::digest(b"alice")),"grants":[{"repository":"*","read":true,"write":["refs/heads/*"],"force":true,"create":true}]}, {"name":"bob","token_sha256":format!("{:x}",Sha256::digest(b"bob")),"grants":[{"repository":"project","read":true,"write":["refs/heads/*"],"force":true,"create":false}]}, {"name":"ci","token_sha256":format!("{:x}",Sha256::digest(b"ci")),"grants":[{"repository":"project","read":true,"write":["refs/heads/*"],"force":false,"create":false}]}, @@ -374,31 +374,20 @@ fn direct_atomic_and_partial_push_cannot_bypass_pr_protection() { .unwrap(); assert!(!s.rpc("alice", Operation::PublishBatch {}, &bytes).0.ok); let upload_id = format!("{:x}", Sha256::digest(&bytes)); - assert!( - s.rpc( - "alice", - Operation::UploadSlice { - transfer: upload_id.clone(), - total: bytes.len() as u64, - offset: 0 - }, - &bytes - ) - .0 - .ok - ); - let uploaded = s + let binding = protocol::UploadBinding::for_payload(Operation::PublishBatch {}, &bytes).unwrap(); + let upload = s .rpc( "alice", - Operation::ApplyUpload { - transfer: upload_id, - operation: Box::new(Operation::PublishBatch {}), + Operation::ScopedUploadSlice { + session: upload_id, + binding, + offset: 0, }, - &[], + &bytes, ) .0; - assert!(!uploaded.ok); - assert!(uploaded.error.unwrap().contains("protected")); + assert!(!upload.ok); + assert!(upload.error.unwrap().contains("protected")); let partial = binary::encode(&protocol::OptionsPublication { publication: binary::decode(&bytes).unwrap(), options: vec![], @@ -415,6 +404,269 @@ fn direct_atomic_and_partial_push_cannot_bypass_pr_protection() { assert_eq!(repo.resolve("HEAD").unwrap(), base); } +#[test] +fn scoped_uploads_bind_authenticated_actor_and_recover_the_same_result() { + let t = Temp::new(); + let (repo, fork, base, head) = fixture(&t); + let s = Server::start(&t.0, false, &[]); + let bytes = fork + .network_bundle(std::slice::from_ref(&head), std::slice::from_ref(&base)) + .unwrap() + .1; + let operation = Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: None, + new: Some(head.clone()), + force: false, + }; + let binding = protocol::UploadBinding::for_payload(operation.clone(), &bytes).unwrap(); + let payload_file = t.0.join("upload-payload.bin"); + fs::write(&payload_file, &bytes).unwrap(); + let mut generator = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args([ + "--format", + "json", + "upload-binding", + payload_file.to_str().unwrap(), + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + generator + .stdin + .take() + .unwrap() + .write_all( + &serde_json::to_vec(&protocol::UploadBindingRequest { + version: 1, + operation: Box::new(operation), + }) + .unwrap(), + ) + .unwrap(); + let generated: serde_json::Value = + serde_json::from_str(&success(generator.wait_with_output().unwrap())).unwrap(); + let generated: protocol::UploadBinding = + serde_json::from_value(generated["result"]["value"].clone()).unwrap(); + assert_eq!( + binary::encode(&generated).unwrap(), + binary::encode(&binding).unwrap() + ); + let session = "a".repeat(64); + let chunk = || Operation::ScopedUploadSlice { + session: session.clone(), + binding: binding.clone(), + offset: 0, + }; + let query = || Operation::QueryScopedUpload { + session: session.clone(), + binding: binding.clone(), + }; + let apply = || Operation::ApplyScopedUpload { + session: session.clone(), + binding: binding.clone(), + }; + let cancel = || Operation::CancelScopedUpload { + session: session.clone(), + binding: binding.clone(), + }; + assert!(s.rpc("alice", chunk(), &bytes).0.ok); + assert!(!s.rpc("bob", chunk(), &bytes).0.ok); + assert!(!s.rpc("bob", query(), &[]).0.ok); + assert!(!s.rpc("bob", cancel(), &[]).0.ok); + assert!(!s.rpc("bob", apply(), &[]).0.ok); + let (first, _) = s.rpc("alice", apply(), &[]); + assert!(first.ok, "{first:?}"); + assert_eq!(repo.resolve("topic").unwrap(), head); + let (again, _) = s.rpc("alice", apply(), &[]); + assert!(again.ok); + assert_eq!(again.tip, first.tip); + let (status, bytes) = s.rpc("alice", query(), &[]); + assert!(status.ok); + let status: protocol::ScopedUploadStatus = binary::decode(&bytes).unwrap(); + match &status.state { + Some(protocol::ScopedUploadState::FinishedV4 { receipt }) => { + assert!(receipt.response.ok); + assert_eq!(receipt.scope.actor, "alice"); + assert_eq!(receipt.scope.repository, "project"); + assert_eq!(receipt.scope.session, session); + assert_eq!(receipt.updates[0].name, "topic"); + assert_eq!(receipt.updates[0].new.as_deref(), Some(head.as_str())); + assert!(receipt.rejections[0].is_none()); + } + _ => panic!("expected a v4 receipt"), + } + let mut client = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .args([ + "--format", + "json", + "scoped-upload-rpc", + &format!("http://{}/project", s.address), + ]) + .env("WASM_GIT_REMOTE_TOKEN", "alice") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let upload_request = protocol::ScopedUploadRequest { + version: 1, + command: protocol::ScopedUploadCommand::Query { + session: session.clone(), + binding: binding.clone(), + }, + }; + client + .stdin + .take() + .unwrap() + .write_all( + &serde_json::to_vec(&upload_request).unwrap(), + ) + .unwrap(); + let raw = success(client.wait_with_output().unwrap()); + let reply: serde_json::Value = serde_json::from_str(&raw).unwrap(); + let reply: protocol::ScopedUploadReply = + serde_json::from_value(reply["result"]["value"].clone()).unwrap(); + assert!( + matches!(reply, protocol::ScopedUploadReply::Status { status: protocol::ScopedUploadStatus { state: Some(protocol::ScopedUploadState::FinishedV4 { receipt }), .. }, .. } if receipt.response.ok) + ); + let request = serde_json::to_string(&upload_request).unwrap(); + let validation = format!(r#"{{"kind":"upload_cli_reply","repository":"project","request":{request},"process_exit":0,"response":{raw}}}"#); + let mut validator = Command::new(env!("CARGO_BIN_EXE_wasm-git")).args(["--format", "json", "integration-validate"]).stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap(); + validator.stdin.take().unwrap().write_all(validation.as_bytes()).unwrap(); + assert!(validator.wait_with_output().unwrap().status.success()); + assert!(!s.rpc("alice", cancel(), &[]).0.ok); +} + +#[test] +fn scoped_noop_rejections_and_dry_runs_are_durable_terminal_decisions() { + let t = Temp::new(); + let (repo, fork, base, head) = fixture(&t); + repo.create_branch("topic", &base).unwrap(); + let s = Server::start(&t.0, false, &[]); + let bundle = fork + .network_bundle(std::slice::from_ref(&head), std::slice::from_ref(&base)) + .unwrap() + .1; + fn run( + s: &Server, + session: String, + operation: Operation, + bytes: &[u8], + ) -> (Response, Vec, protocol::ScopedUploadStatus) { + let binding = protocol::UploadBinding::for_payload(operation, bytes).unwrap(); + assert!( + s.rpc( + "alice", + Operation::ScopedUploadSlice { + session: session.clone(), + binding: binding.clone(), + offset: 0 + }, + bytes + ) + .0 + .ok + ); + let (response, payload) = s.rpc( + "alice", + Operation::ApplyScopedUpload { + session: session.clone(), + binding: binding.clone(), + }, + &[], + ); + let (query, state) = s.rpc( + "alice", + Operation::QueryScopedUpload { session, binding }, + &[], + ); + assert!(query.ok, "{query:?}"); + (response, payload, binary::decode(&state).unwrap()) + } + let same = Operation::UpdateRef { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: Some(base.clone()), + new: Some(base.clone()), + force: false, + }; + let (response, _, status) = run(&s, "1".repeat(64), same, &bundle); + assert!(response.ok, "{response:?}"); + assert!( + matches!(status.state, Some(protocol::ScopedUploadState::FinishedV4 { receipt }) if receipt.response.ok && receipt.updates[0].expected == receipt.updates[0].new) + ); + let update = |expected: String| RefUpdate { + namespace: RefNamespace::Branch, + name: "topic".into(), + expected: Some(expected), + new: Some(head.clone()), + force: false, + }; + let payload = |expected: String| { + binary::encode(&protocol::OptionsPublication { + publication: BatchPublication { + updates: vec![update(expected)], + bundle: bundle.clone(), + }, + options: vec![], + }) + .unwrap() + }; + let (response, bytes, status) = run( + &s, + "2".repeat(64), + Operation::PublishPartial { dry_run: false }, + &payload("f".repeat(64)), + ); + assert!(response.ok, "{response:?}"); + assert!(binary::decode::(&bytes) + .unwrap() + .rejections[0] + .is_some()); + assert!( + matches!(status.state, Some(protocol::ScopedUploadState::FinishedV4 { receipt }) if receipt.response.ok && receipt.rejections[0].is_some()) + ); + let (response, _, status) = run( + &s, + "3".repeat(64), + Operation::PublishPartial { dry_run: true }, + &payload(base.clone()), + ); + assert!(response.ok, "{response:?}"); + assert!( + matches!(status.state, Some(protocol::ScopedUploadState::FinishedV4 { receipt }) if receipt.response.ok && receipt.dry_run) + ); + assert_eq!(repo.resolve("topic").unwrap(), base); + let (response, _, status) = run( + &s, + "4".repeat(64), + Operation::CheckBatch {}, + &payload(base.clone()), + ); + assert!(response.ok, "{response:?}"); + assert!( + matches!(status.state, Some(protocol::ScopedUploadState::FinishedV4 { receipt }) if receipt.response.ok) + ); + let (response, _, status) = run( + &s, + "5".repeat(64), + Operation::Push { + branch: "topic".into(), + expected: Some(base.clone()), + force: false, + }, + b"invalid bundle", + ); + assert!(!response.ok && !response.publication_unknown); + assert!( + matches!(status.state, Some(protocol::ScopedUploadState::FinishedV4 { receipt }) if !receipt.response.ok && !receipt.response.publication_unknown) + ); + assert_eq!(repo.resolve("topic").unwrap(), base); +} + #[test] fn named_tree_pr_diff_keeps_additions_deletions_paths_and_version_leases() { use std::collections::BTreeMap; diff --git a/tests/support/https_proxy.py b/tests/support/https_proxy.py new file mode 100644 index 0000000..50fa65b --- /dev/null +++ b/tests/support/https_proxy.py @@ -0,0 +1,56 @@ +"""Loopback TLS termination for real native integration tests; no mock replies.""" +import socket +import socketserver +import ssl +import sys + +context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +context.load_cert_chain(sys.argv[1], sys.argv[2]) +backend_host, backend_port = sys.argv[3].rsplit(':', 1) + + +class Handler(socketserver.BaseRequestHandler): + def handle(self): + self.request.settimeout(20) + try: + with context.wrap_socket(self.request, server_side=True) as client: + data = bytearray() + while b'\r\n\r\n' not in data: + part = client.recv(1) + if not part: + return + data.extend(part) + if len(data) > 16384: + raise ValueError('oversized headers') + headers = data.decode('ascii').split('\r\n') + lengths = [int(line.split(':', 1)[1]) for line in headers if line.lower().startswith('content-length:')] + if len(lengths) != 1 or not 0 <= lengths[0] <= 64 * 1024**2: + raise ValueError('invalid request length') + with socket.create_connection((backend_host, int(backend_port)), timeout=20) as upstream: + upstream.sendall(data) + remaining = lengths[0] + while remaining: + part = client.recv(min(65536, remaining)) + if not part: + return + remaining -= len(part) + upstream.sendall(part) + upstream.shutdown(socket.SHUT_WR) + while True: + part = upstream.recv(65536) + if not part: + break + client.sendall(part) + except (BrokenPipeError, ConnectionResetError, ssl.SSLError): + # A deliberately lost reply or an untrusted TLS handshake has no + # application response to manufacture. + return + + +class Server(socketserver.ThreadingTCPServer): + daemon_threads = True + + +with Server(('127.0.0.1', 0), Handler) as server: + print(f'127.0.0.1:{server.server_address[1]}', flush=True) + server.serve_forever() diff --git a/tests/trace_cli.rs b/tests/trace_cli.rs index 5a049dd..d6cebab 100644 --- a/tests/trace_cli.rs +++ b/tests/trace_cli.rs @@ -1109,13 +1109,14 @@ fn locked_or_corrupt_history_is_rejected_without_cleaning_someone_elses_files() let root = history.commit(&bytes, "root"); let tip = history.commit(&bytes, "same bytes, later commit"); let lock = Path::new(&history.repo).join(".wasm-git/write.lock"); - std::fs::write(&lock, b"another writer\n").unwrap(); + let held = std::fs::OpenOptions::new().read(true).write(true).open(&lock).unwrap(); + held.try_lock().unwrap(); let before = snapshot(&history.directory); let output = invoke(&["trace", &history.repo, &tip, "--range", "0:1"]); assert!(!output.status.success()); assert!(String::from_utf8_lossy(&output.stderr).contains("locked")); assert_eq!(snapshot(&history.directory), before); - std::fs::remove_file(lock).unwrap(); + drop(held); // A valid tip must not hide corruption in an ancestor outside the range. let ancestor = Path::new(&history.repo) .join(".wasm-git/objects") diff --git a/tests/tree_resolution_cli.rs b/tests/tree_resolution_cli.rs index 912ecbf..9fcc227 100644 --- a/tests/tree_resolution_cli.rs +++ b/tests/tree_resolution_cli.rs @@ -257,7 +257,8 @@ fn invalid_leases_branch_and_locks_never_publish_staged_bytes() { } for name in ["index.lock", "write.lock"] { let lock = t.path(&format!(".wasm-git/{name}")); - fs::write(&lock, b"held by test").unwrap(); + let held = fs::OpenOptions::new().read(true).write(true).open(&lock).unwrap(); + held.try_lock().unwrap(); let locked = snapshot(&t.0); fail(&[ "merge", @@ -270,7 +271,7 @@ fn invalid_leases_branch_and_locks_never_publish_staged_bytes() { &ours, ]); assert_eq!(snapshot(&t.0), locked); - fs::remove_file(lock).unwrap(); + drop(held); } assert_eq!(snapshot(&t.0), before); fail(&[ diff --git a/tests/upstream_cli.rs b/tests/upstream_cli.rs index e0360ad..59c88aa 100644 --- a/tests/upstream_cli.rs +++ b/tests/upstream_cli.rs @@ -519,18 +519,34 @@ fn upstream_metadata_commands_obey_index_remote_and_writer_locks_without_partial fixture.fetch(); for lock in ["index.lock", "remote.lock", "write.lock"] { let file = fixture.local.join(format!(".wasm-git/{lock}")); - fs::write(&file, b"fixed held lock").unwrap(); + let held = if lock == "remote.lock" { + fs::write(&file, b"fixed held lock").unwrap(); + None + } else { + let held = fs::OpenOptions::new().read(true).write(true).open(&file).unwrap(); + held.try_lock().unwrap(); + Some(held) + }; fixture.reject(&["branch", fixture.repo(), "-u", "origin/main"]); - fs::remove_file(file).unwrap(); + drop(held); + if lock == "remote.lock" { fs::remove_file(file).unwrap(); } } fixture.ok(&["branch", fixture.repo(), "-u", "origin/main"]); for lock in ["index.lock", "remote.lock", "write.lock"] { let file = fixture.local.join(format!(".wasm-git/{lock}")); - fs::write(&file, b"fixed held lock").unwrap(); + let held = if lock == "remote.lock" { + fs::write(&file, b"fixed held lock").unwrap(); + None + } else { + let held = fs::OpenOptions::new().read(true).write(true).open(&file).unwrap(); + held.try_lock().unwrap(); + Some(held) + }; fixture.reject(&["branch", fixture.repo(), "--unset-upstream"]); fixture.reject(&["branch", fixture.repo(), "-vv"]); fixture.reject(&["rev-parse", fixture.repo(), "@{u}"]); - fs::remove_file(file).unwrap(); + drop(held); + if lock == "remote.lock" { fs::remove_file(file).unwrap(); } } assert_eq!(fixture.head("@{u}"), fixture.head("origin/main")); } diff --git a/tests/worktree_cli.rs b/tests/worktree_cli.rs index 90af083..d3a7c74 100644 --- a/tests/worktree_cli.rs +++ b/tests/worktree_cli.rs @@ -155,7 +155,7 @@ fn worktree_locks_moves_and_force_removal_preserve_shared_history() { json(&["worktree", p(&primary), "move", p(&linked), p(&moved)]); assert!(!linked.exists()); assert_eq!(fs::read(moved.join("module.wasm")).unwrap(), b"dirty bytes"); - assert!(!moved.join(".wasm-git/index.lock").exists()); + assert!(moved.join(".wasm-git/index.lock").is_file()); json(&["status", p(&moved)]); fail(&["worktree", p(&primary), "remove", p(&moved)]); json(&["worktree", p(&primary), "remove", p(&moved), "-f"]); diff --git a/tests/writer_lock_cli.rs b/tests/writer_lock_cli.rs new file mode 100644 index 0000000..4a0e150 --- /dev/null +++ b/tests/writer_lock_cli.rs @@ -0,0 +1,339 @@ +#![cfg(all(feature = "client", unix))] + +use std::fs::{self, OpenOptions}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{symlink, FileTypeExt, MetadataExt}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, Receiver}; +use std::time::{Duration, Instant}; +use wasm_git::repository::Repository; + +static NEXT: AtomicU64 = AtomicU64::new(0); +const WASM: &[u8] = b"\0asm\x01\0\0\0"; + +struct Temp(PathBuf); +impl Temp { + fn new() -> Self { + let parent = Path::new(env!("CARGO_MANIFEST_DIR")).join(".tmp/writer-lock-tests"); + fs::create_dir_all(&parent).unwrap(); + let path = parent.join(format!( + "{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&path).unwrap(); + Self(path) + } +} +impl Drop for Temp { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +struct Running(Child); +impl Drop for Running { + fn drop(&mut self) { + if self.0.try_wait().ok().flatten().is_none() { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } +} + +fn seed(temp: &Temp) -> (PathBuf, String) { + let root = temp.0.join("repo"); + let repo = Repository::init(&root).unwrap(); + let tip = repo.commit(WASM, "initial commit").unwrap(); + (root, tip) +} + +fn linked(root: &Path, temp: &Temp) -> PathBuf { + linked_named(root, temp, "linked") +} + +fn linked_named(root: &Path, temp: &Temp, name: &str) -> PathBuf { + let linked = temp.0.join(name); + let output = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .arg("worktree") + .arg(root) + .arg("add") + .arg(&linked) + .args(["-b", name, "--legacy-path", "module.wasm"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + linked +} + +fn start_batch( + root: &Path, + commands: &str, +) -> (Running, std::process::ChildStdin, Receiver) { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .arg("update-ref") + .arg(root) + .arg("--stdin") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + if tx.send(line.unwrap()).is_err() { + break; + } + } + }); + write!(stdin, "start\n{commands}prepare\n").unwrap(); + stdin.flush().unwrap(); + assert_eq!( + rx.recv_timeout(Duration::from_secs(30)).unwrap(), + "start: ok" + ); + assert_eq!( + rx.recv_timeout(Duration::from_secs(30)).unwrap(), + "prepare: ok" + ); + (Running(child), stdin, rx) +} + +fn inode(path: &Path) -> (u64, u64) { + let metadata = fs::metadata(path).unwrap(); + (metadata.dev(), metadata.ino()) +} + +#[test] +fn killed_prepared_writer_releases_one_inode_shared_by_worktrees_and_aliases() { + let temp = Temp::new(); + let (root, tip) = seed(&temp); + let linked = linked(&root, &temp); + let alias_parent = temp.0.join("alias"); + symlink(&temp.0, &alias_parent).unwrap(); + let alias = alias_parent.join("repo"); + let path = root.join(".wasm-git/write.lock"); + let before = inode(&path); + let (mut writer, _stdin, _rx) = + start_batch(&root, &format!("create refs/tags/prepared {tip}\n")); + + for worktree in [&root, &linked, &alias] { + let repo = Repository::open(worktree).unwrap(); + assert!(repo.branches().unwrap_err().contains("locked")); + } + let hardlink = temp.0.join("lock-alias"); + fs::hard_link(&path, &hardlink).unwrap(); + let other = OpenOptions::new() + .read(true) + .write(true) + .open(&hardlink) + .unwrap(); + assert!(other.try_lock().is_err()); + assert_eq!(inode(&hardlink), before); + + writer.0.kill().unwrap(); + assert!(!writer.0.wait().unwrap().success()); + assert_eq!(inode(&path), before); + assert!(Repository::open(&linked) + .unwrap() + .resolve("prepared") + .is_err()); + let repo = Repository::open(&alias).unwrap(); + assert_eq!(repo.create_tag("after-crash", "HEAD").unwrap(), tip); + assert_eq!(inode(&path), before); + assert!(path.is_file()); +} + +#[test] +fn concurrent_first_acquisition_publishes_only_one_stable_lock_inode() { + let temp = Temp::new(); + let (root, tip) = seed(&temp); + let path = root.join(".wasm-git/write.lock"); + let trees: Vec<_> = (0..4) + .map(|index| linked_named(&root, &temp, &format!("linked-{index}"))) + .collect(); + let mut workers = Vec::new(); + for (index, tree) in trees.iter().enumerate() { + let mut child = Command::new(env!("CARGO_BIN_EXE_wasm-git")) + .arg("update-ref") + .arg(tree) + .arg("--stdin") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + if tx.send(line.unwrap()).is_err() { + break; + } + } + }); + write!(stdin, "start\n").unwrap(); + stdin.flush().unwrap(); + match rx.recv_timeout(Duration::from_secs(30)) { + Ok(line) => assert_eq!(line, "start: ok"), + Err(error) => { + let _ = child.kill(); + let _ = child.wait(); + let mut stderr = String::new(); + child + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + panic!("worker {index} could not start ({error}): {stderr}"); + } + } + workers.push((Running(child), stdin, rx, index)); + } + // Every process now holds its own worktree index, but no writer guard. + // Reproduce a pre-upgrade repository with no writer lock file. + fs::remove_file(&path).unwrap(); + for (_, stdin, _, index) in &mut workers { + write!(stdin, "create refs/tags/race-{index} {tip}\nprepare\n").unwrap(); + stdin.flush().unwrap(); + } + let mut acquired = 0; + for (child, _, rx, index) in &mut workers { + match rx.recv_timeout(Duration::from_secs(30)) { + Ok(line) => { + assert_eq!(line, "prepare: ok"); + acquired += 1; + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + let status = child.0.wait().unwrap(); + let mut stderr = String::new(); + child + .0 + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + eprintln!("worker {index} stderr: {stderr}"); + assert!( + !status.success(), + "worker {index} exited successfully: {stderr}" + ); + assert!( + stderr.contains("resource is locked"), + "worker {index}: {stderr}" + ); + } + Err(error) => { + let _ = child.0.kill(); + let _ = child.0.wait(); + let mut stderr = String::new(); + child + .0 + .stderr + .take() + .unwrap() + .read_to_string(&mut stderr) + .unwrap(); + panic!("worker {index} did not finish preparing ({error}): {stderr}"); + } + } + } + assert_eq!(acquired, 1); + let identity = inode(&path); + for (mut child, stdin, _, _) in workers { + drop(stdin); + let _ = child.0.wait().unwrap(); + } + assert!(Repository::open(&root).unwrap().branches().is_ok()); + assert_eq!(inode(&path), identity); +} + +#[test] +fn killed_committed_writer_rolls_forward_its_original_journal() { + const COUNT: usize = 512; + let temp = Temp::new(); + let (root, tip) = seed(&temp); + let linked = linked(&root, &temp); + let lock = root.join(".wasm-git/write.lock"); + let identity = inode(&lock); + let mut commands = String::new(); + for index in 0..COUNT { + commands.push_str(&format!("create refs/tags/crash-{index:04} {tip}\n")); + } + let (mut writer, mut stdin, _rx) = start_batch(&root, &commands); + stdin.write_all(b"commit\n").unwrap(); + stdin.flush().unwrap(); + let journal = root.join(".wasm-git/ref-transaction.bin"); + let deadline = Instant::now() + Duration::from_secs(30); + while !journal.is_file() { + assert!( + Instant::now() < deadline, + "writer did not publish its journal" + ); + assert!( + writer.0.try_wait().unwrap().is_none(), + "writer exited before its journal was observed" + ); + std::thread::sleep(Duration::from_millis(1)); + } + writer.0.kill().unwrap(); + assert!(!writer.0.wait().unwrap().success()); + assert!( + journal.is_file(), + "test did not interrupt the committed transaction" + ); + assert_eq!(inode(&lock), identity); + + let recovered = Repository::open(&linked).unwrap(); + assert!(!journal.exists()); + let tags = recovered.tags().unwrap(); + assert_eq!(tags.len(), COUNT); + for index in 0..COUNT { + assert_eq!(tags.get(&format!("crash-{index:04}")), Some(&tip)); + } + assert_eq!(inode(&lock), identity); +} + +#[test] +fn legacy_and_redirected_lock_files_are_never_taken_over() { + let temp = Temp::new(); + let (root, _) = seed(&temp); + let lock = root.join(".wasm-git/write.lock"); + let legacy = [b"WGTLCK\0\x01".as_slice(), &42u32.to_be_bytes()].concat(); + // Controlled fixture conversion with no live owner simulates an old binary's lock. + fs::write(&lock, &legacy).unwrap(); + let repo = Repository::open(&root).unwrap(); + assert!(repo.branches().unwrap_err().contains("legacy")); + assert_eq!(fs::read(&lock).unwrap(), legacy); + + fs::remove_file(&lock).unwrap(); + let outside = temp.0.join("outside"); + fs::write(&outside, b"untouched").unwrap(); + symlink(&outside, &lock).unwrap(); + assert!(repo.branches().is_err()); + assert_eq!(fs::read(&outside).unwrap(), b"untouched"); + assert!(fs::symlink_metadata(&lock) + .unwrap() + .file_type() + .is_symlink()); + + fs::remove_file(&lock).unwrap(); + let fifo = std::ffi::CString::new(lock.as_os_str().as_bytes()).unwrap(); + // SAFETY: fifo is a live NUL-terminated path in this test's directory. + assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0); + assert!(repo.branches().is_err()); + assert!(fs::symlink_metadata(&lock).unwrap().file_type().is_fifo()); +} diff --git a/tools/release.py b/tools/release.py index f9e04e1..2d51839 100644 --- a/tools/release.py +++ b/tools/release.py @@ -277,7 +277,7 @@ def verify_windows_runtime(path): def package(args): version = tomllib.loads((ROOT / "Cargo.toml").read_text())["package"]["version"] name = f"wasm-git-{version}-{args.label}" - destination = SCRATCH / "dist" + destination = Path(args.destination).resolve() if args.destination else SCRATCH / "dist" destination.mkdir(parents=True, exist_ok=True) # Explicit allowlist: no test data, build trees, credentials or profiles. files = [Path(args.client).resolve(), ROOT / "LICENSE", ROOT / "README.md", @@ -288,6 +288,26 @@ def package(args): ROOT / "documents" / "UWVM2_ROS_EXTENSIONS.zh_CN.md"] if args.server: files.append(Path(args.server).resolve()) + temporary = None + if args.include_contract: + if not args.server: + raise RuntimeError("integration package requires both native client and server") + SCRATCH.mkdir(parents=True, exist_ok=True) + temporary = tempfile.TemporaryDirectory(dir=SCRATCH, prefix="package-contract-") + scratch = Path(temporary.name) + capability_bytes = subprocess.check_output([str(files[0]), "--format", "json", "integration-capabilities"]) + capability_record = json.loads(capability_bytes) + validation = json.dumps({"kind": "capabilities_cli_reply", "process_exit": 0, "response": capability_record}).encode() + subprocess.run([str(files[0]), "--format", "json", "integration-validate"], input=validation, stdout=subprocess.DEVNULL, check=True) + capabilities = scratch / "integration-capabilities.json" + capabilities.write_bytes(capability_bytes) + sums = scratch / "BINARY-SHA256SUMS" + sums.write_text("".join(f"{hashlib.sha256(path.read_bytes()).hexdigest()} {path.name}\n" for path in (files[0], Path(args.server).resolve()))) + files.extend([ROOT / "src" / "protocol.rs", ROOT / "src" / "binary.rs", capabilities, sums]) + if args.source_manifest: + files.append(Path(args.source_manifest).resolve()) + elif args.source_manifest: + raise RuntimeError("--source-manifest requires --include-contract") if args.label.endswith("windows-msvc"): verify_windows_runtime(Path(args.client).resolve()) if args.server: @@ -297,15 +317,17 @@ def package(args): raise RuntimeError(f"missing or symlinked release input: {path}") if args.label.endswith("windows-msvc") or args.label.endswith("windows-gnu"): archive = destination / (name + ".zip") - with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as output: + with zipfile.ZipFile(archive, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as output: for path in files: output.write(path, f"{name}/{path.name}") else: archive = destination / (name + ".tar.gz") - with tarfile.open(archive, "w:gz") as output: + with tarfile.open(archive, "x:gz") as output: for path in files: output.add(path, arcname=f"{name}/{path.name}", recursive=False) print(archive) + if temporary: + temporary.cleanup() def inventory(_args): @@ -344,6 +366,10 @@ def main(): child.add_argument("--label", required=True) if name == "smoke": child.add_argument("--runner-arg", action="append", default=[]) + else: + child.add_argument("--destination") + child.add_argument("--include-contract", action="store_true") + child.add_argument("--source-manifest") commands.add_parser("inventory") commands.add_parser("checksums") args = parser.parse_args() diff --git a/webgui/test_webgui.py b/webgui/test_webgui.py index 3f2268d..f640005 100644 --- a/webgui/test_webgui.py +++ b/webgui/test_webgui.py @@ -285,7 +285,7 @@ def test_server_service_audit_and_native_policy_compile(self): self.request("/api/jobs/cancel", {"id": job["id"]}) self.wait_job(job, success=None) - policy = {"version": 1, "principals": [{"name": "alice", "token_sha256": hashlib.sha256(b"gui-test").hexdigest(), + policy = {"version": 2, "principals": [{"name": "alice", "token_sha256": hashlib.sha256(b"gui-test").hexdigest(), "grants": [{"repository": "team/*", "read": True, "write": ["refs/heads/*"], "force": False, "create": True}]}]} protection = {"version": 1, "rules": [{"repository": "team/*", "branches": ["refs/heads/main"], "required_reviews": 0, "required_checks": []}]}