Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
34 changes: 34 additions & 0 deletions spec/Adapters/Auth/instagram.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,40 @@ describe('InstagramAdapter', function () {
'Instagram code is required.'
);
});

it('should send the access token as a single request parameter with insecure auth', async function () {
await reconfigureServer({
auth: {
instagram: {
enableInsecureAuth: true,
},
},
});
const requests = [];
const fetch = global.fetch;
spyOn(global, 'fetch').and.callFake((url, options) => {
if (typeof url === 'string' && url.startsWith(Parse.serverURL)) {
return fetch(url, options);
}
requests.push(new URL(url));
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'mockUserId' }) });
});

const authData = {
access_token: 'token&fields=username#fragment',
id: 'mockUserId',
};
await Parse.User.logInWith('instagram', { authData });

expect(requests.length).toBe(1);
expect(requests[0].origin).toBe('https://graph.instagram.com');
expect(requests[0].pathname).toBe('/me');
expect([...requests[0].searchParams]).toEqual([
['fields', 'id'],
['access_token', 'token&fields=username#fragment'],
]);
expect(requests[0].hash).toBe('');
});
});

});
85 changes: 85 additions & 0 deletions spec/Adapters/Auth/wechat.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,5 +232,90 @@ describe('WeChatAdapter', function () {
jasmine.objectContaining({ message: 'WeChat auth is invalid for this user.' })
);
});

// Records the requests to WeChat and answers each with the JSON that `respond` returns
function recordWeChatRequests(respond) {
const requests = [];
const fetch = global.fetch;
spyOn(global, 'fetch').and.callFake((url, options) => {
if (typeof url === 'string' && url.startsWith(Parse.serverURL)) {
return fetch(url, options);
}
const requestUrl = new URL(url);
requests.push(requestUrl);
return Promise.resolve({ ok: true, json: () => Promise.resolve(respond(requestUrl)) });
});
return requests;
}

it('should send the code as a single request parameter', async function () {
const requests = recordWeChatRequests(url =>
url.pathname === '/sns/oauth2/access_token'
? { access_token: 'validAccessToken', openid: 'user123', errcode: 0 }
: { errcode: 0, id: 'user123' }
);

const authData = { code: 'code&appid=otherAppId#fragment' };
await Parse.User.logInWith('wechat', { authData });

expect(requests[0].pathname).toBe('/sns/oauth2/access_token');
expect([...requests[0].searchParams]).toEqual([
['appid', 'validAppId'],
['secret', 'validAppSecret'],
['code', 'code&appid=otherAppId#fragment'],
['grant_type', 'authorization_code'],
]);
expect(requests[0].hash).toBe('');
});

it('should send the access token as a single request parameter with insecure auth', async function () {
const requests = recordWeChatRequests(() => ({ errcode: 0, id: 'user123' }));

await reconfigureServer({
auth: {
wechat: {
appId: 'validAppId',
appSecret: 'validAppSecret',
enableInsecureAuth: true,
},
},
});

const authData = { access_token: 'token&openid=otherUser#fragment', id: 'user123' };
await Parse.User.logInWith('wechat', { authData });

expect(requests.length).toBe(1);
expect(requests[0].pathname).toBe('/sns/auth');
expect([...requests[0].searchParams]).toEqual([
['access_token', 'token&openid=otherUser#fragment'],
['openid', 'user123'],
]);
expect(requests[0].hash).toBe('');
});

it('should send the user id as a single request parameter with insecure auth', async function () {
const requests = recordWeChatRequests(() => ({ errcode: 0, id: 'user123&openid=otherUser' }));

await reconfigureServer({
auth: {
wechat: {
appId: 'validAppId',
appSecret: 'validAppSecret',
enableInsecureAuth: true,
},
},
});

const authData = { access_token: 'validAccessToken', id: 'user123&openid=otherUser' };
await Parse.User.logInWith('wechat', { authData });

expect(requests.length).toBe(1);
expect(requests[0].pathname).toBe('/sns/auth');
expect([...requests[0].searchParams]).toEqual([
['access_token', 'validAccessToken'],
['openid', 'user123&openid=otherUser'],
]);
expect(requests[0].hash).toBe('');
});
});
});
87 changes: 87 additions & 0 deletions spec/AuthenticationAdapters.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,51 @@ describe('AuthenticationProviders', function () {
expect(httpsRequest.get.calls.first().args[0].includes('appsecret_proof')).toBe(true);
});

it('should send the Facebook access token as a single request parameter', async () => {
const crypto = require('crypto');
const httpsRequest = require('../lib/Adapters/Auth/httpsRequest');
const requests = [];
spyOn(httpsRequest, 'get').and.callFake(url => {
const requestUrl = new URL(url);
requests.push(requestUrl);
return Promise.resolve(requestUrl.pathname === '/app' ? { id: 'appId' } : { id: 'userId' });
});
await reconfigureServer({
auth: {
facebook: {
appIds: ['appId'],
appSecret: 'secret_sauce',
},
},
});
const access_token = 'token&fields=name#fragment';
await request({
method: 'POST',
url: 'http://localhost:8378/1/users',
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
},
body: JSON.stringify({ authData: { facebook: { id: 'userId', access_token } } }),
});
const appsecret_proof = crypto
.createHmac('sha256', 'secret_sauce')
.update(access_token)
.digest('hex');
expect(requests.map(url => url.pathname)).toEqual(['/app', '/me']);
expect([...requests[0].searchParams]).toEqual([
['access_token', access_token],
['appsecret_proof', appsecret_proof],
]);
expect([...requests[1].searchParams]).toEqual([
['fields', 'id'],
['access_token', access_token],
['appsecret_proof', appsecret_proof],
]);
expect(requests.map(url => url.hash)).toEqual(['', '']);
});

