-
Notifications
You must be signed in to change notification settings - Fork 497
Expand file tree
/
Copy pathpoc-csrf-demo.cjs
More file actions
216 lines (187 loc) Β· 7.62 KB
/
poc-csrf-demo.cjs
File metadata and controls
216 lines (187 loc) Β· 7.62 KB
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
/**
* poc-csrf-demo.cjs β safe regression checker for OAuth CSRF state validation.
*
* Exercises the auth flow callback logic with mocked HTTP requests to verify
* that missing or mismatched state parameters are correctly rejected.
*
* Usage (from the clasp repo root):
* npm run compile && node poc-csrf-demo.cjs
*
* Against the original (unpatched) source, reject cases will FAIL.
* Against the patched source, all 6 cases should PASS.
*/
'use strict';
const http = require('http');
const results = [];
let exitCode = 0;
function log(status, label, detail) {
const tag = status === 'PASS' ? 'PASS' : 'FAIL';
if (tag === 'FAIL') exitCode = 1;
console.log(`${tag} ${label}: ${detail}`);
results.push({tag, label, detail});
}
function sendRequest(port, query) {
return new Promise((resolve, reject) => {
const req = http.get(`http://localhost:${port}${query}`, (res) => {
let body = '';
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => resolve({status: res.statusCode, body}));
});
req.on('error', reject);
req.setTimeout(3000, () => { req.destroy(); reject(new Error('timeout')); });
});
}
async function testLocalhostNoState(LocalServerAuthorizationCodeFlow, OAuth2Client) {
const client = new OAuth2Client({
clientId: 'test-id', clientSecret: 'test-secret', redirectUri: 'http://localhost',
});
const flow = new LocalServerAuthorizationCodeFlow(client, 0);
const redirectUri = await flow.getRedirectUri();
const port = new URL(redirectUri).port;
const expectedState = 'correct_state_value';
// Start listening but swallow the open() call side effects
const codePromise = flow.promptAndReturnCode(
`https://accounts.google.com/o/oauth2/v2/auth?state=${expectedState}`,
expectedState,
).catch(() => null); // swallow expected rejection
// Small delay for server to bind
await new Promise(r => setTimeout(r, 50));
try {
const resp = await sendRequest(port, '?code=attacker_code');
await codePromise;
if (resp.status === 400) {
log('PASS', 'local callback without state', 'expected reject, observed reject (HTTP 400)');
} else {
log('FAIL', 'local callback without state',
`expected reject, observed accept; status=${resp.status}`);
}
} catch (_err) {
log('PASS', 'local callback without state', 'expected reject, connection rejected');
}
}
async function testLocalhostWrongState(LocalServerAuthorizationCodeFlow, OAuth2Client) {
const client = new OAuth2Client({
clientId: 'test-id', clientSecret: 'test-secret', redirectUri: 'http://localhost',
});
const flow = new LocalServerAuthorizationCodeFlow(client, 0);
const redirectUri = await flow.getRedirectUri();
const port = new URL(redirectUri).port;
const expectedState = 'correct_state_value';
const codePromise = flow.promptAndReturnCode(
`https://accounts.google.com/o/oauth2/v2/auth?state=${expectedState}`,
expectedState,
).catch(() => null);
await new Promise(r => setTimeout(r, 50));
try {
const resp = await sendRequest(port, '?code=attacker_code&state=wrong_state');
await codePromise;
if (resp.status === 400) {
log('PASS', 'local callback with mismatched state', 'expected reject, observed reject (HTTP 400)');
} else {
log('FAIL', 'local callback with mismatched state',
`expected reject, observed accept; status=${resp.status}`);
}
} catch (_err) {
log('PASS', 'local callback with mismatched state', 'expected reject, connection rejected');
}
}
async function testLocalhostCorrectState(LocalServerAuthorizationCodeFlow, OAuth2Client) {
const client = new OAuth2Client({
clientId: 'test-id', clientSecret: 'test-secret', redirectUri: 'http://localhost',
});
const flow = new LocalServerAuthorizationCodeFlow(client, 0);
const redirectUri = await flow.getRedirectUri();
const port = new URL(redirectUri).port;
const expectedState = 'correct_state_value';
const codePromise = flow.promptAndReturnCode(
`https://accounts.google.com/o/oauth2/v2/auth?state=${expectedState}`,
expectedState,
);
await new Promise(r => setTimeout(r, 50));
try {
const resp = await sendRequest(port, `?code=legit_code&state=${expectedState}`);
const code = await codePromise;
if (code === 'legit_code' && resp.status === 200) {
log('PASS', 'local callback with matching state', 'expected accept, observed accept');
} else {
log('FAIL', 'local callback with matching state', `unexpected status=${resp.status}`);
}
} catch (err) {
log('FAIL', 'local callback with matching state', `expected accept, observed reject: ${err.message}`);
}
}
async function testServerlessCallbacks() {
console.log('\n=== Serverless (paste URL) flow ===\n');
let parseAuthResponseUrl;
try {
const mod = await import('./build/src/auth/auth_code_flow.js');
parseAuthResponseUrl = mod.parseAuthResponseUrl;
} catch (err) {
console.error('Could not import auth_code_flow. Run "npm run compile" first.');
process.exit(2);
}
const expectedState = 'correct_state_value';
// Test 4: pasted URL without state
{
const {code, state} = parseAuthResponseUrl('http://localhost:8888?code=attacker_code');
if (!state || state !== expectedState) {
log('PASS', 'serverless pasted URL without state', 'expected reject, observed reject');
} else {
log('FAIL', 'serverless pasted URL without state',
`expected reject, observed accept; code="${code}"`);
}
}
// Test 5: pasted URL with wrong state
{
const {code, state} = parseAuthResponseUrl(
'http://localhost:8888?code=attacker_code&state=wrong_state',
);
if (!state || state !== expectedState) {
log('PASS', 'serverless pasted URL with mismatched state', 'expected reject, observed reject');
} else {
log('FAIL', 'serverless pasted URL with mismatched state',
`expected reject, observed accept; code="${code}"`);
}
}
// Test 6: pasted URL with correct state
{
const {code, state} = parseAuthResponseUrl(
`http://localhost:8888?code=legit_code&state=${expectedState}`,
);
if (state === expectedState && code === 'legit_code') {
log('PASS', 'serverless pasted URL with matching state', 'expected accept, observed accept');
} else {
log('FAIL', 'serverless pasted URL with matching state', 'expected accept, observed reject');
}
}
}
async function main() {
console.log('OAuth CSRF state validation β regression check');
console.log('='.repeat(52));
// Load compiled modules
let LocalServerAuthorizationCodeFlow, OAuth2Client;
try {
const lmod = await import('./build/src/auth/localhost_auth_code_flow.js');
LocalServerAuthorizationCodeFlow = lmod.LocalServerAuthorizationCodeFlow;
const gmod = await import('google-auth-library');
OAuth2Client = gmod.OAuth2Client;
} catch (err) {
console.error('Could not load modules. Run "npm install && npm run compile" first.');
console.error(err.message);
process.exit(2);
}
console.log('\n=== Localhost callback flow ===\n');
await testLocalhostNoState(LocalServerAuthorizationCodeFlow, OAuth2Client);
await testLocalhostWrongState(LocalServerAuthorizationCodeFlow, OAuth2Client);
await testLocalhostCorrectState(LocalServerAuthorizationCodeFlow, OAuth2Client);
await testServerlessCallbacks();
console.log('\n' + '='.repeat(52));
const passed = results.filter(r => r.tag === 'PASS').length;
const failed = results.filter(r => r.tag === 'FAIL').length;
console.log(`${passed} passed, ${failed} failed out of ${results.length} checks`);
process.exit(exitCode);
}
main().catch(err => {
console.error('Unhandled error:', err);
process.exit(2);
});