diff --git a/packages/onebot/src/actions/stream-download.ts b/packages/onebot/src/actions/stream-download.ts index 5e45dd94..02216779 100644 --- a/packages/onebot/src/actions/stream-download.ts +++ b/packages/onebot/src/actions/stream-download.ts @@ -26,7 +26,11 @@ import { defineStreamAction, f } from '../action-kit'; import type { ApiActionContext } from '../api-handler'; import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types'; import { type StreamSink, StreamStatus } from '../streaming'; -import { STREAM_ROOT, registerActiveStreamItem } from '../stream-storage'; +import { + STREAM_ROOT, + ensureStreamDirectory, + registerActiveStreamItem, +} from '../stream-storage'; const DEFAULT_CHUNK_BYTES = 64 * 1024; const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size @@ -224,6 +228,7 @@ async function resolveDownload( let st: fs.Stats | null = null; try { st = fs.statSync(local); } catch { st = null; } if (st?.isFile()) { + ensureStreamDirectory(STREAM_ROOT); // Fence against the *real* path so a symlink inside the root can't point // out (lexical resolve alone would follow it). let real = local; diff --git a/packages/onebot/src/actions/stream-file.ts b/packages/onebot/src/actions/stream-file.ts index 36d12593..bff3487d 100644 --- a/packages/onebot/src/actions/stream-file.ts +++ b/packages/onebot/src/actions/stream-file.ts @@ -30,6 +30,7 @@ import { STREAM_ROOT, STREAM_UPLOAD_DIR, clearInactiveStreamStorage, + ensureStreamDirectory, registerActiveStreamItem, } from '../stream-storage'; @@ -149,7 +150,7 @@ function createUpload(p: UploadParams, account: string): UploadState { const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`); assertWithin(STREAM_UPLOAD_DIR, tempDir); assertWithin(STREAM_UPLOAD_DIR, finalPath); - fs.mkdirSync(tempDir, { recursive: true }); + ensureStreamDirectory(tempDir); const key = account ? `${account}:${p.stream_id}` : p.stream_id; const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]); diff --git a/packages/onebot/src/stream-storage.ts b/packages/onebot/src/stream-storage.ts index bf4ed37d..4dfd96ad 100644 --- a/packages/onebot/src/stream-storage.ts +++ b/packages/onebot/src/stream-storage.ts @@ -24,11 +24,32 @@ export class StreamStorage { private nextActiveItemId = 1; constructor(root: string) { - this.root = resolveWithExistingAncestor(root); + this.root = resolveManagedRoot(root); this.uploadDir = path.join(this.root, 'upload'); this.downloadDir = path.join(this.root, 'download'); } + /** + * Create a directory inside the managed root without following a substituted + * directory link. Existing directories remain usable when they belong to the + * current account and cannot be modified by other local accounts. + */ + ensureDirectory(directory: string): void { + const resolved = path.resolve(directory); + if (resolved !== this.root && !isStrictDescendant(this.root, resolved)) { + throw new Error(`stream directory is outside the managed root: ${directory}`); + } + + let current = this.root; + ensureManagedDirectory(current); + const relative = path.relative(this.root, resolved); + if (!relative) return; + for (const segment of relative.split(path.sep)) { + current = path.join(current, segment); + ensureManagedDirectory(current); + } + } + registerActiveItem(paths: string[]): () => void { const normalized = paths.map((item) => { const resolved = path.resolve(item); @@ -91,9 +112,7 @@ export class StreamStorage { private assertRootDirectoryOrMissing(): boolean { try { const stat = fs.lstatSync(this.root); - if (!stat.isDirectory()) { - throw new Error(`managed stream root is not a directory: ${this.root}`); - } + assertManagedDirectory(this.root, stat); return true; } catch (error) { if (isMissing(error)) return false; @@ -201,23 +220,57 @@ function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } -function resolveWithExistingAncestor(input: string): string { - let existing = path.resolve(input); - const suffix: string[] = []; - while (true) { - try { - fs.lstatSync(existing); - break; - } catch (error) { - if (!isMissing(error)) throw error; - const parent = path.dirname(existing); - if (parent === existing) throw error; - suffix.unshift(path.basename(existing)); - existing = parent; - } +function assertManagedDirectory(directory: string, stat: fs.Stats): void { + if (stat.isSymbolicLink()) { + throw new Error(`managed stream directory must not be a symbolic link: ${directory}`); } - const canonical = fs.realpathSync(existing); - return path.join(canonical, ...suffix); + if (!stat.isDirectory()) { + throw new Error(`managed stream path is not a directory: ${directory}`); + } + + const currentUid = typeof process.getuid === 'function' ? process.getuid() : undefined; + if (currentUid !== undefined && stat.uid !== currentUid) { + throw new Error(`managed stream directory is owned by another account: ${directory}`); + } + if (process.platform !== 'win32' && (stat.mode & 0o022) !== 0) { + throw new Error(`managed stream directory is writable by other accounts: ${directory}`); + } +} + +function ensureManagedDirectory(directory: string): void { + let stat: fs.Stats; + try { + stat = fs.lstatSync(directory); + } catch (error) { + if (!isMissing(error)) throw error; + try { + fs.mkdirSync(directory, { mode: 0o700 }); + } catch (mkdirError) { + if (!(mkdirError instanceof Error && 'code' in mkdirError && mkdirError.code === 'EEXIST')) { + throw mkdirError; + } + } + stat = fs.lstatSync(directory); + } + assertManagedDirectory(directory, stat); +} + +function resolveManagedRoot(input: string): string { + const absolute = path.resolve(input); + try { + const stat = fs.lstatSync(absolute); + assertManagedDirectory(absolute, stat); + return fs.realpathSync(absolute); + } catch (error) { + if (!isMissing(error)) throw error; + } + + const parent = path.dirname(absolute); + const parentStat = fs.statSync(parent); + if (!parentStat.isDirectory()) { + throw new Error(`managed stream parent is not a directory: ${parent}`); + } + return path.join(fs.realpathSync(parent), path.basename(absolute)); } export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream')); @@ -229,6 +282,10 @@ export function registerActiveStreamItem(paths: string[]): () => void { return streamStorage.registerActiveItem(paths); } +export function ensureStreamDirectory(directory: string): void { + streamStorage.ensureDirectory(directory); +} + export function snapshotStreamStorage(): StreamStorageSnapshot { return streamStorage.snapshot(); } diff --git a/packages/onebot/tests/stream-storage.test.ts b/packages/onebot/tests/stream-storage.test.ts index d2983a51..06c12f6b 100644 --- a/packages/onebot/tests/stream-storage.test.ts +++ b/packages/onebot/tests/stream-storage.test.ts @@ -97,6 +97,48 @@ describe('StreamStorage', () => { .toThrow(/root inspection denied/); }); + it('rejects a managed root that is already a symbolic link', () => { + const externalDir = path.join(container, 'external'); + const externalFile = path.join(externalDir, 'keep.bin'); + writeSized(externalFile, 12); + fs.symlinkSync(externalDir, root); + + expect(() => new StreamStorage(root)).toThrow(/symbolic link/i); + expect(fs.readFileSync(externalFile)).toHaveLength(12); + }); + + it('rejects a symbolic-link replacement before creating managed children', () => { + const externalDir = path.join(container, 'late-external'); + fs.mkdirSync(externalDir); + fs.symlinkSync(externalDir, root); + + expect(() => storage.ensureDirectory(storage.uploadDir)).toThrow(/symbolic link/i); + expect(fs.readdirSync(externalDir)).toEqual([]); + }); + + it.runIf(typeof process.getuid === 'function')('rejects a root owned by another account', () => { + fs.mkdirSync(root); + const uid = process.getuid!(); + vi.spyOn(process, 'getuid').mockReturnValue(uid + 1); + + expect(() => new StreamStorage(root)).toThrow(/owned by another account/i); + }); + + it.runIf(process.platform !== 'win32')('rejects a root writable by other accounts', () => { + fs.mkdirSync(root, { mode: 0o777 }); + fs.chmodSync(root, 0o777); + + expect(() => new StreamStorage(root)).toThrow(/writable by other accounts/i); + }); + + it('keeps ordinary existing directories usable', () => { + fs.mkdirSync(root, { mode: 0o755 }); + + const existing = new StreamStorage(root); + expect(() => existing.ensureDirectory(existing.uploadDir)).not.toThrow(); + expect(fs.lstatSync(existing.uploadDir).isDirectory()).toBe(true); + }); + it('removes a symlink without following it outside the managed root', () => { const externalDir = path.join(root, '..', `${path.basename(root)}-external`); const externalFile = path.join(externalDir, 'keep.bin');