it('properly loads a custom adapter with options', () => {
const options = {
custom: {
Expand Down Expand Up @@ -1636,6 +1681,48 @@ describe('phant auth adapter', () => {
});
});

describe('vkontakte auth adapter', () => {
const httpsRequest = require('../lib/Adapters/Auth/httpsRequest');

it('should send the access token as a single request parameter', async () => {
const options = {
vkontakte: {
enableInsecureAuth: true,
appIds: ['appId'],
appSecret: 'appSecret',
apiVersion: '5.131',
},
};
await reconfigureServer({
enableInsecureAuthAdapters: true,
auth: options,
});
const requests = [];
spyOn(httpsRequest, 'get').and.callFake(url => {
const requestUrl = new URL(url);
requests.push(requestUrl);
return Promise.resolve(
requestUrl.hostname === 'oauth.vk.com'
? { access_token: 'serviceToken' }
: { response: [{ id: 111 }] }
);
});
const authData = {
id: 111,
access_token: 'token&user_ids=222#fragment',
};
const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('vkontakte', options);
await adapter.validateAuthData(authData, providerOptions);
const userRequest = requests.find(url => url.hostname === 'api.vk.com');
expect(userRequest.pathname).toBe('/method/users.get');
expect([...userRequest.searchParams]).toEqual([
['access_token', 'token&user_ids=222#fragment'],
['v', '5.131'],
]);
expect(userRequest.hash).toBe('');
});
});

describe('facebook limited auth adapter', () => {
const facebook = require('../lib/Adapters/Auth/facebook');
const jwt = require('jsonwebtoken');
Expand Down
10 changes: 4 additions & 6 deletions src/Adapters/Auth/facebook.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,8 @@ function validateGraphToken(authData, options = {}) {
if (!Array.isArray(options.appIds) || !options.appIds.length) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is not configured.');
}
return graphRequest(
'me?fields=id&access_token=' + authData.access_token + getAppSecretPath(authData, options)
).then(data => {
const query = new URLSearchParams({ fields: 'id', access_token: authData.access_token });
return graphRequest(`me?${query}${getAppSecretPath(authData, options)}`).then(data => {
if ((data && data.id == authData.id) || (process.env.TESTING && authData.id === 'test')) {
return;
}
Expand All @@ -104,9 +103,8 @@ async function validateGraphAppId(appIds, authData, options) {
if (!appIds.length) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is not configured.');
}
const data = await graphRequest(
`app?access_token=${access_token}${getAppSecretPath(authData, options)}`
);
const query = new URLSearchParams({ access_token });
const data = await graphRequest(`app?${query}${getAppSecretPath(authData, options)}`);
if (!data || !appIds.includes(data.id)) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is invalid for this user.');
}
Expand Down
3 changes: 2 additions & 1 deletion src/Adapters/Auth/instagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ class InstagramAdapter extends BaseAuthCodeAdapter {

async getUserFromAccessToken(accessToken, authData) {
const apiURL = 'https://graph.instagram.com/';
const path = `${apiURL}me?fields=id&access_token=${accessToken}`;
const query = new URLSearchParams({ fields: 'id', access_token: accessToken });
const path = `${apiURL}me?${query}`;

const response = await fetch(path);

Expand Down
9 changes: 5 additions & 4 deletions src/Adapters/Auth/vkontakte.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ async function validateAuthData(authData, params) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Vk appIds or appSecret is incorrect.');
}

const vkUser = await request(
'api.vk.com',
`method/users.get?access_token=${authData.access_token}&v=${params.apiVersion}`
);
const query = new URLSearchParams({
access_token: authData.access_token,
v: params.apiVersion,
});
const vkUser = await request('api.vk.com', `method/users.get?${query}`);

if (!vkUser?.response?.length || vkUser.response[0].id !== authData.id) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Vk auth is invalid for this user.');
Expand Down
19 changes: 9 additions & 10 deletions src/Adapters/Auth/wechat.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ class WeChatAdapter extends BaseAuthCodeAdapter {
}

async getUserFromAccessToken(access_token, authData) {
const response = await fetch(
`https://api.weixin.qq.com/sns/auth?access_token=${access_token}&openid=${authData.id}`
);
const query = new URLSearchParams({ access_token, openid: authData.id });
const response = await fetch(`https://api.weixin.qq.com/sns/auth?${query}`);

const data = await response.json();

Expand All @@ -97,13 +96,13 @@ class WeChatAdapter extends BaseAuthCodeAdapter {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'WeChat auth requires a code to be sent.');
}

const appId = this.clientId;
const appSecret = this.clientSecret


const response = await fetch(
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${authData.code}&grant_type=authorization_code`
);
const query = new URLSearchParams({
appid: this.clientId,
secret: this.clientSecret,
code: authData.code,
grant_type: 'authorization_code',
});
const response = await fetch(`https://api.weixin.qq.com/sns/oauth2/access_token?${query}`);

const data = await response.json();

Expand Down
Loading