@openai/codex-security 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { constants, existsSync } from "node:fs";
4
- import { chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
4
+ import { chmod, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile, } from "node:fs/promises";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { createRequire } from "node:module";
7
7
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
@@ -72,7 +72,9 @@ export async function prepareCodexSecurityCredentialHome(environment = process.e
72
72
  const canonical = await realpath(path);
73
73
  requireModelSafeOutputDir(canonical);
74
74
  validateLocation?.(canonical);
75
- await requirePrivateCredentialHome(metadata, canonical);
75
+ await requireSecureCredentialHome(canonical, {
76
+ metadata,
77
+ });
76
78
  return canonical;
77
79
  }
78
80
  catch (error) {
@@ -81,6 +83,58 @@ export async function prepareCodexSecurityCredentialHome(environment = process.e
81
83
  throw new OutputDirectoryError(`Unable to prepare the Codex Security credential home: ${path}`, { cause: error });
82
84
  }
83
85
  }
86
+ /**
87
+ * Re-verify the credential home before every use.
88
+ *
89
+ * Durable cross-process `(st_dev, st_ino)` pins are deferred: there is no
90
+ * workbench row for credential homes, and path+mode+trusted-ancestry checks on
91
+ * each use already close the cross-user rename/replace class. Lock acquisition
92
+ * still pins identity for the duration of a single lock session.
93
+ */
94
+ export async function requireSecureCredentialHome(path, options = {}) {
95
+ const platform = options.platform ?? process.platform;
96
+ let metadata = options.metadata;
97
+ if (metadata === undefined) {
98
+ try {
99
+ metadata = await lstat(path);
100
+ }
101
+ catch (error) {
102
+ throw new OutputDirectoryError(`Unable to inspect the Codex Security credential home: ${path}`, { cause: error });
103
+ }
104
+ }
105
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
106
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
107
+ }
108
+ const canonical = await realpath(path);
109
+ requireModelSafeOutputDir(canonical);
110
+ const canonicalMetadata = await lstat(canonical);
111
+ if (canonicalMetadata.dev !== metadata.dev ||
112
+ canonicalMetadata.ino !== metadata.ino) {
113
+ throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
114
+ }
115
+ metadata = canonicalMetadata;
116
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
117
+ throw new OutputDirectoryError(`Codex Security credential home is not a directory: ${path}`);
118
+ }
119
+ if (options.expectedDevice !== undefined &&
120
+ options.expectedInode !== undefined &&
121
+ (metadata.dev !== options.expectedDevice ||
122
+ metadata.ino !== options.expectedInode)) {
123
+ throw new OutputDirectoryError(`Codex Security credential home was replaced: ${canonical}`);
124
+ }
125
+ if (platform === "win32") {
126
+ if (options.validateWindowsAcl !== false) {
127
+ await requirePrivateCredentialHome(metadata, canonical, {
128
+ platform,
129
+ secureWindowsHome: options.secureWindowsHome,
130
+ });
131
+ }
132
+ return metadata;
133
+ }
134
+ await requirePrivateCredentialHome(metadata, canonical, { platform });
135
+ await requireSecureOutputAncestry(canonical);
136
+ return metadata;
137
+ }
84
138
  export async function requirePrivateCredentialHome(metadata, path, options = {}) {
85
139
  if ((options.platform ?? process.platform) !== "win32") {
86
140
  requirePrivateOutputDirectory(metadata, path);
@@ -123,12 +177,37 @@ async function secureWindowsCredentialHome(path) {
123
177
  maxBuffer: 1024 * 1024,
124
178
  });
125
179
  }
