Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions packages/@n8n/client-oauth2/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ export interface OAuth2AccessTokenErrorResponse extends Record<string, unknown>
* Based on RFC 8414: https://www.rfc-editor.org/rfc/rfc8414.html
*/
export interface OAuthAuthorizationServerMetadata {
/** The authorization server's identifier */
issuer: string;

/** URL of the authorization server's authorization endpoint */
authorization_endpoint: string;

Expand All @@ -51,15 +48,21 @@ export interface OAuthAuthorizationServerMetadata {
/** URL of the authorization server's dynamic client registration endpoint */
registration_endpoint: string;

/** Array of OAuth 2.0 response_type values supported */
response_types_supported: string[];

/** Array of OAuth 2.0 grant type values supported */
grant_types_supported: string[];
/**
* Array of OAuth 2.0 grant type values supported
* If omitted, the default is ['authorization_code', 'implicit']
*/
grant_types_supported?: string[];

/** Array of client authentication methods supported by the token endpoint */
token_endpoint_auth_methods_supported: string[];
/**
* Array of client authentication methods supported by the token endpoint
* If omitted, the default is ['client_secret_basic']
*/
token_endpoint_auth_methods_supported?: string[];

/** Array of PKCE code challenge methods supported */
code_challenge_methods_supported: string[];
/**
* Array of PKCE code challenge methods supported
* If omitted, the server does not support PKCE
*/
code_challenge_methods_supported?: string[];
}
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,81 @@ describe('OAuth2CredentialController', () => {
});
},
);

it.each([
[
{
authorization_endpoint: 'invalid',
token_endpoint: 'https://example.com/token',
registration_endpoint: 'https://example.com/registration',
},
],
[
{
authorization_endpoint: 'https://example.com/auth',
token_endpoint: 'invalid',
registration_endpoint: 'https://example.com/registration',
},
],
[
{
authorization_endpoint: 'https://example.com/auth',
token_endpoint: 'https://example.com/token',
registration_endpoint: 'invalid',
},
],
])(
'should throw a BadRequestError when OAuth2 server metadata is invalid',
async (response) => {
credentialsFinderService.findCredentialForUser.mockResolvedValueOnce(credential);
credentialsHelper.getDecrypted.mockResolvedValueOnce({});
credentialsHelper.applyDefaultsAndOverwrites.mockResolvedValue({
useDynamicClientRegistration: true,
serverUrl: 'https://example.com',
});
nock('https://example.com')
.get('/.well-known/oauth-authorization-server')
.reply(200, response);

const req = mock<OAuthRequest.OAuth2Credential.Auth>({ user, query: { id: '1' } });
await expect(controller.getAuthUri(req)).rejects.toThrowError(
/Invalid OAuth2 server metadata/,
);
},
);

it('should throw a BadRequestError when the registration response is invalid', async () => {
credentialsFinderService.findCredentialForUser.mockResolvedValueOnce(credential);
credentialsHelper.getDecrypted.mockResolvedValueOnce({});
credentialsHelper.applyDefaultsAndOverwrites.mockResolvedValue({
useDynamicClientRegistration: true,
serverUrl: 'https://example.com',
});
nock('https://example.com')
.get('/.well-known/oauth-authorization-server')
.reply(200, {
authorization_endpoint: 'https://example.com/auth',
token_endpoint: 'https://example.com/token',
registration_endpoint: 'https://example.com/registration',
grant_types_supported: ['authorization_code', 'refresh_token'],
token_endpoint_auth_methods_supported: ['client_secret_basic'],
code_challenge_methods_supported: ['S256'],
})
.post('/registration', {
redirect_uris: ['http://localhost:5678/rest/oauth2-credential/callback'],
token_endpoint_auth_method: 'client_secret_basic',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
client_name: 'n8n',
client_uri: 'https://n8n.io/',
})
.reply(200, { invalid: 'invalid' });

const req = mock<OAuthRequest.OAuth2Credential.Auth>({ user, query: { id: '1' } });
await expect(controller.getAuthUri(req)).rejects.toThrowError(
/Invalid client registration response/,
);
});
});

