Skip to content

Commit 9deeb60

Browse files
author
hzq
committed
Confirm Windows staging ACLs after an unacknowledged update
1 parent ed65472 commit 9deeb60

6 files changed

Lines changed: 128 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ English · [简体中文](CHANGELOG.zh-CN.md)
44

55
## Unreleased
66

7+
- Profile writers now report which protection or revision check stopped an edit. Windows staging verifies the actual permissions after an unconfirmed ACL update before retrying; it still refuses to publish from an unprotected temporary path.
78
- Verifying a known caller key fetches just the selected model rather than downloading the catalog. Gateways without a model-detail endpoint still use the list. Individual model lookups no longer expand the aliases of unrelated agents.
89
- Quickstart and connect no longer issue caller keys just because a check timed out or the gateway returned a temporary error. Quickstart preserves a restricted key and installs a confirmed replacement for a rejected one without deleting the original first.
910
- After an interrupted first setup, `oaa init` can finish with the original private owner key. It refuses unsafe or incomplete keys and never overwrites an existing configuration or issues a replacement key for it.

‎CHANGELOG.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
## 未发布
66

7+
- 配置更新冲突会指出具体是写锁、源文件版本还是临时文件权限检查未通过。Windows 设置临时目录或文件权限后若未收到确认,会先核对实际权限;无法证明安全时仍拒绝发布。
78
- 校验已有调用密钥时只查询目标模型,不再下载整份目录;不支持单模型接口的旧网关仍回退到列表。网关查询单个模型时也不再展开其他智能体的路由别名。
89
- 快速启动和连接智能体时,网关超时或暂时出错不再触发补发调用密钥。快速启动会保留权限受限的密钥;确需替换已被网关拒绝的密钥时,也不再先删除原文件。
910
- 首次初始化中断后,`oaa init` 可以沿用已经写好的私有管理员密钥,补齐配置。残缺或权限不安全的密钥不会被采用,已有配置也不会被覆盖或被补发新密钥。

‎src/config/profile-update.ts‎

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,27 @@ import { DatabaseSync } from 'node:sqlite';
66
import { setTimeout as delay } from 'node:timers/promises';
77
import { promisify } from 'node:util';
88
import { Fault, relativeName } from '../core/util.js';
9-
import { restrictToOwner, runWindowsProfileScript } from '../core/win-acl.js';
9+
import { protectWindowsStage, runWindowsProfileScript } from '../core/win-acl.js';
1010

1111
const exec = promisify(execFile);
12-
const conflict = () =>
12+
const conflict = (reason: string) =>
1313
new Fault(
1414
'profile_config_conflict',
15-
'The profile configuration changed, is busy or cannot retain its protections. Reload it before retrying.',
15+
`Profile update stopped: ${reason}. Reload the configuration before retrying.`,
1616
409,
1717
);
1818
const info = (file: string) => lstat(file, { bigint: true });
1919
const identical = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino;
20-
const unchanged = (a: BigIntStats, b: BigIntStats) =>
21-
identical(a, b) && a.size === b.size && a.ctimeNs === b.ctimeNs && a.mtimeNs === b.mtimeNs;
20+
const revisionChange = (a: BigIntStats, b: BigIntStats) =>
21+
!identical(a, b)
22+
? 'file identity'
23+
: a.size !== b.size
24+
? 'file size'
25+
: a.mtimeNs !== b.mtimeNs
26+
? 'modification time'
27+
: a.ctimeNs !== b.ctimeNs
28+
? 'change time'
29+
: undefined;
2230

