Skip to content

Commit 021a391

Browse files
committed
fix: Auth adapters for Facebook, Instagram, VK and WeChat send auth data unencoded in provider requests
1 parent a3f152f commit 021a391

7 files changed

Lines changed: 226 additions & 21 deletions

File tree

‎spec/Adapters/Auth/instagram.spec.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,40 @@ describe('InstagramAdapter', function () {
278278
'Instagram code is required.'
279279
);
280280
});
281+
282+
it('should send the access token as a single request parameter with insecure auth', async function () {
283+
await reconfigureServer({
284+
auth: {
285+
instagram: {
286+
enableInsecureAuth: true,
287+
},
288+
},
289+
});
290+
const requests = [];
291+
const fetch = global.fetch;
292+
spyOn(global, 'fetch').and.callFake((url, options) => {
293+
if (typeof url === 'string' && url.startsWith(Parse.serverURL)) {
294+
return fetch(url, options);
295+
}
296+
requests.push(new URL(url));
297+
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'mockUserId' }) });
298+
});
299+
300+
const authData = {
301+
access_token: 'token&fields=username#fragment',
302+
id: 'mockUserId',
303+
};
304+
await Parse.User.logInWith('instagram', { authData });
305+
306+
expect(requests.length).toBe(1);
307+
expect(requests[0].origin).toBe('https://graph.instagram.com');
308+
expect(requests[0].pathname).toBe('/me');
309+
expect([...requests[0].searchParams]).toEqual([
310+
['fields', 'id'],
311+
['access_token', 'token&fields=username#fragment'],
312+
]);
313+
expect(requests[0].hash).toBe('');
314+
});
281315
});
282316

283317
});

‎spec/Adapters/Auth/wechat.spec.js‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,5 +232,90 @@ describe('WeChatAdapter', function () {
232232
jasmine.objectContaining({ message: 'WeChat auth is invalid for this user.' })
233233
);
234234
});
235+
236+
// Records the requests to WeChat and answers each with the JSON that `respond` returns
237+
function recordWeChatRequests(respond) {
238+
const requests = [];
239+
const fetch = global.fetch;
240+
spyOn(global, 'fetch').and.callFake((url, options) => {
241+
if (typeof url === 'string' && url.startsWith(Parse.serverURL)) {
242+
return fetch(url, options);
243+
}
244+
const requestUrl = new URL(url);
245+
requests.push(requestUrl);
246+
return Promise.resolve({ ok: true, json: () => Promise.resolve(respond(requestUrl)) });
247+
});
248+
return requests;
249+
}
250+
251+
it('should send the code as a single request parameter', async function () {
252+
const requests = recordWeChatRequests(url =>
253+
url.pathname === '/sns/oauth2/access_token'
254+
? { access_token: 'validAccessToken', openid: 'user123', errcode: 0 }
255+
: { errcode: 0, id: 'user123' }
256+
);
257+
258+
const authData = { code: 'code&appid=otherAppId#fragment' };
259+
await Parse.User.logInWith('wechat', { authData });
260+
261+
expect(requests[0].pathname).toBe('/sns/oauth2/access_token');
262+
expect([...requests[0].searchParams]).toEqual([
263+
['appid', 'validAppId'],
264+
['secret', 'validAppSecret'],
265+
['code', 'code&appid=otherAppId#fragment'],
266+
['grant_type', 'authorization_code'],
267+
]);
268+
expect(requests[0].hash).toBe('');
269+
});
270+
271+
it('should send the access token as a single request parameter with insecure auth', async function () {
272+
const requests = recordWeChatRequests(() => ({ errcode: 0, id: 'user123' }));
273+
274+
await reconfigureServer({
275+
auth: {
276+
wechat: {
277+
appId: 'validAppId',
278+
appSecret: 'validAppSecret',
279+
enableInsecureAuth: true,
280+
},
281+
},
282+
});
283+
284+
const authData = { access_token: 'token&openid=otherUser#fragment', id: 'user123' };
285+
await Parse.User.logInWith('wechat', { authData });
286+
287+
expect(requests.length).toBe(1);
288+
expect(requests[0].pathname).toBe('/sns/auth');
289+
expect([...requests[0].searchParams]).toEqual([
290+
['access_token', 'token&openid=otherUser#fragment'],
291+
['openid', 'user123'],
292+
]);
293+
expect(requests[0].hash).toBe('');
294+
});
295+
296+
it('should send the user id as a single request parameter with insecure auth', async function () {
297+
const requests = recordWeChatRequests(() => ({ errcode: 0, id: 'user123&openid=otherUser' }));
298+
299+
await reconfigureServer({
300+
auth: {
301+
wechat: {
302+
appId: 'validAppId',
303+
appSecret: 'validAppSecret',
304+
enableInsecureAuth: true,
305+
},
306+
},
307+
});
308+
309+
const authData = { access_token: 'validAccessToken', id: 'user123&openid=otherUser' };
310+
await Parse.User.logInWith('wechat', { authData });
311+
312+
expect(requests.length).toBe(1);
313+
expect(requests[0].pathname).toBe('/sns/auth');
314+
expect([...requests[0].searchParams]).toEqual([
315+
['access_token', 'validAccessToken'],
316+
['openid', 'user123&openid=otherUser'],
317+
]);
318+
expect(requests[0].hash).toBe('');
319+
});
235320
});
236321
});

