mirror of
https://github.com/whyour/qinglong.git
synced 2026-09-20 16:07:11 +08:00
feat(ql3): add secure console task editing
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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')),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user