-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCreateTokenTool.test.ts
More file actions
406 lines (340 loc) · 12.9 KB
/
Copy pathCreateTokenTool.test.ts
File metadata and controls
406 lines (340 loc) · 12.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright (c) Mapbox, Inc.
// Licensed under the MIT License.
import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest';
import {
setupHttpRequest,
assertHeadersSent
} from '../../utils/httpPipelineUtils.js';
import { MapboxApiBasedTool } from '../../../src/tools/MapboxApiBasedTool.js';
import { CreateTokenTool } from '../../../src/tools/create-token-tool/CreateTokenTool.js';
import { HttpRequest } from 'src/utils/types.js';
// Create a token with username in the payload
const payload = Buffer.from(JSON.stringify({ u: 'testuser' })).toString(
'base64'
);
const mockToken = `eyJhbGciOiJIUzI1NiJ9.${payload}.signature`;
beforeAll(() => {
process.env.MAPBOX_ACCESS_TOKEN = mockToken;
});
type TextContent = { type: 'text'; text: string };
describe('CreateTokenTool', () => {
afterEach(() => {
vi.clearAllMocks();
});
function createTokenTool(httpRequest: HttpRequest) {
const instance = new CreateTokenTool({ httpRequest });
instance['log'] = vi.fn();
return instance;
}
describe('tool metadata', () => {
it('should have correct name and description', () => {
const { httpRequest } = setupHttpRequest();
const tool = createTokenTool(httpRequest);
expect(tool.name).toBe('create_token_tool');
expect(tool.description).toBe(
'Create a new Mapbox public access token with specified scopes and optional URL restrictions.'
);
});
it('should have correct input schema', async () => {
const { CreateTokenSchema } = await import(
'../../../src/tools/create-token-tool/CreateTokenTool.input.schema.js'
);
expect(CreateTokenSchema).toBeDefined();
});
});
describe('validation', () => {
it('validates required input fields', async () => {
const { httpRequest } = setupHttpRequest();
const tool = createTokenTool(httpRequest);
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('invalid_type');
});
it('validates allowedUrls array length', async () => {
const { httpRequest } = setupHttpRequest();
const tool = createTokenTool(httpRequest);
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 { httpRequest } = setupHttpRequest();
const tool = createTokenTool(httpRequest);
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_value');
});
it('throws error when unable to extract username from token', async () => {
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`;
vi.stubEnv('MAPBOX_ACCESS_TOKEN', invalidToken);
// Setup fetch mock to prevent actual API calls
const { httpRequest } = setupHttpRequest({
ok: true,
status: 200,
statusText: 'OK',
headers: new Headers(),
json: async () => ({ token: 'test-token' })
} as Response);
const toolWithInvalidToken = new CreateTokenTool({ httpRequest });
toolWithInvalidToken['log'] = vi.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
vi.unstubAllEnvs();
if (originalEnvToken) {
vi.stubEnv('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',
usage: 'pk',
client: 'api',
default: false
};
const { httpRequest, mockHttpRequest } = setupHttpRequest({
ok: true,
json: async () => mockResponse
} as Response);
const tool = createTokenTool(httpRequest);
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(mockHttpRequest).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(mockHttpRequest);
});
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'],
usage: 'pk',
client: 'api',
default: false
};
const { httpRequest, mockHttpRequest } = setupHttpRequest({
ok: true,
json: async () => mockResponse
} as Response);
const tool = createTokenTool(httpRequest);
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 = mockHttpRequest.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 token with expiration', async () => {
const expiresAt = '2024-12-31T23:59:59.000Z';
const mockResponse = {
token: 'pk.eyJ1IjoidGVzdHVzZXIiLCJhIjoiY2xwMTIzNDU2In0.test',
note: 'Token with expiration',
id: 'cktest789',
scopes: ['styles:read'],
created: '2024-01-01T00:00:00.000Z',
modified: '2024-01-01T00:00:00.000Z',
expires: expiresAt,
usage: 'pk',
client: 'api',
default: false
};
const { mockHttpRequest, httpRequest } = setupHttpRequest({
ok: true,
json: async () => mockResponse
} as Response);
const tool = createTokenTool(httpRequest);
const result = await tool.run({
note: 'Token with expiration',
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 = mockHttpRequest.mock.calls[0];
const requestBody = JSON.parse(lastCall[1].body as string);
expect(requestBody.expires).toEqual(expiresAt);
});
it('handles API errors gracefully', async () => {
const { httpRequest } = setupHttpRequest({
ok: false,
status: 401,
statusText: 'Unauthorized',
text: async () =>
'{"message": "Token does not have required scopes", "code": "TokenScopesInvalid"}'
} as Response);
const tool = createTokenTool(httpRequest);
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('Failed to create token: 401');
});
it('handles network errors', async () => {
const { httpRequest } = setupHttpRequest({
ok: false,
status: 0,
statusText: 'Network Error',
text: async () => 'Network error'
});
const tool = createTokenTool(httpRequest);
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.mapboxApiEndpoint;
try {
// Temporarily modify the static property
vi.stubEnv('MAPBOX_API_ENDPOINT', 'https://api.staging.mapbox.com/');
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',
usage: 'pk',
client: 'api',
default: false
};
const { mockHttpRequest, httpRequest } = setupHttpRequest({
ok: true,
json: async () => mockResponse
} as Response);
const toolWithCustomEndpoint = new CreateTokenTool({ httpRequest });
toolWithCustomEndpoint['log'] = vi.fn();
await toolWithCustomEndpoint.run({
note: 'Test token',
scopes: ['styles:read']
});
expect(mockHttpRequest).toHaveBeenCalledWith(
expect.stringContaining('https://api.staging.mapbox.com/tokens/v2/'),
expect.any(Object)
);
} finally {
// Restore
vi.unstubAllEnvs();
if (originalEndpoint) {
vi.stubEnv('MAPBOX_API_ENDPOINT', originalEndpoint);
}
}
});
it('handles schema validation failures gracefully and logs warning', async () => {
// API response that doesn't match schema (missing required fields)
const invalidMockResponse = {
token: 'pk.test',
note: 'Test token',
// Missing required fields like 'id', 'created', 'modified', etc.
unexpectedField: 'some value'
};
const { httpRequest } = setupHttpRequest({
ok: true,
json: async () => invalidMockResponse
} as Response);
const tool = createTokenTool(httpRequest);
const logSpy = vi.spyOn(tool as any, 'log');
const result = await tool.run({
note: 'Test token',
scopes: ['styles:read']
});
// Should not error - graceful fallback to raw data
expect(result.isError).toBe(false);
expect(result.content[0]).toHaveProperty('type', 'text');
// Should log a warning about validation failure
expect(logSpy).toHaveBeenCalledWith(
'warning',
expect.stringContaining(
'CreateTokenTool: Output schema validation failed'
)
);
// Should return the raw data despite validation failure
const responseData = JSON.parse((result.content[0] as TextContent).text);
expect(responseData).toEqual(invalidMockResponse);
expect(responseData).toHaveProperty('unexpectedField');
});
});
});