File size: 8,070 Bytes
f0634fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * FileTokenStorage tests β€” round-trip persistence + permission checks.
 *
 * Scope guards: tokens never leak to process.env or other files; permission
 * 0600 is enforced; corrupted files return undefined rather than throwing.
 */

import { chmodSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

import { afterEach, beforeEach, describe, expect, it } from 'vitest';

import { FileTokenStorage } from '../src/storage';
import type { TokenInfo } from '../src/types';

function makeTmpDir(): string {
  const dir = join(
    tmpdir(),
    `kimi-storage-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
  );
  mkdirSync(dir, { recursive: true });
  return dir;
}

function sampleToken(overrides: Partial<TokenInfo> = {}): TokenInfo {
  return {
    accessToken: 'at-abc',
    refreshToken: 'rt-xyz',
    expiresAt: 1_700_000_000,
    scope: 'read write',
    tokenType: 'Bearer',
    expiresIn: 3600,
    ...overrides,
  };
}

describe('FileTokenStorage', () => {
  let dir: string;
  let storage: FileTokenStorage;

  beforeEach(() => {
    dir = makeTmpDir();
    storage = new FileTokenStorage(dir);
  });

  afterEach(() => {
    rmSync(dir, { recursive: true, force: true });
  });

  it('returns undefined when no token exists', async () => {
    expect(await storage.load('kimi-code')).toBeUndefined();
  });

  it('round-trips a token via save/load', async () => {
    const token = sampleToken();
    await storage.save('kimi-code', token);
    const loaded = await storage.load('kimi-code');
    expect(loaded).toEqual(token);
  });

  it('persists tokens in snake_case JSON (Python-compatible)', async () => {
    const token = sampleToken();
    await storage.save('kimi-code', token);
    const raw = readFileSync(join(dir, 'kimi-code.json'), 'utf-8');
    const parsed = JSON.parse(raw) as Record<string, unknown>;
    expect(parsed['access_token']).toBe('at-abc');
    expect(parsed['refresh_token']).toBe('rt-xyz');
    expect(parsed['expires_at']).toBe(1_700_000_000);
    expect(parsed['token_type']).toBe('Bearer');
    expect(parsed['expires_in']).toBe(3600);
    expect(parsed['accessToken']).toBeUndefined();
  });

  it.skipIf(process.platform === 'win32')('writes the credentials file with mode 0600', async () => {
    await storage.save('kimi-code', sampleToken());
    const stat = statSync(join(dir, 'kimi-code.json'));
    // eslint-disable-next-line no-bitwise
    expect(stat.mode & 0o777).toBe(0o600);
  });

  it('remove() deletes the file; load() then returns undefined', async () => {
    await storage.save('kimi-code', sampleToken());
    await storage.remove('kimi-code');
    expect(await storage.load('kimi-code')).toBeUndefined();
  });

  it('remove() is idempotent when file is absent', async () => {
    await expect(storage.remove('never-existed')).resolves.toBeUndefined();
  });

  it('save() overwrites an existing token atomically', async () => {
    await storage.save('kimi-code', sampleToken({ accessToken: 'first' }));
    await storage.save('kimi-code', sampleToken({ accessToken: 'second' }));
    const loaded = await storage.load('kimi-code');
    expect(loaded?.accessToken).toBe('second');
  });

  it('load() returns undefined on corrupt JSON (does not throw)', async () => {
    const file = join(dir, 'kimi-code.json');
    writeFileSync(file, '{ not json', 'utf-8');
    chmodSync(file, 0o600);
    expect(await storage.load('kimi-code')).toBeUndefined();
  });

  it('load() returns undefined on malformed payload (not a dict)', async () => {
    const file = join(dir, 'kimi-code.json');
    writeFileSync(file, '["array", "instead"]', 'utf-8');
    chmodSync(file, 0o600);
    expect(await storage.load('kimi-code')).toBeUndefined();
  });

  it('load() tolerates missing numeric fields by defaulting to 0', async () => {
    const file = join(dir, 'kimi-code.json');
    writeFileSync(file, JSON.stringify({ access_token: 'a', refresh_token: 'r' }), 'utf-8');
    chmodSync(file, 0o600);
    const token = await storage.load('kimi-code');
    expect(token?.expiresAt).toBe(0);
    expect(token?.expiresIn).toBe(0);
  });

  it('list() returns all stored token names', async () => {
    await storage.save('kimi-code', sampleToken());
    await storage.save('other-provider', sampleToken());
    const names = await storage.list();
    expect(names.toSorted()).toEqual(['kimi-code', 'other-provider']);
  });

  it('list() ignores non-JSON files in the credentials dir', async () => {
    await storage.save('kimi-code', sampleToken());
    writeFileSync(join(dir, 'kimi-code.lock'), 'lock', 'utf-8');
    writeFileSync(join(dir, 'readme.txt'), 'readme', 'utf-8');
    const names = await storage.list();
    expect(names).toEqual(['kimi-code']);
  });

  it.skipIf(process.platform === 'win32')('creates the credentials dir with mode 0700 if missing', async () => {
    const freshDir = join(dir, 'nested', 'sub');
    const s = new FileTokenStorage(freshDir);
    await s.save('kimi-code', sampleToken());
    const stat = statSync(freshDir);
    // eslint-disable-next-line no-bitwise
    expect(stat.mode & 0o777).toBe(0o700);
  });

  it('refuses path-traversal names on save (B1)', async () => {
    await expect(storage.save('../../etc/passwd', sampleToken())).rejects.toThrow(
      /Invalid token name/,
    );
  });

  it('refuses path-traversal names on load', async () => {
    await expect(storage.load('../etc/passwd')).rejects.toThrow(/Invalid token name/);
  });

  it('refuses path-traversal names on remove', async () => {
    await expect(storage.remove('../etc/passwd')).rejects.toThrow(/Invalid token name/);
  });

  it('refuses leading-dot names (hidden file abuse)', async () => {
    await expect(storage.save('.hidden', sampleToken())).rejects.toThrow(/Invalid token name/);
  });

  it('refuses empty name', async () => {
    await expect(storage.save('', sampleToken())).rejects.toThrow(/Invalid token name/);
  });

  // ── atomic save leaves no .tmp sibling ────────────────────────────────

  it('save() leaves no *.tmp.* sibling once the rename completes', async () => {
    // Atomic save must clean up its temp artefact after rename. Uses
    // `target.tmp.<pid>.<rand>` then renameSync; this test asserts the
    // resulting directory contains only the canonical file.
    await storage.save('kimi-code', sampleToken());
    const { readdirSync } = await import('node:fs');
    const entries = readdirSync(dir);
    const tmps = entries.filter((name) => name.startsWith('kimi-code.json.tmp.'));
    expect(tmps).toEqual([]);
    expect(entries).toContain('kimi-code.json');
  });

  it('save() + load() preserves expires_in and expires_at roundtrip', async () => {
    // The wire format records both `expires_at` and `expires_in`; the
    // load path must restore both fields without loss.
    const token = sampleToken({ expiresAt: 1_800_000_000, expiresIn: 7200 });
    await storage.save('kimi-code', token);
    const loaded = await storage.load('kimi-code');
    expect(loaded?.expiresAt).toBe(1_800_000_000);
    expect(loaded?.expiresIn).toBe(7200);
  });

  it('load() of a wire payload missing scope/token_type uses safe defaults', async () => {
    // A legacy file written without the optional `scope` / `token_type`
    // fields must still load; the defaults come from `tokenFromWire`.
    const file = join(dir, 'kimi-code.json');
    writeFileSync(
      file,
      JSON.stringify({
        access_token: 'a',
        refresh_token: 'r',
        expires_at: 1,
        expires_in: 60,
      }),
      'utf-8',
    );
    chmodSync(file, 0o600);
    const loaded = await storage.load('kimi-code');
    expect(loaded?.accessToken).toBe('a');
    expect(loaded?.refreshToken).toBe('r');
    // Defaults should be strings (empty / 'Bearer'), never undefined.
    expect(typeof loaded?.scope).toBe('string');
    expect(typeof loaded?.tokenType).toBe('string');
  });
});