Skip to content

Commit

Permalink
Makes sure CORSMiddleware always adds before ErrorMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
grosch committed Apr 16, 2020
1 parent 2698e2c commit 54578f5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Sources/Vapor/Middleware/CORSMiddleware.swift
Expand Up @@ -97,14 +97,14 @@ public final class CORSMiddleware: Middleware {
allowedHeaders: [HTTPHeaders.Name],
allowCredentials: Bool = false,
cacheExpiration: Int? = 600,
exposedHeaders: [String]? = nil
exposedHeaders: [HTTPHeaders.Name]? = nil
) {
self.allowedOrigin = allowedOrigin
self.allowedMethods = allowedMethods.map({ "\($0)" }).joined(separator: ", ")
self.allowedHeaders = allowedHeaders.map({ $0.description }).joined(separator: ", ")
self.allowedHeaders = allowedHeaders.map({ String(describing: $0) }).joined(separator: ", ")
self.allowCredentials = allowCredentials
self.cacheExpiration = cacheExpiration
self.exposedHeaders = exposedHeaders?.joined(separator: ", ")
self.exposedHeaders = exposedHeaders?.map({ String(describing: $0) }).joined(separator: ", ")
}
}

Expand Down
9 changes: 9 additions & 0 deletions Sources/Vapor/Middleware/MiddlewareConfiguration.swift
Expand Up @@ -19,6 +19,15 @@ public struct Middlewares {
/// Otherwise, use the type-based method and register the `Middleware`
/// using factory method to `Services`.
public mutating func use(_ middleware: Middleware) {
// CORS middleware must come before the ErrorMiddleware. While
// we could just always add cors first, that breaks people who want
// a specific order for other items. So just find the ErrorMiddleare
// and add it before that
if let corsMiddleware = middleware as? CORSMiddleware,
let index = self.storage.firstIndex(where: { $0 is ErrorMiddleware }) {
self.storage.insert(corsMiddleware, at: index)
}

self.storage.append(middleware)
}

Expand Down
16 changes: 16 additions & 0 deletions Tests/VaporTests/MiddlewareTests.swift
@@ -1,3 +1,4 @@
@testable import Vapor
import XCTVapor

final class MiddlewareTests: XCTestCase {
Expand Down Expand Up @@ -29,4 +30,19 @@ final class MiddlewareTests: XCTestCase {
XCTAssertEqual(res.body.string, "done")
}
}

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

let cors = CORSMiddleware.init(configuration: .default())
app.middleware.use(cors)

let middlewares = app.middleware.resolve()

let errorMiddleware = try XCTUnwrap(middlewares.firstIndex(where: { $0 is ErrorMiddleware }))
let corsMiddleware = try XCTUnwrap(middlewares.firstIndex(where: { $0 is CORSMiddleware }))

XCTAssertLessThan(corsMiddleware, errorMiddleware)
}
}

0 comments on commit 54578f5

Please sign in to comment.