feat(storage): add managed storage controls
Enforce a global log quota with configurable retention and observable degradation. Add authenticated storage reporting and safe cleanup controls to the settings UI. Protect active stream transfers and isolate parallel test resources.
This commit is contained in:
33 files changed
+5115
-136
No files matched your search
@@ -0,0 +1,26 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterAll } from 'vitest';
|
||||
|
||||
const originalTempEnv = {
|
||||
TMPDIR: process.env.TMPDIR,
|
||||
TMP: process.env.TMP,
|
||||
TEMP: process.env.TEMP,
|
||||
};
|
||||
const testTempDir = fs.mkdtempSync(path.join(
|
||||
os.tmpdir(),
|
||||
`snowluma-onebot-vitest-${process.pid}-${process.env.VITEST_POOL_ID ?? '0'}-`,
|
||||
));
|
||||
|
||||
process.env.TMPDIR = testTempDir;
|
||||
process.env.TMP = testTempDir;
|
||||
process.env.TEMP = testTempDir;
|
||||
|
||||
afterAll(() => {
|
||||
for (const [name, value] of Object.entries(originalTempEnv)) {
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
fs.rmSync(testTempDir, { recursive: true, force: true });
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import path from 'path';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import { __test } from '../src/actions/stream-download';
|
||||
import { STREAM_DOWNLOAD_DIR, __test as fileTest } from '../src/actions/stream-file';
|
||||
import { clearInactiveStreamStorage } from '../src/stream-storage';
|
||||
import type { StreamSink } from '../src/streaming';
|
||||
|
||||
const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record<string, any>);
|
||||
|
||||
@@ -74,6 +76,49 @@ describe('download_file_stream (local, fenced)', () => {
|
||||
await h.processStreamRequest(JSON.stringify({ action: 'download_file_stream', params: { file: '/etc/passwd' } }), (j) => frames.push(j));
|
||||
expect(parse(frames).at(-1)).toMatchObject({ status: 'failed', data: { type: 'error' } });
|
||||
});
|
||||
|
||||
it('protects a local stream file from cleanup while it is being downloaded', async () => {
|
||||
fs.mkdirSync(STREAM_DOWNLOAD_DIR, { recursive: true });
|
||||
const fp = path.join(STREAM_DOWNLOAD_DIR, 'active.bin');
|
||||
fs.writeFileSync(fp, 'active download');
|
||||
|
||||
let unblock!: () => void;
|
||||
let reachedFirstFrame!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => { unblock = resolve; });
|
||||
const firstFrame = new Promise<void>((resolve) => { reachedFirstFrame = resolve; });
|
||||
let sent = false;
|
||||
const sink: StreamSink = {
|
||||
send: async () => {
|
||||
if (sent) return;
|
||||
sent = true;
|
||||
reachedFirstFrame();
|
||||
await blocked;
|
||||
},
|
||||
};
|
||||
|
||||
const running = __test.runDownload(
|
||||
fp,
|
||||
65536,
|
||||
{} as ApiActionContext,
|
||||
sink,
|
||||
'auto',
|
||||
);
|
||||
await firstFrame;
|
||||
|
||||
try {
|
||||
const duringDownload = clearInactiveStreamStorage();
|
||||
expect(duringDownload.skippedActiveItems).toBeGreaterThanOrEqual(1);
|
||||
expect(duringDownload.failures).toEqual([]);
|
||||
expect(fs.existsSync(fp)).toBe(true);
|
||||
} finally {
|
||||
unblock();
|
||||
await running;
|
||||
}
|
||||
const afterDownload = clearInactiveStreamStorage();
|
||||
expect(afterDownload.deletedFiles).toBeGreaterThanOrEqual(1);
|
||||
expect(afterDownload.failures).toEqual([]);
|
||||
expect(fs.existsSync(fp)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SSRF guard', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createHash } from 'crypto';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
import { __test, STREAM_UPLOAD_DIR } from '../src/actions/stream-file';
|
||||
|
||||
const { handleUpload, cleanDir, uploads } = __test;
|
||||
const { handleUpload, cleanupUpload, cleanDir, uploads } = __test;
|
||||
type UP = Parameters<typeof handleUpload>[0];
|
||||
|
||||
const b64 = (s: string | Buffer): string => Buffer.from(s).toString('base64');
|
||||
@@ -23,8 +23,8 @@ function mk(p: Partial<UP> & { stream_id: string }): UP {
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of [...uploads.keys()]) cleanupUpload(key, true);
|
||||
cleanDir(STREAM_UPLOAD_DIR);
|
||||
uploads.clear();
|
||||
});
|
||||
|
||||
describe('upload_file_stream', () => {
|
||||
@@ -181,4 +181,27 @@ describe('clean_stream_temp_file', () => {
|
||||
expect(fs.existsSync(outside)).toBe(true);
|
||||
fs.rmSync(outside, { force: true });
|
||||
});
|
||||
|
||||
it('preserves active uploads while removing inactive stream files', async () => {
|
||||
const id = 'active-clean';
|
||||
await handleUpload(mk({
|
||||
stream_id: id,
|
||||
total_chunks: 2,
|
||||
chunk_index: 0,
|
||||
chunk_data: b64('first'),
|
||||
}));
|
||||
const state = uploads.get(id)!;
|
||||
const activeChunk = path.join(state.tempDir, '0.chunk');
|
||||
const stale = path.join(STREAM_UPLOAD_DIR, 'stale.bin');
|
||||
fs.writeFileSync(stale, 'stale');
|
||||
|
||||
const h = new ApiHandler({} as ApiActionContext);
|
||||
const result = await h.handle('clean_stream_temp_file', {});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
expect(result.data).toMatchObject({ skipped_active: 1 });
|
||||
expect(uploads.has(id)).toBe(true);
|
||||
expect(fs.existsSync(activeChunk)).toBe(true);
|
||||
expect(fs.existsSync(stale)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StreamStorage } from '../src/stream-storage';
|
||||
|
||||
let container: string;
|
||||
let root: string;
|
||||
let storage: StreamStorage;
|
||||
|
||||
function writeSized(filePath: string, bytes: number): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, Buffer.alloc(bytes));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-stream-storage-'));
|
||||
root = path.join(container, 'managed');
|
||||
storage = new StreamStorage(root);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(container, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('StreamStorage', () => {
|
||||
it('summarizes only the managed stream root', () => {
|
||||
writeSized(path.join(storage.uploadDir, 'upload.bin'), 10);
|
||||
writeSized(path.join(storage.downloadDir, 'download.bin'), 20);
|
||||
writeSized(path.join(root, '..', `${path.basename(root)}-outside.bin`), 99);
|
||||
|
||||
expect(storage.snapshot()).toEqual({
|
||||
totalBytes: 30,
|
||||
fileCount: 2,
|
||||
activeItemCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('clears inactive files while preserving every path of an active transfer', () => {
|
||||
const activeDir = path.join(storage.uploadDir, 'active');
|
||||
const activeChunk = path.join(activeDir, '0.chunk');
|
||||
const activeFinal = path.join(storage.uploadDir, 'active__file.bin');
|
||||
const staleUpload = path.join(storage.uploadDir, 'stale.bin');
|
||||
const staleDownload = path.join(storage.downloadDir, 'stale.bin');
|
||||
writeSized(activeChunk, 3);
|
||||
writeSized(activeFinal, 5);
|
||||
writeSized(staleUpload, 7);
|
||||
writeSized(staleDownload, 11);
|
||||
const release = storage.registerActiveItem([activeDir, activeFinal]);
|
||||
|
||||
expect(storage.clearInactive()).toEqual({
|
||||
deletedFiles: 2,
|
||||
freedBytes: 18,
|
||||
skippedActiveItems: 1,
|
||||
failures: [],
|
||||
});
|
||||
expect(fs.existsSync(activeChunk)).toBe(true);
|
||||
expect(fs.existsSync(activeFinal)).toBe(true);
|
||||
expect(fs.existsSync(staleUpload)).toBe(false);
|
||||
expect(fs.existsSync(staleDownload)).toBe(false);
|
||||
|
||||
release();
|
||||
expect(storage.clearInactive()).toMatchObject({
|
||||
deletedFiles: 2,
|
||||
freedBytes: 8,
|
||||
skippedActiveItems: 0,
|
||||
failures: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects active paths outside its managed root', () => {
|
||||
expect(() => storage.registerActiveItem([path.join(root, '..', 'outside')]))
|
||||
.toThrow(/outside/i);
|
||||
});
|
||||
|
||||
it('does not hide canonicalization failures while establishing its root', () => {
|
||||
vi.spyOn(fs, 'realpathSync').mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('canonicalization denied'), { code: 'EACCES' });
|
||||
});
|
||||
|
||||
expect(() => new StreamStorage(path.join(container, 'another-managed')))
|
||||
.toThrow(/canonicalization denied/);
|
||||
});
|
||||
|
||||
it('does not treat root inspection failures as a missing ancestor', () => {
|
||||
const candidate = path.join(container, 'inspection-denied');
|
||||
const originalLstat = fs.lstatSync.bind(fs);
|
||||
vi.spyOn(fs, 'lstatSync').mockImplementation((filePath) => {
|
||||
if (String(filePath) === candidate) {
|
||||
throw Object.assign(new Error('root inspection denied'), { code: 'EACCES' });
|
||||
}
|
||||
return originalLstat(filePath);
|
||||
});
|
||||
|
||||
expect(() => new StreamStorage(candidate))
|
||||
.toThrow(/root inspection denied/);
|
||||
});
|
||||
|
||||
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');
|
||||
writeSized(externalFile, 12);
|
||||
fs.mkdirSync(storage.uploadDir, { recursive: true });
|
||||
fs.symlinkSync(externalDir, path.join(storage.uploadDir, 'linked'));
|
||||
|
||||
const result = storage.clearInactive();
|
||||
|
||||
expect(result.deletedFiles).toBe(1);
|
||||
expect(result.failures).toEqual([]);
|
||||
expect(fs.existsSync(externalFile)).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user