Skip to content

Commit

Permalink
Pass X-Request-Id if present (#3072)
Browse files Browse the repository at this point in the history
* Pass X-Request-Id if present
* Add test for honoring of request ID header
  • Loading branch information
paunik committed Sep 22, 2023
1 parent a4b0715 commit d79fad4
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Sources/Vapor/HTTP/Headers/HTTPHeaders+Name.swift
Expand Up @@ -421,6 +421,8 @@ extension HTTPHeaders {
public static let xForwardedHost = Name("X-Forwarded-Host")
/// X-Forwarded-Proto header.
public static let xForwardedProto = Name("X-Forwarded-Proto")
/// X-Request-Id header.
public static let xRequestId = Name("X-Request-Id")
}

/// Add a header name/value pair to the block.
Expand Down
6 changes: 5 additions & 1 deletion Sources/Vapor/Request/Request.swift
Expand Up @@ -250,7 +250,11 @@ public final class Request: CustomStringConvertible {
self.storage = .init()
self.isKeepAlive = true
self.logger = logger
self.logger[metadataKey: "request-id"] = .string(id)
if let requestId = self.headers[.xRequestId].first {
self.logger[metadataKey: "request-id"] = .string(requestId)
} else {
self.logger[metadataKey: "request-id"] = .string(UUID().uuidString)
}
self.byteBufferAllocator = byteBufferAllocator
}
}
7 changes: 7 additions & 0 deletions Tests/VaporTests/HTTPHeaderTests.swift
Expand Up @@ -201,6 +201,13 @@ final class HTTPHeaderTests: XCTestCase {
)
}

func testXRequestId() throws {
var headers = HTTPHeaders()
let xRequestId = UUID().uuidString
headers.replaceOrAdd(name: .xRequestId, value: xRequestId)
XCTAssertEqual(headers.first(name: "X-Request-Id"), xRequestId)
}

func testContentDisposition() throws {
let headers = HTTPHeaders([
("Content-Disposition", #"form-data; name="fieldName"; filename="filename.jpg""#)
Expand Down
18 changes: 18 additions & 0 deletions Tests/VaporTests/RequestTests.swift
Expand Up @@ -99,6 +99,24 @@ final class RequestTests: XCTestCase {
}
}

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

app.get("remote") {
if case .string(let string) = $0.logger[metadataKey: "request-id"] {
return string
} else {
throw Abort(.notFound)
}
}

try app.testable(method: .running(port: 0)).test(.GET, "remote", beforeRequest: { req in
req.headers.add(name: .xRequestId, value: "test")
}, afterResponse: { res in
XCTAssertEqual(res.body.string, "test")
})
}

func testRequestRemoteAddress() throws {
let app = Application(.testing)
Expand Down

0 comments on commit d79fad4

Please sign in to comment.