|
| 1 | +import Foundation |
| 2 | + |
| 3 | +#if canImport(FoundationNetworking) |
| 4 | + import FoundationNetworking |
| 5 | +#endif |
| 6 | + |
| 7 | +/// A plugin for debugging HTTP responses by printing response details to the console. |
| 8 | +/// |
| 9 | +/// This plugin prints comprehensive response information including status code, headers, and body content. |
| 10 | +/// It's designed as a debugging tool and should only be used temporarily during development. |
| 11 | +/// |
| 12 | +/// ## Usage |
| 13 | +/// |
| 14 | +/// Add to your RESTClient for debugging: |
| 15 | +/// |
| 16 | +/// ```swift |
| 17 | +/// let client = RESTClient( |
| 18 | +/// baseURL: URL(string: "https://api.example.com")!, |
| 19 | +/// responsePlugins: [PrintResponsePlugin()], // debugOnly: true, redactAPIKey: true by default |
| 20 | +/// errorBodyToMessage: { _ in "Error" } |
| 21 | +/// ) |
| 22 | +/// ``` |
| 23 | +/// |
| 24 | +/// Both `debugOnly` and `redactAPIKey` default to `true` for security. You can disable these built-in protections if needed: |
| 25 | +/// |
| 26 | +/// ```swift |
| 27 | +/// // Default behavior (recommended) |
| 28 | +/// PrintResponsePlugin() // debugOnly: true, redactAPIKey: true |
| 29 | +/// |
| 30 | +/// // Disable debugOnly to log in production (discouraged) |
| 31 | +/// PrintResponsePlugin(debugOnly: false) |
| 32 | +/// |
| 33 | +/// // Disable redactAPIKey for debugging auth issues (use carefully) |
| 34 | +/// PrintResponsePlugin(redactAPIKey: false) |
| 35 | +/// ``` |
| 36 | +/// |
| 37 | +/// ## Output Example |
| 38 | +/// |
| 39 | +/// ``` |
| 40 | +/// [RESTClient] Response 200 from 'https://api.example.com/v1/users/123' |
| 41 | +/// |
| 42 | +/// Response headers: |
| 43 | +/// Content-Type: application/json |
| 44 | +/// Date: Wed, 08 Aug 2025 10:30:00 GMT |
| 45 | +/// Server: nginx/1.18.0 |
| 46 | +/// Set-Cookie: session_token=[redacted] |
| 47 | +/// X-Request-ID: req_abc123def456 |
| 48 | +/// |
| 49 | +/// Response body: |
| 50 | +/// { |
| 51 | +/// "id": 123, |
| 52 | +/// "name": "John Doe", |
| 53 | + |
| 54 | +/// "created_at": "2023-08-01T10:30:00Z" |
| 55 | +/// } |
| 56 | +/// ``` |
| 57 | +/// |
| 58 | +/// - Note: By default, logging only occurs in DEBUG builds and API keys are redacted for security. |
| 59 | +/// - Important: The plugin is safe to leave in your code with default settings thanks to `debugOnly` protection. |
| 60 | +@available(iOS 16, macOS 13, tvOS 16, watchOS 9, *) |
| 61 | +public struct PrintResponsePlugin: RESTClient.ResponsePlugin { |
| 62 | + /// Whether logging should only occur in DEBUG builds. |
| 63 | + /// |
| 64 | + /// When `true` (default), responses are only logged in DEBUG builds. |
| 65 | + /// When `false`, responses are logged in both DEBUG and release builds (not recommended for production). |
| 66 | + public let debugOnly: Bool |
| 67 | + |
| 68 | + /// Whether to redact API keys from sensitive headers in output. |
| 69 | + /// |
| 70 | + /// When `true` (default), sensitive headers like Authorization and Set-Cookie are replaced with "[redacted]" for security. |
| 71 | + /// When `false`, the full header value is shown (use carefully for debugging auth issues). |
| 72 | + public let redactAPIKey: Bool |
| 73 | + |
| 74 | + /// Creates a new print response plugin. |
| 75 | + /// |
| 76 | + /// - Parameters: |
| 77 | + /// - debugOnly: Whether logging should only occur in DEBUG builds. Defaults to `true`. |
| 78 | + /// - redactAPIKey: Whether to redact API keys from sensitive headers. Defaults to `true`. |
| 79 | + public init(debugOnly: Bool = true, redactAPIKey: Bool = true) { |
| 80 | + self.debugOnly = debugOnly |
| 81 | + self.redactAPIKey = redactAPIKey |
| 82 | + } |
| 83 | + |
| 84 | + /// Applies the plugin to the response, printing response details if conditions are met. |
| 85 | + /// |
| 86 | + /// This method is called automatically by RESTClient after receiving the response. |
| 87 | + /// The response and data are passed through unchanged. |
| 88 | + /// |
| 89 | + /// - Parameters: |
| 90 | + /// - response: The HTTPURLResponse to potentially log. |
| 91 | + /// - data: The response body data to potentially log. |
| 92 | + /// - Throws: Does not throw errors, but passes through any errors from the response processing. |
| 93 | + public func apply(to response: inout HTTPURLResponse, data: inout Data) throws { |
| 94 | + if self.debugOnly { |
| 95 | + #if DEBUG |
| 96 | + self.printResponse(response, data: data) |
| 97 | + #endif |
| 98 | + } else { |
| 99 | + self.printResponse(response, data: data) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /// Prints detailed response information to the console. |
| 104 | + /// |
| 105 | + /// - Parameters: |
| 106 | + /// - response: The HTTPURLResponse to print details for. |
| 107 | + /// - data: The response body data to print. |
| 108 | + private func printResponse(_ response: HTTPURLResponse, data: Data) { |
| 109 | + var responseBodyString: String? |
| 110 | + if !data.isEmpty { |
| 111 | + responseBodyString = String(data: data, encoding: .utf8) |
| 112 | + } |
| 113 | + |
| 114 | + // Clean headers formatting - sorted alphabetically for consistency, no AnyHashable wrappers |
| 115 | + var headersString = "" |
| 116 | + let cleanHeaders = response.allHeaderFields |
| 117 | + .compactMapValues { "\($0)" } |
| 118 | + .sorted { "\($0.key)" < "\($1.key)" } |
| 119 | + .map { " \($0.key): \(self.shouldRedactHeader("\($0.key)") ? "[redacted]" : $0.value)" } |
| 120 | + .joined(separator: "\n") |
| 121 | + headersString = cleanHeaders.isEmpty ? " (none)" : "\n\(cleanHeaders)" |
| 122 | + |
| 123 | + print( |
| 124 | + "[RESTClient] Response \(response.statusCode) from '\(response.url!)'\n\nResponse headers:\(headersString)\n\nResponse body:\n\(responseBodyString ?? "No body")" |
| 125 | + ) |
| 126 | + } |
| 127 | + |
| 128 | + /// Determines whether a header should be redacted for security. |
| 129 | + /// |
| 130 | + /// - Parameter headerName: The header name to check. |
| 131 | + /// - Returns: `true` if the header should be redacted when `redactAPIKey` is enabled. |
| 132 | + private func shouldRedactHeader(_ headerName: String) -> Bool { |
| 133 | + guard self.redactAPIKey else { return false } |
| 134 | + |
| 135 | + let lowercasedName = headerName.lowercased() |
| 136 | + |
| 137 | + // Exact header name matches |
| 138 | + let exactMatches = [ |
| 139 | + "authorization", "cookie", "set-cookie", "x-api-key", "x-auth-token", |
| 140 | + "x-access-token", "bearer", "apikey", "api-key", "access-token", |
| 141 | + "refresh-token", "jwt", "session-token", "csrf-token", "x-csrf-token", "x-session-id", |
| 142 | + ] |
| 143 | + |
| 144 | + // Substring patterns that indicate sensitive content |
| 145 | + let sensitivePatterns = ["password", "secret", "token"] |
| 146 | + |
| 147 | + return exactMatches.contains(lowercasedName) || sensitivePatterns.contains { lowercasedName.contains($0) } |
| 148 | + } |
| 149 | +} |
0 commit comments