126
- export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal) {
180
+ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
181
+ const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
182
+ const expectedDevice = homeMetadata.dev;
183
+ const expectedInode = homeMetadata.ino;
127
184
  const lock = join(codexHome, CREDENTIAL_LOCK_NAME);
128
185
  const ownerPath = join(lock, "owner.json");
129
186
  const token = randomUUID();
130
187
  while (true) {
131
188
  throwIfSignalAborted(signal);
189
+ await requireSecureCredentialHome(codexHome, {
190
+ ...securityOptions,
191
+ expectedDevice,
192
+ expectedInode,
193
+ validateWindowsAcl: false,
194
+ });
195
+ const existingLock = await lstat(lock).catch((error) => {
196
+ if (nodeErrorCode(error) === "ENOENT")
197
+ return null;
198
+ throw error;
199
+ });
200
+ if (existingLock !== null) {
201
+ if (await recoverStaleCredentialHomeLock(lock))
202
+ continue;
203
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
204
+ continue;
205
+ }
206
+ await requireSecureCredentialHome(codexHome, {
207
+ ...securityOptions,
208
+ expectedDevice,
209
+ expectedInode,
210
+ });
132
211
  try {
133
212
  await mkdir(lock, { mode: 0o700 });
134
213
  }
@@ -151,6 +230,11 @@ export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal)
151
230
  return async () => {
152
231
  if (released)
153
232
  return;
233
+ await requireSecureCredentialHome(codexHome, {
234
+ ...securityOptions,
235
+ expectedDevice,
236
+ expectedInode,
237
+ });
154
238
  const owner = JSON.parse(await readFile(ownerPath, "utf8"));
155
239
  if (owner.token !== token) {
156
240
  throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
@@ -214,6 +298,7 @@ async function recoverStaleCredentialHomeLock(lock) {
214
298
  return true;
215
299
  }
216
300
  export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
301
+ await requireSecureCredentialHome(codexHome);
217
302
  const marker = join(codexHome, CREDENTIAL_LOGOUT_MARKER);
218
303
  if (!loggedOut) {
219
304
  await rm(marker, { force: true });
@@ -237,6 +322,7 @@ export async function setCodexSecurityCredentialLogout(codexHome, loggedOut) {
237
322
  }
238
323
  }
239
324
  export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
325
+ await requireSecureCredentialHome(codexHome);
240
326
  try {
241
327
  const marker = await lstat(join(codexHome, CREDENTIAL_LOGOUT_MARKER));
242
328
  if (!marker.isFile() || marker.isSymbolicLink()) {
@@ -251,6 +337,7 @@ export async function codexSecurityCredentialAllowsAmbientImport(codexHome) {
251
337
  }
252
338
  }
253
339
  export async function codexSecurityHasStoredFileCredentials(codexHome) {
340
+ await requireSecureCredentialHome(codexHome);
254
341
  const path = join(codexHome, "auth.json");
255
342
  let metadata;
256
343
  try {
@@ -264,8 +351,19 @@ export async function codexSecurityHasStoredFileCredentials(codexHome) {
264
351
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
265
352
  throw new OutputDirectoryError(`Codex Security stored authentication is not a regular file: ${path}`);
266
353
  }
354
+ requirePrivateCredentialFile(metadata, path);
267
355
  return true;
268
356
  }
357
+ export function requirePrivateCredentialFile(metadata, path, effectiveUid = process.geteuid?.()) {
358
+ if (process.platform === "win32")
359
+ return;
360
+ if ((metadata.mode & 0o077) !== 0) {
361
+ throw new OutputDirectoryError(`Codex Security stored authentication must not be accessible to other users: ${path}`);
362
+ }
363
+ if (effectiveUid !== undefined && metadata.uid !== effectiveUid) {
364
+ throw new OutputDirectoryError(`Codex Security stored authentication must be owned by the current user: ${path}`);
365
+ }
366
+ }
269
367
  export async function preserveCodexSecurityPluginRegistration(codexHome, config) {
270
368
  let existing;
271
369
  try {
@@ -390,6 +488,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
390
488
  throw new OutputDirectoryError(`Scan output directory is not empty: ${path}. To keep the existing results and start a new scan, add --archive-existing.`);
391
489
  }
392
490
  requirePrivateOutputDirectory(metadata, path);
491
+ await requireSecureOutputAncestry(path);
393
492
  const canonical = await realpath(path);
394
493
  requireModelSafeOutputDir(canonical);
395
494
  return canonical;
@@ -400,6 +499,7 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
400
499
  if ((await stat(parent)).isDirectory()) {
401
500
  const canonical = resolve(await realpath(parent), relative(parent, path));
402
501
  requireModelSafeOutputDir(canonical);
502
+ await requireSecureOutputAncestry(canonical);
403
503
  return canonical;
404
504
  }
405
505
  break;
@@ -507,6 +607,7 @@ export async function validatePreparedOutputDir(path, validateLocation) {
507
607
  throw new OutputDirectoryError(`Scan output directory must be empty: ${path}`);
508
608
  }
509
609
  requirePrivateOutputDirectory(metadata, path);
610
+ await requireSecureOutputAncestry(canonical);
510
611
  return canonical;
511
612
  }
512
613
  export function requirePrivateOutputDirectory(metadata, path, effectiveUid = process.geteuid?.()) {
@@ -519,6 +620,57 @@ export function requirePrivateOutputDirectory(metadata, path, effectiveUid = pro
519
620
  throw new OutputDirectoryError(`Scan output directory must be owned by the current user: ${path}`);
520
621
  }
521
622
  }
623
+ /** Reject shared parents whose owner can rename or replace private scan output. */
624
+ export async function requireSecureOutputAncestry(path, effectiveUid = process.geteuid?.()) {
625
+ if (process.platform === "win32")
626
+ return;
627
+ let current = dirname(resolve(path));
628
+ while (true) {
629
+ try {
630
+ current = await realpath(current);
631
+ break;
632
+ }
633
+ catch (error) {
634
+ if (nodeErrorCode(error) !== "ENOENT") {
635
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
636
+ }
637
+ const parent = dirname(current);
638
+ if (parent === current) {
639
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
640
+ }
641
+ current = parent;
642
+ }
643
+ }
644
+ while (true) {
645
+ let metadata;
646
+ try {
647
+ metadata = await lstat(current);
648
+ }
649
+ catch (error) {
650
+ throw new OutputDirectoryError(`Unable to inspect scan output parent directory: ${current}`, { cause: error });
651
+ }
652
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
653
+ throw new OutputDirectoryError(`Scan output parent must be a non-symlink directory: ${current}`);
654
+ }
655
+ requireTrustedOutputAncestor(metadata, current, effectiveUid);
656
+ const parent = dirname(current);
657
+ if (parent === current)
658
+ return;
659
+ current = parent;
660
+ }
661
+ }
662
+ export function requireTrustedOutputAncestor(metadata, path, effectiveUid = process.geteuid?.()) {
663
+ if (effectiveUid !== undefined &&
664
+ metadata.uid !== 0 &&
665
+ metadata.uid !== effectiveUid) {
666
+ throw new OutputDirectoryError(`Scan output parent must have a trusted owner: ${path}`);
667
+ }
668
+ if ((metadata.mode & 0o022) === 0)
669
+ return;
670
+ if ((metadata.mode & 0o1000) === 0) {
671
+ throw new OutputDirectoryError(`Scan output parent must not be group- or world-writable without the sticky bit: ${path}`);
672
+ }
673
+ }
522
674
  async function removeEmptyDirectories(path, root) {
523
675
  let current = path;
524
676
  while (true) {
@@ -562,6 +714,9 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
562
714
  return false;
563
715
  }
564
716
  await mkdir(isolatedHome, { recursive: true, mode: 0o700 });
717
+ if (process.platform !== "win32" && (process.umask() & 0o700) !== 0) {
718
+ await chmod(isolatedHome, 0o700);
719
+ }
565
720
  if (await codexSecurityHasStoredFileCredentials(isolatedHome))
566
721
  return true;
567
722
  const destination = join(isolatedHome, "auth.json");
@@ -570,7 +725,15 @@ export async function importAmbientAuth(ambientHome, isolatedHome) {
570
725
  await copyFile(source, temporary, constants.COPYFILE_EXCL);
571
726
  await chmod(temporary, 0o600);
572
727
  try {
573
- await copyFile(temporary, destination, constants.COPYFILE_EXCL);
728
+ try {
729
+ await link(temporary, destination);
730
+ }
731
+ catch (error) {
732
+ if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "EMLINK"].includes(nodeErrorCode(error) ?? "")) {
733
+ throw error;
734
+ }
735
+ await copyFile(temporary, destination, constants.COPYFILE_EXCL);
736
+ }
574
737
  }
575
738
  catch (error) {
576
739
  if (nodeErrorCode(error) === "EEXIST" &&
@@ -802,20 +965,21 @@ async function pluginProjectionFingerprint(root, signal) {
802
965
  else {
803
966
  paths = [];
804
967
  const pending = [canonical];
805
- let entries = 0;
968
+ let entries = 1;
806
969
  while (pending.length > 0) {
807
970
  throwIfSignalAborted(signal);
808
971
  const path = pending.pop();
809
972
  const metadata = await lstat(path);
810
- if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
811
- throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${path}`);
812
- }
813
973
  if (metadata.isSymbolicLink()) {
814
974
  throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${path}`);
815
975
  }
816
976
  if (metadata.isDirectory()) {
817
- for (const entry of await readdir(path)) {
818
- pending.push(join(path, entry));
977
+ for await (const entry of pluginDirectoryEntries(path, signal)) {
978
+ const child = join(path, entry);
979
+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
980
+ throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${child}`);
981
+ }
982
+ pending.push(child);
819
983
  }
820
984
  }
821
985
  else if (metadata.isFile()) {
@@ -1179,7 +1343,7 @@ async function copyPluginTree(source, destination, signal) {
1179
1343
  { source, destination },
1180
1344
  ];
1181
1345
  const directories = new Map();
1182
- let entries = 0;
1346
+ let entries = 1;
1183
1347
  let size = 0;
1184
1348
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1185
1349
  try {
@@ -1188,26 +1352,26 @@ async function copyPluginTree(source, destination, signal) {
1188
1352
  const current = pending.pop();
1189
1353
  await requirePluginAncestors(source, current.source, directories, signal);
1190
1354
  const metadata = await lstat(current.source);
1191
- if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
1192
- throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${current.source}`);
1193
- }
1194
1355
  if (metadata.isSymbolicLink()) {
1195
1356
  throw new PluginBootstrapError(`Plugin contains an unsafe source path: ${current.source}`);
1196
1357
  }
1197
1358
  if (metadata.isDirectory()) {
1198
- const children = await readdir(current.source);
1359
+ for await (const entry of pluginDirectoryEntries(current.source, signal)) {
1360
+ const childSource = join(current.source, entry);
1361
+ if (++entries > MAX_PLUGIN_COPY_ENTRIES) {
1362
+ throw new PluginBootstrapError(`Plugin source exceeds the copy entry limit: ${childSource}`);
1363
+ }
1364
+ pending.push({
1365
+ source: childSource,
1366
+ destination: join(current.destination, entry),
1367
+ });
1368
+ }
1199
1369
  const afterRead = await lstat(current.source);
1200
1370
  if (!samePluginFile(metadata, afterRead)) {
1201
1371
  throw new PluginBootstrapError(`Plugin directory changed while it was being copied: ${current.source}`);
1202
1372
  }
1203
1373
  directories.set(current.source, afterRead);
1204
1374
  await mkdir(current.destination, { mode: 0o700 });
1205
- for (const child of children) {
1206
- pending.push({
1207
- source: join(current.source, child),
1208
- destination: join(current.destination, child),
1209
- });
1210
- }
1211
1375
  continue;
1212
1376
  }
1213
1377
  if (!metadata.isFile()) {
@@ -1253,6 +1417,23 @@ async function copyPluginTree(source, destination, signal) {
1253
1417
  throw error;
1254
1418
  }
1255
1419
  }
1420
+ async function* pluginDirectoryEntries(path, signal) {
1421
+ throwIfSignalAborted(signal);
1422
+ const directory = await opendir(path);
1423
+ try {
1424
+ for (;;) {
1425
+ throwIfSignalAborted(signal);
1426
+ const entry = await directory.read();
1427
+ throwIfSignalAborted(signal);
1428
+ if (entry === null)
1429
+ return;
1430
+ yield entry.name;
1431
+ }
1432
+ }
1433
+ finally {
1434
+ await directory.close();
1435
+ }
1436
+ }
1256
1437
  async function requirePluginAncestors(root, path, directories, signal) {
1257
1438
  const relativePath = relative(root, path);
1258
1439
  if (relativePath === ".." ||