|
| 1 | +import { constants, type BigIntStats } from 'node:fs'; |
| 2 | +import { copyFile, link, lstat, open, realpath, unlink } from 'node:fs/promises'; |
| 3 | +import { randomBytes, randomUUID } from 'node:crypto'; |
| 4 | +import { execFile } from 'node:child_process'; |
| 5 | +import path from 'node:path'; |
| 6 | +import { promisify } from 'node:util'; |
| 7 | +import { Fault, sha } from '../core/util.js'; |
| 8 | +import { ownerControlsOrphanKey, restrictToOwner } from '../core/win-acl.js'; |
| 9 | + |
| 10 | +const code = (error: unknown) => (error as NodeJS.ErrnoException).code; |
| 11 | +const alreadyInitialized = () => |
| 12 | + Object.assign(new Error('config.json already exists; left unchanged.'), { code: 'EEXIST' }); |
| 13 | +const unsafeKey = () => |
| 14 | + new Fault( |
| 15 | + 'profile_key_conflict', |
| 16 | + 'Cannot safely resume initialization from admin.token. The original was not replaced. Use a new private profile or inspect the existing one.', |
| 17 | + 409, |
| 18 | + ); |
| 19 | +const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino; |
| 20 | +const info = (file: string) => lstat(file, { bigint: true }); |
| 21 | +const keyTemp = (dir: string, bytes: Buffer) => path.join(dir, `.oaa-init-key-${sha(bytes)}.tmp`); |
| 22 | + |
| 23 | +async function missing(file: string): Promise<boolean> { |
| 24 | + try { |
| 25 | + await lstat(file); |
| 26 | + return false; |
| 27 | + } catch (error) { |
| 28 | + if (code(error) === 'ENOENT') return true; |
| 29 | + throw error; |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +export async function requireNewConfig(file: string): Promise<void> { |
| 34 | + if (!(await missing(file))) throw alreadyInitialized(); |
| 35 | +} |
| 36 | + |
| 37 | +async function removeTemp(file: string): Promise<void> { |
| 38 | + try { |
| 39 | + await unlink(file); |
| 40 | + } catch (error) { |
| 41 | + if (code(error) !== 'ENOENT') throw error; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +/** Stage complete bytes and publish without replacing an operator's or another initializer's file. */ |
| 46 | +async function publishNew(temp: string, target: string, bytes: Buffer): Promise<boolean> { |
| 47 | + const out = await open(temp, 'wx', 0o600); |
| 48 | + try { |
| 49 | + try { |
| 50 | + if (process.platform === 'win32') await restrictToOwner(temp); |
| 51 | + await out.writeFile(bytes); |
| 52 | + await out.sync(); |
| 53 | + } finally { |
| 54 | + await out.close(); |
| 55 | + } |
| 56 | + try { |
| 57 | + try { |
| 58 | + await link(temp, target); |
| 59 | + } catch (error) { |
| 60 | + // Keep create-only behavior on volumes without hard links. A damaged copy is never adopted. |
| 61 | + if (!['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EPERM'].includes(code(error) ?? '')) throw error; |
| 62 | + await copyFile(temp, target, constants.COPYFILE_EXCL); |
| 63 | + if (process.platform === 'win32') await restrictToOwner(target); |
| 64 | + } |
| 65 | + return true; |
| 66 | + } catch (error) { |
| 67 | + if (code(error) === 'EEXIST') return false; |
| 68 | + throw error; |
| 69 | + } |
| 70 | + } finally { |
| 71 | + await removeTemp(temp); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +async function darwinOrphanAclIsPrivate(dir: string): Promise<boolean> { |
| 76 | + // An extended allow entry can grant access even on a mode-0600 file on macOS. |
| 77 | + try { |
| 78 | + const { stdout } = await promisify(execFile)('/bin/ls', ['-lde', '.', 'admin.token'], { |
| 79 | + cwd: dir, |
| 80 | + env: { LC_ALL: 'C', LANG: 'C' }, |
| 81 | + timeout: 3000, |
| 82 | + maxBuffer: 65536, |
| 83 | + }); |
| 84 | + return stdout |
| 85 | + .split('\n') |
| 86 | + .filter((line) => /^\s*\d+:/.test(line)) |
| 87 | + .every((line) => /\bdeny\b/.test(line) && !/\ballow\b/.test(line)); |
| 88 | + } catch { |
| 89 | + return false; |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +async function verifyOrphan(dir: string, file: string): Promise<void> { |
| 94 | + const uid = process.getuid?.(); |
| 95 | + const parent = await info(dir); |
| 96 | + const before = await info(file); |
| 97 | + const privateFile = (s: BigIntStats) => |
| 98 | + s.isFile() && |
| 99 | + s.size === 43n && |
| 100 | + (uid === undefined || (s.uid === BigInt(uid) && (s.mode & 0o077n) === 0n)); |
| 101 | + if ( |
| 102 | + !privateFile(before) || |
| 103 | + (uid !== undefined && (parent.uid !== BigInt(uid) || (parent.mode & 0o022n) !== 0n)) |
| 104 | + ) |
| 105 | + throw unsafeKey(); |
| 106 | + if (process.platform === 'win32' && !(await ownerControlsOrphanKey(file, dir))) throw unsafeKey(); |
| 107 | + if (process.platform === 'darwin' && !(await darwinOrphanAclIsPrivate(dir))) throw unsafeKey(); |
| 108 | + const handle = await open( |
| 109 | + file, |
| 110 | + constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0), |
| 111 | + ); |
| 112 | + try { |
| 113 | + const opened = await handle.stat({ bigint: true }); |
| 114 | + if (!same(before, opened) || !privateFile(opened) || opened.nlink > 2n) throw unsafeKey(); |
| 115 | + const bytes = Buffer.alloc(44); |
| 116 | + const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0); |
| 117 | + const key = bytes.subarray(0, bytesRead); |
| 118 | + const encoded = key.toString('latin1'); |
| 119 | + if (bytesRead !== 43 || Buffer.from(encoded, 'base64url').toString('base64url') !== encoded) |
| 120 | + throw unsafeKey(); |
| 121 | + if (opened.nlink === 2n) { |
| 122 | + // A process may die between linking its completed key and dropping this exact staging name. |
| 123 | + const temp = keyTemp(dir, key); |
| 124 | + try { |
| 125 | + if (!same(opened, await info(temp))) throw unsafeKey(); |
| 126 | + await removeTemp(temp); |
| 127 | + } catch (error) { |
| 128 | + if (code(error) !== 'ENOENT') throw error; |
| 129 | + } |
| 130 | + } |
| 131 | + const final = await info(file); |
| 132 | + if ( |
| 133 | + !same(opened, final) || |
| 134 | + opened.mtimeNs !== final.mtimeNs || |
| 135 | + !privateFile(final) || |
| 136 | + final.nlink !== 1n |
| 137 | + ) |
| 138 | + throw unsafeKey(); |
| 139 | + } finally { |
| 140 | + await handle.close(); |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +export async function publishInitialFiles(root: string, config: string): Promise<void> { |
| 145 | + const dir = await realpath(root); |
| 146 | + const file = path.join(dir, 'config.json'), |
| 147 | + key = path.join(dir, 'admin.token'); |
| 148 | + await requireNewConfig(file); |
| 149 | + let created = false; |
| 150 | + if (await missing(key)) { |
| 151 | + const bytes = Buffer.from(randomBytes(32).toString('base64url')); |
| 152 | + created = await publishNew(keyTemp(dir, bytes), key, bytes); |
| 153 | + } |
| 154 | + if (!created) await verifyOrphan(dir, key); |
| 155 | + if ( |
| 156 | + !(await publishNew( |
| 157 | + path.join(dir, `.oaa-init-config-${randomUUID()}.tmp`), |
| 158 | + file, |
| 159 | + Buffer.from(config), |
| 160 | + )) |
| 161 | + ) |
| 162 | + throw alreadyInitialized(); |
| 163 | +} |
0 commit comments