-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathcookies.ts
427 lines (345 loc) · 11.3 KB
/
cookies.ts
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// @ts-nocheck
import _ from 'lodash'
import Promise from 'bluebird'
import $utils from '../../cypress/utils'
import $errUtils from '../../cypress/error_utils'
import { $Location } from '../../cypress/location'
// TODO: add hostOnly to COOKIE_PROPS
// https://github.com/cypress-io/cypress/issues/363
// https://github.com/cypress-io/cypress/issues/17527
const COOKIE_PROPS = 'name value path secure httpOnly expiry domain sameSite'.split(' ')
const commandNameRe = /(:)(\w)/
function pickCookieProps (cookie) {
if (!cookie) return cookie
if (_.isArray(cookie)) {
return cookie.map(pickCookieProps)
}
return _.pick(cookie, COOKIE_PROPS)
}
const getCommandFromEvent = (event) => {
return event.replace(commandNameRe, (match, p1, p2) => {
return p2.toUpperCase()
})
}
const mergeDefaults = function (obj) {
// we always want to be able to see and influence cookies
// on our superdomain
const { superDomain } = $Location.create(window.location.href)
// and if the user did not provide a domain
// then we know to set the default to be origin
const merge = (o) => {
return _.defaults(o, { domain: superDomain })
}
if (_.isArray(obj)) {
return _.map(obj, merge)
}
return merge(obj)
}
// from https://developer.chrome.com/extensions/cookies#type-SameSiteStatus
// note that `unspecified` is purposely omitted - Firefox and Chrome set
// different defaults, and Firefox lacks support for `unspecified`, so
// `undefined` is used in lieu of `unspecified`
// @see https://bugzilla.mozilla.org/show_bug.cgi?id=1624668
const VALID_SAMESITE_VALUES = ['no_restriction', 'lax', 'strict']
const normalizeSameSite = (sameSite) => {
if (_.isUndefined(sameSite)) {
return sameSite
}
if (_.isString(sameSite)) {
sameSite = sameSite.toLowerCase()
}
if (sameSite === 'none') {
// "None" is the value sent in the header for `no_restriction`, so allow it here for convenience
sameSite = 'no_restriction'
}
return sameSite
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Attributes
function cookieValidatesHostPrefix (options) {
return options.secure === false || (options.path && options.path !== '/')
}
function cookieValidatesSecurePrefix (options) {
return options.secure === false
}
export default function (Commands, Cypress, cy, state, config) {
const automateCookies = function (event, obj = {}, log, timeout) {
const automate = () => {
return Cypress.automation(event, mergeDefaults(obj))
.catch((err) => {
return $errUtils.throwErr(err, { onFail: log })
})
}
if (!timeout) {
return automate()
}
// need to remove the current timeout
// because we're handling timeouts ourselves
cy.clearTimeout(event)
return automate()
.timeout(timeout)
.catch(Promise.TimeoutError, (err) => {
return $errUtils.throwErrByPath('cookies.timed_out', {
onFail: log,
args: {
cmd: getCommandFromEvent(event),
timeout,
},
})
})
}
const getAndClear = (log, timeout, options = {}) => {
return automateCookies('get:cookies', options, log, timeout)
.then((resp) => {
// bail early if we got no cookies!
if (resp && (resp.length === 0)) {
return resp
}
// iterate over all of these and ensure none are allowed
// or preserved
const cookies = Cypress.Cookies.getClearableCookies(resp)
return automateCookies('clear:cookies', cookies, log, timeout)
})
.then(pickCookieProps)
}
const handleBackendError = (command, action, onFail) => {
return (err) => {
if (!_.includes(err.stack, err.message)) {
err.stack = `${err.message}\n${err.stack}`
}
if (err.name === 'CypressError') {
throw err
}
$errUtils.throwErrByPath('cookies.backend_error', {
args: {
action,
cmd: command,
browserDisplayName: Cypress.browser.displayName,
error: err,
},
onFail,
errProps: {
appendToStack: {
title: 'From Node.js Internals',
content: err.stack,
},
},
})
}
}
// TODO: handle failure here somehow
// maybe by tapping into the Cypress reset
// stuff, or handling this in the runner itself?
// Cypress sessions will clear cookies on its own before each test
Cypress.on('test:before:run:async', () => {
if (!Cypress.config('experimentalSessionSupport')) {
return getAndClear()
}
})
return Commands.addAll({
getCookie (name, options = {}) {
const userOptions = options
options = _.defaults({}, userOptions, {
log: true,
timeout: config('responseTimeout'),
})
if (options.log) {
options._log = Cypress.log({
message: name,
timeout: options.timeout,
consoleProps () {
let c
const obj = {}
c = options.cookie
if (c) {
obj['Yielded'] = c
} else {
obj['Yielded'] = 'null'
obj['Note'] = `No cookie with the name: '${name}' was found.`
}
return obj
},
})
}
const onFail = options._log
if (!_.isString(name)) {
$errUtils.throwErrByPath('getCookie.invalid_argument', { onFail })
}
return automateCookies('get:cookie', { name }, options._log, options.timeout)
.then(pickCookieProps)
.then((resp) => {
options.cookie = resp
return resp
})
.catch(handleBackendError('getCookie', 'reading the requested cookie from', onFail))
},
getCookies (options = {}) {
const userOptions = options
options = _.defaults({}, userOptions, {
log: true,
timeout: config('responseTimeout'),
})
if (options.log) {
options._log = Cypress.log({
message: '',
timeout: options.timeout,
consoleProps () {
let c
const obj = {}
c = options.cookies
if (c) {
obj['Yielded'] = c
obj['Num Cookies'] = c.length
}
return obj
},
})
}
return automateCookies('get:cookies', _.pick(options, 'domain'), options._log, options.timeout)
.then(pickCookieProps)
.then((resp) => {
options.cookies = resp
return resp
})
.catch(handleBackendError('getCookies', 'reading cookies from', options._log))
},
setCookie (name, value, options = {}) {
const userOptions = options
options = _.defaults({}, userOptions, {
name,
value,
path: '/',
secure: false,
httpOnly: false,
log: true,
expiry: $utils.addTwentyYears(),
timeout: config('responseTimeout'),
})
const cookie = pickCookieProps(options)
if (options.log) {
options._log = Cypress.log({
message: [name, value],
timeout: options.timeout,
consoleProps () {
let c
const obj = {}
c = options.cookie
if (c) {
obj['Yielded'] = c
}
return obj
},
})
}
const onFail = options._log
cookie.sameSite = normalizeSameSite(cookie.sameSite)
if (!_.isUndefined(cookie.sameSite) && !VALID_SAMESITE_VALUES.includes(cookie.sameSite)) {
$errUtils.throwErrByPath('setCookie.invalid_samesite', {
onFail,
args: {
value: options.sameSite, // for clarity, throw the error with the user's unnormalized option
validValues: VALID_SAMESITE_VALUES,
},
})
}
// cookies with SameSite=None must also set Secure
// @see https://web.dev/samesite-cookies-explained/#changes-to-the-default-behavior-without-samesite
if (cookie.sameSite === 'no_restriction' && cookie.secure !== true) {
$errUtils.throwErrByPath('setCookie.secure_not_set_with_samesite_none', {
onFail,
args: {
value: options.sameSite, // for clarity, throw the error with the user's unnormalized option
},
})
}
if (!_.isString(name) || !_.isString(value)) {
$errUtils.throwErrByPath('setCookie.invalid_arguments', { onFail })
}
if (options.name.startsWith('__Secure-') && cookieValidatesSecurePrefix(options)) {
$errUtils.throwErrByPath('setCookie.secure_prefix', { onFail })
}
if (options.name.startsWith('__Host-') && cookieValidatesHostPrefix(options)) {
$errUtils.throwErrByPath('setCookie.host_prefix', { onFail })
}
return automateCookies('set:cookie', cookie, options._log, options.timeout)
.then(pickCookieProps)
.then((resp) => {
options.cookie = resp
return resp
}).catch(handleBackendError('setCookie', 'setting the requested cookie in', onFail))
},
clearCookie (name, options = {}) {
const userOptions = options
options = _.defaults({}, userOptions, {
log: true,
timeout: config('responseTimeout'),
})
if (options.log) {
options._log = Cypress.log({
message: name,
timeout: options.timeout,
consoleProps () {
let c
const obj = {}
obj['Yielded'] = 'null'
c = options.cookie
if (c) {
obj['Cleared Cookie'] = c
} else {
obj['Note'] = `No cookie with the name: '${name}' was found or removed.`
}
return obj
},
})
}
const onFail = options._log
if (!_.isString(name)) {
$errUtils.throwErrByPath('clearCookie.invalid_argument', { onFail })
}
// TODO: prevent clearing a cypress namespace
return automateCookies('clear:cookie', { name }, options._log, options.timeout)
.then(pickCookieProps)
.then((resp) => {
options.cookie = resp
// null out the current subject
return null
})
.catch(handleBackendError('clearCookie', 'clearing the requested cookie in', onFail))
},
clearCookies (options = {}) {
const userOptions = options
options = _.defaults({}, userOptions, {
log: true,
timeout: config('responseTimeout'),
})
if (options.log) {
options._log = Cypress.log({
message: '',
timeout: options.timeout,
consoleProps () {
let c
const obj = {}
obj['Yielded'] = 'null'
if ((c = options.cookies) && c.length) {
obj['Cleared Cookies'] = c
obj['Num Cookies'] = c.length
} else {
obj['Note'] = 'No cookies were found or removed.'
}
return obj
},
})
}
return getAndClear(options._log, options.timeout, { domain: options.domain })
.then((resp) => {
options.cookies = resp
// null out the current subject
return null
}).catch((err) => {
// make sure we always say to clearCookies
err.message = err.message.replace('getCookies', 'clearCookies')
throw err
})
.catch(handleBackendError('clearCookies', 'clearing cookies in', options._log))
},
})
}