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
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { promises as fs } from 'node:fs';
import * as path from 'node:path';
import {
MCPOAuthTokenStorage,
MCPOAuthToken,
MCPOAuthCredentials,
} from './oauth-token-storage.js';
// Mock file system operations
vi.mock('node:fs', () => ({
promises: {
readFile: vi.fn(),
writeFile: vi.fn(),
mkdir: vi.fn(),
unlink: vi.fn(),
},
mkdirSync: vi.fn(),
}));
vi.mock('node:os', () => ({
homedir: vi.fn(() => '/mock/home'),
}));
describe('MCPOAuthTokenStorage', () => {
const mockToken: MCPOAuthToken = {
accessToken: 'access_token_123',
refreshToken: 'refresh_token_456',
tokenType: 'Bearer',
scope: 'read write',
expiresAt: Date.now() + 3600000, // 1 hour from now
};
const mockCredentials: MCPOAuthCredentials = {
serverName: 'test-server',
token: mockToken,
clientId: 'test-client-id',
tokenUrl: 'https://auth.example.com/token',
updatedAt: Date.now(),
};
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('loadTokens', () => {
it('should return empty map when token file does not exist', async () => {
vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
const tokens = await MCPOAuthTokenStorage.loadTokens();
expect(tokens.size).toBe(0);
expect(console.error).not.toHaveBeenCalled();
});
it('should load tokens from file successfully', async () => {
const tokensArray = [mockCredentials];
vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(tokensArray));
const tokens = await MCPOAuthTokenStorage.loadTokens();
expect(tokens.size).toBe(1);
expect(tokens.get('test-server')).toEqual(mockCredentials);
expect(fs.readFile).toHaveBeenCalledWith(
path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
'utf-8',
);
});
it('should handle corrupted token file gracefully', async () => {
vi.mocked(fs.readFile).mockResolvedValue('invalid json');
const tokens = await MCPOAuthTokenStorage.loadTokens();
expect(tokens.size).toBe(0);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Failed to load MCP OAuth tokens'),
);
});
it('should handle file read errors other than ENOENT', async () => {
const error = new Error('Permission denied');
vi.mocked(fs.readFile).mockRejectedValue(error);
const tokens = await MCPOAuthTokenStorage.loadTokens();
expect(tokens.size).toBe(0);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Failed to load MCP OAuth tokens'),
);
});
});
describe('saveToken', () => {
it('should save token with restricted permissions', async () => {
vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
vi.mocked(fs.mkdir).mockResolvedValue(undefined);
vi.mocked(fs.writeFile).mockResolvedValue(undefined);
await MCPOAuthTokenStorage.saveToken(
'test-server',
mockToken,
'client-id',
'https://token.url',
);
expect(fs.mkdir).toHaveBeenCalledWith(
path.join('/mock/home', '.gemini'),
{ recursive: true },
);
expect(fs.writeFile).toHaveBeenCalledWith(
path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
expect.stringContaining('test-server'),
{ mode: 0o600 },
);
});
it('should update existing token for same server', async () => {
const existingCredentials = {
...mockCredentials,
serverName: 'existing-server',
};
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([existingCredentials]),
);
vi.mocked(fs.writeFile).mockResolvedValue(undefined);
const newToken = { ...mockToken, accessToken: 'new_access_token' };
await MCPOAuthTokenStorage.saveToken('existing-server', newToken);
const writeCall = vi.mocked(fs.writeFile).mock.calls[0];
const savedData = JSON.parse(writeCall[1] as string);
expect(savedData).toHaveLength(1);
expect(savedData[0].token.accessToken).toBe('new_access_token');
expect(savedData[0].serverName).toBe('existing-server');
});
it('should handle write errors gracefully', async () => {
vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
vi.mocked(fs.mkdir).mockResolvedValue(undefined);
const writeError = new Error('Disk full');
vi.mocked(fs.writeFile).mockRejectedValue(writeError);
await expect(
MCPOAuthTokenStorage.saveToken('test-server', mockToken),
).rejects.toThrow('Disk full');
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Failed to save MCP OAuth token'),
);
});
});
describe('getToken', () => {
it('should return token for existing server', async () => {
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([mockCredentials]),
);
const result = await MCPOAuthTokenStorage.getToken('test-server');
expect(result).toEqual(mockCredentials);
});
it('should return null for non-existent server', async () => {
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([mockCredentials]),
);
const result = await MCPOAuthTokenStorage.getToken('non-existent');
expect(result).toBeNull();
});
it('should return null when no tokens file exists', async () => {
vi.mocked(fs.readFile).mockRejectedValue({ code: 'ENOENT' });
const result = await MCPOAuthTokenStorage.getToken('test-server');
expect(result).toBeNull();
});
});
describe('removeToken', () => {
it('should remove token for specific server', async () => {
const credentials1 = { ...mockCredentials, serverName: 'server1' };
const credentials2 = { ...mockCredentials, serverName: 'server2' };
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([credentials1, credentials2]),
);
vi.mocked(fs.writeFile).mockResolvedValue(undefined);
await MCPOAuthTokenStorage.removeToken('server1');
const writeCall = vi.mocked(fs.writeFile).mock.calls[0];
const savedData = JSON.parse(writeCall[1] as string);
expect(savedData).toHaveLength(1);
expect(savedData[0].serverName).toBe('server2');
});
it('should remove token file when no tokens remain', async () => {
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([mockCredentials]),
);
vi.mocked(fs.unlink).mockResolvedValue(undefined);
await MCPOAuthTokenStorage.removeToken('test-server');
expect(fs.unlink).toHaveBeenCalledWith(
path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
);
expect(fs.writeFile).not.toHaveBeenCalled();
});
it('should handle removal of non-existent token gracefully', async () => {
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([mockCredentials]),
);
await MCPOAuthTokenStorage.removeToken('non-existent');
expect(fs.writeFile).not.toHaveBeenCalled();
expect(fs.unlink).not.toHaveBeenCalled();
});
it('should handle file operation errors gracefully', async () => {
vi.mocked(fs.readFile).mockResolvedValue(
JSON.stringify([mockCredentials]),
);
vi.mocked(fs.unlink).mockRejectedValue(new Error('Permission denied'));
await MCPOAuthTokenStorage.removeToken('test-server');
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Failed to remove MCP OAuth token'),
);
});
});
describe('isTokenExpired', () => {
it('should return false for token without expiry', () => {
const tokenWithoutExpiry = { ...mockToken };
delete tokenWithoutExpiry.expiresAt;
const result = MCPOAuthTokenStorage.isTokenExpired(tokenWithoutExpiry);
expect(result).toBe(false);
});
it('should return false for valid token', () => {
const futureToken = {
...mockToken,
expiresAt: Date.now() + 3600000, // 1 hour from now
};
const result = MCPOAuthTokenStorage.isTokenExpired(futureToken);
expect(result).toBe(false);
});
it('should return true for expired token', () => {
const expiredToken = {
...mockToken,
expiresAt: Date.now() - 3600000, // 1 hour ago
};
const result = MCPOAuthTokenStorage.isTokenExpired(expiredToken);
expect(result).toBe(true);
});
it('should return true for token expiring within buffer time', () => {
const soonToExpireToken = {
...mockToken,
expiresAt: Date.now() + 60000, // 1 minute from now (within 5-minute buffer)
};
const result = MCPOAuthTokenStorage.isTokenExpired(soonToExpireToken);
expect(result).toBe(true);
});
});
describe('clearAllTokens', () => {
it('should remove token file successfully', async () => {
vi.mocked(fs.unlink).mockResolvedValue(undefined);
await MCPOAuthTokenStorage.clearAllTokens();
expect(fs.unlink).toHaveBeenCalledWith(
path.join('/mock/home', '.gemini', 'mcp-oauth-tokens.json'),
);
});
it('should handle non-existent file gracefully', async () => {
vi.mocked(fs.unlink).mockRejectedValue({ code: 'ENOENT' });
await MCPOAuthTokenStorage.clearAllTokens();
expect(console.error).not.toHaveBeenCalled();
});
it('should handle other file errors gracefully', async () => {
vi.mocked(fs.unlink).mockRejectedValue(new Error('Permission denied'));
await MCPOAuthTokenStorage.clearAllTokens();
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining('Failed to clear MCP OAuth tokens'),
);
});
});
});
|