describe('handleCallback', () => {
Expand Down
40 changes: 32 additions & 8 deletions packages/cli/src/controllers/oauth/oauth2-credential.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,27 @@ import {
} from 'n8n-workflow';
import pkceChallenge from 'pkce-challenge';
import * as qs from 'querystring';
import { z } from 'zod';

import { AbstractOAuthController, skipAuthOnOAuthCallback } from './abstract-oauth.controller';

import { GENERIC_OAUTH2_CREDENTIALS_WITH_EDITABLE_SCOPE as GENERIC_OAUTH2_CREDENTIALS_WITH_EDITABLE_SCOPE } from '@/constants';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { OAuthRequest } from '@/requests';

import { AbstractOAuthController, skipAuthOnOAuthCallback } from './abstract-oauth.controller';
const oAuthAuthorizationServerMetadataSchema = z.object({
authorization_endpoint: z.string().url(),
token_endpoint: z.string().url(),
registration_endpoint: z.string().url(),
grant_types_supported: z.array(z.string()).optional(),
token_endpoint_auth_methods_supported: z.array(z.string()).optional(),
code_challenge_methods_supported: z.array(z.string()).optional(),
});

const dynamicClientRegistrationResponseSchema = z.object({
client_id: z.string(),
client_secret: z.string().optional(),
});

@RestController('/oauth2-credential')
export class OAuth2CredentialController extends AbstractOAuthController {
Expand Down Expand Up @@ -63,22 +78,24 @@ export class OAuth2CredentialController extends AbstractOAuthController {
const { data } = await axios.get<OAuthAuthorizationServerMetadata>(
`${serverUrl.origin}/.well-known/oauth-authorization-server`,
);
const { authorization_endpoint, token_endpoint, registration_endpoint } = data;
if (!authorization_endpoint || !token_endpoint || !registration_endpoint) {
const metadataValidation = oAuthAuthorizationServerMetadataSchema.safeParse(data);
if (!metadataValidation.success) {
throw new BadRequestError(
'The OAuth2 server does not support dynamic client registration. Missing endpoints in metadata.',
`Invalid OAuth2 server metadata: ${metadataValidation.error.errors.map((e) => e.message).join(', ')}`,
);
}

const { authorization_endpoint, token_endpoint, registration_endpoint } =
metadataValidation.data;
oauthCredentials.authUrl = authorization_endpoint;
oauthCredentials.accessTokenUrl = token_endpoint;
toUpdate.authUrl = authorization_endpoint;
toUpdate.accessTokenUrl = token_endpoint;

const { grantType, authentication } = this.selectGrantTypeAndAuthenticationMethod(
data.grant_types_supported,
data.token_endpoint_auth_methods_supported,
data.code_challenge_methods_supported,
metadataValidation.data.grant_types_supported ?? ['authorization_code', 'implicit'],
metadataValidation.data.token_endpoint_auth_methods_supported ?? ['client_secret_basic'],
metadataValidation.data.code_challenge_methods_supported ?? [],
);
oauthCredentials.grantType = grantType;
toUpdate.grantType = grantType;
Expand Down Expand Up @@ -106,8 +123,15 @@ export class OAuth2CredentialController extends AbstractOAuthController {
client_id: string;
client_secret?: string;
}>(registration_endpoint, registerPayload);
const registrationValidation =
dynamicClientRegistrationResponseSchema.safeParse(registerResult);
if (!registrationValidation.success) {
throw new BadRequestError(
`Invalid client registration response: ${registrationValidation.error.errors.map((e) => e.message).join(', ')}`,
);
}

const { client_id, client_secret } = registerResult;
const { client_id, client_secret } = registrationValidation.data;
oauthCredentials.clientId = client_id;
toUpdate.clientId = client_id;
if (client_secret) {
Expand Down
Loading