Sharkey/packages/backend/test/e2e/oauth.ts

877 lines
28 KiB
TypeScript
Raw Normal View History

2023-06-04 14:30:18 +03:00
/**
* 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.
*/
2023-04-02 22:59:38 +03:00
process.env.NODE_ENV = 'test';
import * as assert from 'assert';
2023-04-16 17:03:14 +03:00
import { AuthorizationCode, type AuthorizationTokenConfig } from 'simple-oauth2';
2023-04-02 22:59:38 +03:00
import pkceChallenge from 'pkce-challenge';
import { JSDOM } from 'jsdom';
2023-04-10 21:29:11 +03:00
import * as misskey from 'misskey-js';
2023-06-04 15:50:30 +03:00
import Fastify, { type FastifyReply, type FastifyInstance } from 'fastify';
2023-04-10 15:49:18 +03:00
import { port, relativeFetch, signup, startServer } from '../utils.js';
import type { INestApplicationContext } from '@nestjs/common';
2023-04-02 22:59:38 +03:00
2023-04-10 11:17:41 +03:00
const host = `http://127.0.0.1:${port}`;
2023-04-03 23:32:12 +03:00
const clientPort = port + 1;
const redirect_uri = `http://127.0.0.1:${clientPort}/redirect`;
2023-06-04 18:37:38 +03:00
const basicAuthParams: AuthorizationParamsExtended = {
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
};
2023-04-16 17:03:14 +03:00
interface AuthorizationParamsExtended {
redirect_uri: string;
scope: string | string[];
state: string;
code_challenge?: string;
code_challenge_method?: string;
}
interface AuthorizationTokenConfigExtended extends AuthorizationTokenConfig {
2023-06-04 14:30:18 +03:00
code_verifier: string | undefined;
2023-04-16 17:03:14 +03:00
}
2023-04-03 23:32:12 +03:00
function getClient(): AuthorizationCode<'client_id'> {
return new AuthorizationCode({
client: {
id: `http://127.0.0.1:${clientPort}/`,
2023-05-12 00:09:24 +03:00
secret: '',
2023-04-03 23:32:12 +03:00
},
auth: {
2023-04-10 11:17:41 +03:00
tokenHost: host,
2023-04-03 23:32:12 +03:00
tokenPath: '/oauth/token',
authorizePath: '/oauth/authorize',
},
options: {
authorizationMethod: 'body',
},
});
}
2023-04-10 18:48:45 +03:00
function getMeta(html: string): { transactionId: string | undefined, clientName: string | undefined } {
2023-04-03 23:32:12 +03:00
const fragment = JSDOM.fragment(html);
2023-04-10 15:49:18 +03:00
return {
transactionId: fragment.querySelector<HTMLMetaElement>('meta[name="misskey:oauth:transaction-id"]')?.content,
clientName: fragment.querySelector<HTMLMetaElement>('meta[name="misskey:oauth:client-name"]')?.content,
};
2023-04-03 23:32:12 +03:00
}
2023-06-04 01:16:51 +03:00
function fetchDecision(transactionId: string, user: misskey.entities.MeSignup, { cancel }: { cancel?: boolean } = {}): Promise<Response> {
2023-04-10 11:17:41 +03:00
return fetch(new URL('/oauth/decision', host), {
2023-04-03 23:32:12 +03:00
method: 'post',
body: new URLSearchParams({
2023-06-04 15:20:52 +03:00
transaction_id: transactionId,
2023-04-03 23:32:12 +03:00
login_token: user.token,
cancel: cancel ? 'cancel' : '',
}),
redirect: 'manual',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
});
}
2023-04-10 21:29:11 +03:00
async function fetchDecisionFromResponse(response: Response, user: misskey.entities.MeSignup, { cancel }: { cancel?: boolean } = {}): Promise<Response> {
2023-04-10 15:49:18 +03:00
const { transactionId } = getMeta(await response.text());
2023-06-04 15:20:52 +03:00
assert.ok(transactionId);
2023-04-03 23:32:12 +03:00
2023-06-04 15:20:52 +03:00
return await fetchDecision(transactionId, user, { cancel });
2023-04-03 23:32:12 +03:00
}
2023-06-04 15:50:30 +03:00
async function fetchAuthorizationCode(user: misskey.entities.MeSignup, scope: string, code_challenge: string): Promise<{ client: AuthorizationCode, code: string }> {
2023-06-04 15:13:55 +03:00
const client = getClient();
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);
2023-06-04 15:20:52 +03:00
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
2023-06-04 15:13:55 +03:00
assert.ok(location.searchParams.has('code'));
2023-06-04 15:20:52 +03:00
const code = new URL(location).searchParams.get('code');
assert.ok(code);
2023-06-04 15:13:55 +03:00
return { client, code };
}
2023-06-11 21:58:28 +03:00
function assertIndirectError(response: Response, error: string): void {
assert.strictEqual(response.status, 302);
2023-06-13 23:55:23 +03:00
const locationHeader = response.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
assert.strictEqual(location.searchParams.get('error'), error);
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc9207#name-response-parameter-iss
2023-06-13 23:55:23 +03:00
assert.strictEqual(location.searchParams.get('iss'), 'http://misskey.local');
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-4.1.2.1
2023-06-13 23:55:23 +03:00
assert.ok(location.searchParams.has('state'));
2023-06-11 21:58:28 +03:00
}
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);
2023-06-11 21:58:28 +03:00
}
2023-04-02 22:59:38 +03:00
describe('OAuth', () => {
let app: INestApplicationContext;
2023-04-10 15:49:18 +03:00
let fastify: FastifyInstance;
2023-04-02 22:59:38 +03:00
2023-04-10 21:29:11 +03:00
let alice: misskey.entities.MeSignup;
let bob: misskey.entities.MeSignup;
2023-04-02 22:59:38 +03:00
beforeAll(async () => {
app = await startServer();
2023-04-10 18:48:45 +03:00
alice = await signup({ username: 'alice' });
2023-04-10 21:29:11 +03:00
bob = await signup({ username: 'bob' });
2023-04-10 18:48:45 +03:00
}, 1000 * 60 * 2);
beforeEach(async () => {
2023-06-14 01:22:39 +03:00
process.env.MISSKEY_TEST_CHECK_IP_RANGE = '';
2023-04-10 15:49:18 +03:00
fastify = Fastify();
fastify.get('/', async (request, reply) => {
reply.send(`
<!DOCTYPE html>
<link rel="redirect_uri" href="/redirect" />
<div class="h-app"><div class="p-name">Misklient
`);
});
2023-04-10 17:26:04 +03:00
await fastify.listen({ port: clientPort });
2023-04-10 18:48:45 +03:00
});
2023-04-02 22:59:38 +03:00
afterAll(async () => {
await app.close();
2023-04-10 18:48:45 +03:00
});
afterEach(async () => {
2023-04-10 15:49:18 +03:00
await fastify.close();
2023-04-02 22:59:38 +03:00
});
test('Full flow', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-02 22:59:38 +03:00
2023-04-03 23:32:12 +03:00
const client = getClient();
2023-04-02 22:59:38 +03:00
2023-04-03 23:32:12 +03:00
const response = await fetch(client.authorizeURL({
2023-04-02 22:59:38 +03:00
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge,
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-02 22:59:38 +03:00
assert.strictEqual(response.status, 200);
2023-04-10 15:49:18 +03:00
const meta = getMeta(await response.text());
assert.strictEqual(typeof meta.transactionId, 'string');
2023-06-04 15:20:52 +03:00
assert.ok(meta.transactionId);
2023-04-10 18:48:45 +03:00
assert.strictEqual(meta.clientName, 'Misklient');
2023-04-02 22:59:38 +03:00
2023-06-04 15:20:52 +03:00
const decisionResponse = await fetchDecision(meta.transactionId, alice);
2023-04-02 22:59:38 +03:00
assert.strictEqual(decisionResponse.status, 302);
assert.ok(decisionResponse.headers.has('location'));
2023-06-04 15:20:52 +03:00
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
2023-04-02 22:59:38 +03:00
assert.strictEqual(location.origin + location.pathname, redirect_uri);
assert.ok(location.searchParams.has('code'));
assert.strictEqual(location.searchParams.get('state'), 'state');
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc9207#name-response-parameter-iss
assert.strictEqual(location.searchParams.get('iss'), 'http://misskey.local');
2023-04-02 22:59:38 +03:00
2023-06-04 15:20:52 +03:00
const code = new URL(location).searchParams.get('code');
assert.ok(code);
2023-04-02 22:59:38 +03:00
const token = await client.getToken({
2023-06-04 15:20:52 +03:00
code,
2023-04-02 22:59:38 +03:00
redirect_uri,
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-02 22:59:38 +03:00
assert.strictEqual(typeof token.token.access_token, 'string');
assert.strictEqual(token.token.token_type, 'Bearer');
2023-04-09 22:21:10 +03:00
assert.strictEqual(token.token.scope, 'write:notes');
2023-04-07 11:06:07 +03:00
const createResponse = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${token.token.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
assert.strictEqual(createResponse.status, 200);
const createResponseBody: any = await createResponse.json();
assert.strictEqual(createResponseBody.createdNote.text, 'test');
2023-04-02 22:59:38 +03:00
});
2023-04-03 23:32:12 +03:00
2023-04-10 21:29:11 +03:00
test('Two concurrent flows', async () => {
const client = getClient();
2023-05-12 00:09:24 +03:00
const pkceAlice = await pkceChallenge(128);
const pkceBob = await pkceChallenge(128);
2023-04-10 21:29:11 +03:00
const responseAlice = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: pkceAlice.code_challenge,
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-10 21:29:11 +03:00
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',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-10 21:29:11 +03:00
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 locationAlice = new URL(decisionResponseAlice.headers.get('location')!);
assert.ok(locationAlice.searchParams.has('code'));
const locationBob = new URL(decisionResponseBob.headers.get('location')!);
assert.ok(locationBob.searchParams.has('code'));
const tokenAlice = await client.getToken({
code: locationAlice.searchParams.get('code')!,
redirect_uri,
code_verifier: pkceAlice.code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-10 21:29:11 +03:00
const tokenBob = await client.getToken({
code: locationBob.searchParams.get('code')!,
redirect_uri,
code_verifier: pkceBob.code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-10 21:29:11 +03:00
const createResponseAlice = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${tokenAlice.token.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
assert.strictEqual(createResponseAlice.status, 200);
const createResponseBob = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${tokenBob.token.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
assert.strictEqual(createResponseAlice.status, 200);
const createResponseBodyAlice = await createResponseAlice.json() as { createdNote: misskey.entities.Note };
assert.strictEqual(createResponseBodyAlice.createdNote.user.username, 'alice');
const createResponseBodyBob = await createResponseBob.json() as { createdNote: misskey.entities.Note };
assert.strictEqual(createResponseBodyBob.createdNote.user.username, 'bob');
});
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc7636.html
2023-04-08 16:52:43 +03:00
describe('PKCE', () => {
2023-06-14 01:22:39 +03:00
// 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".'
2023-04-08 16:52:43 +03:00
test('Require PKCE', async () => {
const client = getClient();
2023-04-08 17:03:20 +03:00
// Pattern 1: No PKCE fields at all
2023-04-08 16:52:43 +03:00
let response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
2023-06-11 21:32:58 +03:00
}), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_request');
2023-04-08 16:52:43 +03:00
2023-04-08 17:03:20 +03:00
// Pattern 2: Only code_challenge
2023-04-08 16:52:43 +03:00
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_request');
2023-04-08 16:52:43 +03:00
2023-06-11 21:59:39 +03:00
// Pattern 3: Only code_challenge_method
2023-04-08 16:52:43 +03:00
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge_method: 'S256',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_request');
2023-04-08 16:52:43 +03:00
2023-06-11 21:59:39 +03:00
// Pattern 4: Unsupported code_challenge_method
2023-04-08 16:52:43 +03:00
response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'SSSS',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_request');
2023-04-08 16:52:43 +03:00
});
2023-04-03 23:32:12 +03:00
2023-06-04 14:30:18 +03:00
// 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', () => {
2023-06-05 23:14:55 +03:00
for (const [title, wrong_verifier] of Object.entries(tests)) {
2023-06-04 14:30:18 +03:00
test(title, async () => {
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
2023-06-04 14:30:18 +03:00
await assert.rejects(client.getToken({
code,
redirect_uri,
2023-06-05 23:14:55 +03:00
code_verifier: wrong_verifier,
2023-06-04 14:30:18 +03:00
} as AuthorizationTokenConfigExtended));
});
}
2023-04-08 16:52:43 +03:00
});
2023-04-03 23:32:12 +03:00
});
2023-06-05 23:14:55 +03:00
// 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));
});
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 }));
await assert.rejects(client.getToken({
code,
redirect_uri,
code_verifier,
} as AuthorizationTokenConfigExtended));
});
});
2023-04-03 23:32:12 +03:00
test('Cancellation', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-03 23:32:12 +03:00
assert.strictEqual(response.status, 200);
const decisionResponse = await fetchDecisionFromResponse(response, alice, { cancel: true });
2023-04-08 16:52:43 +03:00
assert.strictEqual(decisionResponse.status, 302);
2023-06-11 21:32:58 +03:00
const locationHeader = decisionResponse.headers.get('location');
assert.ok(locationHeader);
const location = new URL(locationHeader);
2023-04-03 23:32:12 +03:00
assert.ok(!location.searchParams.has('code'));
assert.ok(location.searchParams.has('error'));
});
2023-04-05 21:47:12 +03:00
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc6749.html#section-3.3
2023-04-08 21:31:18 +03:00
describe('Scope', () => {
2023-06-14 01:22:39 +03:00
// "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)
2023-04-08 21:31:18 +03:00
test('Missing scope', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_scope');
2023-04-08 21:31:18 +03:00
});
2023-04-05 21:47:12 +03:00
2023-04-08 21:31:18 +03:00
test('Empty scope', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: '',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_scope');
2023-04-08 21:31:18 +03:00
});
test('Unknown scopes', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'test:unknown test:unknown2',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-06-11 21:32:58 +03:00
} as AuthorizationParamsExtended), { redirect: 'manual' });
2023-06-11 21:58:28 +03:00
assertIndirectError(response, 'invalid_scope');
2023-04-08 21:31:18 +03:00
});
2023-06-14 01:22:39 +03:00
// "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)
2023-04-08 21:31:18 +03:00
test('Partially known scopes', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 22:21:10 +03:00
2023-04-08 21:31:18 +03:00
// Just get the known scope for this case for backward compatibility
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(
alice,
'write:notes test:unknown test:unknown2',
code_challenge,
);
2023-04-09 22:21:10 +03:00
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-09 22:21:10 +03:00
assert.strictEqual(token.token.scope, 'write:notes');
2023-04-08 21:31:18 +03:00
});
test('Known scopes', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes read:account',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-08 21:31:18 +03:00
assert.strictEqual(response.status, 200);
});
2023-04-09 22:21:10 +03:00
test('Duplicated scopes', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 22:21:10 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(
alice,
'write:notes write:notes read:account read:account',
2023-04-09 22:21:10 +03:00
code_challenge,
2023-06-04 15:13:55 +03:00
);
2023-04-09 22:21:10 +03:00
const token = await client.getToken({
code,
redirect_uri,
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-09 22:21:10 +03:00
assert.strictEqual(token.token.scope, 'write:notes read:account');
});
test('Scope check by API', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 22:21:10 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'read:account', code_challenge);
2023-04-09 22:21:10 +03:00
const token = await client.getToken({
2023-06-04 15:13:55 +03:00
code,
2023-04-09 22:21:10 +03:00
redirect_uri,
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-09 22:21:10 +03:00
assert.strictEqual(typeof token.token.access_token, 'string');
const createResponse = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${token.token.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
2023-06-15 23:06:19 +03:00
assert.strictEqual(createResponse.status, 403);
2023-04-09 22:21:10 +03:00
});
2023-04-09 15:01:44 +03:00
});
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc6750.html
2023-04-09 15:01:44 +03:00
test('Authorization header', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 15:01:44 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
2023-04-09 15:01:44 +03:00
const token = await client.getToken({
2023-06-04 15:13:55 +03:00
code,
2023-04-09 15:01:44 +03:00
redirect_uri,
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended);
2023-04-09 15:01:44 +03:00
// Pattern 1: No preceding "Bearer "
let createResponse = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: token.token.access_token as string,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
assert.strictEqual(createResponse.status, 401);
// Pattern 2: Incorrect token
createResponse = await relativeFetch('api/notes/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${(token.token.access_token as string).slice(0, -1)}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ text: 'test' }),
});
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc6750.html#section-3.1
// "The access token provided is expired, revoked, malformed, or
// invalid for other reasons. The resource SHOULD respond with
// the HTTP 401 (Unauthorized) status code."
// (but it's SHOULD not MUST. 403 should be okay for now.)
2023-04-09 15:01:44 +03:00
assert.strictEqual(createResponse.status, 403);
2023-06-04 18:37:38 +03:00
// TODO: error code (wrong Authorization header should emit OAuth error instead of Misskey API error)
2023-04-08 21:31:18 +03:00
});
2023-06-14 01:22:39 +03:00
// 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."
2023-04-09 17:43:19 +03:00
describe('Redirection', () => {
test('Invalid redirect_uri at authorization endpoint', async () => {
const client = getClient();
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',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-06-11 21:58:28 +03:00
await assertDirectError(response, 400, 'invalid_request');
2023-04-09 17:43:19 +03:00
});
2023-04-10 15:49:18 +03:00
test('Invalid redirect_uri including the valid one at authorization endpoint', async () => {
const client = getClient();
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',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-06-11 21:58:28 +03:00
await assertDirectError(response, 400, 'invalid_request');
2023-04-10 15:49:18 +03:00
});
2023-04-09 19:49:58 +03:00
test('No redirect_uri at authorization endpoint', async () => {
const client = getClient();
const response = await fetch(client.authorizeURL({
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-06-11 21:58:28 +03:00
await assertDirectError(response, 400, 'invalid_request');
2023-04-09 19:49:58 +03:00
});
2023-04-09 17:43:19 +03:00
test('Invalid redirect_uri at token endpoint', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 17:43:19 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
2023-04-09 17:43:19 +03:00
await assert.rejects(client.getToken({
2023-06-04 15:13:55 +03:00
code,
2023-04-09 17:43:19 +03:00
redirect_uri: 'http://127.0.0.2/',
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended));
2023-04-09 17:43:19 +03:00
});
2023-04-10 15:49:18 +03:00
test('Invalid redirect_uri including the valid one at token endpoint', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-09 19:49:58 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
2023-04-09 19:49:58 +03:00
await assert.rejects(client.getToken({
2023-06-04 15:13:55 +03:00
code,
2023-04-10 15:49:18 +03:00
redirect_uri: 'http://127.0.0.1/redirection',
2023-04-09 19:49:58 +03:00
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended));
2023-04-09 19:49:58 +03:00
});
2023-04-10 15:49:18 +03:00
test('No redirect_uri at token endpoint', async () => {
2023-05-12 00:09:24 +03:00
const { code_challenge, code_verifier } = await pkceChallenge(128);
2023-04-10 15:49:18 +03:00
2023-06-04 15:13:55 +03:00
const { client, code } = await fetchAuthorizationCode(alice, 'write:notes', code_challenge);
2023-04-10 15:49:18 +03:00
await assert.rejects(client.getToken({
2023-06-04 15:13:55 +03:00
code,
2023-04-10 15:49:18 +03:00
code_verifier,
2023-04-16 17:03:14 +03:00
} as AuthorizationTokenConfigExtended));
2023-04-10 15:49:18 +03:00
});
2023-04-09 17:43:19 +03:00
});
2023-06-14 01:22:39 +03:00
// https://datatracker.ietf.org/doc/html/rfc8414
2023-04-10 11:17:41 +03:00
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'));
});
2023-04-05 21:47:12 +03:00
2023-06-11 21:58:28 +03:00
// Any error on decision endpoint is solely on Misskey side and nothing to do with the client.
// Do not use indirect error here.
2023-06-04 18:37:38 +03:00
describe('Decision endpoint', () => {
test('No login token', async () => {
const client = getClient();
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',
},
});
2023-06-11 21:58:28 +03:00
await assertDirectError(decisionResponse, 400, 'invalid_request');
2023-06-04 18:37:38 +03:00
});
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',
},
});
2023-06-11 21:58:28 +03:00
await assertDirectError(decisionResponse, 400, 'invalid_request');
2023-06-04 18:37:38 +03:00
});
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',
},
});
2023-06-11 21:58:28 +03:00
await assertDirectError(decisionResponse, 403, 'access_denied');
2023-06-04 18:37:38 +03:00
});
});
2023-06-14 01:22:39 +03:00
// https://indieauth.spec.indieweb.org/#client-information-discovery
2023-04-10 17:26:04 +03:00
describe('Client Information Discovery', () => {
2023-04-10 18:48:45 +03:00
describe('Redirection', () => {
2023-06-04 15:50:30 +03:00
const tests: Record<string, (reply: FastifyReply) => void> = {
'Read HTTP header': reply => {
2023-04-10 18:48:45 +03:00
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send(`
2023-06-04 15:50:30 +03:00
<!DOCTYPE html>
<div class="h-app"><div class="p-name">Misklient
`);
},
'Mixed links': reply => {
2023-04-10 18:48:45 +03:00
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send(`
2023-06-04 15:50:30 +03:00
<!DOCTYPE html>
<link rel="redirect_uri" href="/redirect2" />
<div class="h-app"><div class="p-name">Misklient
`);
},
'Multiple items in Link header': reply => {
2023-04-10 18:48:45 +03:00
reply.header('Link', '</redirect2>; rel="redirect_uri",</redirect>; rel="redirect_uri"');
reply.send(`
2023-06-04 15:50:30 +03:00
<!DOCTYPE html>
<div class="h-app"><div class="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"><div class="p-name">Misklient
`);
},
};
2023-04-10 17:26:04 +03:00
2023-06-04 15:50:30 +03:00
for (const [title, replyFunc] of Object.entries(tests)) {
test(title, async () => {
await fastify.close();
2023-04-10 17:26:04 +03:00
2023-06-04 15:50:30 +03:00
fastify = Fastify();
fastify.get('/', async (request, reply) => replyFunc(reply));
await fastify.listen({ port: clientPort });
const client = getClient();
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);
2023-04-10 18:48:45 +03:00
});
2023-06-04 15:50:30 +03:00
}
2023-04-10 17:26:04 +03:00
2023-04-10 18:48:45 +03:00
test('No item', async () => {
await fastify.close();
2023-04-10 17:26:04 +03:00
2023-04-10 18:48:45 +03:00
fastify = Fastify();
fastify.get('/', async (request, reply) => {
reply.send(`
<!DOCTYPE html>
<div class="h-app"><div class="p-name">Misklient
`);
});
await fastify.listen({ port: clientPort });
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-16 00:15:37 +03:00
2023-06-11 21:58:28 +03:00
// direct error because there's no redirect URI to ping
await assertDirectError(response, 400, 'invalid_request');
2023-04-10 18:48:45 +03:00
});
});
test('Disallow loopback', async () => {
2023-06-14 01:22:39 +03:00
process.env.MISSKEY_TEST_CHECK_IP_RANGE = '1';
2023-04-10 18:48:45 +03:00
const client = getClient();
2023-04-10 17:26:04 +03:00
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-06-11 21:58:28 +03:00
await assertDirectError(response, 400, 'invalid_request');
2023-04-10 17:26:04 +03:00
});
2023-04-10 18:48:45 +03:00
test('Missing name', async () => {
2023-04-10 17:26:04 +03:00
await fastify.close();
fastify = Fastify();
fastify.get('/', async (request, reply) => {
2023-04-10 18:48:45 +03:00
reply.header('Link', '</redirect>; rel="redirect_uri"');
reply.send();
2023-04-10 17:26:04 +03:00
});
await fastify.listen({ port: clientPort });
const client = getClient();
const response = await fetch(client.authorizeURL({
redirect_uri,
scope: 'write:notes',
state: 'state',
code_challenge: 'code',
code_challenge_method: 'S256',
2023-04-16 17:03:14 +03:00
} as AuthorizationParamsExtended));
2023-04-10 18:48:45 +03:00
assert.strictEqual(response.status, 200);
assert.strictEqual(getMeta(await response.text()).clientName, `http://127.0.0.1:${clientPort}/`);
2023-04-10 17:26:04 +03:00
});
});
2023-06-06 22:53:59 +03:00
test('Unknown OAuth endpoint', async () => {
const response = await fetch(new URL('/oauth/foo', host));
assert.strictEqual(response.status, 404);
});
2023-04-17 10:26:45 +03:00
2023-06-05 23:14:55 +03:00
// TODO: Add spec links to tests
2023-04-02 22:59:38 +03:00
});