-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
HTTPCookies.swift
290 lines (249 loc) · 9.4 KB
/
HTTPCookies.swift
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
extension HTTPHeaders {
/// Get and set `HTTPCookies` for an HTTP request
/// This accesses the `"Cookie"` header.
public var cookie: HTTPCookies? {
get {
self.parseDirectives(name: .cookie).first.map {
HTTPCookies(directives: $0)
}
}
set {
if let cookieHeader = newValue?.cookieHeader {
self.replaceOrAdd(name: .cookie, value: cookieHeader)
} else {
self.remove(name: .cookie)
}
}
}
/// Get and set `HTTPCookies` for an HTTP response
/// This accesses the `"Set-Cookie"` header.
public var setCookie: HTTPCookies? {
get {
let setCookies: [HTTPSetCookie] = self.parseDirectives(name: .setCookie).compactMap {
HTTPSetCookie(directives: $0)
}
guard !setCookies.isEmpty else {
return nil
}
var cookies = HTTPCookies()
setCookies.forEach { cookie in
cookies[cookie.name] = cookie.value
}
return cookies
}
set {
self.remove(name: .setCookie)
if let cookies = newValue {
for cookieHeader in cookies.setCookieHeaders {
self.add(name: .setCookie, value: cookieHeader)
}
}
}
}
}
struct HTTPSetCookie {
var name: String
var value: HTTPCookies.Value
init?(directives: [HTTPHeaders.Directive]) {
guard let name = directives.first, let value = name.parameter else {
return nil
}
self.name = .init(name.value)
self.value = .init(string: .init(value))
for directive in directives[1...] {
switch directive.value.lowercased() {
case "domain":
guard let parameter = directive.parameter else {
return nil
}
self.value.domain = .init(parameter)
case "path":
guard let parameter = directive.parameter else {
return nil
}
self.value.path = .init(parameter)
case "expires":
guard let parameter = directive.parameter else {
return nil
}
self.value.expires = Date(rfc1123: .init(parameter))
case "httponly":
self.value.isHTTPOnly = true
case "secure":
self.value.isSecure = true
case "max-age":
guard let parameter = directive.parameter else {
return nil
}
self.value.maxAge = Int(parameter) ?? 0
case "samesite":
guard let parameter = directive.parameter else {
return nil
}
self.value.sameSite = HTTPCookies.SameSitePolicy(rawValue: .init(parameter))
default:
return nil
}
}
}
}
/// A collection of `HTTPCookie`s.
public struct HTTPCookies: ExpressibleByDictionaryLiteral {
/// A cookie which can only be sent in requests originating from the same origin as the target domain.
///
/// This restriction mitigates attacks such as cross-site request forgery (XSRF).
public enum SameSitePolicy: String {
/// Strict mode.
case strict = "Strict"
/// Relaxed mode.
case lax = "Lax"
// Cookies marked SameSite=None should also be marked Secure.
case none = "None"
}
/// A single cookie (key/value pair).
public struct Value: ExpressibleByStringLiteral {
// MARK: Static
/// An expired `HTTPCookieValue`.
public static let expired: Value = .init(string: "", expires: Date(timeIntervalSince1970: 0))
// MARK: Properties
/// The cookie's value.
public var string: String
/// The cookie's expiration date
public var expires: Date?
/// The maximum cookie age in seconds.
public var maxAge: Int?
/// The affected domain at which the cookie is active.
public var domain: String?
/// The path at which the cookie is active.
public var path: String?
/// Limits the cookie to secure connections.
public var isSecure: Bool
/// Does not expose the cookie over non-HTTP channels.
public var isHTTPOnly: Bool
/// A cookie which can only be sent in requests originating from the same origin as the target domain.
///
/// This restriction mitigates attacks such as cross-site request forgery (XSRF).
public var sameSite: SameSitePolicy?
// MARK: Init
/// Creates a new `HTTPCookieValue`.
///
/// let cookie = HTTPCookieValue(string: "123")
///
/// - parameters:
/// - value: Value for this cookie.
/// - expires: The cookie's expiration date. Defaults to `nil`.
/// - maxAge: The maximum cookie age in seconds. Defaults to `nil`.
/// - domain: The affected domain at which the cookie is active. Defaults to `nil`.
/// - path: The path at which the cookie is active. Defaults to `"/"`.
/// - isSecure: Limits the cookie to secure connections. If `sameSite` is `none`, this flag will be overriden with `true`. Defaults to `false`.
/// - isHTTPOnly: Does not expose the cookie over non-HTTP channels. Defaults to `false`.
/// - sameSite: See `HTTPSameSitePolicy`. Defaults to `lax`.
public init(
string: String,
expires: Date? = nil,
maxAge: Int? = nil,
domain: String? = nil,
path: String? = "/",
isSecure: Bool = false,
isHTTPOnly: Bool = false,
sameSite: SameSitePolicy? = .lax
) {
self.string = string
self.expires = expires
self.maxAge = maxAge
self.domain = domain
self.path = path
// SameSite=None requires Secure attribute to be set
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
let forceSecure = sameSite == SameSitePolicy.none
self.isSecure = isSecure || forceSecure
self.isHTTPOnly = isHTTPOnly
self.sameSite = sameSite
}
/// See `ExpressibleByStringLiteral`.
public init(stringLiteral value: String) {
self.init(string: value)
}
// MARK: Methods
/// Seriaizes an `HTTPCookie` to a `String`.
public func serialize(name: String) -> String {
var serialized = "\(name)=\(string)"
if let expires = self.expires {
serialized += "; Expires=\(expires.rfc1123)"
}
if let maxAge = self.maxAge {
serialized += "; Max-Age=\(maxAge)"
}
if let domain = self.domain {
serialized += "; Domain=\(domain)"
}
if let path = self.path {
serialized += "; Path=\(path)"
}
if isSecure {
serialized += "; Secure"
}
if isHTTPOnly {
serialized += "; HttpOnly"
}
if let sameSite = self.sameSite {
serialized += "; SameSite"
switch sameSite {
case .lax:
serialized += "=Lax"
case .strict:
serialized += "=Strict"
case .none:
serialized += "=None"
}
}
return serialized
}
}
/// Internal storage.
private var cookies: [String: Value]
/// Creates an empty `HTTPCookies`
public init() {
self.cookies = [:]
}
init(directives: [HTTPHeaders.Directive]) {
self.cookies = directives.reduce(into: [:], { (cookies, directive) in
if let value = directive.parameter {
cookies[.init(directive.value)] = .init(string: .init(value))
}
})
}
/// See `ExpressibleByDictionaryLiteral`.
public init(dictionaryLiteral elements: (String, Value)...) {
var cookies: [String: Value] = [:]
for (name, value) in elements {
cookies[name] = value
}
self.cookies = cookies
}
// MARK: Serialize
/// Seriaizes the `Cookies` for a `Request`
var cookieHeader: String? {
guard !cookies.isEmpty else {
return nil
}
let cookie: String = self.cookies.map { (name, value) in
return "\(name)=\(value.string)"
}.joined(separator: "; ")
return cookie
}
var setCookieHeaders: [String] {
return self.cookies.map { $0.value.serialize(name: $0.key) }
}
// MARK: Access
/// All cookies.
public var all: [String: Value] {
get { return cookies }
set { cookies = newValue }
}
/// Access `HTTPCookies` by name
public subscript(name: String) -> Value? {
get { return cookies[name] }
set { cookies[name] = newValue }
}
}