vapor / http

🚀 Non-blocking, event-driven HTTP built on Swift NIO.
MIT License
240 stars 65 forks source link

Set-Cookie header contains duplicate cookies when adding more than one value #339

Closed joewalsh closed 5 years ago

joewalsh commented 5 years ago

It seems that every time a cookie value is added to response.http.cookies, all of the cookies are appended to the Set-Cookie response header.

So if I have cookies[a] = 1, then do cookies[b] = 2, the resulting header is Set-Cookie: a,a,b

If I then do cookies[c] = 3, the result is Set-Cookie: a,a,b,a,b,c and so on.

My specific case is a Vapor 3 app using SessionsMiddleware, I added another middleware CSRFMiddleware:

import Vapor

final class CSRFMiddleware: Middleware, ServiceType {
    static func makeService(for container: Container) throws -> Self {
        return .init()
    }

    func respond(to req: Request, chainingTo next: Responder) throws -> EventLoopFuture<Response> {
        return try next.respond(to: req).map { res in
            res.http.cookies["csrf"] = HTTPCookieValue(string: "nope", expires: nil, maxAge: nil, domain: nil, path: nil, isSecure: false, isHTTPOnly: false, sameSite: nil)
            return res
        }
    }
}

In configure.swift:

services.register(CSRFMiddleware.self)
...
middlewares.use(CSRFMiddleware.self)
middlewares.use(SessionsMiddleware.self)

Let me know if this is an invalid setup or there's something else I'm missing.