forked from misskey-dev/misskey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.ts
966 lines (813 loc) Β· 30.7 KB
/
oauth.ts
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
/**
* Basic OAuth tests to make sure the library is correctly integrated to Misskey
* and not regressed by version updates or potential migration to another library.
*/
process.env.NODE_ENV = 'test';
import * as assert from 'assert';
import {
AuthorizationCode,
type AuthorizationTokenConfig,
ClientCredentials,
ModuleOptions,
ResourceOwnerPassword,
} from 'simple-oauth2';
import pkceChallenge from 'pkce-challenge';
import { JSDOM } from 'jsdom';
import Fastify, { type FastifyInstance, type FastifyReply } from 'fastify';
import { api, port, sendEnvUpdateRequest, signup } from '../utils.js';
import type * as misskey from 'misskey-js';
const host = `http://127.0.0.1:${port}`;
const clientPort = port + 1;
const redirect_uri = `http://127.0.0.1:${clientPort}/redirect`;
const basicAuthParams: AuthorizationParamsExtended = {
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
};
interface AuthorizationParamsExtended {
redirect_uri: string;
scope: string | string[];
state: string;
code_challenge?: string;
code_challenge_method?: string;
}
interface AuthorizationTokenConfigExtended extends AuthorizationTokenConfig {
code_verifier: string | undefined;
}
interface GetTokenError {
data: {
payload: {
error: string;
}
}
}
const clientConfig: ModuleOptions<'client_id'> = {
client: {
id: `http://127.0.0.1:${clientPort}/`,
secret: '',
},
auth: {
tokenHost: host,
tokenPath: '/oauth/token',
authorizePath: '/oauth/authorize',
},
options: {
authorizationMethod: 'body',
},
};
function getMeta(html: string): { transactionId: string | undefined, clientName: string | undefined } {
const fragment = JSDOM.fragment(html);
return {
transactionId: fragment.querySelector<HTMLMetaElement>('meta[name="misskey:oauth:transaction-id"]')?.content,
clientName: fragment.querySelector<HTMLMetaElement>('meta[name="misskey:oauth:client-name"]')?.content,
};
}
function fetchDecision(transactionId: string, user: misskey.entities.SignupResponse, { cancel }: { cancel?: boolean } = {}): Promise<Response> {
return fetch(new URL('/oauth/decision', host), {
method: 'post',
body: new URLSearchParams({
transaction_id: transactionId,
login_token: user.token,
cancel: cancel ? 'cancel' : '',
}),
redirect: 'manual',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
}
async function fetchDecisionFromResponse(response: Response, user: misskey.entities.SignupResponse, { cancel }: { cancel?: boolean } = {}): Promise<Response> {
const { transactionId } = getMeta(await response.text());
assert.ok(transactionId);
return await fetchDecision(transactionId, user, { cancel });
}
async function fetchAuthorizationCode(user: misskey.entities.SignupResponse, scope: string, code_challenge: string): Promise<{ client: AuthorizationCode, code: string }> {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope,
state: 'state',
code_challenge,
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
const decisionResponse = await fetchDecisionFromResponse(response, user);
assert.strictEqual(decisionResponse.status, 302);
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
assert.ok(location.searchParams.has('code'));
const code = new URL(location).searchParams.get('code');
assert.ok(code);
return { client, code };
}
function assertIndirectError(response: Response, error: string): void {
assert.strictEqual(response.status, 302);
const locationHeader = response.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
assert.strictEqual(location.searchParams.get('error'), error);
// https://datatracker.ietf.org/doc/html/rfc9207#name-response-parameter-iss
assert.strictEqual(location.searchParams.get('iss'), 'http://misskey.local');
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-4.1.2.1
assert.ok(location.searchParams.has('state'));
}
async function assertDirectError(response: Response, status: number, error: string): Promise<void> {
assert.strictEqual(response.status, status);
const data = await response.json();
assert.strictEqual(data.error, error);
}
describe('OAuth', () => {
let fastify: FastifyInstance;
let alice: misskey.entities.SignupResponse;
let bob: misskey.entities.SignupResponse;
let sender: (reply: FastifyReply) => void;
beforeAll(async () => {
alice = await signup({ username: 'alice' });
bob = await signup({ username: 'bob' });
fastify = Fastify();
fastify.get('/', async (request, reply) => {
sender(reply);
});
await fastify.listen({ port: clientPort });
}, 1000 * 60 * 2);
beforeEach(async () => {
await sendEnvUpdateRequest({ key: 'MISSKEY_TEST_CHECK_IP_RANGE', value: '' });
sender = (reply): void => {
reply.send(`
<!DOCTYPE html>
<link rel="redirect_uri" href="/redirect" />
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
};
});
afterAll(async () => {
await fastify.close();
});
test('Full flow', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge,
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
const meta = getMeta(await response.text());
assert.strictEqual(typeof meta.transactionId, 'string');
assert.ok(meta.transactionId);
assert.strictEqual(meta.clientName, 'Misklient');
const decisionResponse = await fetchDecision(meta.transactionId, alice);
assert.strictEqual(decisionResponse.status, 302);
assert.ok(decisionResponse.headers.has('location'));
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
assert.strictEqual(location.origin + location.pathname, redirect_uri);
assert.ok(location.searchParams.has('code'));
assert.strictEqual(location.searchParams.get('state'), 'state');
// https://datatracker.ietf.org/doc/html/rfc9207#name-response-parameter-iss
assert.strictEqual(location.searchParams.get('iss'), 'http://misskey.local');
const code = new URL(location).searchParams.get('code');
assert.ok(code);
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
assert.strictEqual(typeof token.token.access_token, 'string');
assert.strictEqual(token.token.token_type, 'Bearer');
assert.strictEqual(token.token.scope, 'write:notes');
const createResult = await api('notes/create', { text: 'test' }, {
token: token.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResult.status, 200);
const createResultBody = createResult.body as misskey.Endpoints['notes/create']['res'];
assert.strictEqual(createResultBody.createdNote.text, 'test');
});
test('Two concurrent flows', async () => {
const client = new AuthorizationCode(clientConfig);
const pkceAlice = await pkceChallenge(128);
const pkceBob = await pkceChallenge(128);
const responseAlice = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: pkceAlice.code_challenge,
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(responseAlice.status, 200);
const responseBob = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: pkceBob.code_challenge,
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(responseBob.status, 200);
const decisionResponseAlice = await fetchDecisionFromResponse(responseAlice, alice);
assert.strictEqual(decisionResponseAlice.status, 302);
const decisionResponseBob = await fetchDecisionFromResponse(responseBob, bob);
assert.strictEqual(decisionResponseBob.status, 302);
const locationHeaderAlice = decisionResponseAlice.headers.get('location');
assert.ok(locationHeaderAlice);
const locationAlice = new URL(locationHeaderAlice);
const locationHeaderBob = decisionResponseBob.headers.get('location');
assert.ok(locationHeaderBob);
const locationBob = new URL(locationHeaderBob);
const codeAlice = locationAlice.searchParams.get('code');
assert.ok(codeAlice);
const codeBob = locationBob.searchParams.get('code');
assert.ok(codeBob);
const tokenAlice = await client.getToken({
code: codeAlice,
redirect_uri,
code_verifier: pkceAlice.code_verifier,
} as AuthorizationTokenConfigExtended);
const tokenBob = await client.getToken({
code: codeBob,
redirect_uri,
code_verifier: pkceBob.code_verifier,
} as AuthorizationTokenConfigExtended);
const createResultAlice = await api('notes/create', { text: 'test' }, {
token: tokenAlice.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResultAlice.status, 200);
const createResultBob = await api('notes/create', { text: 'test' }, {
token: tokenBob.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResultAlice.status, 200);
const createResultBodyAlice = await createResultAlice.body as misskey.Endpoints['notes/create']['res'];
assert.strictEqual(createResultBodyAlice.createdNote.user.username, 'alice');
const createResultBodyBob = await createResultBob.body as misskey.Endpoints['notes/create']['res'];
assert.strictEqual(createResultBodyBob.createdNote.user.username, 'bob');
});
// https://datatracker.ietf.org/doc/html/rfc7636.html
describe('PKCE', () => {
// https://datatracker.ietf.org/doc/html/rfc7636.html#section-4.4.1
// '... the authorization endpoint MUST return the authorization
// error response with the "error" value set to "invalid_request".'
test('Require PKCE', async () => {
const client = new AuthorizationCode(clientConfig);
// Pattern 1: No PKCE fields at all
let response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
}), { redirect: 'manual' });
assertIndirectError(response, 'invalid_request');
// Pattern 2: Only code_challenge
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_request');
// Pattern 3: Only code_challenge_method
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_request');
// Pattern 4: Unsupported code_challenge_method
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'SSSS',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_request');
});
// Use precomputed challenge/verifier set here for deterministic test
const code_challenge = '4w2GDuvaxXlw2l46k5PFIoIcTGHdzw2i3hrn-C_Q6f7u0-nTYKd-beVEYy9XinYsGtAix.Nnvr.GByD3lAii2ibPRsSDrZgIN0YQb.kfevcfR9aDKoTLyOUm4hW4ABhs';
const code_verifier = 'Ew8VSBiH59JirLlg7ocFpLQ6NXuFC1W_rn8gmRzBKc8';
const tests: Record<string, string | undefined> = {
'Code followed by some junk code': code_verifier + 'x',
'Clipped code': code_verifier.slice(0, 80),
'Some part of code is replaced': code_verifier.slice(0, -10) + 'x'.repeat(10),
'No verifier': undefined,
};
describe('Verify PKCE', () => {
for (const [title, wrong_verifier] of Object.entries(tests)) {
test(title, async () => {
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await assert.rejects(client.getToken({
code,
redirect_uri,
code_verifier: wrong_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
}
});
});
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-4.1.2
// "If an authorization code is used more than once, the authorization server
// MUST deny the request and SHOULD revoke (when possible) all tokens
// previously issued based on that authorization code."
describe('Revoking authorization code', () => {
test('On success', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
await assert.rejects(client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
test('On failure', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await assert.rejects(client.getToken({ code, redirect_uri }), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
await assert.rejects(client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
test('Revoke the already granted access token', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
const createResult = await api('notes/create', { text: 'test' }, {
token: token.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResult.status, 200);
await assert.rejects(client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
const createResult2 = await api('notes/create', { text: 'test' }, {
token: token.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResult2.status, 401);
});
});
test('Cancellation', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
const decisionResponse = await fetchDecisionFromResponse(response, alice, { cancel: true });
assert.strictEqual(decisionResponse.status, 302);
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
assert.ok(!location.searchParams.has('code'));
assert.ok(location.searchParams.has('error'));
});
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-3.3
describe('Scope', () => {
// "If the client omits the scope parameter when requesting
// authorization, the authorization server MUST either process the
// request using a pre-defined default value or fail the request
// indicating an invalid scope."
// (And Misskey does the latter)
test('Missing scope', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_scope');
});
test('Empty scope', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: '',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_scope');
});
test('Unknown scopes', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'test:unknown test:unknown2',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended), { redirect: 'manual' });
assertIndirectError(response, 'invalid_scope');
});
// "If the issued access token scope
// is different from the one requested by the client, the authorization
// server MUST include the "scope" response parameter to inform the
// client of the actual scope granted."
// (Although Misskey always return scope, which is also fine)
test('Partially known scopes', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
// Just get the known scope for this case for backward compatibility
const { client, code } = await fetchAuthorizationCode(
alice,
'write:notes test:unknown test:unknown2',
code_challenge,
);
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
assert.strictEqual(token.token.scope, 'write:notes');
});
test('Known scopes', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes read:account',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
});
test('Duplicated scopes', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(
alice,
'write:notes write:notes read:account read:account',
code_challenge,
);
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
assert.strictEqual(token.token.scope, 'write:notes read:account');
});
test('Scope check by API', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'read:account', code_challenge);
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended);
assert.strictEqual(typeof token.token.access_token, 'string');
const createResult = await api('notes/create', { text: 'test' }, {
token: token.token.access_token as string,
bearer: true,
});
assert.strictEqual(createResult.status, 403);
assert.ok(createResult.headers.get('WWW-Authenticate')?.startsWith('Bearer realm="Misskey", error="insufficient_scope", error_description'));
});
});
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-3.1.2.4
// "If an authorization request fails validation due to a missing,
// invalid, or mismatching redirection URI, the authorization server
// SHOULD inform the resource owner of the error and MUST NOT
// automatically redirect the user-agent to the invalid redirection URI."
describe('Redirection', () => {
test('Invalid redirect_uri at authorization endpoint', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri: 'http://127.0.0.2/',
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
await assertDirectError(response, 400, 'invalid_request');
});
test('Invalid redirect_uri including the valid one at authorization endpoint', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri: 'http://127.0.0.1/redirection',
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
await assertDirectError(response, 400, 'invalid_request');
});
test('No redirect_uri at authorization endpoint', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
await assertDirectError(response, 400, 'invalid_request');
});
test('Invalid redirect_uri at token endpoint', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await assert.rejects(client.getToken({
code,
redirect_uri: 'http://127.0.0.2/',
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
test('Invalid redirect_uri including the valid one at token endpoint', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await assert.rejects(client.getToken({
code,
redirect_uri: 'http://127.0.0.1/redirection',
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
test('No redirect_uri at token endpoint', async () => {
const { code_challenge, code_verifier } = await pkceChallenge(128);
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
await assert.rejects(client.getToken({
code,
code_verifier,
} as AuthorizationTokenConfigExtended), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'invalid_grant');
return true;
});
});
});
// https://datatracker.ietf.org/doc/html/rfc8414
test('Server metadata', async () => {
const response = await fetch(new URL('.well-known/oauth-authorization-server', host));
assert.strictEqual(response.status, 200);
const body = await response.json();
assert.strictEqual(body.issuer, 'http://misskey.local');
assert.ok(body.scopes_supported.includes('write:notes'));
});
// Any error on decision endpoint is solely on Misskey side and nothing to do with the client.
// Do not use indirect error here.
describe('Decision endpoint', () => {
test('No login token', async () => {
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL(basicAuthParams));
assert.strictEqual(response.status, 200);
const { transactionId } = getMeta(await response.text());
assert.ok(transactionId);
const decisionResponse = await fetch(new URL('/oauth/decision', host), {
method: 'post',
body: new URLSearchParams({
transaction_id: transactionId,
}),
redirect: 'manual',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
await assertDirectError(decisionResponse, 400, 'invalid_request');
});
test('No transaction ID', async () => {
const decisionResponse = await fetch(new URL('/oauth/decision', host), {
method: 'post',
body: new URLSearchParams({
login_token: alice.token,
}),
redirect: 'manual',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
await assertDirectError(decisionResponse, 400, 'invalid_request');
});
test('Invalid transaction ID', async () => {
const decisionResponse = await fetch(new URL('/oauth/decision', host), {
method: 'post',
body: new URLSearchParams({
login_token: alice.token,
transaction_id: 'invalid_id',
}),
redirect: 'manual',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
await assertDirectError(decisionResponse, 403, 'access_denied');
});
});
// Only authorization code grant is supported
describe('Grant type', () => {
test('Implicit grant is not supported', async () => {
const url = new URL('/oauth/authorize', host);
url.searchParams.append('response_type', 'token');
const response = await fetch(url);
assertDirectError(response, 501, 'unsupported_response_type');
});
test('Resource owner grant is not supported', async () => {
const client = new ResourceOwnerPassword({
...clientConfig,
auth: {
tokenHost: host,
tokenPath: '/oauth/token',
},
});
await assert.rejects(client.getToken({
username: 'alice',
password: 'test',
}), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'unsupported_grant_type');
return true;
});
});
test('Client credential grant is not supported', async () => {
const client = new ClientCredentials({
...clientConfig,
auth: {
tokenHost: host,
tokenPath: '/oauth/token',
},
});
await assert.rejects(client.getToken({}), (err: GetTokenError) => {
assert.strictEqual(err.data.payload.error, 'unsupported_grant_type');
return true;
});
});
});
// https://indieauth.spec.indieweb.org/#client-information-discovery
describe('Client Information Discovery', () => {
describe('Redirection', () => {
const tests: Record<string, (reply: FastifyReply) => void> = {
'Read HTTP header': reply => {
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send(`
<!DOCTYPE html>
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
},
'Mixed links': reply => {
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send(`
<!DOCTYPE html>
<link rel="redirect_uri" href="/redirect2" />
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
},
'Multiple items in Link header': reply => {
reply.header('Link', '</redirect2>; rel="redirect_uri",</redirect>; rel="redirect_uri"');
reply.send(`
<!DOCTYPE html>
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
},
'Multiple items in HTML': reply => {
reply.send(`
<!DOCTYPE html>
<link rel="redirect_uri" href="/redirect2" />
<link rel="redirect_uri" href="/redirect" />
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
},
};
for (const [title, replyFunc] of Object.entries(tests)) {
test(title, async () => {
sender = replyFunc;
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
});
}
test('No item', async () => {
sender = (reply): void => {
reply.send(`
<!DOCTYPE html>
<div class="h-app"><a href="/" class="u-url p-name">Misklient
`);
};
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
// direct error because there's no redirect URI to ping
await assertDirectError(response, 400, 'invalid_request');
});
});
test('Disallow loopback', async () => {
await sendEnvUpdateRequest({ key: 'MISSKEY_TEST_CHECK_IP_RANGE', value: '1' });
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
await assertDirectError(response, 400, 'invalid_request');
});
test('Missing name', async () => {
sender = (reply): void => {
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send();
};
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
assert.strictEqual(getMeta(await response.text()).clientName, `http://127.0.0.1:${clientPort}/`);
});
test('Mismatching URL in h-app', async () => {
sender = (reply): void => {
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send(`
<!DOCTYPE html>
<div class="h-app"><a href="/foo" class="u-url p-name">Misklient
`);
reply.send();
};
const client = new AuthorizationCode(clientConfig);
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
} as AuthorizationParamsExtended));
assert.strictEqual(response.status, 200);
assert.strictEqual(getMeta(await response.text()).clientName, `http://127.0.0.1:${clientPort}/`);
});
});
test('Unknown OAuth endpoint', async () => {
const response = await fetch(new URL('/oauth/foo', host));
assert.strictEqual(response.status, 404);
});
describe('CORS', () => {
test('Token endpoint should support CORS', async () => {
const response = await fetch(new URL('/oauth/token', host), { method: 'POST' });
assert.ok(!response.ok);
assert.strictEqual(response.headers.get('Access-Control-Allow-Origin'), '*');
});
test('Authorize endpoint should not support CORS', async () => {
const response = await fetch(new URL('/oauth/authorize', host), { method: 'GET' });
assert.ok(!response.ok);
assert.ok(!response.headers.has('Access-Control-Allow-Origin'));
});
test('Decision endpoint should not support CORS', async () => {
const response = await fetch(new URL('/oauth/decision', host), { method: 'POST' });
assert.ok(!response.ok);
assert.ok(!response.headers.has('Access-Control-Allow-Origin'));
});
});
});