File size: 2,261 Bytes
c7d34c1
3e8ea5d
c7d34c1
3e8ea5d
c7d34c1
 
 
 
32151b6
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32151b6
c7d34c1
 
 
 
 
 
 
 
32151b6
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { GET } from './route';
import { NextRequest } from 'next/server';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { afterEach, describe, it } from 'node:test';

const originalAppPassword = process.env.APP_PASSWORD;
const originalAppLogLevel = process.env.APP_LOG_LEVEL;
const PAGE_PASSWORD_FIXTURE = ['customer', 'access', 'code'].join('-');

afterEach(() => {
    if (originalAppPassword === undefined) {
        delete process.env.APP_PASSWORD;
    } else {
        process.env.APP_PASSWORD = originalAppPassword;
    }
    if (originalAppLogLevel === undefined) {
        delete process.env.APP_LOG_LEVEL;
    } else {
        process.env.APP_LOG_LEVEL = originalAppLogLevel;
    }
});

function sha256(value: string): string {
    return createHash('sha256').update(value).digest('hex');
}

describe('GET /api/logs', () => {
    it('rejects log streaming when APP_PASSWORD is not configured', async () => {
        delete process.env.APP_PASSWORD;
        const request = new NextRequest('http://localhost/api/logs');

        const response = await GET(request);

        assert.equal(response.status, 403);
    });

    it('rejects access-code hashes sent in the query string', async () => {
        process.env.APP_PASSWORD = PAGE_PASSWORD_FIXTURE;
        const request = new NextRequest(`http://localhost/api/logs?passwordHash=${sha256(PAGE_PASSWORD_FIXTURE)}`);

        const response = await GET(request);

        assert.equal(response.status, 401);
    });

    it('accepts access-code hashes sent as a bearer token', async () => {
        process.env.APP_PASSWORD = PAGE_PASSWORD_FIXTURE;
        process.env.APP_LOG_LEVEL = 'warn';
        const request = new NextRequest('http://localhost/api/logs', {
            headers: {
                Authorization: `Bearer ${sha256(PAGE_PASSWORD_FIXTURE)}`
            }
        });

        const response = await GET(request);
        assert.ok(response.body);
        const reader = response.body.getReader();
        const chunk = await reader.read();
        await reader.cancel();

        assert.equal(response.status, 200);
        assert.ok(chunk.value);
        assert.match(new TextDecoder().decode(chunk.value), /^: connected/);
    });
});