Skip to content

Commit

Permalink
fix invalid session id handling (#2347)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 committed May 6, 2020
1 parent 6d4a71b commit 74bbf36
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Sources/Vapor/Sessions/SessionsMiddleware.swift
Expand Up @@ -42,7 +42,13 @@ public final class SessionsMiddleware: Middleware {
// A cookie value exists, get the session for it.
let id = SessionID(string: cookieValue.string)
return self.session.readSession(id, for: request).flatMap { data in
request._sessionCache.session = .init(id: id, data: data ?? .init())
if let data = data {
// Session found, restore data and id.
request._sessionCache.session = .init(id: id, data: data)
} else {
// Session id not found, create new session.
request._sessionCache.session = .init()
}
return next.respond(to: request).flatMap { res in
return self.addCookies(to: res, for: request)
}
Expand Down
52 changes: 52 additions & 0 deletions Tests/VaporTests/SessionTests.swift
Expand Up @@ -70,6 +70,58 @@ final class SessionTests: XCTestCase {
}
}

func testInvalidCookie() throws {
let app = Application(.testing)
defer { app.shutdown() }

// Configure sessions.
app.sessions.use(.memory)
app.middleware.use(app.sessions.middleware)

// Adds data to the request session.
app.get("set") { req -> HTTPStatus in
req.session.data["foo"] = "bar"
return .ok
}

// Fetches data from the request session.
app.get("get") { req -> String in
guard let foo = req.session.data["foo"] else {
throw Abort(.badRequest)
}
return foo
}


// Test accessing session with no cookie.
try app.test(.GET, "get") { res in
XCTAssertEqual(res.status, .badRequest)
}

// Test setting session with invalid cookie.
var newCookie: HTTPCookies.Value?
try app.test(.GET, "set", beforeRequest: { req in
req.headers.cookie = ["vapor-session": "foo"]
}, afterResponse: { res in
// We should get a new cookie back.
newCookie = res.headers.setCookie?["vapor-session"]
XCTAssertNotNil(newCookie)
// That is not the same as the invalid cookie we sent.
XCTAssertNotEqual(newCookie?.string, "foo")
XCTAssertEqual(res.status, .ok)
})

// Test accessing newly created session.
try app.test(.GET, "get", beforeRequest: { req in
// Pass cookie from previous request.
req.headers.cookie = ["vapor-session": newCookie!]
}, afterResponse: { res in
// Session access should be successful.
XCTAssertEqual(res.body.string, "bar")
XCTAssertEqual(res.status, .ok)
})
}

func testCookieQuotes() throws {
var headers = HTTPHeaders()
headers.replaceOrAdd(name: .cookie, value: #"foo= "+cookie/value" "#)
Expand Down

0 comments on commit 74bbf36

Please sign in to comment.