2331
const creatingGuards = new Map<string, Promise<void>>();
2432
async function prepareGuard(guard: string) {
@@ -53,7 +61,7 @@ export async function withProfileWriter<T>(
5361
initial.nlink !== 1n ||
5462
(process.getuid && (initial.uid !== BigInt(process.getuid()) || (initial.mode & 0o022n) !== 0n))
5563
)
56-
throw conflict();
64+
throw conflict('writer guard has unexpected type or permissions');
5765
const db = new DatabaseSync(guard);
5866
try {
5967
db.exec('PRAGMA busy_timeout=0');
@@ -74,13 +82,13 @@ export async function withProfileWriter<T>(
7482
'Another caller-key setup is still active; retry without deleting its files.',
7583
503,
7684
);
77-
throw conflict();
85+
throw conflict('another configuration writer is still active');
7886
}
7987
await delay(pause);
8088
if (subject === 'caller-key') pause = Math.min(250, pause * 2);
8189
}
8290
}
83-
if (!identical(initial, await info(guard))) throw conflict();
91+
if (!identical(initial, await info(guard))) throw conflict('writer guard was replaced');
8492
return await apply();
8593
} finally {
8694
db.close();
@@ -89,14 +97,17 @@ export async function withProfileWriter<T>(
8997

9098
async function snapshot(file: string, expected: Buffer): Promise<BigIntStats> {
9199
const named = await info(file);
92-
if (!named.isFile() || named.size !== BigInt(expected.byteLength)) throw conflict();
100+
if (!named.isFile() || named.size !== BigInt(expected.byteLength))
101+
throw conflict('source type or size differs from the reviewed file');
93102
const handle = await open(
94103
file,
95104
constants.O_RDWR | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
96105
);
97106
try {
98107
const s = await handle.stat({ bigint: true });
99-
if (!unchanged(named, s) || !s.isFile()) throw conflict();
108+
const opening = revisionChange(named, s);
109+
if (opening || !s.isFile())
110+
throw conflict(`source changed while opening (${opening ?? 'type'})`);
100111
const buf = Buffer.alloc(Math.min(expected.byteLength, 65536));
101112
for (let offset = 0; offset < expected.length;) {
102113
const { bytesRead } = await handle.read(
@@ -109,10 +120,11 @@ async function snapshot(file: string, expected: Buffer): Promise<BigIntStats> {
109120
!bytesRead ||
110121
!buf.subarray(0, bytesRead).equals(expected.subarray(offset, offset + bytesRead))
111122
)
112-
throw conflict();
123+
throw conflict('source bytes differ from the reviewed configuration');
113124
offset += bytesRead;
114125
}
115-
if (!unchanged(s, await info(file))) throw conflict();
126+
const closing = revisionChange(s, await info(file));
127+
if (closing) throw conflict(`source changed while reading (${closing})`);
116128
return s;
117129
} finally {
118130
await handle.close();
@@ -122,7 +134,8 @@ async function snapshot(file: string, expected: Buffer): Promise<BigIntStats> {
122134
async function destination(file: string, allowSymlink: boolean): Promise<string> {
123135
if (!allowSymlink) {
124136
relativeName(path.basename(file));
125-
if ((await lstat(file)).isSymbolicLink()) throw conflict();
137+
if ((await lstat(file)).isSymbolicLink())
138+
throw conflict('this writer cannot follow a configuration symlink');
126139
}
127140
return realpath(file);
128141
}
@@ -142,7 +155,13 @@ function copyFlags(): Promise<string[]> {
142155

143156
async function prepare(source: string, stage: string, next: string, original: BigIntStats) {
144157
if (process.platform === 'win32') {
145-
if (!(await restrictToOwner(path.dirname(stage)))) throw conflict();
158+
const dir = path.dirname(stage),
159+
expected = await info(dir);
160+
const privacy = await protectWindowsStage(dir, dir);
161+
if (privacy !== 'private')
162+
throw conflict(`temporary directory permissions were not confirmed (${privacy})`);
163+
if (!expected.isDirectory() || !identical(expected, await info(dir)))
164+
throw conflict('temporary directory was replaced');
146165
} else {
147166
if (process.platform === 'darwin') await exec('/bin/chmod', ['-N', path.dirname(stage)]);
148167
// Node copyFile drops ACLs and extended attributes on macOS. Preserve source metadata.
@@ -157,20 +176,28 @@ async function prepare(source: string, stage: string, next: string, original: Bi
157176
copy.gid !== original.gid ||
158177
copy.mode !== original.mode
159178
)
160-
throw conflict();
179+
throw conflict('temporary copy did not preserve source metadata');
161180
}
162181
const out = await open(
163182
stage,
164183
process.platform === 'win32' ? 'wx' : constants.O_RDWR | (constants.O_NOFOLLOW ?? 0),
165184
0o600,
166185
);
167186
try {
168-
if (process.platform === 'win32' && !(await restrictToOwner(stage))) throw conflict();
187+
if (process.platform === 'win32') {
188+
const expected = await out.stat({ bigint: true });
189+
const privacy = await protectWindowsStage(stage, path.dirname(stage));
190+
if (privacy !== 'private')
191+
throw conflict(`temporary file permissions were not confirmed (${privacy})`);
192+
const named = await info(stage);
193+
if (!named.isFile() || named.nlink !== 1n || !identical(expected, named))
194+
throw conflict('temporary file was replaced');
195+
}
169196
await out.truncate(0);
170197
await out.writeFile(next, 'utf8');
171198
await out.sync();
172199
if (process.platform !== 'win32' && (await out.stat({ bigint: true })).mode !== original.mode)
173-
throw conflict();
200+
throw conflict('temporary file mode changed while staging');
174201
} finally {
175202
await out.close();
176203
}
@@ -206,11 +233,10 @@ export async function replaceProfileConfig(
206233
await prepare(target, stage, next, original);
207234
const proposed = await info(stage);
208235
await withProfileWriter(dir, async () => {
209-
if (
210-
(await destination(file, allowSymlink)) !== target ||
211-
!unchanged(original, await snapshot(target, before))
212-
)
213-
throw conflict();
236+
if ((await destination(file, allowSymlink)) !== target)
237+
throw conflict('configuration path now resolves elsewhere');
238+
const change = revisionChange(original, await snapshot(target, before));
239+
if (change) throw conflict(`source changed before replacement (${change})`);
214240
try {
215241
await replace(stage, target);
216242
} catch (error) {

‎src/core/win-acl.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,22 @@ export async function orphanKeyPrivacy(file: string, dir: string): Promise<strin
119119
return typeof code === 'number' ? `acl-query-exit-${code}` : 'acl-query-unavailable';
120120
}
121121
}
122+
123+
/** Only for new, empty staging paths. A lost utility acknowledgement does not undo an applied DACL. */
124+
export async function protectWindowsStage(
125+
file: string,
126+
dir: string,
127+
set = restrictToOwner,
128+
observe = orphanKeyPrivacy,
129+
): Promise<string> {
130+
let state = 'unverified';
131+
for (let attempt = 0; attempt < 2; attempt++) {
132+
if (await set(file)) return 'private';
133+
state = await observe(file, dir);
134+
if (state === 'private') return state;
135+
}
136+
return state;
137+
}
122138
/** The `icacls` argument list that limits `file` to `user`; exported for tests. */
123139
export function icaclsArgs(file: string, user: string): string[] {
124140
return [file, '/inheritance:r', '/grant:r', `${user}:F`, '/q'];

‎test/fixtures/profile-write.mjs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { DatabaseSync } from 'node:sqlite';
22
import path from 'node:path';
33
import { pathToFileURL } from 'node:url';
44
import fs from 'node:fs/promises';
5+
import childProcess from 'node:child_process';
56
import { syncBuiltinESMExports } from 'node:module';
67

78
const [action, file, next] = process.argv.slice(2);
@@ -12,6 +13,27 @@ if (action === 'hold') {
1213
process.send('held');
1314
await hold();
1415
} else {
16+
let lostAclReceipts = 0;
17+
if (action === 'acl-ack-lost') {
18+
const exec = childProcess.execFile;
19+
childProcess.execFile = (program, args, options, callback) => {
20+
if (
21+
path.basename(program).toLowerCase() !== 'icacls.exe' ||
22+
!String(args[0]).includes('.oaa-profile-edit-')
23+
)
24+
return exec(program, args, options, callback);
25+
return exec(program, args, options, (error, stdout, stderr) => {
26+
if (!error) {
27+
lostAclReceipts++;
28+
error = Object.assign(new Error('ACL acknowledgement unavailable'), {
29+
code: 'ETIMEDOUT',
30+
});
31+
}
32+
callback(error, stdout, stderr);
33+
});
34+
};
35+
syncBuiltinESMExports();
36+
}
1537
if (['before-rename', 'lost-ack', 'failed-rename'].includes(action)) {
1638
const rename = fs.rename;
1739
fs.rename = async (source, target) => {
@@ -32,6 +54,8 @@ if (action === 'hold') {
3254
);
3355
try {
3456
await replaceProfileConfig(file, '{"rev":0}\n', next);
57+
if (action === 'acl-ack-lost' && lostAclReceipts !== 2)
58+
throw new Error('Both native ACL updates must have completed');
3559
console.log('published');
3660
} catch (error) {
3761
if (error.code !== 'profile_config_conflict') throw error;

‎test/profile-update.test.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import path from 'node:path';
1919
import { promisify } from 'node:util';
2020
import { initialize } from '../src/config/config.js';
2121
import { replaceProfileConfig } from '../src/config/profile-update.js';
22-
import { restrictToOwner } from '../src/core/win-acl.js';
22+
import { protectWindowsStage, restrictToOwner } from '../src/core/win-acl.js';
2323

2424
const exec = promisify(execFile);
2525
const original = '{"rev":0}\n',
@@ -66,6 +66,43 @@ test('a profile edit publishes whole bytes, preserves protection and rejects sta
6666
assert.deepEqual((await readdir(dir)).sort(), ['.oaa-profile-writer', path.basename(file)]);
6767
});
6868

69+
test('private staging distinguishes a lost ACL acknowledgement from an unconfirmed protection', async () => {
70+
let writes = 0,
71+
observations = 0;
72+
const lost = async () => {
73+
writes++;
74+
return false;
75+
};
76+
assert.equal(
77+
await protectWindowsStage('new', 'parent', lost, async () => {
78+
observations++;
79+
return 'private';
80+
}),
81+
'private',
82+
);
83+
assert.equal(writes, 1);
84+
assert.equal(observations, 1);
85+
writes = 0;
86+
assert.equal(
87+
await protectWindowsStage('new', 'parent', lost, async () => 'shared-key'),
88+
'shared-key',
89+
);
90+
assert.equal(writes, 2, 'unconfirmed protection has a bounded retry, never success');
91+
});
92+
93+
test(
94+
'Windows can publish after the ACL command loses both acknowledgements',
95+
{ skip: process.platform !== 'win32' },
96+
async (t) => {
97+
const { file } = await profile(t);
98+
const r = await exec(process.execPath, [fixture, 'acl-ack-lost', file, changed], {
99+
timeout: 60000,
100+
});
101+
assert.equal(r.stdout.trim(), 'published');
102+
assert.equal(await readFile(file, 'utf8'), changed);
103+
},
104+
);
105+
69106
test(
70107
'only explicitly followed symlinks are edited and other hard links are not mutated',
71108
{ skip: process.platform === 'win32' },

0 commit comments

Comments
 (0)