‎spec/AuthenticationAdapters.spec.js‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,51 @@ describe('AuthenticationProviders', function () {
443443
expect(httpsRequest.get.calls.first().args[0].includes('appsecret_proof')).toBe(true);
444444
});
445445

446+
it('should send the Facebook access token as a single request parameter', async () => {
447+
const crypto = require('crypto');
448+
const httpsRequest = require('../lib/Adapters/Auth/httpsRequest');
449+
const requests = [];
450+
spyOn(httpsRequest, 'get').and.callFake(url => {
451+
const requestUrl = new URL(url);
452+
requests.push(requestUrl);
453+
return Promise.resolve(requestUrl.pathname === '/app' ? { id: 'appId' } : { id: 'userId' });
454+
});
455+
await reconfigureServer({
456+
auth: {
457+
facebook: {
458+
appIds: ['appId'],
459+
appSecret: 'secret_sauce',
460+
},
461+
},
462+
});
463+
const access_token = 'token&fields=name#fragment';
464+
await request({
465+
method: 'POST',
466+
url: 'http://localhost:8378/1/users',
467+
headers: {
468+
'Content-Type': 'application/json',
469+
'X-Parse-Application-Id': 'test',
470+
'X-Parse-REST-API-Key': 'rest',
471+
},
472+
body: JSON.stringify({ authData: { facebook: { id: 'userId', access_token } } }),
473+
});
474+
const appsecret_proof = crypto
475+
.createHmac('sha256', 'secret_sauce')
476+
.update(access_token)
477+
.digest('hex');
478+
expect(requests.map(url => url.pathname)).toEqual(['/app', '/me']);
479+
expect([...requests[0].searchParams]).toEqual([
480+
['access_token', access_token],
481+
['appsecret_proof', appsecret_proof],
482+
]);
483+
expect([...requests[1].searchParams]).toEqual([
484+
['fields', 'id'],
485+
['access_token', access_token],
486+
['appsecret_proof', appsecret_proof],
487+
]);
488+
expect(requests.map(url => url.hash)).toEqual(['', '']);
489+
});
490+
446491
it('properly loads a custom adapter with options', () => {
447492
const options = {
448493
custom: {
@@ -1636,6 +1681,48 @@ describe('phant auth adapter', () => {
16361681
});
16371682
});
16381683

1684+
describe('vkontakte auth adapter', () => {
1685+
const httpsRequest = require('../lib/Adapters/Auth/httpsRequest');
1686+
1687+
it('should send the access token as a single request parameter', async () => {
1688+
const options = {
1689+
vkontakte: {
1690+
enableInsecureAuth: true,
1691+
appIds: ['appId'],
1692+
appSecret: 'appSecret',
1693+
apiVersion: '5.131',
1694+
},
1695+
};
1696+
await reconfigureServer({
1697+
enableInsecureAuthAdapters: true,
1698+
auth: options,
1699+
});
1700+
const requests = [];
1701+
spyOn(httpsRequest, 'get').and.callFake(url => {
1702+
const requestUrl = new URL(url);
1703+
requests.push(requestUrl);
1704+
return Promise.resolve(
1705+
requestUrl.hostname === 'oauth.vk.com'
1706+
? { access_token: 'serviceToken' }
1707+
: { response: [{ id: 111 }] }
1708+
);
1709+
});
1710+
const authData = {
1711+
id: 111,
1712+
access_token: 'token&user_ids=222#fragment',
1713+
};
1714+
const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('vkontakte', options);
1715+
await adapter.validateAuthData(authData, providerOptions);
1716+
const userRequest = requests.find(url => url.hostname === 'api.vk.com');
1717+
expect(userRequest.pathname).toBe('/method/users.get');
1718+
expect([...userRequest.searchParams]).toEqual([
1719+
['access_token', 'token&user_ids=222#fragment'],
1720+
['v', '5.131'],
1721+
]);
1722+
expect(userRequest.hash).toBe('');
1723+
});
1724+
});
1725+
16391726
describe('facebook limited auth adapter', () => {
16401727
const facebook = require('../lib/Adapters/Auth/facebook');
16411728
const jwt = require('jsonwebtoken');

‎src/Adapters/Auth/facebook.js‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,8 @@ function validateGraphToken(authData, options = {}) {
8383
if (!Array.isArray(options.appIds) || !options.appIds.length) {
8484
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is not configured.');
8585
}
86-
return graphRequest(
87-
'me?fields=id&access_token=' + authData.access_token + getAppSecretPath(authData, options)
88-
).then(data => {
86+
const query = new URLSearchParams({ fields: 'id', access_token: authData.access_token });
87+
return graphRequest(`me?${query}${getAppSecretPath(authData, options)}`).then(data => {
8988
if ((data && data.id == authData.id) || (process.env.TESTING && authData.id === 'test')) {
9089
return;
9190
}
@@ -104,9 +103,8 @@ async function validateGraphAppId(appIds, authData, options) {
104103
if (!appIds.length) {
105104
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is not configured.');
106105
}
107-
const data = await graphRequest(
108-
`app?access_token=${access_token}${getAppSecretPath(authData, options)}`
109-
);
106+
const query = new URLSearchParams({ access_token });
107+
const data = await graphRequest(`app?${query}${getAppSecretPath(authData, options)}`);
110108
if (!data || !appIds.includes(data.id)) {
111109
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Facebook auth is invalid for this user.');
112110
}

‎src/Adapters/Auth/instagram.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ class InstagramAdapter extends BaseAuthCodeAdapter {
9797

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

102103
const response = await fetch(path);
103104

‎src/Adapters/Auth/vkontakte.js‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@ async function validateAuthData(authData, params) {
2222
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Vk appIds or appSecret is incorrect.');
2323
}
2424

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

3031
if (!vkUser?.response?.length || vkUser.response[0].id !== authData.id) {
3132
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Vk auth is invalid for this user.');

‎src/Adapters/Auth/wechat.js‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,8 @@ class WeChatAdapter extends BaseAuthCodeAdapter {
7979
}
8080

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

8685
const data = await response.json();
8786

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

100-
const appId = this.clientId;
101-
const appSecret = this.clientSecret
102-
103-
104-
const response = await fetch(
105-
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appSecret}&code=${authData.code}&grant_type=authorization_code`
106-
);
99+
const query = new URLSearchParams({
100+
appid: this.clientId,
101+
secret: this.clientSecret,
102+
code: authData.code,
103+
grant_type: 'authorization_code',
104+
});
105+
const response = await fetch(`https://api.weixin.qq.com/sns/oauth2/access_token?${query}`);
107106

108107
const data = await response.json();
109108

0 commit comments

Comments
 (0)