Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | /** * Tests for RestFs component — path traversal, CRUD, and edge cases via Fastify injection. */ import assert from 'node:assert'; import {mkdir, readFile, rm, symlink, writeFile} from 'node:fs/promises'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; import {after, before, describe, it} from 'node:test'; import fastify, {type FastifyInstance} from 'fastify'; import RestFs from './RestFs.ts'; /** * Helper: create an isolated RestFs + Fastify instance for testing. * Returns { server, baseDir, cleanup }. */ async function setup(options?: {shell?: boolean}): Promise<{ server: FastifyInstance; baseDir: string; cleanup: () => Promise<void>; }> { const baseDir = join( tmpdir(), `restfs-test-${Date.now()}-${Math.random().toString(36).slice(2)}`, ); await mkdir(baseDir, {recursive: true}); // RestFs expects a gateway with registerPlugin — we accumulate the plugin and register it ourselves let capturedPlugin: Parameters<FastifyInstance['register']>[0] | null = null; let capturedOptions: Parameters<FastifyInstance['register']>[1] | null = null; const fakeGateway = { registerPlugin(plugin: typeof capturedPlugin, opts: typeof capturedOptions) { capturedPlugin = plugin; capturedOptions = opts; }, }; const restFs = new RestFs( { enabled: true, baseDir, routePrefix: '/api/fs', maxFileSize: 52428800, auth: false, shell: options?.shell ?? false, }, {gateway: fakeGateway}, ); await restFs.init(); const server = fastify(); // Stub auth config so routes don't require it server.addHook('preValidation', (_req, _reply, done) => done()); if (capturedPlugin) await server.register(capturedPlugin, capturedOptions!); await server.ready(); return { server, baseDir, cleanup: async () => { await server.close(); await rm(baseDir, {recursive: true, force: true}); }, }; } describe('RestFs', () => { let server: FastifyInstance; let baseDir: string; let cleanup: () => Promise<void>; before(async () => { ({server, baseDir, cleanup} = await setup()); }); after(async () => { await cleanup(); }); // ---- CRUD ---- describe('CRUD operations', () => { it('GET /stat/* — returns 404 for non-existent path', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/stat/does-not-exist'}); assert.strictEqual(res.statusCode, 404); }); it('POST /mkdir/* — creates a directory', async () => { const res = await server.inject({method: 'POST', url: '/api/fs/mkdir/test-dir'}); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(res.json(), {success: true}); }); it('GET /stat/* — returns metadata for existing directory', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/stat/test-dir'}); assert.strictEqual(res.statusCode, 200); const body = res.json(); assert.strictEqual(body.type, 'directory'); assert.ok(typeof body.mtime === 'number'); }); it('POST /write/* — writes a file', async () => { const content = Buffer.from('hello world'); const res = await server.inject({ method: 'POST', url: '/api/fs/write/test-dir/file.txt', headers: {'content-type': 'application/octet-stream'}, payload: content, }); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(res.json(), {success: true}); // Verify the file on disk const written = await readFile(join(baseDir, 'test-dir', 'file.txt')); assert.deepStrictEqual(written, content); }); it('POST /write/* — returns 415 for non-binary body', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/write/test-dir/bad.txt', headers: {'content-type': 'application/json'}, payload: JSON.stringify({text: 'oops'}), }); assert.strictEqual(res.statusCode, 415); assert.ok(res.json().error.includes('octet-stream')); }); it('GET /read/* — reads file contents back', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/read/test-dir/file.txt'}); assert.strictEqual(res.statusCode, 200); assert.strictEqual(res.body, 'hello world'); }); it('GET /read/* — returns 404 for non-existent file', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/read/nope.txt'}); assert.strictEqual(res.statusCode, 404); }); it('GET /readdir/* — lists directory entries', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/readdir/test-dir'}); assert.strictEqual(res.statusCode, 200); const entries = res.json(); assert.ok(Array.isArray(entries)); assert.ok(entries.some((e: {name: string}) => e.name === 'file.txt')); }); it('POST /rename — renames a file', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/rename', payload: {oldPath: 'test-dir/file.txt', newPath: 'test-dir/renamed.txt'}, }); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(res.json(), {success: true}); }); it('POST /copy — copies a file', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/copy', payload: {source: 'test-dir/renamed.txt', destination: 'test-dir/copied.txt'}, }); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(res.json(), {success: true}); const content = await readFile(join(baseDir, 'test-dir', 'copied.txt'), 'utf-8'); assert.strictEqual(content, 'hello world'); }); it('DELETE /delete/* — deletes a file', async () => { const res = await server.inject({ method: 'DELETE', url: '/api/fs/delete/test-dir/copied.txt', }); assert.strictEqual(res.statusCode, 200); assert.deepStrictEqual(res.json(), {success: true}); }); it('DELETE /delete/* — returns 404 for non-existent path', async () => { const res = await server.inject({method: 'DELETE', url: '/api/fs/delete/nope.txt'}); assert.strictEqual(res.statusCode, 404); }); it('DELETE /delete/* — deletes directory recursively', async () => { const res = await server.inject({ method: 'DELETE', url: '/api/fs/delete/test-dir?recursive=true', }); assert.strictEqual(res.statusCode, 200); }); }); // ---- Path traversal ---- describe('Path traversal protection', () => { // Note: URL-level .. traversal is normalized by Fastify before routing, // resulting in 404 (route not matched). This is valid HTTP-level protection. // The handler-level resolveSafePath protection is tested via body-based // endpoints (rename, copy) below, which bypass URL normalization. it('rejects .. traversal in URL (Fastify normalizes → 404)', async () => { const res = await server.inject({ method: 'GET', url: '/api/fs/stat/../../../etc/passwd', }); assert.strictEqual(res.statusCode, 404); }); it('rejects .. traversal in readdir URL (Fastify normalizes → 404)', async () => { const res = await server.inject({method: 'GET', url: '/api/fs/readdir/../../'}); assert.strictEqual(res.statusCode, 404); }); it('rejects .. traversal in write URL (Fastify normalizes → 404)', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/write/../escape.txt', headers: {'content-type': 'application/octet-stream'}, payload: Buffer.from('pwned'), }); assert.strictEqual(res.statusCode, 404); }); it('rejects .. traversal in rename (oldPath) — handler-level', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/rename', payload: {oldPath: '../../etc/passwd', newPath: 'safe.txt'}, }); assert.strictEqual(res.statusCode, 403); }); it('rejects .. traversal in rename (newPath) — handler-level', async () => { await writeFile(join(baseDir, 'a.txt'), 'test'); const res = await server.inject({ method: 'POST', url: '/api/fs/rename', payload: {oldPath: 'a.txt', newPath: '../../escape.txt'}, }); assert.strictEqual(res.statusCode, 403); }); it('rejects .. traversal in copy (destination) — handler-level', async () => { await writeFile(join(baseDir, 'b.txt'), 'test'); const res = await server.inject({ method: 'POST', url: '/api/fs/copy', payload: {source: 'b.txt', destination: '../../escape.txt'}, }); assert.strictEqual(res.statusCode, 403); }); }); // ---- Symlink escape ---- describe('Symlink escape protection', () => { it('rejects symlink pointing outside baseDir', async () => { const linkPath = join(baseDir, 'evil-link'); try { await symlink('/tmp', linkPath); } catch { // symlink creation may fail on some CI — skip return; } const res = await server.inject({method: 'GET', url: '/api/fs/stat/evil-link'}); assert.strictEqual(res.statusCode, 403); }); it('rejects write through symlinked parent directory', async () => { const linkPath = join(baseDir, 'escape-dir'); try { await symlink('/tmp', linkPath); } catch { return; } const res = await server.inject({ method: 'POST', url: '/api/fs/write/escape-dir/file.txt', headers: {'content-type': 'application/octet-stream'}, payload: Buffer.from('pwned'), }); assert.strictEqual(res.statusCode, 403); }); }); }); describe('RestFs disabled', () => { it('does not register plugin when enabled is false', async () => { let registered = false; const fakeGateway = { registerPlugin() { registered = true; }, }; const restFs = new RestFs( { enabled: false, baseDir: '/tmp', routePrefix: '/api/fs', maxFileSize: 1024, auth: false, shell: false, }, {gateway: fakeGateway}, ); await restFs.init(); assert.strictEqual(registered, false, 'Plugin should not be registered when disabled'); }); it('does not register plugin when gateway is missing', async () => { const restFs = new RestFs( { enabled: true, baseDir: '/tmp', routePrefix: '/api/fs', maxFileSize: 1024, auth: false, shell: false, }, {}, ); // Should not throw await restFs.init(); }); }); describe('RestFs shell endpoint', () => { let server: FastifyInstance; let _baseDir: string; let cleanup: () => Promise<void>; before(async () => { ({server, baseDir: _baseDir, cleanup} = await setup({shell: true})); }); after(async () => { await cleanup(); }); it('POST /shell — executes a command and streams output', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/shell', payload: {command: 'echo hello'}, }); // Shell uses raw streaming; inject returns the raw response assert.strictEqual(res.statusCode, 200); assert.ok(res.body.includes('hello')); }); it('POST /shell — returns 400 when command is missing', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/shell', payload: {command: ''}, }); assert.strictEqual(res.statusCode, 400); }); it('POST /shell — validates cwd within baseDir', async () => { const res = await server.inject({ method: 'POST', url: '/api/fs/shell', payload: {command: 'pwd', cwd: '../../'}, }); assert.strictEqual(res.statusCode, 400); }); }); |