Skip to content

Commit dde5930

Browse files
author
hzq
committed
Fence node authority until policy writes are confirmed
Verify policy data and its audit entry before updating live node authority. Suspend new work and reconnects during uncertain commits, then recover by reading the original write without replaying it.
1 parent 5de9fce commit dde5930

8 files changed

Lines changed: 528 additions & 80 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,8 @@ Enrollment through `POST /v1/nodes/enroll` or the `node`-scope path of `POST /v1
400400
- `POST /v1/nodes/{id}/revoke`: terminally remove this identity's trust, including connections that passed HTTP upgrade but have not sent their hello yet. Future joins are rejected; active executors reject pending calls and ignore later frames before asynchronous socket closure. An in-flight write/native operation with no confirmed result remains uncertain and requires reconciliation. Repeating the same policy is idempotent; a revoked identity cannot be resumed or re-enrolled. Review and enroll a new identity when replacement is intended.
401401
- `GET /v1/nodes/{id}/history?after=0&limit=50`: owner-scoped policy audit, maximum 100 entries per page. Policy and audit commit in one transaction before dispatch authority changes. A failed audit write does not revoke or pause the node.
402402

403+
If the policy transaction cannot be confirmed, both node views report `policy_confirmed: false`; registrations retain the last confirmed state, and the live inventory reports `accepting: false`, not `drained: true`. The gateway holds new dispatch and node handshakes while it checks both the policy and the audit entry, without repeating the write. It applies the new state after proving commit and lifts the temporary restriction after proving rollback.
404+
403405
The synthetic local worker is protected from these remote credential controls. Use its existing local execution settings or gateway lifecycle instead. Native backend configuration files and node credential files are not rewritten by a policy operation. A config-file credential is still denied by its persisted revocation after restart. Duplicate credential identities and attempts to assign a retained identity to another owner fail closed at startup.
404406

405407
The console exposes pause/resume/revoke controls and retains offline/revoked rows. CLI equivalents are `oaa nodes`, `oaa node drain NODE`, `oaa node resume NODE`, `oaa node revoke NODE`, and `oaa node history NODE`; `oaa resume RESPONSE_ID` resumes a confirmed kernel checkpoint. No node-management MCP tool is exposed to task-calling agents. The updated worker stops retrying after an HTTP 401/403 handshake denial; older workers may retry but remain rejected.

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ WebSocket 已连接不等于节点注册完成。worker 发送 `hello` 后最多
422422
- `POST /v1/nodes/{id}/revoke`:终止性地撤销这个身份的信任,包括已通过 HTTP 升级但还没发 hello 的连接。之后的加入会被拒绝;活跃的执行方拒绝待处理的调用,并在异步关闭套接字之前忽略后续的帧。一个进行中、没有确认结果的写入/原生操作仍然是不确定的,需要对账。重复同一策略是幂等的;已吊销的身份不能被恢复或重新登记。需要替换时,请审查并登记一个新身份。
423423
- `GET /v1/nodes/{id}/history?after=0&limit=50`:限定 owner 的策略审计,每页最多 100 条。策略与审计在派发权限改变之前于同一个事务里提交。审计写入失败不会吊销或暂停该节点。
424424

425+
策略事务无法确认时,登记清单和在线节点清单都标记 `policy_confirmed: false`;登记清单保留上次确认的状态,在线节点清单报告 `accepting: false`,不报告 `drained: true`。网关暂停新任务派发和节点握手,在后台同时核对策略与审计,不重放写入。确认提交后应用新策略;证实回滚后才解除临时限制。
426+
425427
合成的本机 worker 不受这些远程凭据控制的影响。请改用它已有的本机执行设置或网关生命周期。原生后端配置文件与节点凭据文件不会被策略操作改写。配置文件里的凭据,重启之后仍被它持久化的吊销所拒绝。重复的凭据身份,以及把已保留的身份分配给另一个 owner 的尝试,在启动时直接失败(fail closed)。
426428

427429
控制台提供暂停/恢复/吊销控件,并保留离线/已吊销的行。命令行对应的是 `oaa nodes`、`oaa node drain NODE`、`oaa node resume NODE`、`oaa node revoke NODE` 与 `oaa node history NODE`;`oaa resume RESPONSE_ID` 恢复一个已确认的内核检查点。不向执行任务的调用智能体暴露任何节点管理的 MCP 工具。更新后的 worker 在 HTTP 401/403 握手拒绝后停止重试;旧 worker 可能仍会重试,但仍会被拒绝。

‎src/fabric/network.ts‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import {
5555
import type { ArtifactWriteStore } from '../store/large-artifacts.js';
5656
import type { DispatchFence } from '../store/step-preparation.js';
5757
import { IncomingArtifacts, ReceivedResultFault } from './artifact-transfer.js';
58+
import { NodeAuthority } from './node-authority.js';
5859
import {
5960
A2A_LOOKUP_MS,
6061
A2A_TASK_RECOVERY,
@@ -552,7 +553,7 @@ export class NodeHub {
552553
private wakeTimer: NodeJS.Timeout | undefined;
553554
private wakeAt = Infinity;
554555
private heartbeatTimer: NodeJS.Timeout;
555-
private policies = new Map<string, NodePolicy>();
556+
readonly authority: NodeAuthority;
556557
private peers = new Map<WebSocket, string>();
557558
private retiring = new Set<Promise<void>>();
558559
private wss = new WebSocketServer({ noServer: true, maxPayload: LIMITS.nodeMessageBytes });
@@ -568,16 +569,7 @@ export class NodeHub {
568569
'Node credentials must have unique identities.',
569570
409,
570571
);
571-
for (const policy of policies) {
572-
const credential = credentials.find((c) => c.nodeId === policy.nodeId);
573-
if (credential && credential.owner !== policy.owner)
574-
throw new Fault(
575-
'node_owner_conflict',
576-
'A configured node identity is reserved by another owner.',
577-
409,
578-
);
579-
this.policies.set(policy.nodeId, policy);
580-
}
572+
this.authority = new NodeAuthority(credentials, policies);
581573
this.heartbeatTimer = setInterval(
582574
() => {
583575
for (const node of this.nodes.values())
@@ -592,16 +584,16 @@ export class NodeHub {
592584
this.heartbeatTimer.unref();
593585
}
594586
addLocal(credential: NodeCredential, executor: Executor): void {
595-
if (this.policies.has(credential.nodeId))
596-
throw new Fault(
597-
'node_identity_reserved',
598-
'A remote lifecycle policy already reserves this local node ID.',
599-
409,
600-
);
587+
this.authority.requireLocalIdentity(credential.nodeId);
601588
this.register(credential, executor);
602589
}
603590
policy(nodeId: string): NodePolicy['state'] {
604-
return this.policies.get(nodeId)?.state ?? 'active';
591+
return this.authority.state(nodeId);
592+
}
593+
fencePolicy(nodeId: string, owner: string, blocked: boolean): void {
594+
this.authority.fence(nodeId, blocked);
595+
this.notifyChange(owner);
596+
this.pump();
605597
}
606598
/**
607599
* Announce a node-state change that happened outside the hub (e.g. a local backend toggle).
@@ -667,7 +659,7 @@ export class NodeHub {
667659
'Remote credential controls cannot change the local worker.',
668660
409,
669661
);
670-
this.policies.set(policy.nodeId, policy);
662+
this.authority.apply(policy);
671663
const node = this.nodes.get(policy.nodeId);
672664
const affected = node?.active ?? 0;
673665
if (policy.state === 'revoked') {
@@ -749,6 +741,10 @@ export class NodeHub {
749741
socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
750742
return;
751743
}
744+
if (this.authority.isFenced(nodeId)) {
745+
socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n');
746+
return;
747+
}
752748
this.wss.handleUpgrade(req, socket, head, (ws) => {
753749
this.peers.set(ws, nodeId);
754750
ws.once('close', () => this.peers.delete(ws));
@@ -759,6 +755,7 @@ export class NodeHub {
759755
if (
760756
this.closing ||
761757
!this.credentials.includes(credential) ||
758+
this.authority.isFenced(nodeId) ||
762759
this.policy(nodeId) === 'revoked'
763760
)
764761
throw new Error('Node access changed before handshake completion');
@@ -884,8 +881,12 @@ export class NodeHub {
884881
connected_at: n.connectedAt,
885882
admission_state: this.policy(n.credential.nodeId),
886883
accepting: this.policy(n.credential.nodeId) === 'active',
884+
...(this.authority.isFenced(n.credential.nodeId) ? { policy_confirmed: false } : {}),
887885
local: !(n.executor instanceof RemoteExecutor),
888-
drained: this.policy(n.credential.nodeId) === 'draining' && n.active === 0,
886+
drained:
887+
!this.authority.isFenced(n.credential.nodeId) &&
888+
this.policy(n.credential.nodeId) === 'draining' &&
889+
n.active === 0,
889890
}));
890891
}
891892
releaseRun(runId: string): void {

‎src/fabric/node-authority.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import type { NodeCredential, NodePolicy } from '../core/contracts.js';
2+
import { Fault } from '../core/util.js';
3+
4+
/** The durable policy and a temporary dispatch fence are intentionally separate. */
5+
export class NodeAuthority {
6+
private readonly confirmed = new Map<string, NodePolicy>();
7+
private readonly fenced = new Set<string>();
8+
9+
constructor(credentials: readonly NodeCredential[], policies: readonly NodePolicy[]) {
10+
for (const policy of policies) {
11+
const credential = credentials.find((c) => c.nodeId === policy.nodeId);
12+
if (credential && credential.owner !== policy.owner)
13+
throw new Fault(
14+
'node_owner_conflict',
15+
'A configured node identity is reserved by another owner.',
16+
409,
17+
);
18+
this.confirmed.set(policy.nodeId, policy);
19+
}
20+
}
21+
22+
policies(owner: string): NodePolicy[] {
23+
return [...this.confirmed.values()].filter((p) => p.owner === owner);
24+
}
25+
26+
requireLocalIdentity(nodeId: string): void {
27+
if (this.confirmed.has(nodeId) || this.fenced.has(nodeId))
28+
throw new Fault(
29+
'node_identity_reserved',
30+
'A remote lifecycle policy already reserves this local node ID.',
31+
409,
32+
);
33+
}
34+
35+
state(nodeId: string): NodePolicy['state'] {
36+
const confirmed = this.confirmed.get(nodeId)?.state ?? 'active';
37+
return confirmed !== 'revoked' && this.isFenced(nodeId) ? 'draining' : confirmed;
38+
}
39+
40+
isFenced(nodeId: string): boolean {
41+
return this.fenced.has(nodeId);
42+
}
43+
44+
fence(nodeId: string, blocked: boolean): void {
45+
if (blocked) this.fenced.add(nodeId);
46+
else this.fenced.delete(nodeId);
47+
}
48+
49+
apply(policy: NodePolicy): void {
50+
this.confirmed.set(policy.nodeId, policy);
51+
this.fenced.delete(policy.nodeId);
52+
}
53+
}

‎src/gateway/auth.ts‎

Lines changed: 11 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { assertMayManageKey } from './key-guard.js';
2828
import { KeyRevocations } from './key-revocation.js';
2929
import { KeyIssuance } from './key-issuance.js';
3030
import { NodeEnrollment } from './node-enrollment.js';
31+
import { NodePolicyWrites } from './node-policy-writes.js';
3132

3233
import type { StoredKey, AccountKeyView, AccountKeyPolicy } from './key-types.js';
3334
export type { AccountKeyView, AccountKeyPolicy } from './key-types.js';
@@ -46,6 +47,7 @@ export class Auth {
4647
private readonly revocations: KeyRevocations;
4748
private readonly issuance: KeyIssuance;
4849
private readonly enrollment: NodeEnrollment;
50+
private readonly nodePolicyWrites: NodePolicyWrites;
4951
private readonly usage: KeyUsage;
5052
readonly accounting: KeyAccounting;
5153
constructor(readonly store: Store) {
@@ -57,6 +59,7 @@ export class Auth {
5759
this.revocations = new KeyRevocations(store, (key) => this.dropManagedKey(key));
5860
this.issuance = new KeyIssuance(store, (key, order) => this.indexKey(key, order));
5961
this.enrollment = new NodeEnrollment(store);
62+
this.nodePolicyWrites = new NodePolicyWrites(store);
6063
this.reloadManagedKeys();
6164
}
6265
private reloadManagedKeys(): void {
@@ -477,7 +480,7 @@ export class Auth {
477480
if (dropped || released) this.store.authorizationChanged(owner);
478481
}
479482
close(): void {
480-
this.enrollment.close();
483+
this.prepareClose();
481484
this.issuance.close();
482485
this.revocations.close();
483486
this.rates.close();
@@ -503,11 +506,15 @@ export class Auth {
503506
this.enrollment.enroll(credential);
504507
return { credential, token };
505508
}
506-
attachNodeRegistry(registry: Parameters<NodeEnrollment['attach']>[0]): void {
509+
attachNodeRegistry(
510+
registry: Parameters<NodeEnrollment['attach']>[0] & Parameters<NodePolicyWrites['attach']>[0],
511+
): void {
507512
this.enrollment.attach(registry);
513+
this.nodePolicyWrites.attach(registry);
508514
}
509515
prepareClose(): void {
510516
this.enrollment.close();
517+
this.nodePolicyWrites.close();
511518
this.accounting.stopResets();
512519
}
513520
nodeCredentials(): NodeCredential[] {
@@ -531,58 +538,12 @@ export class Auth {
531538
return policy;
532539
});
533540
}
534-
setNodePolicy(
535-
p: Principal,
536-
credential: NodeCredential,
537-
state: NodePolicyState,
538-
reason: string,
539-
): NodePolicy {
541+
setNodePolicy(p: Principal, credential: NodeCredential, state: NodePolicyState, reason: string) {
540542
this.requireNodeAdmin(p);
541543
if (credential.owner !== p.owner)
542544
throw new Fault('node_not_found', 'Node registration not found.', 404);
543545
this.enrollment.requireConfirmed(credential.nodeId, p.owner);
544-
const db = this.store.db;
545-
db.exec('BEGIN IMMEDIATE');
546-
try {
547-
const row = db
548-
.prepare('SELECT payload FROM node_policies WHERE node_id=?')
549-
.get(credential.nodeId);
550-
const prior = row ? nodePolicySchema.parse(JSON.parse(String(row.payload))) : undefined;
551-
if (prior && prior.owner !== p.owner)
552-
throw new Fault('node_owner_conflict', 'Node identity is reserved by another owner.', 409);
553-
if (prior?.state === state) {
554-
db.exec('COMMIT');
555-
return prior;
556-
}
557-
if (prior?.state === 'revoked')
558-
throw new Fault(
559-
'node_revoked',
560-
'Revocation is terminal. Enroll a new node identity after review.',
561-
409,
562-
);
563-
const next: NodePolicy = {
564-
nodeId: credential.nodeId,
565-
owner: p.owner,
566-
state,
567-
actor: p.name,
568-
reason,
569-
updatedAt: Date.now(),
570-
};
571-
const payload = JSON.stringify(next);
572-
db.prepare(
573-
'INSERT INTO node_policies VALUES(?,?,?) ON CONFLICT(node_id) DO UPDATE SET payload=excluded.payload',
574-
).run(next.nodeId, p.owner, payload);
575-
db.prepare('INSERT INTO node_policy_events(node_id,owner,payload) VALUES(?,?,?)').run(
576-
next.nodeId,
577-
p.owner,
578-
payload,
579-
);
580-
db.exec('COMMIT');
581-
return next;
582-
} catch (error) {
583-
if (db.isTransaction) db.exec('ROLLBACK');
584-
throw error;
585-
}
546+
return this.nodePolicyWrites.set(credential.nodeId, p.owner, state, p.name, reason);
586547
}
587548
nodePolicyHistory(p: Principal, nodeId: string, after: number, limit: number) {
588549
this.requireNodeAdmin(p);

0 commit comments

Comments
 (0)