feat(ql3): add secure console task editing

This commit is contained in:
whyour
2026-08-29 13:18:43 +08:00
parent 9089c5a8e6
commit 6239c4d698
19 changed files with 1870 additions and 56 deletions
+2
View File
@@ -11,6 +11,8 @@
最新增量证据(2026-08-29):
- D-422/ADR-0517(已实现源码候选,阶段实物待 CI/milestone):Local Console 不再用隐藏 spec 的 bounded Task read 拼装 update。新增 `POST /api/v3/projects/:projectId/tasks/:taskId/authoring`User Bearer 先通过 `task.update`,再由 owner-private 两分钟一次性 proof 提升为 `local_console`,同时重跑 `task.read/task.update` 并要求 exact Policy fence 一致;完整定义读取后再次确认 credential,记录独立 durable `task.authoring.read` audit,并签发只保存摘要的 10 分钟一次性 lease。lease 绑定 Project/Task/revision/content digest/credential ID+version/User subjectEdge/Standalone 上限 8/32、请求时惰性清理,无数据库表、migration、timer、watcher、daemon、Pool 或新 package。Task update 必须先以 lease 验证旧快照,再用第二份 exact-content proof 确认保存,并继续由 D-421 的事务 authority 执行 expectedRevision、Policy、credential、RoleBinding 与 audit fencecreate 拒绝夹带 lease。Console 只开放可严格识别的内建 argv command 编辑,Task ID 只读,未展示的 environment、Secret bundle、working directory、未来 config 字段与 labels 原样保留。真实 SQLite/loopback 已通过 authoring challenge→完整定义/lease→save challenge→revision 2→bounded read 隐藏 spec→新 fence 启动;真实 Chromium 完成双 proof 更新并验证隐藏 config/labels 不丢失,390×844 无横向溢出。Local API `64/64`18-package clean build/test `3,038 total / 3,016 pass / 22 conditional skip / 0 fail`;三资产 69,723 bytes,默认 Edge 保持 2,737,205 bytes/329 files/58 modulesopt-in Edge/Standalone Console 为 4,077,890/4,078,034 bytes、473 files/12 packages/95 modulesRSS delta 16,269,312/16,318,464 bytespackage/source、122-module Edge import 与 Cluster dependency audit 均 compatible。默认 headless 与 Cluster 路径不变。远端主 CI 与新同源双架构 Console milestone 未闭合前,本项不得冒充现有 D-421 下载产物。
- D-421/ADR-0516(已实现并交付同源双架构 Console Alpha Candidate):Local Web Task mutation 不再受限于短生命周期 CLI 的进程级 active credential。`PUT /api/v3/projects/:projectId/tasks/:taskId` 把 Bearer 限定为 session credential,第一次 exact request 只在 deployment root 内 `0700` 目录发布 `0600`、当前 UID、两分钟、一次性的私有 proof fileHTTP 只返回 authorization ID、canonical request digest、expiry 与 basename,不返回 proof 或宿主绝对路径。proof 绑定 Task 全内容、credential ID/version 与 User subjectEdge/Standalone pending 上限为 8/32,按请求惰性清理,不新增 timer/watcher/daemon。验证后 principal 提升为短期 `local_console`,既有 Task administration service 重跑 PolicySQLite runtime 为每个请求建立独立 credential-fenced repository,并在 Task append 事务内复验 credential/Identity/pepper、actor、Project/RoleBinding fence,原子提交 allowed audit 与 mutation。并发测试证明两个 User repository 不共享 ambient authority,撤销 A 不影响 BRoleBinding 漂移仍原子拒绝;真实 loopback HTTP→私有 proof file→SQLite create 与 Chromium 编辑器/proof ticket 已通过。Console 当前完成 command Task 创建;HTTP 与 CLI 支持完整 create/updateWeb update 等待强认证 authoring read/lease,避免用不含 spec 的 bounded read 覆盖未知字段。三资产合计 62,632 bytesLocal API 56/56、18-package clean build/test 3,030 total/3,008 pass/22 条件跳过/0 failpackage/source、Local image、122-module Edge import 与 Cluster dependency audit 均 compatible。首个阶段提交 `884912d1` 暴露默认 Edge 静态加载管理 authority 的真实回归:x64 21,229,568-byte RSS 超过 20 MiB 门,failed-only 重跑再次失败;修复没有扩大预算,而是改为 proof 验证后的 request-time dynamic import。默认 Edge 恢复 2,737,205 bytes/329 files/58 modulesopt-in Edge/Standalone Console 为 4,041,294/4,041,438 bytes、472 files/12 packages/94 modules,均保有门禁余量;默认 headless 与 Cluster 路径不变。修复提交 `dc1686bd6fb3505174dd9a14098ae5c2c92a1a7f` 的主 CI run `33229592307` 为 41 success/3 expected skip/0 failKubernetes run `33229592293` 成功;显式 Console milestone run `33230227006` 为 42 success/2 scope skip/0 fail,生成 187,797,970-byte amd64、185,029,586-byte arm64 Trial Kit 与 5,623-byte milestone,保留至 2026-09-28。下载索引通过 checksum 与离线 auditor,返回 `compatible=true`。因此 D-421 已是可下载、可验真、可 fresh 试运行的 `3.0.0-alpha.2` 阶段实物,但仍不是公开 release、生产升级或长期支持版本。
- D-420/ADR-0515(已实现,首份真实双架构 Console v5 Trial Kit 已交付):阶段可用的首个自动化从“原生 CI 能通过 API 看到 bounded log marker”推进为“部署者能在 Console 直接观察实际输出”。Local Run HTTP 详情只追加严格验证的 latest Attempt 低敏摘要(ID、序号、状态、时间和 `logAvailable`),不返回 executor handle、Artifact ID、路径、Worker、PID 或错误明细;共享 HIGH 风险 `executeBoundedRunReadProjection` 保持不变,避免 Local UI 字段漂移到内建 Run read/compare Tool。Console 使用既有 `artifact.read` Policy/Audit/credential re-confirm 链,每次固定读取首个 32 KiB base64 窗口,分别显示 available/pending/retired/not-found/unavailable、range 与 truncation,不新增轮询、WebSocket、timer、缓存或整文件下载。三资产增至 48,318 bytes`edge-application-api|standalone-application-api` 为 3,960,535 / 3,960,679 bytes、467 files、12 packages、90 loaded modules,仍低于 6 MiB/640-file 门,默认 headless Edge 保持 2,669,390 bytes/325 files/58 modulesCluster 零变化。Local API 49/49、完整 backend `1,650 total / 1,648 pass / 2 Linux conditional skip / 0 fail`、18-package clean build/test 退出 0package/source、Local image、122-module Edge import 和 Cluster dependency audit 均 compatible。提交 `57953ec8` 的远端 QingLong 3.0 CI 为 41 success / 3 expected artifact-finalizer skip / 0 fail,独立 Kubernetes deployment live contract 为 1/1 success。现有 `task.put` 的进程级 active credential fence 不适合常驻并发 HTTPWeb Task 创建/修订必须以后续“每请求 credential fence + 同事务 Policy/Audit/mutation”切片完成,D-420 不用单因子 Bearer 绕过强认证。
@@ -0,0 +1,71 @@
# ADR-0517:强认证 Local Console Task authoring lease
- 状态:Accepted
- 日期:2026-08-29
- 对应 RFC 切片:D-422
- 关联:ADR-0256、ADR-0377、ADR-0512、ADR-0516
## 背景
ADR-0516 已让 Local Console 以 request-scoped credential fence 和本机一次性 proof 创建 Task,但 bounded Task read 有意隐藏完整 spec。直接用该投影编辑会静默删除环境变量、Secret bundle、工作目录或未来 schema 字段;把完整定义放进普通 Bearer read 又会扩大单因子凭据的读取能力。HTTP update 虽已存在,也必须防止调用方拿旧快照或其他 credential 读取的内容发起修改。
本切片要补齐可实际试用的 Web update,同时保持低配路由设备无后台成本、默认 headless 零增量、Cluster authority 独立。
## 决策
### 1. 完整定义只通过强认证 authoring read 交付
Local API 新增固定路由:
```text
POST /api/v3/projects/:projectId/tasks/:taskId/authoring
```
请求无 body。Bearer 必须解析为 User credential,并先通过 `task.update` Policy。第一次请求只发布 ADR-0516 的 owner-private POSIX presence challenge;验证 proof 前不读取或返回完整定义。proof 验证后形成短生命周期 `local_console` principal,服务同时重新授权 `task.read``task.update`,并要求两项决定的 Project/RoleBinding fence 完全一致。
读取后再次确认 exact credential authority,再记录独立的 durable `task.authoring.read` allowed audit。不存在与跨 Project 继续按既有边界收敛;任何 Policy、credential、SQLite 或 audit 不可用均失败关闭。
### 2. 返回一次性、内容绑定的编辑租约
成功响应返回完整 `TaskDefinitionRecord`,以及 10 分钟内有效的不透明 authoring lease。服务只保存 lease presentation 的 SHA-256,不保存明文;绑定包含:
- Project ID、Task ID、revision 与 content digest
- credential ID/version
- User subject。
lease 只允许消费一次。Edge 最多 8 个,Standalone 最多 32 个;过期项在请求进入时惰性清理,关闭 Local API 时清零 digest。实现不增加数据库表、migration、连接池、timer、watcher、daemon 或网络 listener。
### 3. update 需要 authoring lease 与第二份内容 proof
`PUT /api/v3/projects/:projectId/tasks/:taskId` 的 create 继续不需要 authoring lease,并拒绝调用方夹带 lease。update 必须同时提交 exact lease。服务在发布保存 proof 前检查当前 revision/content/credential 仍与 lease 相同;调用方完成第二次本机 presence 后,再次读取当前定义并原子消费 lease,随后进入 ADR-0516 已有的 credential-fenced Task administration transaction。
authoring proof 证明“允许读取完整旧定义”,保存 proof 证明“操作者确认这份新内容”,两者不得复用。租约检查不能替代事务内 expectedRevision、Policy、credential、RoleBinding 与 audit fence;检查和写入之间的竞争仍由已有 CAS/事务 authority 拒绝。
### 4. Console 只修改它明确展示的字段
Console 对内建 `command + qinglong/command@v1 + argv` 提供“编辑任务”。Task ID 只读;名称、说明、file、逐行 args 与 enabled 可修改。保存时以强认证快照为基底,只替换这些可见字段,labels 与 config 中未展示的 environment、Secret bundle、working directory 及未来兼容字段原样保留。无法严格识别的 kind/schema 继续使用受信 CLI,不提供有损编辑器。
页面仍只把 credential、proof、完整快照与 lease 保存在当前内存,不使用 Cookie、Web Storage、URL、日志或遥测。刷新、断开、关闭编辑器或取消 presence 会丢弃内存状态。
### 5. 部署档位保持分层
- 默认 Edge/Standalone headless 不加载 Local API、Console 或 lease manager
- opt-in Edge Console 的 8 项上限避免低内存设备被长会话拖住;Standalone 为 32
- Cluster 不接受 Local POSIX proof 或内存 lease。多节点 Task authoring 必须由 Cluster Control 的 TLS、RBAC、共享持久 authority 与独立管理面设计完成。
## 不采用的方案
- 不扩大 bounded Task read:普通列表/详情不应泄漏完整执行配置。
- 不让 Bearer 单独取得完整定义:这会把 strong User 降级为浏览器持有单因子 secret。
- 不只用 lease 直接写:读取授权不等于确认新内容,保存仍需要第二份 exact proof。
- 不让 Console 重新构造整个 command config:未展示字段会被静默删除。
- 不建立持久 Web session、轮询或 lease 清理 timer:当前显式操作与惰性清理足够,低配设备不承担常驻成本。
- 不抽象成 Local/Cluster 共用插件:单机 POSIX owner 与多节点身份、审批、HA 不是同一种 authority。
## 结果与验证边界
定向验证覆盖完整定义只在 proof 后返回、两次 credential confirm、read/update Policy fence 一致、durable audit、lease 的 credential/revision/content 绑定、一次性消费、过期与 Edge 容量;PUT 覆盖缺失/过期/漂移 lease 在生成保存 proof 前拒绝,以及 proof 后再检查并消费。真实 SQLite/loopback 旅程覆盖 authoring challenge → 完整 spec/labels → lease → 保存 challenge → revision 2 → bounded read 不泄漏 spec → 新 revision/content fence 启动。
本地 Local API 为 `64/64`18-package clean build/test 为 `3,038 total / 3,016 pass / 22 conditional、platform 或 external-service skip / 0 fail`。package boundary 保持 18 packages 且无 single-source/shallow packageCluster dependency 与 122-module Edge import audit 均 compatible。默认 Edge 为 2,737,205 bytes/329 files/58 modulesopt-in Edge/Standalone Console 为 4,077,890/4,078,034 bytes、473 files、12 packages、95 modulesRSS delta 16,269,312/16,318,464 bytes,均低于既有门。三资产合计 69,723 bytes。真实 Chromium 已完成双 proof 更新到 revision 2,并以 409 模拟断言验证未展示 config/labels 与 lease header 不得丢失;390×844 无横向溢出。
本 ADR 被合入、远端主 CI 及对应 Profile 门通过前只算源码候选;同源 amd64/arm64 Console Trial Kit 与 milestone index 重新生成并离线验真后,才升级为新的可下载阶段产物。既有 D-421 Console v5 milestone 仍是当前可下载实物,不能改名冒充 D-422。
+1
View File
@@ -520,6 +520,7 @@
| [ADR-0514](./ADR-0514-stage-usable-first-automation-journey.md) | 阶段可用的首个自动化旅程 | AcceptedConsole v5 双架构实物已由 D-420 闭合) |
| [ADR-0515](./ADR-0515-bounded-local-console-run-log.md) | Local Console 的有界 Run 日志观察面 | Accepted(首份实际 Console v5 双架构 milestone 已交付) |
| [ADR-0516](./ADR-0516-request-scoped-local-console-task-mutation.md) | request-scoped Local Console Task mutation | Accepted(新双架构 Trial Kit 待本阶段 milestone |
| [ADR-0517](./ADR-0517-strong-local-console-task-authoring-lease.md) | 强认证 Local Console Task authoring lease | Accepted(源码候选,待 CI 与新双架构 milestone |
## 规则
+3
View File
@@ -26,9 +26,12 @@
| D-419 Console 首自动化闭环 | quickstart 创建无网络/SecretRef/Trigger 的示例 Task;原生 CI 使用真实 Owner credential 完成 read、fenced start、`succeeded` 与 bounded log marker | 仍不提供 Web Task 编辑、2.x 升级或生产远程管理 |
| D-420 Console Run 日志观察面 | 选择 Run 后经既有认证/Policy/Audit 链读取 latest Attempt 首个 32 KiB,展示 range、truncation、pending/retired 等明确状态 | 不自动轮询、不提供整文件下载;Web Task 创建/修订仍待独立强认证事务切片 |
| D-421 Console Task 创建切片 | request-scoped credential fence、两分钟一次性本机 proof、同事务 Policy/Audit/Task mutation 已完成;Console 可创建 command Task;同源双架构 Console v5 Trial Kit 与 milestone 已生成并验真 | Web update 等待 authoring read/leaseCluster 不复用 Local proof;仍不是生产或公开发布 |
| D-422 Console Task 安全编辑切片 | 源码候选已实现强认证完整定义读取、10 分钟一次性 authoring lease、第二份 exact save proof 与 revision/content/credential fenceConsole 可无损编辑内建 argv command Task;本地完整 package/Profile/浏览器门已通过 | 待远端主 CI 和新同源双架构 Console milestone;现有 D-421 archive 不包含本能力 |
D-421 已关闭 D-420 记录的“Web Task mutation 必须独立设计”缺口,而且没有改名复用 run `33173769047` 的旧 archive。修复提交 `dc1686bd6fb3505174dd9a14098ae5c2c92a1a7f` 的普通主 CI [run 33229592307](https://github.com/whyour/qinglong/actions/runs/33229592307) 为 41 success/3 expected artifact-finalizer skip/0 fail,同源 Kubernetes deployment [run 33229592293](https://github.com/whyour/qinglong/actions/runs/33229592293) 成功;随后显式 Local Console milestone [run 33230227006](https://github.com/whyour/qinglong/actions/runs/33230227006) 为 42 success/2 scope skip/0 fail。由此 Web 创建能力已进入新的阶段实物,而不再只是候选源码。
D-422 当前仍按“源码候选”登记:本地真实 SQLite/loopback 已证明读取、租约、第二次 proof、更新与新围栏启动闭环;18-package clean build/test 为 `3,038 total / 3,016 pass / 22 conditional skip / 0 fail`Local API `64/64`,默认 Edge 与 opt-in Edge/Standalone Console 资源门及真实 Chromium 双证明编辑均通过。但在远端主 CI 和新的显式双架构 milestone 闭合前,不声称现有下载物已经包含 Web 编辑。阶段产物必须绑定新的 exact commit/run/artifact digest,禁止沿用 D-421 的 archive 名称或证据。
D-418 防止把“20 天代码和测试”冒充“用户已经能下载并完整操作”:源码与普通 CI 已具备生成、审计和实跑两种 Trial Kit 的能力,但只有显式 artifact run 生成且被同 run 的双架构 milestone 收录后,才是可下载阶段产物。操作说明见 [Local Alpha Trial Kit](./ql3-local-alpha-trial-kit.md) 与 [Local Web Console](./ql3-local-web-console.md)。
当前最新可交付 Local Console v5 绑定提交 `dc1686bd6fb3505174dd9a14098ae5c2c92a1a7f` 与 [GitHub Actions run 33230227006](https://github.com/whyour/qinglong/actions/runs/33230227006),保留至 2026-09-28
+9 -9
View File
@@ -55,24 +55,24 @@ ssh -L 5701:127.0.0.1:5701 router.example
1. 输入 Project ID 和 `ql3c_…` API credential,选择“连接本机”。
2. 选择“创建任务”,填写 Task ID、名称、argv 可执行文件和逐行参数,再选择“保存并生成本机证明”。
3. 在部署设备上以 QingLong 数据目录 owner 读取 `<deploymentRoot>/console-presence/<页面显示的 basename>`;把 JSON 的 `proof` 值粘贴回页面。文件为 `0600`、两分钟有效且只能用于这份 exact Task 一次。不要通过聊天、日志或 URL 转发 proof。
4. 创建成功后核对 revision/content fence,再选择“运行一次”。fresh Console Trial Kit 也可直接使用 `alpha-first-automation`
5. 在“运行”中选择 durable Run,按 Event sequence 判断实际进度;Bounded log 只显示 latest Attempt 的首个 32 KiB,后续内容仍需通过 API 分页读取
6. 日志 pending 时使用“刷新”显式重读;retired 表示内容已按保留策略清理,不代表 Run/Event 事实丢失
7. “请求取消”只提交 durable cancellation intent;界面出现 `cancelled|failed|succeeded|timed_out` 终态前,不要认为进程已经停止
8. 完成后选择“断开并清除凭据”,再关闭页面
3. 在部署设备上以 QingLong 数据目录 owner 读取 `<deploymentRoot>/console-presence/<页面显示的 basename>`;把 JSON 的完整 `ql3p_…` proof 值粘贴回页面。文件为 `0600`、两分钟有效且只能用于这份 exact 操作一次。不要通过聊天、日志或 URL 转发 proof。
4. 编辑现有内建 command Task 时先选择“编辑任务”,完成第一次本机证明以读取完整定义并取得 10 分钟一次性编辑租约。保存新内容时页面会要求第二份 proof;第一份只授权读取,不能复用来保存。Task ID 只读,未展示的 command config 与 labels 会原样保留
5. 创建或更新成功后核对 revision/content fence,再选择“运行一次”。fresh Console Trial Kit 也可直接使用 `alpha-first-automation`
6. 在“运行”中选择 durable Run,按 Event sequence 判断实际进度;Bounded log 只显示 latest Attempt 的首个 32 KiB,后续内容仍需通过 API 分页读取
7. 日志 pending 时使用“刷新”显式重读;retired 表示内容已按保留策略清理,不代表 Run/Event 事实丢失
8. “请求取消”只提交 durable cancellation intent;界面出现 `cancelled|failed|succeeded|timed_out` 终态前,不要认为进程已经停止
9. 完成后选择“断开并清除凭据”,再关闭页面。
Credential 只存在当前页面内存,不进入 URL、Cookie 或 Web Storage。页面刷新会丢失 credential,需要重新输入;这是当前安全边界,不是缺陷。
## 当前阶段可用边界
当前可操作闭环是 command Task create/list/read/start 与 Run list/read/events/steps/log/cancel。HTTP `PUT` 也支持提供完整 exact definition 的 update页面暂不负责:
当前可操作闭环是内建 argv command Task create/list/read/update/enable/disable/start 与 Run list/read/events/steps/log/cancel。编辑器只修改当前展示字段,并保留完整快照中的其他 config/labels;其他 kind/schema 继续使用受信管理入口。页面暂不负责:
- 编辑/启停现有 Taskbounded read 不返回完整 spec,不能据此安全覆盖;继续使用 `ql3-task`,后续由 authoring lease/read 切片补齐);
- Identity、Policy、Secret、Plugin Package 或 AI 配置管理;
- 日志整文件下载、终端、文件管理或 2.x 数据迁移;
- LAN/public 暴露、TLS termination、多用户 Web session 或 Cluster 管理。
三项静态资产总计 62,632 bytes,不依赖 CDN、网络字体或前端框架,仍低于 192 KiB 总闭包和单文件 96 KiB 门。`edge-application-api|standalone-application-api` 为 4,041,294 / 4,041,438 bytes、472 files、12 packages、94 loaded modules,仍低于 6 MiB/640-file 门;基础 headless Edge 保持 2,737,205 bytes、329 files、3 packages、58 modules,不携带这些资产。
三项静态资产总计 69,723 bytes,不依赖 CDN、网络字体或前端框架,仍低于 192 KiB 总闭包和单文件 96 KiB 门。`edge-application-api|standalone-application-api` 为 4,077,890 / 4,078,034 bytes、473 files、12 packages、95 loaded modules,仍低于 6 MiB/640-file 门;本机 RSS delta 为 16,269,312 / 16,318,464 bytes,低于 28 MiB。基础 headless Edge 保持 2,737,205 bytes、329 files、3 packages、58 modules,不携带这些资产。
停止 Local API 进程走与 Application 相同的 drain/shutdown 路径。Console 没有独立数据库、后台任务或需要额外清理的持久状态。
@@ -798,6 +798,12 @@ textarea:focus-visible,
resize: vertical;
}
.editor-grid input[readonly] {
color: var(--muted);
border-left: 4px solid var(--signal);
background: var(--fog);
}
.editor-wide {
grid-column: 1 / -1;
}
+183 -29
View File
@@ -5,7 +5,10 @@
const TASK_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TOKEN_PATTERN =
/^ql3c_[A-Za-z0-9][A-Za-z0-9._:-]{0,63}_[A-Za-z0-9_-]{43}$/;
const PRESENCE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const PRESENCE_PATTERN =
/^ql3p_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[A-Za-z0-9_-]{43}$/;
const AUTHORING_LEASE_PATTERN =
/^ql3a_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}_[A-Za-z0-9_-]{43}$/;
const LOG_READ_BYTES = 32 * 1024;
const TERMINAL = new Set(['succeeded', 'failed', 'cancelled', 'timed_out']);
const STATUS_LABELS = Object.freeze({
@@ -39,7 +42,13 @@
strong_authentication_required:
'当前凭据不能执行管理操作;请使用本机 User API Credential。',
task_definition_fence_rejected:
'Task 或授权在确认期间发生变化。请刷新后重新创建。',
'Task 或授权在确认期间发生变化。请刷新后重新编辑。',
task_authoring_lease_required:
'更新 Task 前必须重新读取完整定义。请关闭编辑器后选择“编辑任务”。',
task_authoring_lease_rejected:
'Task、凭据或编辑租约已经变化。请关闭编辑器后重新读取。',
task_authoring_unavailable:
'暂时无法建立安全编辑会话。请稍后重新读取 Task。',
invalid_task_definition: 'Task 定义无效。请检查 ID、命令与参数。',
task_definition_unavailable: 'Task 暂时无法保存。请检查数据库状态。',
run_cancellation_fence_rejected:
@@ -67,6 +76,9 @@
dialogCopy: document.getElementById('confirmation-copy'),
dialogAccept: document.getElementById('confirmation-accept'),
taskEditor: document.getElementById('task-editor-dialog'),
taskEditorTitle: document.getElementById('task-editor-title'),
taskEditorIntro: document.getElementById('task-editor-intro'),
taskEditorNote: document.getElementById('task-editor-note'),
taskEditorForm: document.getElementById('task-editor-form'),
taskEditorClose: document.getElementById('task-editor-close'),
taskEditorSave: document.getElementById('task-editor-save'),
@@ -76,8 +88,10 @@
taskCommand: document.getElementById('task-command-input'),
taskArgs: document.getElementById('task-args-input'),
taskEnabled: document.getElementById('task-enabled-input'),
taskEnabledLabel: document.getElementById('task-enabled-label'),
presenceDialog: document.getElementById('presence-dialog'),
presenceForm: document.getElementById('presence-form'),
presenceCopy: document.getElementById('presence-copy'),
presenceFile: document.getElementById('presence-file'),
presenceProof: document.getElementById('presence-proof-input'),
presenceExpiry: document.getElementById('presence-expiry'),
@@ -93,7 +107,8 @@
view: 'tasks',
selectedId: null,
pendingAction: null,
pendingTaskMutation: null,
pendingPresence: null,
authoringSnapshot: null,
toastTimer: null,
};
@@ -204,6 +219,9 @@
if (options.presence !== undefined) {
headers['x-qinglong-local-presence'] = options.presence;
}
if (options.authoringLease !== undefined) {
headers['x-qinglong-task-authoring-lease'] = options.authoringLease;
}
let response;
try {
response = await fetch(path, {
@@ -345,13 +363,74 @@
nodes.dialog.showModal();
}
function openTaskEditor() {
function openTaskEditor(snapshot = null) {
state.authoringSnapshot = snapshot;
nodes.taskEditorForm.reset();
nodes.taskCommand.value = '/bin/echo';
nodes.taskEnabled.checked = true;
const editing = snapshot !== null;
nodes.taskEditorTitle.textContent = editing
? '编辑命令任务'
: '创建命令任务';
nodes.taskEditorIntro.textContent = editing
? `完整定义已由本机证明读取,并绑定 revision ${snapshot.task.revision}。保存时还会生成一份只绑定新内容的证明。`
: '定义会先绑定到一次本机证明,再以同一事务写入 Task revision 与安全审计。';
nodes.taskEditorNote.textContent = editing
? `编辑租约将在 ${formatTime(
snapshot.authoring.expiresAtMs,
)} 失效关闭后重新选择编辑任务可取得新快照`
: 'Alpha 当前从 Console 创建 qinglong/command@v1;高级 Task schema 仍使用受信任管理入口。';
nodes.taskEnabledLabel.textContent = editing
? '保存后允许运行'
: '创建后允许运行';
nodes.taskId.readOnly = editing;
if (editing) nodes.taskId.setAttribute('aria-readonly', 'true');
else nodes.taskId.removeAttribute('aria-readonly');
if (editing) {
const command = snapshot.task.spec.config.command;
nodes.taskId.value = snapshot.task.taskId;
nodes.taskName.value = snapshot.task.name;
nodes.taskDescription.value = snapshot.task.description || '';
nodes.taskCommand.value = command.file;
nodes.taskArgs.value = command.args.join('\n');
nodes.taskEnabled.checked = snapshot.task.enabled;
} else {
nodes.taskCommand.value = '/bin/echo';
nodes.taskEnabled.checked = true;
}
nodes.taskEditor.returnValue = '';
nodes.taskEditor.showModal();
nodes.taskId.focus();
(editing ? nodes.taskName : nodes.taskId).focus();
}
function authoringSnapshot(value, expectedTaskId) {
const task = value?.task;
const authoring = value?.authoring;
const command = task?.spec?.config?.command;
if (
!task ||
task.taskId !== expectedTaskId ||
!Number.isSafeInteger(task.revision) ||
task.revision < 1 ||
typeof task.contentDigest !== 'string' ||
!/^[a-f0-9]{64}$/u.test(task.contentDigest) ||
task.kind !== 'command' ||
task.spec?.schema !== 'qinglong/command@v1' ||
command?.kind !== 'argv' ||
typeof command.file !== 'string' ||
!Array.isArray(command.args) ||
command.args.length > 128 ||
command.args.some((entry) => typeof entry !== 'string') ||
!task.labels ||
typeof task.labels !== 'object' ||
Array.isArray(task.labels) ||
!authoring ||
!AUTHORING_LEASE_PATTERN.test(authoring.lease) ||
!Number.isSafeInteger(authoring.expiresAtMs) ||
authoring.revision !== task.revision ||
authoring.contentDigest !== task.contentDigest
) {
throw new ConsoleRequestError('response_unavailable', 503, null);
}
return Object.freeze({ task, authoring });
}
function taskDraft() {
@@ -369,28 +448,46 @@
if (!name || !file || args.length > 128) {
throw new TypeError('名称、命令或参数数量无效。');
}
return Object.freeze({
taskId,
body: Object.freeze({
expectedRevision: null,
mutationId: newMutationId(),
name,
...(description ? { description } : {}),
kind: 'command',
spec: Object.freeze({
const snapshot = state.authoringSnapshot;
const spec = snapshot
? Object.freeze({
...snapshot.task.spec,
config: Object.freeze({
...snapshot.task.spec.config,
command: Object.freeze({
...snapshot.task.spec.config.command,
kind: 'argv',
file,
args,
}),
}),
})
: Object.freeze({
schema: 'qinglong/command@v1',
config: Object.freeze({
command: Object.freeze({ kind: 'argv', file, args }),
}),
}),
labels: Object.freeze({ 'qinglong.source': 'local-console' }),
});
return Object.freeze({
taskId,
...(snapshot ? { authoringLease: snapshot.authoring.lease } : {}),
body: Object.freeze({
expectedRevision: snapshot ? snapshot.task.revision : null,
mutationId: newMutationId(),
name,
...(description ? { description } : {}),
kind: 'command',
spec,
labels: snapshot
? snapshot.task.labels
: Object.freeze({ 'qinglong.source': 'local-console' }),
enabled: nodes.taskEnabled.checked,
occurredAtMs: Date.now(),
}),
});
}
function showPresenceChallenge(mutation, challenge) {
function showPresenceChallenge(action, challenge) {
if (
challenge?.code !== 'local_presence_required' ||
typeof challenge.proofFileName !== 'string' ||
@@ -399,7 +496,16 @@
) {
throw new ConsoleRequestError('response_unavailable', 503, null);
}
state.pendingTaskMutation = Object.freeze({ mutation, challenge });
state.pendingPresence = Object.freeze({ ...action, challenge });
const authoringRead = action.kind === 'authoring';
nodes.presenceCopy.textContent = authoringRead
? '读取完整 Task 定义需要部署设备上的一次性证明。返回的编辑租约不替代保存时的新内容证明。'
: '使用部署 QingLong 的系统用户读取下面的私有文件。证明只绑定这次 Task 内容,且只能使用一次。';
nodes.presenceSubmit.textContent = authoringRead
? '验证并加载定义'
: action.mutation.body.expectedRevision === null
? '验证并创建'
: '验证并更新';
nodes.presenceFile.textContent = `console-presence/${challenge.proofFileName}`;
nodes.presenceExpiry.textContent = `证明将在 ${formatTime(
challenge.expiresAtMs,
@@ -432,10 +538,13 @@
method: 'PUT',
body: mutation.body,
acceptStatus: 428,
...(mutation.authoringLease
? { authoringLease: mutation.authoringLease }
: {}),
},
);
if (value.code === 'local_presence_required') {
showPresenceChallenge(mutation, value);
showPresenceChallenge({ kind: 'mutation', mutation }, value);
return;
}
throw new ConsoleRequestError('response_unavailable', 503, null);
@@ -446,8 +555,27 @@
}
}
async function beginTaskAuthoring(task) {
try {
const value = await api(
`/api/v3/projects/${state.project}/tasks/${task.taskId}/authoring`,
{ method: 'POST', acceptStatus: 428 },
);
if (value.code === 'local_presence_required') {
showPresenceChallenge(
{ kind: 'authoring', taskId: task.taskId },
value,
);
return;
}
throw new ConsoleRequestError('response_unavailable', 503, null);
} catch (error) {
showToast(describeError(error), 'error');
}
}
async function completeTaskMutation() {
const pending = state.pendingTaskMutation;
const pending = state.pendingPresence;
const proof = nodes.presenceProof.value.trim();
if (!pending || !PRESENCE_PATTERN.test(proof)) {
nodes.presenceError.textContent =
@@ -459,20 +587,40 @@
nodes.presenceSubmit.disabled = true;
nodes.presenceError.hidden = true;
try {
if (pending.kind === 'authoring') {
const value = await api(
`/api/v3/projects/${state.project}/tasks/${pending.taskId}/authoring`,
{ method: 'POST', presence: proof },
);
const snapshot = authoringSnapshot(value, pending.taskId);
state.pendingPresence = null;
nodes.presenceProof.value = '';
nodes.presenceDialog.close();
openTaskEditor(snapshot);
showToast('完整 Task 定义已加载;保存仍需要新的本机证明。');
return;
}
const value = await api(
`/api/v3/projects/${state.project}/tasks/${pending.mutation.taskId}`,
{
method: 'PUT',
body: pending.mutation.body,
presence: proof,
...(pending.mutation.authoringLease
? { authoringLease: pending.mutation.authoringLease }
: {}),
},
);
state.pendingTaskMutation = null;
const updated = pending.mutation.body.expectedRevision !== null;
state.pendingPresence = null;
state.authoringSnapshot = null;
nodes.presenceProof.value = '';
nodes.presenceDialog.close();
showToast(
value.status === 'existing'
? '已找到同一 Task 请求。'
: updated
? 'Task 已更新。'
: 'Task 已创建。',
);
state.selectedId = pending.mutation.taskId;
@@ -575,6 +723,9 @@
);
fragment.append(facts);
const actions = element('div', 'detail-actions');
if (task.kind === 'command' && task.specSchema === 'qinglong/command@v1') {
actions.append(actionButton('编辑任务', () => beginTaskAuthoring(task)));
}
if (task.enabled) {
actions.append(
actionButton('运行一次', () => {
@@ -933,7 +1084,8 @@
state.token = null;
state.selectedId = null;
state.pendingAction = null;
state.pendingTaskMutation = null;
state.pendingPresence = null;
state.authoringSnapshot = null;
if (nodes.taskEditor.open) nodes.taskEditor.close();
if (nodes.presenceDialog.open) nodes.presenceDialog.close();
nodes.token.value = '';
@@ -980,16 +1132,18 @@
nodes.disconnect.addEventListener('click', disconnect);
nodes.refresh.addEventListener('click', refresh);
nodes.createTask.addEventListener('click', openTaskEditor);
nodes.taskEditorClose.addEventListener('click', () =>
nodes.taskEditor.close(),
);
nodes.createTask.addEventListener('click', () => openTaskEditor());
nodes.taskEditorClose.addEventListener('click', () => {
state.authoringSnapshot = null;
nodes.taskEditor.close();
});
nodes.taskEditorForm.addEventListener('submit', async (event) => {
event.preventDefault();
await saveTaskDraft();
});
nodes.presenceCancel.addEventListener('click', () => {
state.pendingTaskMutation = null;
state.pendingPresence = null;
state.authoringSnapshot = null;
nodes.presenceProof.value = '';
nodes.presenceDialog.close();
});
@@ -135,11 +135,11 @@
<div class="dialog-heading">
<div>
<p class="eyebrow">Task authoring</p>
<h2>创建命令任务</h2>
<h2 id="task-editor-title">创建命令任务</h2>
</div>
<button class="quiet-button" id="task-editor-close" type="button">关闭</button>
</div>
<p class="editor-intro">
<p class="editor-intro" id="task-editor-intro">
定义会先绑定到一次本机证明,再以同一事务写入 Task revision 与安全审计。
</p>
<div class="editor-grid">
@@ -171,10 +171,10 @@
</label>
<label class="editor-check">
<input id="task-enabled-input" type="checkbox" checked />
<span>创建后允许运行</span>
<span id="task-enabled-label">创建后允许运行</span>
</label>
</div>
<p class="editor-note">
<p class="editor-note" id="task-editor-note">
Alpha 当前从 Console 创建 <code>qinglong/command@v1</code>;高级 Task schema 仍使用受信任管理入口。
</p>
<div class="dialog-actions">
@@ -189,8 +189,8 @@
<form id="presence-form" autocomplete="off">
<p class="eyebrow">Local presence · 02:00</p>
<h2>从部署设备取得证明</h2>
<p>
使用部署 QingLong 的系统用户读取下面的私有文件。证明只绑定这次 Task 内容,且只能使用一次。
<p id="presence-copy">
使用部署 QingLong 的系统用户读取下面的私有文件。证明只绑定这次操作,且只能使用一次。
</p>
<code class="proof-ticket" id="presence-file"></code>
<label class="presence-input">
@@ -208,7 +208,7 @@
<p class="presence-error" id="presence-error" role="alert" hidden></p>
<div class="dialog-actions">
<button class="quiet-button" id="presence-cancel" type="button">取消</button>
<button class="primary-button" id="presence-submit" type="submit">验证并创建</button>
<button class="primary-button" id="presence-submit" type="submit">验证并继续</button>
</div>
</form>
</dialog>
@@ -27,6 +27,7 @@ import type { LocalApiTaskListRoute } from '../task/taskListRoute';
import type { LocalApiTaskReadRoute } from '../task/taskReadRoute';
import type { LocalApiTaskStartRoute } from '../task/taskStartRoute';
import type { LocalApiTaskPutRoute } from '../task/taskPutRoute';
import type { LocalApiTaskAuthoringRoute } from '../task/taskAuthoringRoute';
import type { LocalApiResponse } from '../transport/contract';
export type LocalApiAdmissionOperation =
@@ -84,6 +85,11 @@ export type LocalApiAdmissionOperation =
operationId: 'task.put';
projectId: string;
taskId: string;
}>
| Readonly<{
operationId: 'task.authoring';
projectId: string;
taskId: string;
}>;
export interface LocalApiAdmissionRequest {
@@ -91,6 +97,7 @@ export interface LocalApiAdmissionRequest {
readonly operation: LocalApiAdmissionOperation;
readonly authorization: string | null;
readonly localPresence: string | null;
readonly taskAuthoringLease: string | null;
readonly signal: AbortSignal;
}
@@ -120,6 +127,7 @@ export interface LocalApiAdmissionOptions {
readonly taskReadRoute: LocalApiTaskReadRoute;
readonly taskStartRoute: LocalApiTaskStartRoute;
readonly taskPutRoute: LocalApiTaskPutRoute;
readonly taskAuthoringRoute: LocalApiTaskAuthoringRoute;
readonly now?: () => number;
readonly randomUuid?: () => string;
}
@@ -199,6 +207,7 @@ export function createLocalApiAdmission(
typeof options.taskReadRoute?.handle !== 'function' ||
typeof options.taskStartRoute?.handle !== 'function' ||
typeof options.taskPutRoute?.handle !== 'function' ||
typeof options.taskAuthoringRoute?.handle !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.randomUuid !== undefined &&
typeof options.randomUuid !== 'function')
@@ -260,6 +269,26 @@ export function createLocalApiAdmission(
taskId: taskPutOperation.taskId,
body,
presence: request.localPresence,
authoringLease: request.taskAuthoringLease,
authenticated,
signal: request.signal,
});
},
});
}
if (request.operation.operationId === 'task.authoring') {
const taskAuthoringOperation = request.operation;
return Object.freeze({
bodyMode: 'none' as const,
maximumBodyBytes: 0,
async handle(body: unknown | null) {
if (body !== null) return response(400, 'invalid_request_body');
return options.taskAuthoringRoute.handle({
requestId: request.requestId,
projectId: taskAuthoringOperation.projectId,
taskId: taskAuthoringOperation.taskId,
presence: request.localPresence,
authenticated,
signal: request.signal,
});
@@ -415,6 +444,7 @@ export function createLocalApiAdmission(
policyFence: decision.fence,
});
case 'task.put':
case 'task.authoring':
return response(503, 'request_unavailable');
}
},
@@ -21,6 +21,7 @@ import { createLocalApiTaskListRoute } from '../task/taskListRoute';
import { createLocalApiTaskReadRoute } from '../task/taskReadRoute';
import { createLocalApiTaskStartRoute } from '../task/taskStartRoute';
import { createLocalApiTaskPutRoute } from '../task/taskPutRoute';
import { createLocalApiTaskAuthoringRoute } from '../task/taskAuthoringRoute';
import { startLocalApiHttpSurface } from '../transport/httpSurface';
export interface LocalApiProductSurfaceEvent {
@@ -133,6 +134,17 @@ export function createLocalApiProductSurface(
authority.taskStart,
options.randomUuid ?? randomUUID,
);
const taskAuthoringRoute = createLocalApiTaskAuthoringRoute({
profile: authority.profile,
projectPolicy: authority.projectPolicy,
taskDefinitions: authority.taskDefinitions,
securityAudit: authority.securityAudit,
presenceProof,
...(options.now === undefined ? {} : { now: options.now }),
...(options.randomUuid === undefined
? {}
: { randomUuid: options.randomUuid }),
});
const taskPutRoute = createLocalApiTaskPutRoute({
projectPolicy: authority.projectPolicy,
taskDefinitions: authority.taskDefinitions,
@@ -147,6 +159,7 @@ export function createLocalApiProductSurface(
},
securityAudit: authority.securityAudit,
presenceProof,
taskAuthoringLeases: taskAuthoringRoute.leases,
...(options.now === undefined ? {} : { now: options.now }),
...(options.randomUuid === undefined
? {}
@@ -166,6 +179,7 @@ export function createLocalApiProductSurface(
taskReadRoute,
taskStartRoute,
taskPutRoute,
taskAuthoringRoute,
...(options.now === undefined ? {} : { now: options.now }),
...(options.randomUuid === undefined
? {}
@@ -183,6 +197,7 @@ export function createLocalApiProductSurface(
: { randomUuid: options.randomUuid }),
});
} catch (error) {
taskAuthoringRoute.close();
presenceProof.close();
throw error;
}
@@ -201,6 +216,7 @@ export function createLocalApiProductSurface(
);
let stopResult = await active.stopAndDrain();
try {
taskAuthoringRoute.close();
presenceProof.close();
} catch {
stopResult = 'timed_out';
@@ -0,0 +1,699 @@
import {
createHash,
randomBytes,
randomUUID,
timingSafeEqual,
} from 'node:crypto';
import type { LocalApplicationProfile } from '@qinglong/local-application';
import {
ProjectPolicyEngine,
ProjectPolicyUnavailableError,
type ProjectPolicyRepository,
} from '@qinglong/runtime-core/project-policy';
import {
normalizeSecurityPolicyDecision,
normalizeSecurityPrincipal,
type SecurityPolicyDecision,
type SecurityPrincipal,
} from '@qinglong/runtime-core/security';
import {
normalizeSecurityAuditRecord,
type SecurityAuditOutcome,
type SecurityAuditSink,
} from '@qinglong/runtime-core/security-audit';
import {
TaskDefinitionUnavailableError,
type TaskDefinitionRecord,
type TaskDefinitionSource,
} from '@qinglong/runtime-core/task-definition';
import type { AuthenticatedLocalApiRequest } from '../authentication/credentialAuthenticator';
import {
LocalPresenceProofUnavailableError,
type LocalPresenceBinding,
type LocalPresenceProofManager,
} from '../authentication/localPresenceProof';
import type { LocalApiResponse } from '../transport/contract';
const LEASE_TTL_MS = 10 * 60_000;
const LEASE_PATTERN =
/^ql3a_([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})_([A-Za-z0-9_-]{43})$/;
const SHA256_PATTERN = /^[a-f0-9]{64}$/;
export interface LocalApiTaskAuthoringLeaseBinding {
readonly projectId: string;
readonly taskId: string;
readonly revision: number;
readonly contentDigest: string;
readonly credentialId: string;
readonly credentialVersion: number;
readonly subjectType: 'user';
readonly subjectId: string;
}
export interface LocalApiTaskAuthoringLeases {
inspect(
presentation: string | null,
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
): boolean;
consume(
presentation: string | null,
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
): boolean;
}
export interface LocalApiTaskAuthoringRequest {
readonly requestId: string;
readonly projectId: string;
readonly taskId: string;
readonly presence: string | null;
readonly authenticated: Readonly<AuthenticatedLocalApiRequest>;
readonly signal: AbortSignal;
}
export interface LocalApiTaskAuthoringRoute {
readonly leases: LocalApiTaskAuthoringLeases;
handle(
request: Readonly<LocalApiTaskAuthoringRequest>,
): Promise<LocalApiResponse>;
close(): void;
}
export interface LocalApiTaskAuthoringRouteOptions {
readonly profile: LocalApplicationProfile;
readonly projectPolicy: ProjectPolicyRepository;
readonly taskDefinitions: Pick<
TaskDefinitionSource,
'findCurrentTaskDefinition'
>;
readonly securityAudit: SecurityAuditSink;
readonly presenceProof: LocalPresenceProofManager;
readonly now?: () => number;
readonly randomUuid?: () => string;
readonly randomSecret?: () => Buffer;
}
interface PendingTaskAuthoringLease {
readonly leaseId: string;
readonly bindingDigest: string;
readonly presentationDigest: Buffer;
readonly expiresAtMs: number;
}
function response(
statusCode: number,
body: Readonly<Record<string, unknown>>,
): LocalApiResponse {
return Object.freeze({ statusCode, body: Object.freeze(body) });
}
function timestamp(now: () => number): number {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new LocalPresenceProofUnavailableError('clock is invalid');
}
return value;
}
function bindingDigest(
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
): string {
if (
!binding ||
typeof binding !== 'object' ||
Array.isArray(binding) ||
Object.keys(binding).sort().join('\0') !==
[
'contentDigest',
'credentialId',
'credentialVersion',
'projectId',
'revision',
'subjectId',
'subjectType',
'taskId',
]
.sort()
.join('\0') ||
typeof binding.projectId !== 'string' ||
binding.projectId.length < 1 ||
binding.projectId.length > 128 ||
typeof binding.taskId !== 'string' ||
binding.taskId.length < 1 ||
binding.taskId.length > 128 ||
!Number.isSafeInteger(binding.revision) ||
binding.revision < 1 ||
!SHA256_PATTERN.test(binding.contentDigest) ||
typeof binding.credentialId !== 'string' ||
binding.credentialId.length < 1 ||
binding.credentialId.length > 64 ||
!Number.isSafeInteger(binding.credentialVersion) ||
binding.credentialVersion < 1 ||
binding.subjectType !== 'user' ||
typeof binding.subjectId !== 'string' ||
binding.subjectId.length < 1 ||
binding.subjectId.length > 128
) {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease binding is invalid',
);
}
return createHash('sha256')
.update('qinglong3.local-api-task-authoring-lease-binding.v1\0', 'utf8')
.update(binding.projectId, 'utf8')
.update('\0', 'utf8')
.update(binding.taskId, 'utf8')
.update('\0', 'utf8')
.update(String(binding.revision), 'utf8')
.update('\0', 'utf8')
.update(binding.contentDigest, 'utf8')
.update('\0', 'utf8')
.update(binding.credentialId, 'utf8')
.update('\0', 'utf8')
.update(String(binding.credentialVersion), 'utf8')
.update('\0', 'utf8')
.update(binding.subjectId, 'utf8')
.digest('hex');
}
function presenceBinding(
request: Readonly<LocalApiTaskAuthoringRequest>,
): Readonly<LocalPresenceBinding> {
if (
request.authenticated.principal.subject.type !== 'user' ||
request.authenticated.credentialFence.subjectType !== 'user'
) {
throw new LocalPresenceProofUnavailableError(
'strong User credential is required',
);
}
return Object.freeze({
requestDigest: createHash('sha256')
.update('qinglong3.local-api-task-authoring-read.v1\0', 'utf8')
.update(request.projectId, 'utf8')
.update('\0', 'utf8')
.update(request.taskId, 'utf8')
.digest('hex'),
credentialId: request.authenticated.credentialFence.credentialId,
credentialVersion: request.authenticated.credentialFence.credentialVersion,
subjectType: 'user',
subjectId: request.authenticated.credentialFence.subjectId,
});
}
function authoringLeaseBinding(
request: Readonly<LocalApiTaskAuthoringRequest>,
definition: Readonly<TaskDefinitionRecord>,
): Readonly<LocalApiTaskAuthoringLeaseBinding> {
if (request.authenticated.credentialFence.subjectType !== 'user') {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease requires a User credential',
);
}
return Object.freeze({
projectId: request.projectId,
taskId: request.taskId,
revision: definition.revision,
contentDigest: definition.contentDigest,
credentialId: request.authenticated.credentialFence.credentialId,
credentialVersion: request.authenticated.credentialFence.credentialVersion,
subjectType: 'user',
subjectId: request.authenticated.credentialFence.subjectId,
});
}
function strongPrincipal(
authenticated: Readonly<AuthenticatedLocalApiRequest>,
proof: Readonly<{
authorizationId: string;
authenticatedAtMs: number;
expiresAtMs: number;
}>,
): Readonly<SecurityPrincipal> {
return normalizeSecurityPrincipal(
{
subject: authenticated.principal.subject,
authenticationId: `local_presence:${proof.authorizationId}`,
authenticatedAtMs: proof.authenticatedAtMs,
expiresAtMs: Math.min(
proof.expiresAtMs,
authenticated.principal.expiresAtMs,
),
assurance: 'local_console',
},
proof.authenticatedAtMs,
);
}
async function recordAudit(
audit: SecurityAuditSink,
values: {
readonly eventId: string;
readonly requestId: string;
readonly projectId: string;
readonly principal: Readonly<SecurityPrincipal> | null;
readonly outcome: SecurityAuditOutcome;
readonly reasons: readonly string[];
readonly fence: SecurityPolicyDecision['fence'];
readonly occurredAtMs: number;
},
): Promise<boolean> {
try {
await audit.record(
normalizeSecurityAuditRecord({
eventId: values.eventId,
requestId: values.requestId,
operationId: 'task.authoring.read',
projectId: values.projectId,
subject: values.principal?.subject ?? null,
authenticationId: values.principal?.authenticationId ?? null,
outcome: values.outcome,
reasons: values.reasons,
fence: values.fence,
occurredAtMs: values.occurredAtMs,
}),
);
return true;
} catch {
return false;
}
}
function sameFence(
left: SecurityPolicyDecision['fence'],
right: SecurityPolicyDecision['fence'],
): boolean {
return (
left !== null &&
right !== null &&
left.projectVersion === right.projectVersion &&
left.bindingVersion !== null &&
left.bindingVersion === right.bindingVersion
);
}
export function createLocalApiTaskAuthoringRoute(
options: Readonly<LocalApiTaskAuthoringRouteOptions>,
): Readonly<LocalApiTaskAuthoringRoute> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
(options.profile !== 'edge' && options.profile !== 'standalone') ||
typeof options.projectPolicy?.resolve !== 'function' ||
typeof options.taskDefinitions?.findCurrentTaskDefinition !== 'function' ||
typeof options.securityAudit?.record !== 'function' ||
typeof options.presenceProof?.issue !== 'function' ||
typeof options.presenceProof?.consume !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.randomUuid !== undefined &&
typeof options.randomUuid !== 'function') ||
(options.randomSecret !== undefined &&
typeof options.randomSecret !== 'function')
) {
throw new TypeError('Local API Task authoring route options are invalid');
}
const now = options.now ?? Date.now;
const uuid = options.randomUuid ?? randomUUID;
const secret = options.randomSecret ?? (() => randomBytes(32));
const policy = new ProjectPolicyEngine(options.projectPolicy);
const maximumPending = options.profile === 'edge' ? 8 : 32;
const pending = new Map<string, PendingTaskAuthoringLease>();
let closed = false;
const sweep = (nowMs: number) => {
for (const [leaseId, lease] of pending) {
if (lease.expiresAtMs > nowMs) continue;
lease.presentationDigest.fill(0);
pending.delete(leaseId);
}
};
const leaseMatches = (
presentation: string | null,
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
consume: boolean,
): boolean => {
if (closed || typeof presentation !== 'string') return false;
const nowMs = timestamp(now);
sweep(nowMs);
const match = LEASE_PATTERN.exec(presentation);
if (!match) return false;
const lease = pending.get(match[1]!);
if (!lease) return false;
const actual = createHash('sha256')
.update('qinglong3.local-api-task-authoring-lease.v1\0', 'utf8')
.update(presentation, 'utf8')
.digest();
let valid = false;
try {
valid =
lease.expiresAtMs > nowMs &&
lease.bindingDigest === bindingDigest(binding) &&
timingSafeEqual(actual, lease.presentationDigest);
} catch {
valid = false;
} finally {
actual.fill(0);
}
if (valid && consume) {
pending.delete(lease.leaseId);
lease.presentationDigest.fill(0);
}
return valid;
};
const leases: LocalApiTaskAuthoringLeases = Object.freeze({
inspect(
presentation: string | null,
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
) {
return leaseMatches(presentation, binding, false);
},
consume(
presentation: string | null,
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
) {
return leaseMatches(presentation, binding, true);
},
});
const issueLease = (
binding: Readonly<LocalApiTaskAuthoringLeaseBinding>,
): Readonly<{ lease: string; expiresAtMs: number }> => {
if (closed) {
throw new LocalPresenceProofUnavailableError(
'Task authoring route is closed',
);
}
const nowMs = timestamp(now);
sweep(nowMs);
if (pending.size >= maximumPending) {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease capacity is exhausted',
);
}
const leaseId = uuid();
const material = secret();
if (!Buffer.isBuffer(material) || material.byteLength !== 32) {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease entropy is unavailable',
);
}
let presentation: string | undefined;
try {
presentation = `ql3a_${leaseId}_${material.toString('base64url')}`;
if (!LEASE_PATTERN.test(presentation)) {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease identity is invalid',
);
}
const expiresAtMs = nowMs + LEASE_TTL_MS;
pending.set(
leaseId,
Object.freeze({
leaseId,
bindingDigest: bindingDigest(binding),
presentationDigest: createHash('sha256')
.update('qinglong3.local-api-task-authoring-lease.v1\0', 'utf8')
.update(presentation, 'utf8')
.digest(),
expiresAtMs,
}),
);
return Object.freeze({ lease: presentation, expiresAtMs });
} finally {
material.fill(0);
presentation = undefined;
}
};
return Object.freeze({
leases,
async handle(request: Readonly<LocalApiTaskAuthoringRequest>) {
if (closed || request.signal.aborted) {
return response(503, { code: 'request_unavailable' });
}
const occurredAtMs = timestamp(now);
let initialDecision: Readonly<SecurityPolicyDecision>;
try {
initialDecision = normalizeSecurityPolicyDecision(
await policy.authorize(
request.authenticated.principal,
request.projectId,
'task.update',
),
);
} catch (error) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: request.authenticated.principal,
outcome: 'authorization_unavailable',
reasons: ['policy_unavailable'],
fence: null,
occurredAtMs,
});
return response(503, {
code:
audited && error instanceof ProjectPolicyUnavailableError
? 'authorization_unavailable'
: 'security_audit_unavailable',
});
}
if (initialDecision.effect !== 'allow') {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: request.authenticated.principal,
outcome:
initialDecision.effect === 'require_approval'
? 'approval_required'
: 'denied',
reasons: initialDecision.reasons,
fence: initialDecision.fence,
occurredAtMs,
});
return audited
? response(403, {
code:
initialDecision.effect === 'require_approval'
? 'approval_required'
: 'forbidden',
})
: response(503, { code: 'security_audit_unavailable' });
}
sweep(occurredAtMs);
if (pending.size >= maximumPending) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: request.authenticated.principal,
outcome: 'authorization_unavailable',
reasons: ['task_authoring_capacity_exhausted'],
fence: initialDecision.fence,
occurredAtMs,
});
return response(503, {
code: audited
? 'task_authoring_unavailable'
: 'security_audit_unavailable',
});
}
let binding: Readonly<LocalPresenceBinding>;
try {
binding = presenceBinding(request);
} catch {
return response(401, { code: 'strong_authentication_required' });
}
if (!request.presence) {
let challenge;
try {
challenge = options.presenceProof.issue(binding);
} catch {
return response(503, { code: 'local_presence_unavailable' });
}
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: request.authenticated.principal,
outcome: 'approval_required',
reasons: ['local_presence_required'],
fence: initialDecision.fence,
occurredAtMs,
});
return audited
? response(428, {
code: 'local_presence_required',
authorizationId: challenge.authorizationId,
requestDigest: challenge.requestDigest,
expiresAtMs: challenge.expiresAtMs,
proofFileName: challenge.proofFileName,
})
: response(503, { code: 'security_audit_unavailable' });
}
let proof;
try {
await request.authenticated.confirm();
proof = options.presenceProof.consume(request.presence, binding);
} catch {
return response(503, { code: 'authentication_unavailable' });
}
if (!proof) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: null,
outcome: 'authentication_rejected',
reasons: ['local_presence_rejected'],
fence: null,
occurredAtMs,
});
return audited
? response(401, { code: 'local_presence_rejected' })
: response(503, { code: 'security_audit_unavailable' });
}
if (request.signal.aborted) {
return response(503, { code: 'request_unavailable' });
}
let principal: Readonly<SecurityPrincipal>;
let readDecision: Readonly<SecurityPolicyDecision>;
let updateDecision: Readonly<SecurityPolicyDecision>;
try {
principal = strongPrincipal(request.authenticated, proof);
[readDecision, updateDecision] = await Promise.all([
policy.authorize(principal, request.projectId, 'task.read'),
policy.authorize(principal, request.projectId, 'task.update'),
]).then(
(values) =>
values.map(normalizeSecurityPolicyDecision) as [
Readonly<SecurityPolicyDecision>,
Readonly<SecurityPolicyDecision>,
],
);
} catch {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal: null,
outcome: 'authorization_unavailable',
reasons: ['policy_unavailable'],
fence: null,
occurredAtMs,
});
return response(503, {
code: audited
? 'authorization_unavailable'
: 'security_audit_unavailable',
});
}
if (
readDecision.effect !== 'allow' ||
updateDecision.effect !== 'allow' ||
!sameFence(readDecision.fence, updateDecision.fence)
) {
const denied =
readDecision.effect !== 'allow' ? readDecision : updateDecision;
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal,
outcome:
denied.effect === 'require_approval'
? 'approval_required'
: 'denied',
reasons: sameFence(readDecision.fence, updateDecision.fence)
? denied.reasons
: ['policy_fence_mismatch'],
fence: denied.fence,
occurredAtMs,
});
return audited
? response(403, {
code:
denied.effect === 'require_approval'
? 'approval_required'
: 'forbidden',
})
: response(503, { code: 'security_audit_unavailable' });
}
let definition: Readonly<TaskDefinitionRecord> | null;
try {
definition = await options.taskDefinitions.findCurrentTaskDefinition(
request.projectId,
request.taskId,
);
await request.authenticated.confirm();
} catch (error) {
return response(503, {
code:
error instanceof TaskDefinitionUnavailableError
? 'task_definition_unavailable'
: 'authentication_unavailable',
});
}
if (!definition) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal,
outcome: 'allowed',
reasons: updateDecision.reasons,
fence: updateDecision.fence,
occurredAtMs,
});
if (!audited) {
return response(503, { code: 'security_audit_unavailable' });
}
return response(404, { code: 'task_not_found' });
}
const authoringBinding = authoringLeaseBinding(request, definition);
let authoring;
try {
authoring = issueLease(authoringBinding);
} catch {
return response(503, { code: 'task_authoring_unavailable' });
}
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
projectId: request.projectId,
principal,
outcome: 'allowed',
reasons: updateDecision.reasons,
fence: updateDecision.fence,
occurredAtMs,
});
if (!audited) {
leases.consume(authoring.lease, authoringBinding);
return response(503, { code: 'security_audit_unavailable' });
}
return response(200, {
task: definition,
authoring: Object.freeze({
lease: authoring.lease,
expiresAtMs: authoring.expiresAtMs,
revision: definition.revision,
contentDigest: definition.contentDigest,
}),
});
},
close() {
if (closed) return;
closed = true;
for (const lease of pending.values()) {
lease.presentationDigest.fill(0);
}
pending.clear();
},
});
}
@@ -44,6 +44,10 @@ import {
type LocalPresenceProofManager,
} from '../authentication/localPresenceProof';
import type { LocalApiResponse } from '../transport/contract';
import type {
LocalApiTaskAuthoringLeaseBinding,
LocalApiTaskAuthoringLeases,
} from './taskAuthoringRoute';
const BODY_KEYS = Object.freeze([
'enabled',
@@ -63,6 +67,7 @@ export interface LocalApiTaskPutRequest {
readonly taskId: string;
readonly body: unknown | null;
readonly presence: string | null;
readonly authoringLease: string | null;
readonly authenticated: Readonly<AuthenticatedLocalApiRequest>;
readonly signal: AbortSignal;
}
@@ -79,6 +84,7 @@ export interface LocalApiTaskPutRouteOptions {
) => Promise<TaskDefinitionAdministrationRepository>;
readonly securityAudit: SecurityAuditSink;
readonly presenceProof: LocalPresenceProofManager;
readonly taskAuthoringLeases: LocalApiTaskAuthoringLeases;
readonly now?: () => number;
readonly randomUuid?: () => string;
}
@@ -171,6 +177,31 @@ function operationId(
return command.expectedRevision === null ? 'task.create' : 'task.update';
}
function authoringLeaseBinding(
command: Readonly<AppendTaskDefinitionRevisionCommand>,
definition: Readonly<TaskDefinitionRecord>,
authenticated: Readonly<AuthenticatedLocalApiRequest>,
): Readonly<LocalApiTaskAuthoringLeaseBinding> {
if (
command.expectedRevision === null ||
authenticated.credentialFence.subjectType !== 'user'
) {
throw new LocalPresenceProofUnavailableError(
'Task authoring lease requires an update by a User credential',
);
}
return Object.freeze({
projectId: command.projectId,
taskId: command.taskId,
revision: definition.revision,
contentDigest: definition.contentDigest,
credentialId: authenticated.credentialFence.credentialId,
credentialVersion: authenticated.credentialFence.credentialVersion,
subjectType: 'user',
subjectId: authenticated.credentialFence.subjectId,
});
}
function summary(value: Readonly<TaskDefinitionRecord>) {
return Object.freeze({
taskId: value.taskId,
@@ -244,6 +275,8 @@ export function createLocalApiTaskPutRoute(
typeof options.securityAudit?.record !== 'function' ||
typeof options.presenceProof?.issue !== 'function' ||
typeof options.presenceProof?.consume !== 'function' ||
typeof options.taskAuthoringLeases?.inspect !== 'function' ||
typeof options.taskAuthoringLeases?.consume !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.randomUuid !== undefined &&
typeof options.randomUuid !== 'function')
@@ -326,6 +359,75 @@ export function createLocalApiTaskPutRoute(
: 'forbidden',
});
}
let inspectedAuthoringBinding:
| Readonly<LocalApiTaskAuthoringLeaseBinding>
| undefined;
if (command.expectedRevision === null) {
if (request.authoringLease !== null) {
return response(400, { code: 'invalid_task_authoring_lease' });
}
} else {
if (request.authoringLease === null) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: request.authenticated,
outcome: 'denied',
reasons: ['task_authoring_lease_required'],
fence: decision.fence,
occurredAtMs,
});
return audited
? response(428, { code: 'task_authoring_lease_required' })
: response(503, { code: 'security_audit_unavailable' });
}
try {
const definition =
await options.taskDefinitions.findCurrentTaskDefinition(
command.projectId,
command.taskId,
);
if (!definition) {
return response(409, { code: 'task_authoring_lease_rejected' });
}
inspectedAuthoringBinding = authoringLeaseBinding(
command,
definition,
request.authenticated,
);
if (
definition.revision !== command.expectedRevision ||
!options.taskAuthoringLeases.inspect(
request.authoringLease,
inspectedAuthoringBinding,
)
) {
const audited = await recordAudit(options.securityAudit, {
eventId: uuid(),
requestId: request.requestId,
operationId: operation,
projectId: request.projectId,
authenticated: request.authenticated,
outcome: 'denied',
reasons: ['task_authoring_lease_rejected'],
fence: decision.fence,
occurredAtMs,
});
return audited
? response(409, { code: 'task_authoring_lease_rejected' })
: response(503, { code: 'security_audit_unavailable' });
}
} catch (error) {
return response(503, {
code:
error instanceof TaskDefinitionUnavailableError
? 'task_definition_unavailable'
: 'task_authoring_unavailable',
});
}
}
let binding: Readonly<LocalPresenceBinding>;
try {
binding = presenceBinding(command, request.authenticated);
@@ -405,6 +507,32 @@ export function createLocalApiTaskPutRoute(
} catch {
return response(503, { code: 'authentication_unavailable' });
}
if (inspectedAuthoringBinding) {
try {
const current =
await options.taskDefinitions.findCurrentTaskDefinition(
command.projectId,
command.taskId,
);
if (
!current ||
current.revision !== command.expectedRevision ||
!options.taskAuthoringLeases.consume(
request.authoringLease,
authoringLeaseBinding(command, current, request.authenticated),
)
) {
return response(409, { code: 'task_authoring_lease_rejected' });
}
} catch (error) {
return response(503, {
code:
error instanceof TaskDefinitionUnavailableError
? 'task_definition_unavailable'
: 'task_authoring_unavailable',
});
}
}
try {
const mutations =
await options.taskDefinitionAdministrationForCredential(
@@ -21,7 +21,7 @@ import type { LocalApiResponse } from './contract';
const MAX_HEADER_BYTES = 8 * 1_024;
const MAX_URL_BYTES = 512;
const MAX_RESPONSE_BYTES = 64 * 1_024;
const MAX_RESPONSE_BYTES = 80 * 1_024;
const RUN_READ_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/runs\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})$/;
const RUN_LIST_ROUTE_PATTERN =
@@ -40,6 +40,8 @@ const TASK_READ_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/tasks\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})$/;
const TASK_START_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/tasks\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/runs$/;
const TASK_AUTHORING_ROUTE_PATTERN =
/^\/api\/v3\/projects\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/tasks\/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})\/authoring$/;
const RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const TASK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const LOCAL_CONSOLE_CONTENT_SECURITY_POLICY =
@@ -97,6 +99,15 @@ function localPresence(request: IncomingMessage): string | null {
return values[0]!;
}
function taskAuthoringLease(request: IncomingMessage): string | null {
const values = rawHeaderValues(request, 'x-qinglong-task-authoring-lease');
if (values.length === 0) return null;
if (values.length !== 1 || values[0]!.length > 160) {
throw new TypeError('invalid_task_authoring_lease');
}
return values[0]!;
}
function hasRequestBody(request: IncomingMessage): boolean {
const transferEncoding = rawHeaderValues(request, 'transfer-encoding');
const contentLength = rawHeaderValues(request, 'content-length');
@@ -445,6 +456,14 @@ function route(
const path = separator < 0 ? rawUrl : rawUrl.slice(0, separator);
const rawQuery = separator < 0 ? undefined : rawUrl.slice(separator + 1);
if (request.method === 'POST') {
const taskAuthoringMatch = TASK_AUTHORING_ROUTE_PATTERN.exec(path);
if (taskAuthoringMatch && rawQuery === undefined) {
return Object.freeze({
operationId: 'task.authoring',
projectId: taskAuthoringMatch[1]!,
taskId: taskAuthoringMatch[2]!,
});
}
const taskStartMatch = TASK_START_ROUTE_PATTERN.exec(path);
if (taskStartMatch && rawQuery === undefined) {
return Object.freeze({
@@ -720,11 +739,24 @@ export async function startLocalApiHttpSurface(
request.resume();
return;
}
let presentedTaskAuthoringLease: string | null;
try {
presentedTaskAuthoringLease = taskAuthoringLease(request);
} catch {
send(
response,
requestId,
errorResponse(400, 'invalid_task_authoring_lease'),
);
request.resume();
return;
}
const admissionRequest: LocalApiAdmissionRequest = Object.freeze({
requestId,
operation: resolvedRoute,
authorization: authorization(request),
localPresence: presentedLocalPresence,
taskAuthoringLease: presentedTaskAuthoringLease,
signal: abort.signal,
});
let operation: Promise<void>;
@@ -23,6 +23,7 @@ function request(overrides = {}) {
}),
authorization: 'Bearer opaque',
localPresence: null,
taskAuthoringLease: null,
signal: new AbortController().signal,
...overrides,
});
@@ -145,6 +146,12 @@ function fixture(overrides = {}) {
return { statusCode: 201, body: { status: 'created' } };
},
},
taskAuthoringRoute: {
async handle(value) {
events.push(`task-authoring:${value.projectId}:${value.taskId}`);
return { statusCode: 200, body: { task: { taskId: value.taskId } } };
},
},
now: () => 10_000,
randomUuid: () => '019f70c0-0000-4000-8000-000000000002',
...overrides,
@@ -422,6 +429,31 @@ test('defers Task put Policy, audit and strong confirmation to the request-bound
assert.deepEqual(events, ['authenticate', 'task-put:prj_default:task-a']);
});
test('defers strong Task authoring read and local presence to the route', async () => {
const { admission, events } = fixture();
const prepared = await admission.prepare(
request({
operation: Object.freeze({
operationId: 'task.authoring',
projectId: 'prj_default',
taskId: 'task-a',
}),
localPresence: 'ql3p_proof',
}),
);
assert.equal(prepared.bodyMode, 'none');
assert.equal(prepared.maximumBodyBytes, 0);
assert.deepEqual(events, ['authenticate']);
assert.deepEqual(await prepared.handle(null), {
statusCode: 200,
body: { task: { taskId: 'task-a' } },
});
assert.deepEqual(events, [
'authenticate',
'task-authoring:prj_default:task-a',
]);
});
test('audits authentication rejection before returning a challenge', async () => {
const events = [];
const { admission } = fixture({
@@ -78,13 +78,21 @@ test('loads one bounded offline Console asset closure', () => {
assert.match(text, /日志已按保留策略清理/u);
assert.match(text, /method: 'PUT'/u);
assert.match(text, /x-qinglong-local-presence/u);
assert.match(text, /x-qinglong-task-authoring-lease/u);
assert.match(text, /local_presence_required/u);
assert.match(text, /state\.pendingTaskMutation/u);
assert.match(text, /state\.pendingPresence/u);
assert.match(text, /tasks\/\$\{task\.taskId\}\/authoring/u);
assert.match(text, /\^ql3p_/u);
assert.match(text, /\.\.\.snapshot\.task\.spec\.config/u);
assert.match(text, /snapshot\.task\.labels/u);
assert.match(text, /setAttribute\('aria-readonly', 'true'\)/u);
}
if (requestPath === '/') {
assert.match(text, /id="task-editor-dialog"/u);
assert.match(text, /id="presence-dialog"/u);
assert.match(text, /保存并生成本机证明/u);
assert.match(text, /id="task-editor-title"/u);
assert.match(text, /id="presence-copy"/u);
}
}
assert.ok(totalBytes <= 192 * 1024);
@@ -298,6 +298,7 @@ test('serves only the fixed canonical loopback Run route and drains idempotently
headers: {
authorization: 'Bearer opaque',
'x-qinglong-local-presence': 'ql3p_request_bound_proof',
'x-qinglong-task-authoring-lease': 'ql3a_exact_snapshot_lease',
'content-type': 'application/json',
'content-length': String(Buffer.byteLength(taskPutBody)),
},
@@ -312,6 +313,7 @@ test('serves only the fixed canonical loopback Run route and drains idempotently
taskId: 'task_1',
});
assert.equal(observed[8].localPresence, 'ql3p_request_bound_proof');
assert.equal(observed[8].taskAuthoringLease, 'ql3a_exact_snapshot_lease');
const log = await request(
port,
@@ -335,6 +337,25 @@ test('serves only the fixed canonical loopback Run route and drains idempotently
range: { offset: 0, length: 16 * 1024 },
});
const authoring = await request(
port,
'/api/v3/projects/prj_default/tasks/task_1/authoring',
{
method: 'POST',
headers: {
authorization: 'Bearer opaque',
'x-qinglong-local-presence': 'ql3p_authoring_read_proof',
},
},
);
assert.equal(authoring.statusCode, 200);
assert.deepEqual(observed[11].operation, {
operationId: 'task.authoring',
projectId: 'prj_default',
taskId: 'task_1',
});
assert.equal(observed[11].localPresence, 'ql3p_authoring_read_proof');
for (const invalidPath of [
'/api/v3/projects/prj_default/runs/run_123?expanded=true',
'/api/v3/projects/prj_default/runs/run%5f123',
@@ -404,7 +425,7 @@ test('serves only the fixed canonical loopback Run route and drains idempotently
assert.equal(invalid.statusCode, 400);
assert.deepEqual(invalid.body, { code: 'invalid_run_step_list_query' });
}
assert.equal(observed.length, 11);
assert.equal(observed.length, 12);
assert.deepEqual(
await Promise.all([surface.stopAndDrain(), surface.stopAndDrain()]),
['stopped', 'stopped'],
@@ -681,6 +702,37 @@ test('serves the reviewed worst-case 64-item Run Step list inside the fixed resp
assert.ok(Number(response.headers['content-length']) < 65_536);
});
test('serves one maximum-size Task authoring snapshot inside the bounded response cap', async (t) => {
const port = await reservePort();
const surface = await startLocalApiHttpSurface({
profile: 'edge',
host: '127.0.0.1',
port,
admission: preparedAdmission(async (value) => ({
statusCode: 200,
body: {
task: {
taskId: value.operation.taskId,
spec: {
schema: 'qinglong/command@v1',
payload: 'x'.repeat(64 * 1024),
},
},
},
})),
});
t.after(() => surface.stopAndDrain());
const response = await request(
port,
'/api/v3/projects/default/tasks/task-large/authoring',
{ method: 'POST' },
);
assert.equal(response.statusCode, 200);
assert.equal(response.body.task.taskId, 'task-large');
assert.ok(Number(response.headers['content-length']) > 64 * 1024);
assert.ok(Number(response.headers['content-length']) < 80 * 1024);
});
test('bounds Edge admission concurrency and drains accepted work', async (t) => {
const port = await reservePort();
let admissions = 0;
@@ -586,11 +586,119 @@ test('serves an authenticated Run through one real SQLite authority and durable
assert.equal(JSON.stringify(taskCreated).includes('console-created'), true);
assert.equal(JSON.stringify(taskCreated).includes('/bin/echo'), false);
const authoringPath = '/api/v3/projects/default/tasks/task-1/authoring';
const authoringChallenge = await request(
port,
`Bearer ${TOKEN}`,
authoringPath,
{ method: 'POST' },
);
assert.equal(authoringChallenge.statusCode, 428);
assert.equal(authoringChallenge.body.code, 'local_presence_required');
const authoringProof = JSON.parse(
fs.readFileSync(
path.join(
root,
'console-presence',
authoringChallenge.body.proofFileName,
),
'utf8',
),
);
const authoring = await request(port, `Bearer ${TOKEN}`, authoringPath, {
method: 'POST',
headers: {
'x-qinglong-local-presence': authoringProof.proof,
},
});
assert.equal(authoring.statusCode, 200);
assert.equal(authoring.body.task.revision, 1);
assert.deepEqual(
authoring.body.task.spec,
JSON.parse(JSON.stringify(taskDefinition.spec)),
);
assert.deepEqual(
authoring.body.task.labels,
JSON.parse(JSON.stringify(taskDefinition.labels)),
);
assert.equal(
authoring.body.authoring.contentDigest,
taskDefinition.contentDigest,
);
assert.match(authoring.body.authoring.lease, /^ql3a_[A-Za-z0-9_-]+$/);
const taskUpdateBody = JSON.stringify({
expectedRevision: authoring.body.task.revision,
mutationId: '019f7300-0000-4000-8000-000000000702',
name: 'Local API Task updated',
...(authoring.body.task.description === undefined
? {}
: { description: authoring.body.task.description }),
kind: authoring.body.task.kind,
spec: authoring.body.task.spec,
labels: authoring.body.task.labels,
enabled: true,
occurredAtMs: NOW,
});
const taskUpdateOptions = {
method: 'PUT',
headers: {
'x-qinglong-task-authoring-lease': authoring.body.authoring.lease,
'content-type': 'application/json',
'content-length': String(Buffer.byteLength(taskUpdateBody)),
},
body: taskUpdateBody,
};
const taskUpdateChallenge = await request(
port,
`Bearer ${TOKEN}`,
'/api/v3/projects/default/tasks/task-1',
taskUpdateOptions,
);
assert.equal(taskUpdateChallenge.statusCode, 428);
const taskUpdateProof = JSON.parse(
fs.readFileSync(
path.join(
root,
'console-presence',
taskUpdateChallenge.body.proofFileName,
),
'utf8',
),
);
const taskUpdated = await request(
port,
`Bearer ${TOKEN}`,
'/api/v3/projects/default/tasks/task-1',
{
...taskUpdateOptions,
headers: {
...taskUpdateOptions.headers,
'x-qinglong-local-presence': taskUpdateProof.proof,
},
},
);
assert.equal(taskUpdated.statusCode, 200);
assert.equal(taskUpdated.body.status, 'updated');
assert.equal(taskUpdated.body.task.revision, 2);
assert.equal(taskUpdated.body.task.name, 'Local API Task updated');
assert.equal(taskUpdated.body.task.enabled, true);
const updatedTask = await request(
port,
`Bearer ${TOKEN}`,
'/api/v3/projects/default/tasks/task-1',
);
assert.equal(updatedTask.body.task.revision, 2);
assert.equal(updatedTask.body.task.name, 'Local API Task updated');
assert.equal(updatedTask.body.task.enabled, true);
assert.equal(JSON.stringify(updatedTask).includes('/bin/echo'), false);
const taskStartBody = JSON.stringify({
schema: 'qinglong/task-start@v1',
mutationId: '019f7300-0000-7000-8000-000000000800',
expectedRevision: taskDefinition.revision,
expectedContentDigest: taskDefinition.contentDigest,
expectedRevision: updatedTask.body.task.revision,
expectedContentDigest: updatedTask.body.task.contentDigest,
});
const taskStartOptions = {
method: 'POST',
@@ -607,12 +715,15 @@ test('serves an authenticated Run through one real SQLite authority and durable
taskStartPath,
taskStartOptions,
);
assert.equal(started.statusCode, 202);
assert.equal(started.statusCode, 202, JSON.stringify(started));
assert.equal(started.body.schema, 'qinglong/task-start@v1');
assert.equal(started.body.status, 'accepted');
assert.equal(started.body.runStatus, 'queued');
assert.equal(started.body.executorType, 'local_process');
assert.equal(started.body.taskContentDigest, taskDefinition.contentDigest);
assert.equal(
started.body.taskContentDigest,
updatedTask.body.task.contentDigest,
);
const taskStartReplay = await request(
port,
`Bearer ${TOKEN}`,
@@ -745,8 +856,8 @@ test('serves an authenticated Run through one real SQLite authority and durable
`SELECT operation_id, outcome FROM "QingLong3SecurityAuditEvents"
WHERE operation_id IN (
'run.get', 'run.list', 'run.events.list', 'run.steps.list',
'run.cancel', 'task.create', 'task.get', 'task.list'
, 'task.start', 'run.log.read'
'run.cancel', 'task.authoring.read', 'task.create', 'task.get',
'task.list', 'task.start', 'task.update', 'run.log.read'
)
ORDER BY operation_id, outcome`,
)
@@ -761,13 +872,18 @@ test('serves an authenticated Run through one real SQLite authority and durable
'run.list:allowed',
'run.log.read:allowed',
'run.steps.list:allowed',
'task.authoring.read:allowed',
'task.authoring.read:approval_required',
'task.create:allowed',
'task.create:approval_required',
'task.get:allowed',
'task.get:allowed',
'task.get:allowed',
'task.list:allowed',
'task.start:allowed',
'task.start:allowed',
'task.update:allowed',
'task.update:approval_required',
],
);
assert.deepEqual(
@@ -0,0 +1,355 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { test } = require('node:test');
const {
createTaskDefinitionRecord,
} = require('@qinglong/runtime-core/task-definition');
const {
createLocalPresenceProofManager,
} = require('../dist/authentication/localPresenceProof.js');
const {
createLocalApiTaskAuthoringRoute,
} = require('../dist/task/taskAuthoringRoute.js');
const PRINCIPAL = Object.freeze({
subject: Object.freeze({ type: 'user', id: 'owner' }),
authenticationId: 'local_credential:owner-console:1',
authenticatedAtMs: 9_000,
expiresAtMs: 1_000_000,
assurance: 'single_factor',
});
const FENCE = Object.freeze({
credentialId: 'owner-console',
credentialVersion: 1,
pepperKeyId: 'owner-v1',
materialDigest: 'a'.repeat(64),
subjectType: 'user',
subjectId: 'owner',
secretDigest: 'b'.repeat(64),
notBeforeAtMs: 1,
expiresAtMs: 1_000_000,
});
function uuidFactory() {
let sequence = 400;
return () => {
sequence += 1;
return `019fa000-0000-4000-8000-${String(sequence).padStart(12, '0')}`;
};
}
function definition(revision = 3) {
const first = createTaskDefinitionRecord(
{
projectId: 'default',
taskId: 'task-console',
expectedRevision: null,
mutationId: '019fa000-0000-4000-8000-000000000101',
name: 'Editable Task',
description: 'Full definition stays behind strong authoring read',
kind: 'command',
spec: Object.freeze({
schema: 'qinglong/command@v1',
config: Object.freeze({
command: Object.freeze({
kind: 'argv',
file: '/bin/echo',
args: Object.freeze(['before']),
}),
}),
}),
labels: Object.freeze({ 'qinglong.source': 'local-console' }),
enabled: true,
occurredAtMs: 10_000,
},
10_000,
);
return Object.freeze({ ...first, revision });
}
function fixture(t, overrides = {}) {
const deploymentRoot = fs.mkdtempSync(
path.join(os.tmpdir(), 'ql3-task-authoring-'),
);
fs.chmodSync(deploymentRoot, 0o700);
t.after(() => fs.rmSync(deploymentRoot, { recursive: true, force: true }));
let now = 10_000;
let current = definition();
const calls = [];
const presenceProof = createLocalPresenceProofManager({
deploymentRoot,
profile: 'edge',
now: () => now,
randomUuid: uuidFactory(),
randomSecret: () => Buffer.alloc(32, 17),
});
t.after(() => presenceProof.close());
const projectPolicy = {
async resolve(projectId, subject) {
calls.push(['policy', projectId, subject]);
return {
project: {
id: projectId,
name: 'Default',
slug: 'default',
status: 'active',
version: 3,
createdAtMs: 1,
updatedAtMs: 2,
},
binding: {
projectId,
subject,
version: 5,
state: 'active',
role: 'owner',
mutationId: 'owner-binding',
changedBy: { type: 'user', id: 'bootstrap-owner' },
createdAtMs: 2,
},
};
},
async append() {
throw new Error('not used');
},
};
const route = createLocalApiTaskAuthoringRoute({
profile: 'edge',
projectPolicy,
taskDefinitions: {
async findCurrentTaskDefinition() {
calls.push(['read']);
return current;
},
},
securityAudit: {
async record(record) {
calls.push(['audit', record]);
},
},
presenceProof,
now: () => now,
randomUuid: uuidFactory(),
randomSecret: () => Buffer.alloc(32, 19),
...overrides,
});
t.after(() => route.close());
const authenticated = Object.freeze({
principal: PRINCIPAL,
credentialFence: FENCE,
async confirm() {
calls.push(['confirm']);
},
});
return {
route,
calls,
deploymentRoot,
authenticated,
current: () => current,
setCurrent(value) {
current = value;
},
setNow(value) {
now = value;
},
};
}
function request(state, overrides = {}) {
return Object.freeze({
requestId: 'local:019fa000-0000-4000-8000-000000000301',
projectId: 'default',
taskId: 'task-console',
presence: null,
authenticated: state.authenticated,
signal: new AbortController().signal,
...overrides,
});
}
function proof(state, challenge) {
return JSON.parse(
fs.readFileSync(
path.join(
state.deploymentRoot,
'console-presence',
challenge.body.proofFileName,
),
'utf8',
),
).proof;
}
function leaseBinding(state, overrides = {}) {
const task = state.current();
return Object.freeze({
projectId: 'default',
taskId: 'task-console',
revision: task.revision,
contentDigest: task.contentDigest,
credentialId: FENCE.credentialId,
credentialVersion: FENCE.credentialVersion,
subjectType: 'user',
subjectId: FENCE.subjectId,
...overrides,
});
}
async function openAuthoring(state) {
const challenge = await state.route.handle(request(state));
assert.equal(challenge.statusCode, 428);
return state.route.handle(
request(state, { presence: proof(state, challenge) }),
);
}
test('returns the full exact definition only after local presence and issues one credential-bound lease', async (t) => {
const state = fixture(t);
const value = await openAuthoring(state);
assert.equal(value.statusCode, 200);
assert.deepEqual(value.body.task.spec, state.current().spec);
assert.deepEqual(value.body.task.labels, state.current().labels);
assert.equal(value.body.task.description, state.current().description);
assert.equal(value.body.authoring.revision, state.current().revision);
assert.equal(
value.body.authoring.contentDigest,
state.current().contentDigest,
);
assert.match(value.body.authoring.lease, /^ql3a_[A-Za-z0-9_-]+$/);
assert.equal(state.calls.filter(([kind]) => kind === 'confirm').length, 2);
assert.deepEqual(
state.calls
.filter(([kind]) => kind === 'audit')
.map(([, record]) => [
record.operationId,
record.outcome,
record.reasons[0],
]),
[
['task.authoring.read', 'approval_required', 'local_presence_required'],
['task.authoring.read', 'allowed', 'role_grant'],
],
);
assert.equal(
state.route.leases.inspect(value.body.authoring.lease, leaseBinding(state)),
true,
);
assert.equal(
state.route.leases.inspect(
value.body.authoring.lease,
leaseBinding(state, { credentialVersion: 2 }),
),
false,
);
assert.equal(
state.route.leases.consume(value.body.authoring.lease, leaseBinding(state)),
true,
);
assert.equal(
state.route.leases.consume(value.body.authoring.lease, leaseBinding(state)),
false,
);
});
test('binds a lease to the exact revision/content and expires it without a timer', async (t) => {
const state = fixture(t);
const value = await openAuthoring(state);
const lease = value.body.authoring.lease;
assert.equal(
state.route.leases.inspect(
lease,
leaseBinding(state, { contentDigest: 'f'.repeat(64) }),
),
false,
);
state.setNow(value.body.authoring.expiresAtMs);
assert.equal(state.route.leases.inspect(lease, leaseBinding(state)), false);
});
test('rejects non-User and unauthorized requests before publishing a proof', async (t) => {
const state = fixture(t, {
projectPolicy: {
async resolve(projectId, subject) {
return {
project: {
id: projectId,
name: 'Default',
slug: 'default',
status: 'active',
version: 3,
createdAtMs: 1,
updatedAtMs: 2,
},
binding: {
projectId,
subject,
version: 5,
state: 'active',
role: 'viewer',
mutationId: 'viewer-binding',
changedBy: { type: 'user', id: 'bootstrap-owner' },
createdAtMs: 2,
},
};
},
async append() {
throw new Error('not used');
},
},
});
assert.deepEqual(await state.route.handle(request(state)), {
statusCode: 403,
body: { code: 'forbidden' },
});
assert.deepEqual(
fs.readdirSync(path.join(state.deploymentRoot, 'console-presence')),
[],
);
const system = Object.freeze({
...state.authenticated,
principal: Object.freeze({
...PRINCIPAL,
subject: Object.freeze({ type: 'system', id: 'runtime' }),
assurance: 'service',
}),
credentialFence: Object.freeze({
...FENCE,
subjectType: 'system',
subjectId: 'runtime',
}),
});
assert.deepEqual(
await state.route.handle(request(state, { authenticated: system })),
{ statusCode: 403, body: { code: 'forbidden' } },
);
});
test('bounds Edge authoring leases to eight and clears them on close', async (t) => {
const state = fixture(t);
const leases = [];
for (let index = 0; index < 8; index += 1) {
const value = await openAuthoring(state);
assert.equal(value.statusCode, 200);
leases.push(value.body.authoring.lease);
}
const exhausted = await state.route.handle(request(state));
assert.deepEqual(exhausted, {
statusCode: 503,
body: { code: 'task_authoring_unavailable' },
});
state.route.close();
assert.equal(
state.route.leases.inspect(leases[0], leaseBinding(state)),
false,
);
assert.deepEqual(await state.route.handle(request(state)), {
statusCode: 503,
body: { code: 'request_unavailable' },
});
});
@@ -65,12 +65,17 @@ function uuidFactory() {
}
function fixture(t, overrides = {}) {
const {
currentDefinition: initialCurrentDefinition = null,
...routeOverrides
} = overrides;
const deploymentRoot = fs.mkdtempSync(
path.join(os.tmpdir(), 'ql3-task-put-'),
);
fs.chmodSync(deploymentRoot, 0o700);
t.after(() => fs.rmSync(deploymentRoot, { recursive: true, force: true }));
let now = 10_000;
let currentDefinition = initialCurrentDefinition;
const calls = [];
const presenceProof = createLocalPresenceProofManager({
deploymentRoot,
@@ -111,7 +116,7 @@ function fixture(t, overrides = {}) {
};
const taskDefinitions = {
async findCurrentTaskDefinition() {
return null;
return currentDefinition;
},
async findTaskDefinitionRevision() {
return null;
@@ -144,9 +149,17 @@ function fixture(t, overrides = {}) {
},
},
presenceProof,
taskAuthoringLeases: {
inspect() {
return true;
},
consume() {
return true;
},
},
now: () => now,
randomUuid: uuidFactory(),
...overrides,
...routeOverrides,
});
const authenticated = Object.freeze({
principal: PRINCIPAL,
@@ -163,6 +176,9 @@ function fixture(t, overrides = {}) {
setNow(value) {
now = value;
},
setCurrentDefinition(value) {
currentDefinition = value;
},
};
}
@@ -173,6 +189,7 @@ function request(state, body, overrides = {}) {
taskId: 'task-console',
body,
presence: null,
authoringLease: null,
authenticated: state.authenticated,
signal: new AbortController().signal,
...overrides,
@@ -290,3 +307,95 @@ test('fails closed for malformed bodies, non-User credentials and expired presen
);
assert.equal(state.calls.filter(([kind]) => kind === 'mutation').length, 0);
});
test('requires and consumes one exact authoring lease before an update mutation', async (t) => {
const current = createTaskDefinitionRecord(
{ projectId: 'default', taskId: 'task-console', ...taskBody() },
10_000,
);
let consumed = false;
const state = fixture(t, {
currentDefinition: current,
taskAuthoringLeases: {
inspect(value, binding) {
state.calls.push(['lease-inspect', value, binding]);
return value === 'ql3a_exact_lease' && !consumed;
},
consume(value, binding) {
state.calls.push(['lease-consume', value, binding]);
if (value !== 'ql3a_exact_lease' || consumed) return false;
consumed = true;
return true;
},
},
});
const update = taskBody({
expectedRevision: current.revision,
mutationId: '019f9000-0000-4000-8000-000000000102',
name: 'Updated through an authoring lease',
});
assert.deepEqual(await state.route.handle(request(state, update)), {
statusCode: 428,
body: { code: 'task_authoring_lease_required' },
});
const challenge = await state.route.handle(
request(state, update, { authoringLease: 'ql3a_exact_lease' }),
);
assert.equal(challenge.statusCode, 428);
const updated = await state.route.handle(
request(state, update, {
authoringLease: 'ql3a_exact_lease',
presence: readProof(state, challenge),
}),
);
assert.equal(updated.statusCode, 200);
assert.equal(updated.body.status, 'updated');
assert.equal(
state.calls.filter(([kind]) => kind === 'lease-inspect').length,
2,
);
assert.equal(
state.calls.filter(([kind]) => kind === 'lease-consume').length,
1,
);
assert.equal(state.calls.filter(([kind]) => kind === 'mutation').length, 1);
assert.deepEqual(
await state.route.handle(
request(state, update, { authoringLease: 'ql3a_exact_lease' }),
),
{ statusCode: 409, body: { code: 'task_authoring_lease_rejected' } },
);
});
test('rejects a stale authoring lease before issuing a second local proof', async (t) => {
const current = createTaskDefinitionRecord(
{ projectId: 'default', taskId: 'task-console', ...taskBody() },
10_000,
);
const state = fixture(t, {
currentDefinition: current,
taskAuthoringLeases: {
inspect(_value, binding) {
return binding.revision === current.revision;
},
consume() {
return true;
},
},
});
const update = taskBody({
expectedRevision: current.revision,
mutationId: '019f9000-0000-4000-8000-000000000103',
});
state.setCurrentDefinition(Object.freeze({ ...current, revision: 2 }));
assert.deepEqual(
await state.route.handle(
request(state, update, { authoringLease: 'ql3a_stale_lease' }),
),
{ statusCode: 409, body: { code: 'task_authoring_lease_rejected' } },
);
assert.deepEqual(
fs.readdirSync(path.join(state.deploymentRoot, 'console-presence')),
[],
);
});