forked from honojs/node-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve-static.test.ts
More file actions
538 lines (469 loc) · 20.1 KB
/
Copy pathserve-static.test.ts
File metadata and controls
538 lines (469 loc) · 20.1 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import { Hono } from 'hono'
import request from 'supertest'
import { chmodSync, rmSync, statSync, symlinkSync } from 'node:fs'
import path from 'node:path'
import { serveStatic } from './../src/serve-static'
import { createAdaptorServer } from './../src/server'
describe('Serve Static Middleware', () => {
const app = new Hono<{
Variables: {
path: string
}
}>()
app.use(
'/static/*',
serveStatic({
root: './test/assets',
onFound: (path, c) => {
c.header('X-Custom', `Found the file at ${path}`)
if (c.req.query('type')) {
c.header('Content-Type', c.req.query('type'))
}
},
})
)
app.use('/favicon.ico', serveStatic({ path: './test/assets/favicon.ico' }))
app.use(
'/dot-static/*',
serveStatic({
root: './test/assets',
rewriteRequestPath: (path) => path.replace(/^\/dot-static/, '/.static'),
})
)
app.use(
'/static-with-context-path-route/*',
async (c, next) => {
c.set('path', '/static-with-context-path')
await next()
},
serveStatic({
root: './test/assets',
rewriteRequestPath: (path, c) =>
path.replace('static-with-context-path-route', c.get('path')),
})
)
let notFoundMessage = ''
app.use(
'/on-not-found/*',
serveStatic({
root: './not-found',
onNotFound: (path, c) => {
notFoundMessage = `${path} is not found, request to ${c.req.path}`
},
})
)
app.use(
'/static-with-precompressed/*',
serveStatic({
root: './test/assets',
precompressed: true,
})
)
const server = createAdaptorServer(app)
it('Should return index.html', async () => {
const res = await request(server).get('/static/')
expect(res.status).toBe(200)
expect(res.text).toBe('<h1>Hello Hono</h1>')
expect(res.headers['content-type']).toBe('text/html; charset=utf-8')
expect(res.headers['x-custom']).toMatch(
/Found the file at test[\/\\]assets[\/\\]static[\/\\]index\.html$/
)
})
it('Should return hono.html', async () => {
const res = await request(server).get('/static/hono.html')
expect(res.status).toBe(200)
expect(res.text).toBe('<h1>This is Hono.html</h1>')
expect(res.headers['content-type']).toBe('text/html; charset=utf-8')
})
it('Should return correct headers for icons', async () => {
const res = await request(server).get('/favicon.ico')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/x-icon')
})
it('Should return correct headers and data for json files', async () => {
const res = await request(server).get('/static/data.json')
expect(res.status).toBe(200)
expect(res.body).toEqual({
id: 1,
name: 'Foo Bar',
flag: true,
})
expect(res.headers['content-type']).toBe('application/json')
})
it('Should return correct headers and data for text', async () => {
const res = await request(server).get('/static/plain.txt')
const stats = statSync(path.join(__dirname, 'assets', 'static', 'plain.txt'))
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['last-modified']).toBe(stats.mtime.toUTCString())
expect(res.text).toBe('This is plain.txt')
})
it('Should return 404 for non-existent files', async () => {
const res = await request(server).get('/static/does-not-exist.html')
expect(res.status).toBe(404)
expect(res.headers['content-type']).toBe('text/plain; charset=UTF-8')
expect(res.text).toBe('404 Not Found')
})
it('Should return 200 with rewriteRequestPath', async () => {
const res = await request(server).get('/dot-static/plain.txt')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.text).toBe('This is plain.txt')
})
it('Should return 404 with rewriteRequestPath', async () => {
const res = await request(server).get('/dot-static/does-no-exists.txt')
expect(res.status).toBe(404)
})
it('Should return 200 with rewriteRequestPath with the context', async () => {
const res = await request(server).get('/static-with-context-path-route/plain.txt')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.text).toBe('This is plain.txt')
})
it('Should return 200 response to HEAD request', async () => {
const res = await request(server).head('/static/plain.txt')
const stats = statSync(path.join(__dirname, 'assets', 'static', 'plain.txt'))
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('17')
expect(res.headers['last-modified']).toBe(stats.mtime.toUTCString())
expect(res.text).toBe(undefined)
})
it('Should return correct headers and data with range headers', async () => {
let res = await request(server).get('/static/plain.txt').set('range', '0-9')
const stats = statSync(path.join(__dirname, 'assets', 'static', 'plain.txt'))
expect(res.status).toBe(206)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('10')
expect(res.headers['content-range']).toBe('bytes 0-9/17')
expect(res.headers['last-modified']).toBe(stats.mtime.toUTCString())
expect(res.headers['date']).not.toBe(stats.mtime.toUTCString())
expect(res.headers['date']).not.toBe(stats.birthtime.toUTCString())
expect(res.text.length).toBe(10)
expect(res.text).toBe('This is pl')
res = await request(server).get('/static/plain.txt').set('range', '10-16')
expect(res.status).toBe(206)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('7')
expect(res.headers['content-range']).toBe('bytes 10-16/17')
expect(res.text.length).toBe(7)
expect(res.text).toBe('ain.txt')
})
it('Should return correct headers and data if client range exceeds the data size', async () => {
const res = await request(server).get('/static/plain.txt').set('range', '0-20')
expect(res.status).toBe(206)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.headers['content-length']).toBe('17')
expect(res.headers['content-range']).toBe('bytes 0-16/17')
expect(res.text.length).toBe(17)
expect(res.text).toBe('This is plain.txt')
})
it('Should handle invalid range header gracefully without NaN error', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'hello')
expect(res.status).toBe(206)
expect(res.headers['content-length']).toBe('17')
expect(res.headers['content-range']).toBe('bytes 0-16/17')
})
it('Should return the last N bytes for a suffix range', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=-5')
expect(res.status).toBe(206)
expect(res.headers['content-length']).toBe('5')
expect(res.headers['content-range']).toBe('bytes 12-16/17')
expect(res.text).toBe('n.txt')
})
it('Should return the whole file for a suffix range exceeding the file size', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=-100')
expect(res.status).toBe(206)
expect(res.headers['content-range']).toBe('bytes 0-16/17')
expect(res.text).toBe('This is plain.txt')
})
it('Should return exactly 1 byte for range bytes=0-0', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=0-0')
expect(res.status).toBe(206)
expect(res.headers['content-length']).toBe('1')
expect(res.headers['content-range']).toBe('bytes 0-0/17')
expect(res.text).toBe('T')
})
it('Should return 416 when the range start is beyond the end of the file', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=100-200')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */17')
})
it('Should return 416 when the range start is beyond the file size, even if the window is small', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=20-25')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */17')
})
it('Should return 416 when the range start is after the range end', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=10-5')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */17')
})
it('Should return 416 for a zero-length suffix range', async () => {
const res = await request(server).get('/static/plain.txt').set('range', 'bytes=-0')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */17')
})
it.each(['bytes=0-1x', 'bytes=x-1', 'bytes=0-1-2', 'bytes=-5-extra'])(
'Should treat a malformed range as the whole file: %s',
async (range) => {
const res = await request(server).get('/static/plain.txt').set('range', range)
expect(res.status).toBe(206)
expect(res.headers['content-range']).toBe('bytes 0-16/17')
expect(res.text).toBe('This is plain.txt')
}
)
it('Should return 416 instead of crashing for a range request on an empty file', async () => {
const res = await request(server).get('/static/foo..bar.txt').set('range', 'bytes=0-0')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */0')
})
it('Should return 416 instead of crashing for a malformed range on an empty file', async () => {
const res = await request(server).get('/static/foo..bar.txt').set('range', 'hello')
expect(res.status).toBe(416)
expect(res.headers['content-range']).toBe('bytes */0')
})
it('Should handle the `onNotFound` option', async () => {
const res = await request(server).get('/on-not-found/foo.txt')
expect(res.status).toBe(404)
expect(notFoundMessage).toMatch(
/not-found[\/\\]on-not-found[\/\\]foo\.txt is not found, request to \/on-not-found\/foo\.txt$/
)
})
it('Should handle the `onFound` option', async () => {
const res = await request(server).get(
'/static/data.json?type=application/json;%20charset=utf-8'
)
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('application/json; charset=utf-8')
})
it('Should handle double dots in URL', async () => {
const res = await request(server).get('/static/../secret.txt')
expect(res.status).toBe(404)
})
// Skip on Windows as symlink behavior is different
;(process.platform === 'win32' ? it.skip : it)('Should follow symlinks', async () => {
const symlinkPath = path.join(__dirname, 'assets', 'static', 'symlink.html')
const symlinkTarget = path.join(__dirname, 'assets', 'static', 'index.html')
try {
// force: true so it doesn't throw if the symlink doesn't exist
rmSync(symlinkPath, { force: true })
symlinkSync(symlinkTarget, symlinkPath)
const res = await request(server).get('/static/symlink.html')
expect(res.status).toBe(200)
expect(res.text).toBe('<h1>Hello Hono</h1>')
} finally {
rmSync(symlinkPath, { force: true })
}
})
it('Should handle URIError thrown while decoding URI component', async () => {
const res = await request(server).get('/static/%c0%afsecret.txt')
expect(res.status).toBe(404)
})
it('Should handle an extension less files', async () => {
const res = await request(server).get('/static/extensionless')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('application/octet-stream')
expect(res.body.toString()).toBe('Extensionless')
})
it('Should return a pre-compressed zstd response - /static-with-precompressed/hello.txt', async () => {
// Check if it returns a normal response
let res = await request(server).get('/static-with-precompressed/hello.txt')
let stats = statSync(path.join(__dirname, 'assets', 'static-with-precompressed', 'hello.txt'))
expect(res.status).toBe(200)
expect(res.headers['content-length']).toBe('20')
expect(res.headers['last-modified']).toBe(stats.mtime.toUTCString())
expect(res.text).toBe('Hello Not Compressed')
res = await request(server)
.get('/static-with-precompressed/hello.txt')
.set('Accept-Encoding', 'zstd')
stats = statSync(path.join(__dirname, 'assets', 'static-with-precompressed', 'hello.txt.zst'))
expect(res.status).toBe(200)
expect(res.headers['content-length']).toBe('21')
expect(res.headers['content-encoding']).toBe('zstd')
expect(res.headers['last-modified']).toBe(stats.mtime.toUTCString())
expect(res.headers['vary']).toBe('Accept-Encoding')
expect(res.text).toBe('Hello zstd Compressed')
})
it('Should return a pre-compressed brotli response - /static-with-precompressed/hello.txt', async () => {
const res = await request(server)
.get('/static-with-precompressed/hello.txt')
.set('Accept-Encoding', 'wompwomp, gzip, br, deflate, zstd')
expect(res.status).toBe(200)
expect(res.headers['content-length']).toBe('23')
expect(res.headers['content-encoding']).toBe('br')
expect(res.headers['vary']).toBe('Accept-Encoding')
expect(res.text).toBe('Hello br Compressed')
})
it('Should not return a pre-compressed response - /static-with-precompressed/hello.txt', async () => {
const res = await request(server)
.get('/static-with-precompressed/hello.txt')
.set('Accept-Encoding', 'wompwomp, unknown')
expect(res.status).toBe(200)
expect(res.headers['content-encoding']).toBeUndefined()
expect(res.headers['vary']).toBeUndefined()
expect(res.text).toBe('Hello Not Compressed')
})
it('Should return a pre-compressed response for an octet-stream file - /static-with-precompressed/hello.bin', async () => {
const res = await request(server)
.get('/static-with-precompressed/hello.bin')
.set('Accept-Encoding', 'gzip, br, zstd')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('application/octet-stream')
expect(res.headers['content-length']).toBe('23')
expect(res.headers['content-encoding']).toBe('br')
expect(res.headers['vary']).toBe('Accept-Encoding')
expect(res.body.toString()).toBe('Hello br Compressed')
})
describe('Absolute path', () => {
const rootPaths = [
path.join(__dirname, 'assets'),
__dirname + path.sep + '..' + path.sep + 'test' + path.sep + 'assets',
]
rootPaths.forEach((root) => {
describe(root, () => {
const app = new Hono()
const server = createAdaptorServer(app)
app.use('/static/*', serveStatic({ root }))
app.use('/favicon.ico', serveStatic({ path: root + path.sep + 'favicon.ico' }))
it('Should return index.html', async () => {
const res = await request(server).get('/static')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/html; charset=utf-8')
expect(res.text).toBe('<h1>Hello Hono</h1>')
})
it('Should return correct headers and data for text', async () => {
const res = await request(server).get('/static/plain.txt')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/plain; charset=utf-8')
expect(res.text).toBe('This is plain.txt')
})
it('Should return correct headers for icons', async () => {
const res = await request(server).get('/favicon.ico')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/x-icon')
})
})
})
})
describe('Root and path combination tests', () => {
const rootPaths = [
path.join(__dirname, 'assets'),
path.join(__dirname, 'assets'),
__dirname + path.sep + '..' + path.sep + 'test' + path.sep + 'assets',
]
const optionPaths = ['favicon.ico', '/favicon.ico']
rootPaths.forEach((root) => {
optionPaths.forEach((optionPath) => {
describe(`${root} + ${optionPath}`, () => {
const app = new Hono()
const server = createAdaptorServer(app)
app.use(
'/favicon.ico',
serveStatic({
root,
path: optionPath,
})
)
it('Should return 200 response if both root and path set', async () => {
const res = await request(server).get('/favicon.ico')
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('image/x-icon')
})
})
})
})
})
describe('Path traversal security tests', () => {
const app = new Hono()
const server = createAdaptorServer(app)
app.use('/static/*', serveStatic({ root: './test/assets' }))
it('Should prevent path traversal attacks with double dots', async () => {
const res = await request(server).get('/static/../secret.txt')
expect(res.status).toBe(404)
})
it('Should prevent path traversal attacks with multiple levels', async () => {
const res = await request(server).get('/static/../../package.json')
expect(res.status).toBe(404)
})
it('Should prevent path traversal attacks with mixed separators', async () => {
const res = await request(server).get('/static/..\\..\\package.json')
expect(res.status).toBe(404)
})
it('Should prevent path traversal attacks with encoded dots', async () => {
const res = await request(server).get('/static/%2e%2e%2fsecret.txt')
expect(res.status).toBe(404)
})
it('Should accept filename with double dots', async () => {
const res = await request(server).get('/static/foo..bar.txt')
expect(res.status).toBe(200)
})
})
describe('Path mismatch security tests', () => {
const app = new Hono()
const server = createAdaptorServer(app)
app.use('/static/admin/*', async (c, next) => {
c.header('X-Authorized', 'true')
await next()
})
app.use('/static/*', serveStatic({ root: './test/assets' }))
it('Should not allow bypass via path mismatch between middleware and serveStatic', async () => {
const res = await request(server).get('/static/admin/secret.txt')
expect(res.headers['x-authorized']).toBe('true')
expect(res.text).toBe('secret')
const res2 = await request(server).get('/static/admin%2Fsecret.txt')
expect(res2.status).toBe(404)
expect(res2.headers['x-authorized']).toBeUndefined()
expect(res2.text).not.toBe('secret')
const res3 = await request(server).get('/static//admin/secret.txt')
expect(res3.status).toBe(404)
const res4 = await request(server).get('/static/admin%5Csecret.txt')
expect(res4.status).toBe(404)
expect(res4.headers['x-authorized']).toBeUndefined()
expect(res4.text).not.toBe('secret')
})
})
describe('Stream error handling', () => {
const testFile = path.join(__dirname, 'assets', 'static', 'plain.txt')
console.log(testFile)
let originalMode: number
beforeEach(() => {
const stats = statSync(testFile)
originalMode = stats.mode
// Remove read permission to trigger stream error
chmodSync(testFile, 0o000)
})
afterEach(() => {
chmodSync(testFile, originalMode)
})
// Skip on Windows as chmod doesn't work for file permissions
;(process.platform === 'win32' ? it.skip : it)(
'Should handle read permission errors gracefully',
async () => {
const app = new Hono()
app.use('/static/*', serveStatic({ root: './test/assets' }))
const server = createAdaptorServer(app)
await expect(request(server).get('/static/plain.txt')).rejects.toThrow()
}
)
})
})
describe('Serve Static Middleware with wrong path', () => {
it('Should show an error when the path is wrong', async () => {
const logSpy = vi.spyOn(console, 'error')
const app = new Hono<{
Variables: {
path: string
}
}>()
app.use(
'*',
serveStatic({
root: './public',
})
)
expect(logSpy).toHaveBeenCalledWith(
"serveStatic: root path './public' is not found, are you sure it's correct?"
)
})
})