okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
4.9 KiB96 linesraw
1/**
2 * #4535: the shared listener and the tunnel origin compare the API key in constant time (as the engine does since #213).
3 * Both sides are hashed, so a wrong length is as cheap and as safe as a wrong value; a missing or non-string header
4 * never matches; no key set still means open access (0.2.2).
5 */
6import test from 'node:test';
7import assert from 'node:assert/strict';
8import http from 'node:http';
9import { mkdtempSync, rmSync } from 'node:fs';
10import { tmpdir } from 'node:os';
11import { join } from 'node:path';
12import { sameSecret } from '../server/util.mjs';
13import { createLocalShare } from '../server/local-share.mjs';
14
15const home = mkdtempSync(join(tmpdir(), 'strata-serving-compare-'));
16process.env.STRATA_HOME = home;
17const serving = await import('../server/serving.mjs');
18test.after(() => { try { rmSync(home, { recursive: true, force: true }); } catch { /* temp folder */ } });
19
20const KEY = 'sk-strata-0123456789abcdef0123456789abcdef';
21serving.init({ send() {} }, { port: 8080, host: '127.0.0.1' });
22serving.patch({ apiKey: KEY });
23const asks = headers => serving.authorized({ headers });
24
25test('sameSecret: equal strings match; different, shorter, longer, empty and non-string never do', () => {
26  assert.equal(sameSecret(KEY, KEY), true);
27  assert.equal(sameSecret(KEY.slice(0, -1), KEY), false, 'a prefix of the key');
28  assert.equal(sameSecret(KEY + 'x', KEY), false, 'the key plus one character');
29  assert.equal(sameSecret('x'.repeat(KEY.length), KEY), false, 'same length, other content');
30  assert.equal(sameSecret('x', KEY), false);
31  assert.equal(sameSecret('x'.repeat(100000), KEY), false, 'a very long value is safe');
32  assert.equal(sameSecret('', KEY), false);
33  assert.equal(sameSecret('', ''), false, 'an empty secret is "not set", never equal to an empty header');
34  for (const odd of [undefined, null, 5, {}, [KEY], true, Buffer.from(KEY)]) assert.equal(sameSecret(odd, KEY), false, String(typeof odd));
35  assert.equal(sameSecret(KEY, undefined), false);
36  assert.equal(sameSecret('kéy-中文', 'kéy-中文'), true, 'non-ASCII keys compare by their characters');
37  assert.equal(sameSecret('kéy', 'key'), false);
38});
39
40test('authorized: Bearer and x-api-key pass with the key; wrong lengths, invalid tokens and malformed headers fail', () => {
41  assert.equal(asks({ authorization: `Bearer ${KEY}` }), true);
42  assert.equal(asks({ 'x-api-key': KEY }), true);
43  assert.equal(asks({ authorization: 'Bearer wrong', 'x-api-key': KEY }), true, 'a wrong Bearer with the right x-api-key passes, as before');
44  assert.equal(asks({ authorization: `Bearer ${KEY}`, 'x-api-key': 'wrong' }), true);
45  for (const headers of [
46    {},
47    { authorization: '' },
48    { authorization: 'Bearer ' },
49    { authorization: 'Bearer' },
50    { authorization: 'Bearer wrong' },
51    { authorization: `Bearer ${KEY.slice(0, -1)}` },
52    { authorization: `Bearer ${KEY}x` },
53    { authorization: `Bearer ${'a'.repeat(5000)}` },
54    { authorization: KEY },
55    { authorization: `bearer ${KEY}` },
56    { authorization: `Basic ${KEY}` },
57    { 'x-api-key': '' },
58    { 'x-api-key': KEY.slice(1) },
59    { 'x-api-key': `${KEY} ` },
60    { 'x-api-key': [KEY] },
61    { 'x-api-key': 12345 },
62    { authorization: ['Bearer ' + KEY] },
63  ]) assert.equal(asks(headers), false, JSON.stringify(headers).slice(0, 80));
64  assert.equal(serving.authorized({}), false, 'a request without headers at all');
65});
66
67test('authorized: with no key set the listener stays open (the 0.2.2 decision)', () => {
68  serving.patch({ apiKey: null });
69  assert.equal(asks({}), true);
70  assert.equal(asks({ authorization: 'Bearer anything' }), true);
71  serving.patch({ apiKey: KEY });
72  assert.equal(asks({}), false);
73});
74
75test('a real share request: the right key reaches the model API, a wrong or missing one is refused with 401', async t => {
76  serving.patch({ apiKey: KEY });
77  const seen = [];
78  const handle = async (req, res, path) => {
79    if (!serving.authorized(req)) { res.writeHead(401, { 'content-type': 'application/json' }); res.end('{"error":"Invalid API key"}'); return; }
80    seen.push(path);
81    res.writeHead(200, { 'content-type': 'application/json' });
82    res.end('{"data":[]}');
83  };
84  // find a free port the way the host does
85  const probe = http.createServer(); await new Promise(r => probe.listen(0, '127.0.0.1', r)); const port = probe.address().port; await new Promise(r => probe.close(r));
86  const real = createLocalShare({ handle, hasKey: () => true, host: '127.0.0.1', port });
87  await real.start();
88  t.after(() => real.stop());
89  const call = headers => fetch(`http://127.0.0.1:${port}/v1/models`, { headers });
90  assert.equal((await call({ authorization: `Bearer ${KEY}` })).status, 200);
91  assert.equal((await call({ 'x-api-key': KEY })).status, 200);
92  assert.equal((await call({ authorization: `Bearer ${KEY}0` })).status, 401);
93  assert.equal((await call({ authorization: 'Bearer short' })).status, 401);
94  assert.equal((await call({})).status, 401);
95  assert.deepEqual(seen, ['/v1/models', '/v1/models']);
96});