From ed8425fec2e3cb884f00c8bca1006dbd57030e40 Mon Sep 17 00:00:00 2001 From: Ben Rosen Date: Thu, 27 Aug 2026 14:53:16 -0500 Subject: [PATCH 1/3] Throw a 400 Bad Request error instead of 500 on decoding failure --- Package.swift | 7 +++ Sources/Routing/Errors/HeaderError.swift | 18 +++++++ .../Routing/Errors/PathParameterError.swift | 21 ++++++++ .../Routing/Errors/QueryParameterError.swift | 21 ++++++++ Sources/Routing/Errors/RequestBodyError.swift | 18 +++++++ Sources/Routing/Headers.swift | 11 ---- Sources/Routing/PathParameters.swift | 14 ----- Sources/Routing/QueryParameters.swift | 14 ----- Sources/Routing/Router.swift | 33 ++++++++++-- .../Routing/Transports/HTTP/HTTPRouter.swift | 38 +++++++++++++ .../Helpers/HTTPRequestFixtures.swift | 54 +++++++++++++++++++ .../RoutingTests/Helpers/Logger+Testing.swift | 15 ++++++ .../RouterBodyDecodingTests.swift | 49 +++++++++++++++++ 13 files changed, 269 insertions(+), 44 deletions(-) create mode 100644 Sources/Routing/Errors/HeaderError.swift create mode 100644 Sources/Routing/Errors/PathParameterError.swift create mode 100644 Sources/Routing/Errors/QueryParameterError.swift create mode 100644 Sources/Routing/Errors/RequestBodyError.swift create mode 100644 Tests/RoutingTests/Helpers/HTTPRequestFixtures.swift create mode 100644 Tests/RoutingTests/Helpers/Logger+Testing.swift create mode 100644 Tests/RoutingTests/RouterBodyDecodingTests.swift diff --git a/Package.swift b/Package.swift index 0cbc72d..31ffaec 100644 --- a/Package.swift +++ b/Package.swift @@ -91,6 +91,13 @@ let package = Package( .product(name: "SwiftParser", package: "swift-syntax"), ] ), + .testTarget( + name: "RoutingTests", + dependencies: [ + "Routing", + .product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"), + ] + ), .testTarget( name: "DynamoQueriesMacrosTests", dependencies: [ diff --git a/Sources/Routing/Errors/HeaderError.swift b/Sources/Routing/Errors/HeaderError.swift new file mode 100644 index 0000000..cd7b4ea --- /dev/null +++ b/Sources/Routing/Errors/HeaderError.swift @@ -0,0 +1,18 @@ +// +// HeaderError.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +/// Thrown by `Headers.require` when a header is absent. +/// `Router.handle` maps it to `400 Bad Request`. +public enum HeaderError: Error { + case missing(String) + + public var message: String { + switch self { + case let .missing(name): + "Missing required header: \(name)" + } + } +} diff --git a/Sources/Routing/Errors/PathParameterError.swift b/Sources/Routing/Errors/PathParameterError.swift new file mode 100644 index 0000000..3cf6e05 --- /dev/null +++ b/Sources/Routing/Errors/PathParameterError.swift @@ -0,0 +1,21 @@ +// +// PathParameterError.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +/// Thrown by `PathParameters.require` when a parameter is absent or not convertible. +/// `Router.handle` maps it to `400 Bad Request`. +public enum PathParameterError: Error { + case missing(String) + case invalidType(name: String, value: String, expectedType: String) + + public var message: String { + switch self { + case let .missing(name): + "Missing required path parameter: \(name)" + case let .invalidType(name, value, expectedType): + "Path parameter '\(name)' value '\(value)' is not a valid \(expectedType)" + } + } +} diff --git a/Sources/Routing/Errors/QueryParameterError.swift b/Sources/Routing/Errors/QueryParameterError.swift new file mode 100644 index 0000000..3c06e05 --- /dev/null +++ b/Sources/Routing/Errors/QueryParameterError.swift @@ -0,0 +1,21 @@ +// +// QueryParameterError.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +/// Thrown by `QueryParameters.require` when a parameter is absent or not convertible. +/// `Router.handle` maps it to `400 Bad Request`. +public enum QueryParameterError: Error { + case missing(String) + case invalidType(name: String, value: String, expectedType: String) + + public var message: String { + switch self { + case let .missing(name): + "Missing required query parameter: \(name)" + case let .invalidType(name, value, expectedType): + "Query parameter '\(name)' value '\(value)' is not a valid \(expectedType)" + } + } +} diff --git a/Sources/Routing/Errors/RequestBodyError.swift b/Sources/Routing/Errors/RequestBodyError.swift new file mode 100644 index 0000000..507cc3b --- /dev/null +++ b/Sources/Routing/Errors/RequestBodyError.swift @@ -0,0 +1,18 @@ +// +// RequestBodyError.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +/// Thrown when a request body cannot be decoded into a handler's `Body` type. +/// `Router.handle` maps it to `400 Bad Request`. +public enum RequestBodyError: Error { + case decodingFailed(any Error) + + public var message: String { + switch self { + case let .decodingFailed(error): + "Invalid request body: \(error)" + } + } +} diff --git a/Sources/Routing/Headers.swift b/Sources/Routing/Headers.swift index f612eaf..7f7af44 100644 --- a/Sources/Routing/Headers.swift +++ b/Sources/Routing/Headers.swift @@ -49,14 +49,3 @@ public struct Headers: Sendable { Set(self.values.keys) } } - -public enum HeaderError: Error { - case missing(String) - - public var message: String { - switch self { - case let .missing(name): - "Missing required header: \(name)" - } - } -} diff --git a/Sources/Routing/PathParameters.swift b/Sources/Routing/PathParameters.swift index d410a3a..59eb47b 100644 --- a/Sources/Routing/PathParameters.swift +++ b/Sources/Routing/PathParameters.swift @@ -51,17 +51,3 @@ public struct PathParameters: Sendable { self.values[name] = value } } - -public enum PathParameterError: Error { - case missing(String) - case invalidType(name: String, value: String, expectedType: String) - - public var message: String { - switch self { - case let .missing(name): - "Missing required path parameter: \(name)" - case let .invalidType(name, value, expectedType): - "Path parameter '\(name)' value '\(value)' is not a valid \(expectedType)" - } - } -} diff --git a/Sources/Routing/QueryParameters.swift b/Sources/Routing/QueryParameters.swift index a35c33f..874650f 100644 --- a/Sources/Routing/QueryParameters.swift +++ b/Sources/Routing/QueryParameters.swift @@ -116,17 +116,3 @@ public struct QueryParameters: Sendable { Set(self.values.keys) } } - -public enum QueryParameterError: Error { - case missing(String) - case invalidType(name: String, value: String, expectedType: String) - - public var message: String { - switch self { - case let .missing(name): - "Missing required query parameter: \(name)" - case let .invalidType(name, value, expectedType): - "Query parameter '\(name)' value '\(value)' is not a valid \(expectedType)" - } - } -} diff --git a/Sources/Routing/Router.swift b/Sources/Routing/Router.swift index edaf494..73848cd 100644 --- a/Sources/Routing/Router.swift +++ b/Sources/Routing/Router.swift @@ -61,6 +61,21 @@ public final class RouterBuilder } } + /// Register a handler at a routing key, JSON-decoding the request body into + /// `Body` before invoking the handler. + /// + /// Available for any `Routable` whose `body: Data` carries JSON. The HTTP and + /// WebSocket adapters both qualify. + public func on( + _ key: [String], + body: Body.Type, + use handler: @Sendable @escaping (R, Body, Logger) async throws -> RouteResponse + ) { + self.on(key) { request, logger in + try await handler(request, Self.decodeBody(Body.self, from: request), logger) + } + } + // MARK: - Routes through middleware /// Register a handler at a routing key, running it through middleware first. @@ -76,9 +91,6 @@ public final class RouterBuilder /// Register a handler at a routing key, running middleware and then JSON-decoding /// the request body into `Body` before invoking the handler. - /// - /// Available for any `Routable` whose `body: Data` carries JSON. The HTTP and - /// WebSocket adapters both qualify. public func on( _ key: [String], through middleware: M, @@ -87,12 +99,21 @@ public final class RouterBuilder ) where M.Input == R { self.on(key) { request, logger in try await middleware.handle(request, next: { output, logger in - let decoded = try JSONDecoder().decode(Body.self, from: request.body) - return try await handler(output, decoded, logger) + try await handler(output, Self.decodeBody(Body.self, from: request), logger) }, logger: logger) } } + /// Decode a JSON request body, wrapping failures in `RequestBodyError` so + /// `Router.handle` can map them to `400 Bad Request`. + private static func decodeBody(_ type: Body.Type, from request: R) throws -> Body { + do { + return try JSONDecoder().decode(Body.self, from: request.body) + } catch { + throw RequestBodyError.decodingFailed(error) + } + } + // MARK: - Groups /// Begin a route group whose registrations all run through the supplied middleware. @@ -159,6 +180,8 @@ public final class Router: Sendable { return .error(statusCode: .badRequest, message: error.message) } catch let error as HeaderError { return .error(statusCode: .badRequest, message: error.message) + } catch let error as RequestBodyError { + return .error(statusCode: .badRequest, message: error.message) } catch { return .error(statusCode: .internalServerError, message: "Internal server error") } diff --git a/Sources/Routing/Transports/HTTP/HTTPRouter.swift b/Sources/Routing/Transports/HTTP/HTTPRouter.swift index 680b7e0..b4b15af 100644 --- a/Sources/Routing/Transports/HTTP/HTTPRouter.swift +++ b/Sources/Routing/Transports/HTTP/HTTPRouter.swift @@ -135,6 +135,44 @@ public extension RouterBuilder where R == HTTPRequest, ) { self.on(HTTPRequest.options(path), use: handler) } + + /// Register a `POST` handler at the given path. + func post( + _ path: String, + use handler: @Sendable @escaping (HTTPRequest, Logger) async throws -> RouteResponse + ) { + self.on(HTTPRequest.post(path), use: handler) + } + + /// Register a `POST` handler at the given path, JSON-decoding the request body + /// into `Body` before invoking the handler. + func post( + _ path: String, + body: Body.Type, + use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse + ) { + self.on(HTTPRequest.post(path), body: body, use: handler) + } + + /// Register a `PUT` handler at the given path, JSON-decoding the request body + /// into `Body` before invoking the handler. + func put( + _ path: String, + body: Body.Type, + use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse + ) { + self.on(HTTPRequest.put(path), body: body, use: handler) + } + + /// Register a `PATCH` handler at the given path, JSON-decoding the request body + /// into `Body` before invoking the handler. + func patch( + _ path: String, + body: Body.Type, + use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse + ) { + self.on(HTTPRequest.patch(path), body: body, use: handler) + } } // MARK: - RouteGroup HTTP sugar diff --git a/Tests/RoutingTests/Helpers/HTTPRequestFixtures.swift b/Tests/RoutingTests/Helpers/HTTPRequestFixtures.swift new file mode 100644 index 0000000..8c5fd49 --- /dev/null +++ b/Tests/RoutingTests/Helpers/HTTPRequestFixtures.swift @@ -0,0 +1,54 @@ +// +// HTTPRequestFixtures.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +import AWSLambdaEvents +import Foundation +import Routing + +enum HTTPRequestFixtures { + /// Builds a request through JSON because `APIGatewayV2Request` has no public initializer. + /// Shaped like a `/{proxy+}` HTTP API (payload 2.0) event. + static func makeRequest( + method: String = "POST", + path: String, + headers: [String: String] = [:], + body: String? = nil + ) throws -> HTTPRequest { + var payload: [String: Any] = [ + "version": "2.0", + "routeKey": "ANY /{proxy+}", + "rawPath": path, + "rawQueryString": "", + "headers": headers, + "pathParameters": ["proxy": path.hasPrefix("/") ? String(path.dropFirst()) : path], + "requestContext": [ + "accountId": "123456789012", + "apiId": "api-id", + "domainName": "example.com", + "domainPrefix": "example", + "http": [ + "method": method, + "path": path, + "protocol": "HTTP/1.1", + "sourceIp": "127.0.0.1", + "userAgent": "test", + ], + "requestId": "request-id", + "routeKey": "ANY /{proxy+}", + "stage": "$default", + "time": "12/Mar/2026:19:03:58 +0000", + "timeEpoch": 1_583_348_638_390, + ], + "isBase64Encoded": false, + ] + if let body { + payload["body"] = body + } + let data = try JSONSerialization.data(withJSONObject: payload) + let event = try JSONDecoder().decode(APIGatewayV2Request.self, from: data) + return HTTPRequest(event: event) + } +} diff --git a/Tests/RoutingTests/Helpers/Logger+Testing.swift b/Tests/RoutingTests/Helpers/Logger+Testing.swift new file mode 100644 index 0000000..b9ce3ff --- /dev/null +++ b/Tests/RoutingTests/Helpers/Logger+Testing.swift @@ -0,0 +1,15 @@ +// +// Logger+Testing.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +import Logging + +extension Logger { + /// Silent logger for router dispatch in tests. + static let testing = Logger( + label: "RoutingTests", + factory: { _ in SwiftLogNoOpLogHandler() } + ) +} diff --git a/Tests/RoutingTests/RouterBodyDecodingTests.swift b/Tests/RoutingTests/RouterBodyDecodingTests.swift new file mode 100644 index 0000000..a5fa63c --- /dev/null +++ b/Tests/RoutingTests/RouterBodyDecodingTests.swift @@ -0,0 +1,49 @@ +// +// RouterBodyDecodingTests.swift +// +// Copyright © 2026 SongShift, LLC. All rights reserved. +// + +import Logging +import Routing +import Testing + +@Suite("Router+bodyDecoding") +struct RouterBodyDecodingTests { + struct Input: Decodable, Sendable { + let id: String + } + + let router: HTTPRouter + + init() { + let builder = HTTPRouterBuilder() + builder.post("/echo", body: Input.self) { _, input, _ in + .string(input.id, statusCode: .ok) + } + self.router = builder.build() + } + + @Test("Valid body is decoded and passed to the handler") + func validBody() async throws { + let response = await router.handle( + try HTTPRequestFixtures.makeRequest(path: "/echo", body: #"{"id":"abc"}"#), + logger: .testing + ) + #expect(response.statusCode == .ok) + #expect(response.body == "abc") + } + + @Test( + "Undecodable body returns 400", + arguments: [nil, "", "not json", #"{"wrong":1}"#, #"{"id":1}"#] as [String?] + ) + func undecodableBody(body: String?) async throws { + let response = await router.handle( + try HTTPRequestFixtures.makeRequest(path: "/echo", body: body), + logger: .testing + ) + #expect(response.statusCode == .badRequest) + #expect(response.body?.contains("Invalid request body") == true) + } +} From d1ecf60f74e1aa08b032009d1e749a2a9b65fe8e Mon Sep 17 00:00:00 2001 From: Ben Rosen Date: Thu, 27 Aug 2026 15:23:51 -0500 Subject: [PATCH 2/3] Don't output raw error --- Sources/Routing/Errors/RequestBodyError.swift | 2 +- Tests/RoutingTests/RouterBodyDecodingTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/Routing/Errors/RequestBodyError.swift b/Sources/Routing/Errors/RequestBodyError.swift index 507cc3b..93aea8e 100644 --- a/Sources/Routing/Errors/RequestBodyError.swift +++ b/Sources/Routing/Errors/RequestBodyError.swift @@ -12,7 +12,7 @@ public enum RequestBodyError: Error { public var message: String { switch self { case let .decodingFailed(error): - "Invalid request body: \(error)" + "The request body could not be decoded." } } } diff --git a/Tests/RoutingTests/RouterBodyDecodingTests.swift b/Tests/RoutingTests/RouterBodyDecodingTests.swift index a5fa63c..3df028e 100644 --- a/Tests/RoutingTests/RouterBodyDecodingTests.swift +++ b/Tests/RoutingTests/RouterBodyDecodingTests.swift @@ -44,6 +44,6 @@ struct RouterBodyDecodingTests { logger: .testing ) #expect(response.statusCode == .badRequest) - #expect(response.body?.contains("Invalid request body") == true) + #expect(response.body?.contains("The request body could not be decoded.") == true) } } From abfa74d42bfaed8e4e8168a44ba803b6817981a6 Mon Sep 17 00:00:00 2001 From: Ben Rosen Date: Thu, 27 Aug 2026 15:46:15 -0500 Subject: [PATCH 3/3] Rename suite name --- Tests/RoutingTests/RouterBodyDecodingTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/RoutingTests/RouterBodyDecodingTests.swift b/Tests/RoutingTests/RouterBodyDecodingTests.swift index 3df028e..f193a41 100644 --- a/Tests/RoutingTests/RouterBodyDecodingTests.swift +++ b/Tests/RoutingTests/RouterBodyDecodingTests.swift @@ -8,7 +8,7 @@ import Logging import Routing import Testing -@Suite("Router+bodyDecoding") +@Suite("Router+BodyDecodingTests") struct RouterBodyDecodingTests { struct Input: Decodable, Sendable { let id: String