#53 step 1: LocalOnlyMiddleware, /rzb/* answers loopback clients only
ServerContext keeps the client's remote address (RemoteAddressRequestContext). A non-loopback or unknown address gets a 403 local_only error; the API key is still required. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
70660e3 parent: 7e968c5 modified
Package.swift +3 -0 | @@ -35,6 +35,8 @@ let package = Package( | ||
| 35 | 35 | .package(url: "https://github.com/apple/swift-log", from: "1.6.0"), |
| 36 | 36 | // Runs the model lifecycle (preload, keep_alive, unload at shutdown) next to the server. |
| 37 | 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), |
| 38 | + // Already used by Hummingbird; razorbill reads the client's address (SocketAddress). | |
| 39 | + .package(url: "https://github.com/apple/swift-nio.git", from: "2.80.0"), | |
| 38 | 40 | ], |
| 39 | 41 | targets: [ |
| 40 | 42 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. |
| @@ -66,6 +68,7 @@ let package = Package( | ||
| 66 | 68 | "RazorbillCore", |
| 67 | 69 | .product(name: "Hummingbird", package: "hummingbird"), |
| 68 | 70 | .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"), |
| 71 | + .product(name: "NIOCore", package: "swift-nio"), | |
| 69 | 72 | ] |
| 70 | 73 | ), |
| 71 | 74 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. |
| @@ -35,6 +35,8 @@ let package = Package( | |||
| 35 | .package(url: "https://github.com/apple/swift-log", from: "1.6.0"), | 35 | .package(url: "https://github.com/apple/swift-log", from: "1.6.0"), |
| 36 | // Runs the model lifecycle (preload, keep_alive, unload at shutdown) next to the server. | 36 | // Runs the model lifecycle (preload, keep_alive, unload at shutdown) next to the server. |
| 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), | 37 | .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"), |
| 38 | + // Already used by Hummingbird; razorbill reads the client's address (SocketAddress). | ||
| 39 | + .package(url: "https://github.com/apple/swift-nio.git", from: "2.80.0"), | ||
| 38 | ], | 40 | ], |
| 39 | targets: [ | 41 | targets: [ |
| 40 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. | 42 | // Engine protocol, model cache, configuration reading, FakeEngine. No MLX. |
| @@ -66,6 +68,7 @@ let package = Package( | |||
| 66 | "RazorbillCore", | 68 | "RazorbillCore", |
| 67 | .product(name: "Hummingbird", package: "hummingbird"), | 69 | .product(name: "Hummingbird", package: "hummingbird"), |
| 68 | .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"), | 70 | .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"), |
| 71 | + .product(name: "NIOCore", package: "swift-nio"), | ||
| 69 | ] | 72 | ] |
| 70 | ), | 73 | ), |
| 71 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. | 74 | // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`. |
added
Sources/RazorbillServer/LocalOnly.swift +67 -0 | new file mode 100644 | ||
| @@ -0,0 +1,67 @@ | ||
| 1 | +import Hummingbird | |
| 2 | +import NIOCore | |
| 3 | + | |
| 4 | +/// Lets through only the requests that come from this machine; the others get a 403 | |
| 5 | +/// `local_only` error. Guards razorbill's own `/rzb/*` routes, which a local tool (`rzb tui`) | |
| 6 | +/// uses to watch and steer the server: they stay closed to the network even when the server | |
| 7 | +/// listens on `0.0.0.0`. The API key, when one is set, is still required (``APIKeyMiddleware`` | |
| 8 | +/// runs first). | |
| 9 | +/// | |
| 10 | +/// ```swift | |
| 11 | +/// let local = router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | |
| 12 | +/// local.get("/status") { _, _ in … } | |
| 13 | +/// ``` | |
| 14 | +struct LocalOnlyMiddleware: RouterMiddleware { | |
| 15 | + func handle( | |
| 16 | + _ request: Request, context: ServerContext, | |
| 17 | + next: (Request, ServerContext) async throws -> Response | |
| 18 | + ) async throws -> Response { | |
| 19 | + try Self.check(path: request.uri.path, from: context.remoteAddress) | |
| 20 | + return try await next(request, context) | |
| 21 | + } | |
| 22 | + | |
| 23 | + /// Throws the 403 `local_only` error unless `address` is on this machine. | |
| 24 | + static func check(path: String, from address: SocketAddress?) throws { | |
| 25 | + guard isLoopback(address) else { | |
| 26 | + throw OpenAIError( | |
| 27 | + .forbidden, | |
| 28 | + message: "\(path) only answers requests from the machine running the server.", | |
| 29 | + type: "invalid_request_error", code: "local_only") | |
| 30 | + } | |
| 31 | + } | |
| 32 | + | |
| 33 | + /// The address belongs to this machine: IPv4 `127.0.0.0/8`, IPv6 `::1`, an IPv4-mapped | |
| 34 | + /// loopback (`::ffff:127.0.0.1`), or a Unix socket. `nil` (no address known) is refused. | |
| 35 | + /// | |
| 36 | + /// ```swift | |
| 37 | + /// LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: "127.0.0.1", port: 0)) // true | |
| 38 | + /// LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: "192.168.1.5", port: 0)) // false | |
| 39 | + /// ``` | |
| 40 | + static func isLoopback(_ address: SocketAddress?) -> Bool { | |
| 41 | + switch address { | |
| 42 | + case .v4(let ipv4): | |
| 43 | + return isLoopbackIPv4(ipv4.address.sin_addr.s_addr.bigEndian) | |
| 44 | + case .v6(let ipv6): | |
| 45 | + return isLoopbackIPv6(withUnsafeBytes(of: ipv6.address.sin6_addr) { Array($0) }) | |
| 46 | + case .unixDomainSocket: | |
| 47 | + return true | |
| 48 | + case nil: | |
| 49 | + return false | |
| 50 | + } | |
| 51 | + } | |
| 52 | + | |
| 53 | + /// `address` in host byte order: loopback is the whole `127.0.0.0/8` block. | |
| 54 | + static func isLoopbackIPv4(_ address: UInt32) -> Bool { | |
| 55 | + address >> 24 == 127 | |
| 56 | + } | |
| 57 | + | |
| 58 | + /// `bytes`: the 16 bytes of the address in network order. | |
| 59 | + static func isLoopbackIPv6(_ bytes: [UInt8]) -> Bool { | |
| 60 | + guard bytes.count == 16 else { return false } | |
| 61 | + let loopback: [UInt8] = Array(repeating: 0, count: 15) + [1] | |
| 62 | + if bytes == loopback { return true } | |
| 63 | + let mappedPrefix: [UInt8] = Array(repeating: 0, count: 10) + [0xFF, 0xFF] | |
| 64 | + guard Array(bytes[0 ..< 12]) == mappedPrefix else { return false } | |
| 65 | + return bytes[12] == 127 | |
| 66 | + } | |
| 67 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | +import Hummingbird | ||
| 2 | +import NIOCore | ||
| 3 | + | ||
| 4 | +/// Lets through only the requests that come from this machine; the others get a 403 | ||
| 5 | +/// `local_only` error. Guards razorbill's own `/rzb/*` routes, which a local tool (`rzb tui`) | ||
| 6 | +/// uses to watch and steer the server: they stay closed to the network even when the server | ||
| 7 | +/// listens on `0.0.0.0`. The API key, when one is set, is still required (``APIKeyMiddleware`` | ||
| 8 | +/// runs first). | ||
| 9 | +/// | ||
| 10 | +/// ```swift | ||
| 11 | +/// let local = router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | ||
| 12 | +/// local.get("/status") { _, _ in … } | ||
| 13 | +/// ``` | ||
| 14 | +struct LocalOnlyMiddleware: RouterMiddleware { | ||
| 15 | + func handle( | ||
| 16 | + _ request: Request, context: ServerContext, | ||
| 17 | + next: (Request, ServerContext) async throws -> Response | ||
| 18 | + ) async throws -> Response { | ||
| 19 | + try Self.check(path: request.uri.path, from: context.remoteAddress) | ||
| 20 | + return try await next(request, context) | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + /// Throws the 403 `local_only` error unless `address` is on this machine. | ||
| 24 | + static func check(path: String, from address: SocketAddress?) throws { | ||
| 25 | + guard isLoopback(address) else { | ||
| 26 | + throw OpenAIError( | ||
| 27 | + .forbidden, | ||
| 28 | + message: "\(path) only answers requests from the machine running the server.", | ||
| 29 | + type: "invalid_request_error", code: "local_only") | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + /// The address belongs to this machine: IPv4 `127.0.0.0/8`, IPv6 `::1`, an IPv4-mapped | ||
| 34 | + /// loopback (`::ffff:127.0.0.1`), or a Unix socket. `nil` (no address known) is refused. | ||
| 35 | + /// | ||
| 36 | + /// ```swift | ||
| 37 | + /// LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: "127.0.0.1", port: 0)) // true | ||
| 38 | + /// LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: "192.168.1.5", port: 0)) // false | ||
| 39 | + /// ``` | ||
| 40 | + static func isLoopback(_ address: SocketAddress?) -> Bool { | ||
| 41 | + switch address { | ||
| 42 | + case .v4(let ipv4): | ||
| 43 | + return isLoopbackIPv4(ipv4.address.sin_addr.s_addr.bigEndian) | ||
| 44 | + case .v6(let ipv6): | ||
| 45 | + return isLoopbackIPv6(withUnsafeBytes(of: ipv6.address.sin6_addr) { Array($0) }) | ||
| 46 | + case .unixDomainSocket: | ||
| 47 | + return true | ||
| 48 | + case nil: | ||
| 49 | + return false | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// `address` in host byte order: loopback is the whole `127.0.0.0/8` block. | ||
| 54 | + static func isLoopbackIPv4(_ address: UInt32) -> Bool { | ||
| 55 | + address >> 24 == 127 | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// `bytes`: the 16 bytes of the address in network order. | ||
| 59 | + static func isLoopbackIPv6(_ bytes: [UInt8]) -> Bool { | ||
| 60 | + guard bytes.count == 16 else { return false } | ||
| 61 | + let loopback: [UInt8] = Array(repeating: 0, count: 15) + [1] | ||
| 62 | + if bytes == loopback { return true } | ||
| 63 | + let mappedPrefix: [UInt8] = Array(repeating: 0, count: 10) + [0xFF, 0xFF] | ||
| 64 | + guard Array(bytes[0 ..< 12]) == mappedPrefix else { return false } | ||
| 65 | + return bytes[12] == 127 | ||
| 66 | + } | ||
| 67 | +} | ||
modified
Sources/RazorbillServer/ServerContext.swift +5 -1 | @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import Foundation |
| 2 | 2 | import Hummingbird |
| 3 | +import NIOCore | |
| 3 | 4 | |
| 4 | 5 | /// The per-request context of razorbill's routes. |
| 5 | 6 | /// |
| @@ -12,14 +13,17 @@ import Hummingbird | ||
| 12 | 13 | /// … |
| 13 | 14 | /// } |
| 14 | 15 | /// ``` |
| 15 | -public struct ServerContext: RequestContext { | |
| 16 | +public struct ServerContext: RequestContext, RemoteAddressRequestContext { | |
| 16 | 17 | public var coreContext: CoreRequestContextStorage |
| 17 | 18 | /// Filled by the handler, read by ``RequestLogMiddleware``. |
| 18 | 19 | public let usage: RequestUsage |
| 20 | + /// The client's address, `nil` when the transport has none. ``LocalOnlyMiddleware`` reads it. | |
| 21 | + public let remoteAddress: SocketAddress? | |
| 19 | 22 | |
| 20 | 23 | public init(source: ApplicationRequestContextSource) { |
| 21 | 24 | coreContext = .init(source: source) |
| 22 | 25 | usage = RequestUsage() |
| 26 | + remoteAddress = source.channel.remoteAddress | |
| 23 | 27 | } |
| 24 | 28 | |
| 25 | 29 | /// Largest request body accepted; bigger ones get a 413. |
| @@ -1,5 +1,6 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import Hummingbird | 2 | import Hummingbird |
| 3 | +import NIOCore | ||
| 3 | 4 | ||
| 4 | /// The per-request context of razorbill's routes. | 5 | /// The per-request context of razorbill's routes. |
| 5 | /// | 6 | /// |
| @@ -12,14 +13,17 @@ import Hummingbird | |||
| 12 | /// … | 13 | /// … |
| 13 | /// } | 14 | /// } |
| 14 | /// ``` | 15 | /// ``` |
| 15 | -public struct ServerContext: RequestContext { | 16 | +public struct ServerContext: RequestContext, RemoteAddressRequestContext { |
| 16 | public var coreContext: CoreRequestContextStorage | 17 | public var coreContext: CoreRequestContextStorage |
| 17 | /// Filled by the handler, read by ``RequestLogMiddleware``. | 18 | /// Filled by the handler, read by ``RequestLogMiddleware``. |
| 18 | public let usage: RequestUsage | 19 | public let usage: RequestUsage |
| 20 | + /// The client's address, `nil` when the transport has none. ``LocalOnlyMiddleware`` reads it. | ||
| 21 | + public let remoteAddress: SocketAddress? | ||
| 19 | 22 | ||
| 20 | public init(source: ApplicationRequestContextSource) { | 23 | public init(source: ApplicationRequestContextSource) { |
| 21 | coreContext = .init(source: source) | 24 | coreContext = .init(source: source) |
| 22 | usage = RequestUsage() | 25 | usage = RequestUsage() |
| 26 | + remoteAddress = source.channel.remoteAddress | ||
| 23 | } | 27 | } |
| 24 | 28 | ||
| 25 | /// Largest request body accepted; bigger ones get a 413. | 29 | /// Largest request body accepted; bigger ones get a 413. |
added
Tests/RazorbillServerTests/LocalRoutesTests.swift +67 -0 | new file mode 100644 | ||
| @@ -0,0 +1,67 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import NIOCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +@Suite struct LocalOnlyTests { | |
| 10 | + @Test(arguments: ["127.0.0.1", "127.5.6.7", "::1", "::ffff:127.0.0.1"]) | |
| 11 | + func loopbackAddressesAreLocal(_ address: String) throws { | |
| 12 | + #expect(LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: address, port: 4242))) | |
| 13 | + } | |
| 14 | + | |
| 15 | + @Test(arguments: ["192.168.1.5", "10.0.0.1", "128.0.0.1", "::ffff:10.0.0.1", "fe80::1", "::2"]) | |
| 16 | + func otherAddressesAreNotLocal(_ address: String) throws { | |
| 17 | + #expect(!LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: address, port: 4242))) | |
| 18 | + } | |
| 19 | + | |
| 20 | + @Test func unknownAddressIsNotLocal() { | |
| 21 | + #expect(!LocalOnlyMiddleware.isLoopback(nil)) | |
| 22 | + } | |
| 23 | + | |
| 24 | + @Test func requestFromThisMachinePasses() async throws { | |
| 25 | + let router = testRouter() | |
| 26 | + router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | |
| 27 | + .get("/ping") { _, context -> String in | |
| 28 | + context.remoteAddress == nil ? "no address" : "pong" | |
| 29 | + } | |
| 30 | + try await withLiveServer(router: router) { client in | |
| 31 | + try await client.execute(uri: "/rzb/ping", method: .get) { response in | |
| 32 | + #expect(response.status == .ok) | |
| 33 | + #expect(String(buffer: response.body) == "pong") | |
| 34 | + } | |
| 35 | + } | |
| 36 | + } | |
| 37 | + | |
| 38 | + @Test func remoteRequestGetsAForbiddenError() throws { | |
| 39 | + let remote = try SocketAddress(ipAddress: "192.168.1.5", port: 4242) | |
| 40 | + let error = try #require(throws: OpenAIError.self) { | |
| 41 | + try LocalOnlyMiddleware.check(path: "/rzb/status", from: remote) | |
| 42 | + } | |
| 43 | + #expect(error.status == .forbidden) | |
| 44 | + #expect(error.code == "local_only") | |
| 45 | + #expect( | |
| 46 | + error.message | |
| 47 | + == "/rzb/status only answers requests from the machine running the server.") | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Test func apiKeyIsStillRequired() async throws { | |
| 51 | + var settings = testSettings | |
| 52 | + settings.apiKey = "s3cret" | |
| 53 | + let router = RazorbillServer.makeRouter(settings, models: testModels(settings)) | |
| 54 | + router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | |
| 55 | + .get("/ping") { _, _ in "pong" } | |
| 56 | + try await withLiveServer(settings, router: router) { client in | |
| 57 | + try await client.execute(uri: "/rzb/ping", method: .get) { response in | |
| 58 | + #expect(response.status == .unauthorized) | |
| 59 | + } | |
| 60 | + try await client.execute( | |
| 61 | + uri: "/rzb/ping", method: .get, headers: [.authorization: "Bearer s3cret"] | |
| 62 | + ) { response in | |
| 63 | + #expect(response.status == .ok) | |
| 64 | + } | |
| 65 | + } | |
| 66 | + } | |
| 67 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import NIOCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +@Suite struct LocalOnlyTests { | ||
| 10 | + @Test(arguments: ["127.0.0.1", "127.5.6.7", "::1", "::ffff:127.0.0.1"]) | ||
| 11 | + func loopbackAddressesAreLocal(_ address: String) throws { | ||
| 12 | + #expect(LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: address, port: 4242))) | ||
| 13 | + } | ||
| 14 | + | ||
| 15 | + @Test(arguments: ["192.168.1.5", "10.0.0.1", "128.0.0.1", "::ffff:10.0.0.1", "fe80::1", "::2"]) | ||
| 16 | + func otherAddressesAreNotLocal(_ address: String) throws { | ||
| 17 | + #expect(!LocalOnlyMiddleware.isLoopback(try SocketAddress(ipAddress: address, port: 4242))) | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + @Test func unknownAddressIsNotLocal() { | ||
| 21 | + #expect(!LocalOnlyMiddleware.isLoopback(nil)) | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + @Test func requestFromThisMachinePasses() async throws { | ||
| 25 | + let router = testRouter() | ||
| 26 | + router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | ||
| 27 | + .get("/ping") { _, context -> String in | ||
| 28 | + context.remoteAddress == nil ? "no address" : "pong" | ||
| 29 | + } | ||
| 30 | + try await withLiveServer(router: router) { client in | ||
| 31 | + try await client.execute(uri: "/rzb/ping", method: .get) { response in | ||
| 32 | + #expect(response.status == .ok) | ||
| 33 | + #expect(String(buffer: response.body) == "pong") | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + @Test func remoteRequestGetsAForbiddenError() throws { | ||
| 39 | + let remote = try SocketAddress(ipAddress: "192.168.1.5", port: 4242) | ||
| 40 | + let error = try #require(throws: OpenAIError.self) { | ||
| 41 | + try LocalOnlyMiddleware.check(path: "/rzb/status", from: remote) | ||
| 42 | + } | ||
| 43 | + #expect(error.status == .forbidden) | ||
| 44 | + #expect(error.code == "local_only") | ||
| 45 | + #expect( | ||
| 46 | + error.message | ||
| 47 | + == "/rzb/status only answers requests from the machine running the server.") | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + @Test func apiKeyIsStillRequired() async throws { | ||
| 51 | + var settings = testSettings | ||
| 52 | + settings.apiKey = "s3cret" | ||
| 53 | + let router = RazorbillServer.makeRouter(settings, models: testModels(settings)) | ||
| 54 | + router.group("/rzb").add(middleware: LocalOnlyMiddleware()) | ||
| 55 | + .get("/ping") { _, _ in "pong" } | ||
| 56 | + try await withLiveServer(settings, router: router) { client in | ||
| 57 | + try await client.execute(uri: "/rzb/ping", method: .get) { response in | ||
| 58 | + #expect(response.status == .unauthorized) | ||
| 59 | + } | ||
| 60 | + try await client.execute( | ||
| 61 | + uri: "/rzb/ping", method: .get, headers: [.authorization: "Bearer s3cret"] | ||
| 62 | + ) { response in | ||
| 63 | + #expect(response.status == .ok) | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | +} | ||