-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCreateTokenTool.test.ts
More file actions
370 lines (314 loc) · 11.9 KB
/
CreateTokenTool.test.ts
File metadata and controls
370 lines (314 loc) · 11.9 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
// Set environment variables before any imports
// Create a token with username in the payload
const payload = Buffer.from(JSON.stringify({ u: 'testuser' })).toString(
'base64'
);
process.env.MAPBOX_ACCESS_TOKEN = `eyJhbGciOiJIUzI1NiJ9.${payload}.signature`;
import {
setupFetch,
assertHeadersSent
} from '../../utils/requestUtils.test-helpers.js';
import { MapboxApiBasedTool } from '../MapboxApiBasedTool.js';
import { CreateTokenTool } from './CreateTokenTool.js';
type TextContent = { type: 'text'; text: string };
describe('CreateTokenTool', () => {
let tool: CreateTokenTool;
beforeEach(() => {
tool = new CreateTokenTool();
tool['log'] = jest.fn();
});
afterEach(() => {
jest.clearAllMocks();
});
describe('tool metadata', () => {
it('should have correct name and description', () => {
expect(tool.name).toBe('create_token_tool');
expect(tool.description).toBe(
'Create a new Mapbox access token with specified scopes and optional URL restrictions. Token type (public/secret) is automatically determined by scopes: PUBLIC scopes (styles:tiles, styles:read, fonts:read, datasets:read, vision:read) create public tokens; SECRET scopes create secret tokens that are only visible once upon creation.'
);
});
it('should have correct input schema', () => {
const { CreateTokenSchema } = require('./CreateTokenTool.schema.js');
expect(CreateTokenSchema).toBeDefined();
});
});
describe('validation', () => {
it('validates required input fields', async () => {
const result = await tool.run({});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain('Required');
});
it('validates allowedUrls array length', async () => {
const urls = new Array(101).fill('https://example.com');
const result = await tool.run({
note: 'Test token',
scopes: ['styles:read'],
allowedUrls: urls
});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain('Maximum 100 allowed URLs');
});
it('validates invalid scopes', async () => {
const result = await tool.run({
note: 'Test token',
scopes: ['invalid:scope' as unknown as string]
});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain('Invalid enum value');
});
it('throws error when unable to extract username from token', async () => {
const originalToken = MapboxApiBasedTool.MAPBOX_ACCESS_TOKEN;
const originalEnvToken = process.env.MAPBOX_ACCESS_TOKEN;
try {
// Set a token without username in payload
const invalidPayload = Buffer.from(
JSON.stringify({ sub: 'test' })
).toString('base64');
const invalidToken = `eyJhbGciOiJIUzI1NiJ9.${invalidPayload}.signature`;
Object.defineProperty(MapboxApiBasedTool, 'MAPBOX_ACCESS_TOKEN', {
value: invalidToken,
writable: true,
configurable: true
});
process.env.MAPBOX_ACCESS_TOKEN = invalidToken;
// Setup fetch mock to prevent actual API calls
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
statusText: 'OK',
headers: new Headers(),
json: async () => ({ token: 'test-token' })
} as Response);
const toolWithInvalidToken = new CreateTokenTool();
toolWithInvalidToken['log'] = jest.fn();
const result = await toolWithInvalidToken.run({
note: 'Test token',
scopes: ['styles:read']
});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain(
'MAPBOX_ACCESS_TOKEN does not contain username in payload'
);
} finally {
// Restore
Object.defineProperty(MapboxApiBasedTool, 'MAPBOX_ACCESS_TOKEN', {
value: originalToken,
writable: true,
configurable: true
});
process.env.MAPBOX_ACCESS_TOKEN = originalEnvToken;
}
});
});
describe('execute', () => {
it('creates a token with basic parameters', async () => {
const mockResponse = {
token: 'pk.eyJ1IjoidGVzdHVzZXIiLCJhIjoiY2xwMTIzNDU2In0.test',
note: 'Test token',
id: 'cktest123',
scopes: ['styles:read', 'fonts:read'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z'
};
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
} as Response);
const result = await tool.run({
note: 'Test token',
scopes: ['styles:read', 'fonts:read']
});
expect(result.isError).toBe(false);
expect(result.content[0]).toHaveProperty('type', 'text');
const responseData = JSON.parse((result.content[0] as TextContent).text);
expect(responseData).toMatchObject({
token: mockResponse.token,
note: mockResponse.note,
id: mockResponse.id,
scopes: mockResponse.scopes
});
// Verify the request
expect(fetchMock).toHaveBeenCalledWith(
`https://api.mapbox.com/tokens/v2/testuser?access_token=eyJhbGciOiJIUzI1NiJ9.${payload}.signature`,
{
method: 'POST',
headers: expect.objectContaining({
'Content-Type': 'application/json'
}),
body: JSON.stringify({
note: 'Test token',
scopes: ['styles:read', 'fonts:read']
})
}
);
// Verify User-Agent header was sent
assertHeadersSent(fetchMock);
});
it('creates a token with allowed URLs', async () => {
const mockResponse = {
token: 'pk.eyJ1IjoidGVzdHVzZXIiLCJhIjoiY2xwMTIzNDU2In0.test',
note: 'Restricted token',
id: 'cktest456',
scopes: ['styles:read'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z',
allowedUrls: ['https://example.com', 'https://app.example.com']
};
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
} as Response);
const result = await tool.run({
note: 'Restricted token',
scopes: ['styles:read'],
allowedUrls: ['https://example.com', 'https://app.example.com']
});
expect(result.isError).toBe(false);
const responseData = JSON.parse((result.content[0] as TextContent).text);
expect(responseData.allowedUrls).toEqual(mockResponse.allowedUrls);
// Verify the request body included allowedUrls
const lastCall = fetchMock.mock.calls[0];
const requestBody = JSON.parse(lastCall[1].body as string);
expect(requestBody.allowedUrls).toEqual([
'https://example.com',
'https://app.example.com'
]);
});
it('creates a temporary token with expiration', async () => {
const expiresAt = '2024-12-31T23:59:59.000Z';
const mockResponse = {
token: 'tk.eyJ1IjoidGVzdHVzZXIiLCJhIjoiY2xwMTIzNDU2In0.test',
note: 'Temporary token',
id: 'cktest789',
scopes: ['styles:read'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z',
expires: expiresAt
};
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
} as Response);
const result = await tool.run({
note: 'Temporary token',
scopes: ['styles:read'],
expires: expiresAt
});
expect(result.isError).toBe(false);
const responseData = JSON.parse((result.content[0] as TextContent).text);
expect(responseData.expires).toEqual(expiresAt);
// Verify the request body included expires
const lastCall = fetchMock.mock.calls[0];
const requestBody = JSON.parse(lastCall[1].body as string);
expect(requestBody.expires).toEqual(expiresAt);
});
it('logs warning when creating token with secret scopes', async () => {
const mockResponse = {
token: 'sk.eyJ1IjoidGVzdHVzZXIiLCJhIjoiY2xwMTIzNDU2In0.secret',
note: 'Secret token',
id: 'cksecret123',
scopes: ['tokens:write', 'styles:write'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z'
};
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
} as Response);
const result = await tool.run({
note: 'Secret token',
scopes: ['tokens:write', 'styles:write']
});
expect(result.isError).toBe(false);
// Verify the warning was logged
expect(tool['log']).toHaveBeenCalledWith(
'info',
'CreateTokenTool: Creating a SECRET token due to secret scopes. This token will only be visible once upon creation.'
);
});
it('handles API errors gracefully', async () => {
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: false,
status: 401,
statusText: 'Unauthorized',
text: async () =>
'{"message": "Token does not have required scopes", "code": "TokenScopesInvalid"}'
} as Response);
const result = await tool.run({
note: 'Test token',
scopes: ['tokens:write']
});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain('Failed to create token: 401');
});
it('handles network errors', async () => {
const fetchMock = setupFetch();
fetchMock.mockRejectedValueOnce(new Error('Network error'));
const result = await tool.run({
note: 'Test token',
scopes: ['styles:read']
});
expect(result.isError).toBe(true);
expect(result.content[0]).toHaveProperty('type', 'text');
const errorText = (result.content[0] as TextContent).text;
expect(errorText).toContain('Network error');
});
it('uses custom API endpoint when provided', async () => {
const originalEndpoint = MapboxApiBasedTool.MAPBOX_API_ENDPOINT;
try {
// Temporarily modify the static property
Object.defineProperty(MapboxApiBasedTool, 'MAPBOX_API_ENDPOINT', {
value: 'https://api.staging.mapbox.com/',
writable: true,
configurable: true
});
const toolWithCustomEndpoint = new CreateTokenTool();
toolWithCustomEndpoint['log'] = jest.fn();
const mockResponse = {
token: 'pk.test',
note: 'Test token',
id: 'cktest',
scopes: ['styles:read'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z'
};
const fetchMock = setupFetch();
fetchMock.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
} as Response);
await toolWithCustomEndpoint.run({
note: 'Test token',
scopes: ['styles:read']
});
expect(fetchMock).toHaveBeenCalledWith(
expect.stringContaining('https://api.staging.mapbox.com/tokens/v2/'),
expect.any(Object)
);
} finally {
// Restore
Object.defineProperty(MapboxApiBasedTool, 'MAPBOX_API_ENDPOINT', {
value: originalEndpoint,
writable: true,
configurable: true
});
}
});
});
});