fix(onebot): protect managed stream storage

Validate managed storage before stream files are created, read, or cleaned, and reject unsafe local directory state without changing the public stream actions.

Keep ordinary existing installations compatible and add regression coverage for startup, runtime replacement, ownership, permissions, and normal transfer behavior.
This commit is contained in:
DrSmoothl committed 2026-08-01 17:23:17 +08:00
1 parent 3c772df818
commit ae2e894f14
4 files changed
+127 -22

No files matched your search

@@ -26,7 +26,11 @@ import { defineStreamAction, f } from '../action-kit';
import type { ApiActionContext } from '../api-handler'; import type { ApiActionContext } from '../api-handler';
import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types'; import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types';
import { type StreamSink, StreamStatus } from '../streaming'; 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 DEFAULT_CHUNK_BYTES = 64 * 1024;
const MAX_CHUNK_REQUEST_BYTES = 16 * 1024 * 1024; // cap the client-requested chunk size 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; let st: fs.Stats | null = null;
try { st = fs.statSync(local); } catch { st = null; } try { st = fs.statSync(local); } catch { st = null; }
if (st?.isFile()) { if (st?.isFile()) {
ensureStreamDirectory(STREAM_ROOT);
// Fence against the *real* path so a symlink inside the root can't point // Fence against the *real* path so a symlink inside the root can't point
// out (lexical resolve alone would follow it). // out (lexical resolve alone would follow it).
let real = local; let real = local;
+2 -1
View File
@@ -30,6 +30,7 @@ import {
STREAM_ROOT, STREAM_ROOT,
STREAM_UPLOAD_DIR, STREAM_UPLOAD_DIR,
clearInactiveStreamStorage, clearInactiveStreamStorage,
ensureStreamDirectory,
registerActiveStreamItem, registerActiveStreamItem,
} from '../stream-storage'; } from '../stream-storage';
@@ -149,7 +150,7 @@ function createUpload(p: UploadParams, account: string): UploadState {
const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`); const finalPath = path.join(dirRoot, `${p.stream_id}__${filename}`);
assertWithin(STREAM_UPLOAD_DIR, tempDir); assertWithin(STREAM_UPLOAD_DIR, tempDir);
assertWithin(STREAM_UPLOAD_DIR, finalPath); assertWithin(STREAM_UPLOAD_DIR, finalPath);
fs.mkdirSync(tempDir, { recursive: true }); ensureStreamDirectory(tempDir);
const key = account ? `${account}:${p.stream_id}` : p.stream_id; const key = account ? `${account}:${p.stream_id}` : p.stream_id;
const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]); const releaseStorageActivity = registerActiveStreamItem([tempDir, finalPath]);
+77 -20
View File
@@ -24,11 +24,32 @@ export class StreamStorage {
private nextActiveItemId = 1; private nextActiveItemId = 1;
constructor(root: string) { constructor(root: string) {
this.root = resolveWithExistingAncestor(root); this.root = resolveManagedRoot(root);
this.uploadDir = path.join(this.root, 'upload'); this.uploadDir = path.join(this.root, 'upload');
this.downloadDir = path.join(this.root, 'download'); 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 { registerActiveItem(paths: string[]): () => void {
const normalized = paths.map((item) => { const normalized = paths.map((item) => {
const resolved = path.resolve(item); const resolved = path.resolve(item);
@@ -91,9 +112,7 @@ export class StreamStorage {
private assertRootDirectoryOrMissing(): boolean { private assertRootDirectoryOrMissing(): boolean {
try { try {
const stat = fs.lstatSync(this.root); const stat = fs.lstatSync(this.root);
if (!stat.isDirectory()) { assertManagedDirectory(this.root, stat);
throw new Error(`managed stream root is not a directory: ${this.root}`);
}
return true; return true;
} catch (error) { } catch (error) {
if (isMissing(error)) return false; if (isMissing(error)) return false;
@@ -201,23 +220,57 @@ function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error); return error instanceof Error ? error.message : String(error);
} }
function resolveWithExistingAncestor(input: string): string { function assertManagedDirectory(directory: string, stat: fs.Stats): void {
let existing = path.resolve(input); if (stat.isSymbolicLink()) {
const suffix: string[] = []; throw new Error(`managed stream directory must not be a symbolic link: ${directory}`);
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;
}
} }
const canonical = fs.realpathSync(existing); if (!stat.isDirectory()) {
return path.join(canonical, ...suffix); 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')); 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); return streamStorage.registerActiveItem(paths);
} }
export function ensureStreamDirectory(directory: string): void {
streamStorage.ensureDirectory(directory);
}
export function snapshotStreamStorage(): StreamStorageSnapshot { export function snapshotStreamStorage(): StreamStorageSnapshot {
return streamStorage.snapshot(); return streamStorage.snapshot();
} }
@@ -97,6 +97,48 @@ describe('StreamStorage', () => {
.toThrow(/root inspection denied/); .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', () => { it('removes a symlink without following it outside the managed root', () => {
const externalDir = path.join(root, '..', `${path.basename(root)}-external`); const externalDir = path.join(root, '..', `${path.basename(root)}-external`);
const externalFile = path.join(externalDir, 'keep.bin'); const externalFile = path.join(externalDir, 'keep.bin');