Skip to content

Commit

Permalink
Set x-forwarded-for when proxying a fetch request
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewBarba committed Mar 7, 2023
1 parent 617e350 commit 9b5bc75
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
1 change: 1 addition & 0 deletions Sources/Compute/Fastly/FastlyTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ public enum HTTPHeader: String, HTTPHeaderRepresentable, Codable, Sendable {
case xCache = "x-cache"
case xCacheHits = "x-cache-hits"
case xCompressHint = "x-compress-hint"
case xForwardedFor = "x-forwarded-for"

public var stringValue: String {
rawValue
Expand Down
11 changes: 10 additions & 1 deletion Sources/Compute/Fetch/Fetch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public func fetch (
_ request: IncomingRequest,
origin: String,
streaming: Bool = true,
forwardedFor: Bool = true,
_ options: FetchRequest.Options = .options()
) async throws -> FetchResponse {
guard
Expand Down Expand Up @@ -72,10 +73,18 @@ public func fetch (
body = try await .bytes(request.body.bytes())
}

// Copy the request headers
var headers = options.headers ?? request.headers.dictionary()

// Set the proxied IP address
if forwardedFor, headers[HTTPHeader.xForwardedFor.rawValue] == nil {
headers[HTTPHeader.xForwardedFor.rawValue] = request.clientIpAddress().stringValue
}

return try await fetch(url, .options(
method: options.method ?? request.method,
body: body,
headers: options.headers ?? request.headers.dictionary(),
headers: headers,
searchParams: options.searchParams ?? request.searchParams,
timeoutInterval: options.timeoutInterval,
cachePolicy: options.cachePolicy,
Expand Down

0 comments on commit 9b5bc75

Please sign in to comment.