-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathNIOHTTPServer+SwiftConfiguration.swift
More file actions
489 lines (448 loc) · 21.7 KB
/
Copy pathNIOHTTPServer+SwiftConfiguration.swift
File metadata and controls
489 lines (448 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP Server open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift HTTP Server project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift HTTP Server project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if Configuration
public import Configuration
import NIOCore
import NIOCertificateReloading
import NIOHTTP2
import SwiftASN1
public import X509
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration {
/// Initialize the server configuration from a config reader.
///
/// ## Configuration keys:
///
/// ``NIOHTTPServerConfiguration`` is comprised of four types. Provide configuration for each type under the
/// specified key:
///
/// - **`"bindTarget"`**: A single address and port to bind to (see ``BindTarget/init(config:)``). Use this when
/// binding to exactly one address.
///
/// - **`"bindTargets"`**: Multiple addresses to bind to, provided as parallel string and int arrays under
/// `bindTargets.hosts` and `bindTargets.ports`. Exactly one of `"bindTarget"` or `"bindTargets"` must be
/// provided.
///
/// - **`"http"`**: Supported HTTP versions and protocol settings. Supported keys are `"versions"`
/// (a string array of `"http1_1"` and/or `"http2"`) and, when HTTP/2 is enabled, `"http2"` (see
/// ``HTTP2/init(config:)``).
///
/// - **`"transportSecurity"`**: The transport security mode: plaintext, TLS, or mTLS (see
/// ``TransportSecurity/init(config:customCertificateVerificationCallback:)``).
///
/// - **`"backpressureStrategy"`**: The backpressure strategy (see ``BackPressureStrategy/init(config:)``).
///
/// - Parameters:
/// - config: The configuration reader to read configuration values from.
/// - customCertificateVerificationCallback: A custom client certificate verification callback. This must be
/// provided when `transportSecurity.trustRootsSource` is `"customCertificateVerificationCallback"`, and must be
/// `nil` otherwise.
/// - Throws `NIOHTTPServerConfigurationError/customVerificationCallbackProvidedWhenNotUsingMTLS` if provided
/// when `transportSecurity.mode` is not `"mTLS"`.
/// - Throws `NIOHTTPServerSwiftConfigurationError/trustRootsSourceAndVerificationCallbackMismatch` if there
/// is a mismatch between `transportSecurity.trustRootsSource` and whether a custom certificate verification
/// callback is provided.
/// - Throws `NIOHTTPServerSwiftConfigurationError/singularAndPluralBindTargetsProvided` if both
/// `"bindTarget"` and `"bindTargets"` are provided.
/// - Throws `NIOHTTPServerSwiftConfigurationError/bindTargetsHostsAndPortsLengthMismatch` if
/// `bindTargets.hosts` and `bindTargets.ports` have different lengths.
public init(
config: ConfigReader,
customCertificateVerificationCallback: (
@Sendable ([Certificate]) async throws -> CertificateVerificationResult
)? = nil
) throws {
let snapshot = config.snapshot()
try self.init(
bindTargets: try Self.readBindTargets(from: snapshot),
supportedHTTPVersions: try .init(config: snapshot.scoped(to: "http")),
transportSecurity: try .init(
config: snapshot.scoped(to: "transportSecurity"),
customCertificateVerificationCallback: customCertificateVerificationCallback
),
backpressureStrategy: .init(config: snapshot.scoped(to: "backpressureStrategy"))
)
}
/// Reads bind targets from either the singular `bindTarget` scope or the plural `bindTargets` scope.
/// Exactly one of the two must be provided.
private static func readBindTargets(
from snapshot: ConfigSnapshotReader
) throws -> [BindTarget] {
let bindTargetsScope = snapshot.scoped(to: "bindTargets")
let hosts = bindTargetsScope.stringArray(forKey: "hosts")
let ports = bindTargetsScope.intArray(forKey: "ports")
let hasPlural = hosts != nil || ports != nil
let bindTargetScope = snapshot.scoped(to: "bindTarget")
let singularHost = bindTargetScope.string(forKey: "host")
let singularPort = bindTargetScope.int(forKey: "port")
let hasSingular = singularHost != nil || singularPort != nil
if hasSingular && hasPlural {
throw NIOHTTPServerSwiftConfigurationError.singularAndPluralBindTargetsProvided
}
if hasPlural {
let hosts = hosts ?? []
let ports = ports ?? []
guard hosts.count == ports.count else {
throw NIOHTTPServerSwiftConfigurationError.bindTargetsHostsAndPortsLengthMismatch
}
return zip(hosts, ports).map { .hostAndPort(host: $0, port: $1) }
}
return [try BindTarget(config: bindTargetScope)]
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.BindTarget {
/// Initialize a bind target configuration from a config reader.
///
/// ## Configuration keys:
/// - `host` (string, required): The hostname or IP address the server will bind to (e.g., "localhost", "0.0.0.0").
/// - `port` (int, required): The port number the server will listen on (e.g., 8080, 443).
///
/// - Parameter config: The configuration reader.
public init(config: ConfigSnapshotReader) throws {
self.init(
backing: .hostAndPort(
host: try config.requiredString(forKey: "host"),
port: try config.requiredInt(forKey: "port")
)
)
}
}
private enum HTTPVersionKind: String {
case http1_1
case http2
}
@available(anyAppleOS 26.0, *)
extension Set where Element == NIOHTTPServerConfiguration.HTTPVersion {
/// Initialize a supported HTTP versions configuration from a config reader.
///
/// ## Configuration keys:
/// - `versions` (string array, required): A set of HTTP versions the server should support (permitted values:
/// `"http1_1"`, `"http2"`).
/// - If `"http2"` is contained in this array, then HTTP/2 configuration can be specified under the `"http2"`
/// key. See ``NIOHTTPServerConfiguration/HTTP2/init(config:)`` for the supported keys under `"http2"`.
///
/// - Throws `NIOHTTPServerConfigurationError/noSupportedHTTPVersionsSpecified` if no supported HTTP versions are
/// specified under the "versions" key.
/// - Parameter config: The configuration reader.
public init(config: ConfigSnapshotReader) throws {
self = .init()
let versions = Set<HTTPVersionKind>(
try config.requiredStringArray(forKey: "versions", as: HTTPVersionKind.self)
)
if versions.isEmpty {
throw NIOHTTPServerConfigurationError.noSupportedHTTPVersionsSpecified
}
for version in versions {
switch version {
case .http1_1:
self.insert(.http1_1)
case .http2:
let h2Config = NIOHTTPServerConfiguration.HTTP2(config: config.scoped(to: "http2"))
self.insert(.http2(config: h2Config))
}
}
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.TransportSecurity {
/// Initialize a transport security configuration from a config reader.
///
/// ## Configuration keys:
/// - `mode` (string, required): The transport security mode for the server (permitted values: `"plaintext"`,
/// `"tls"`, `"mTLS"`).
/// - `credentialSource` (string, required for `"tls"` and `"mTLS"`): How TLS credentials are provided (permitted
/// values: `"inline"`, `"file"`).
///
/// ### Configuration keys for `credentialSource: "inline"`:
/// - `certificateChainPEMString` (string, required): PEM-formatted certificate chain content.
/// - `privateKeyPEMString` (string, required, secret): PEM-formatted private key content.
///
/// ### Configuration keys for `credentialSource: "file"`:
/// - `certificateChainPEMPath` (string, required): Path to the certificate chain PEM file.
/// - `privateKeyPEMPath` (string, required): Path to the private key PEM file.
/// - `refreshInterval` (int, optional): The interval (in seconds) at which the certificate chain and private key
/// will be reloaded. If omitted, credentials are loaded from the file only once at startup.
///
/// ### Configuration keys for `mode: "mTLS"`:
/// - `trustRootsSource` (string, required): How trust roots are provided (permitted values: `"inline"`, `"file"`,
/// `"systemDefaults"`, `"customCertificateVerificationCallback"`).
/// - `trustRootsPEMString` (string, required for `trustRootsSource: "inline"`): The root certificates as a
/// PEM-encoded string.
/// - `trustRootsPEMPath` (string, required for `trustRootsSource: "file"`): Path to a PEM file containing root
/// certificates.
/// - `certificateVerificationMode` (string, required): The client certificate validation behavior (permitted
/// values: "optionalVerification" or "noHostnameVerification").
///
/// - Parameters:
/// - config: The configuration reader.
/// - customCertificateVerificationCallback: A custom client certificate verification callback. This argument must
/// be provided when `trustRootsSource` is `"customCertificateVerificationCallback"`, and must be `nil`
/// otherwise.
/// - Throws `NIOHTTPServerConfigurationError/customVerificationCallbackProvidedWhenNotUsingMTLS` if the
/// callback is provided when `mode` is not `"mTLS"`.
/// - Throws `NIOHTTPServerConfigurationError/trustRootsSourceAndVerificationCallbackMismatch` if there is a
/// mismatch between `trustRootsSource` and whether the callback is provided.
public init(
config: ConfigSnapshotReader,
customCertificateVerificationCallback: (
@Sendable ([Certificate]) async throws -> CertificateVerificationResult
)? = nil
) throws {
let mode = try config.requiredString(forKey: "mode", as: TransportSecurityMode.self)
// A custom verification callback can only be used when the server is configured for mTLS.
if let _ = customCertificateVerificationCallback, mode != .mTLS {
throw NIOHTTPServerSwiftConfigurationError.customVerificationCallbackProvidedWhenNotUsingMTLS
}
switch mode {
case .plaintext:
self = .plaintext
case .tls:
self = .tls(credentials: try .init(config: config))
case .mTLS:
self = .mTLS(
credentials: try .init(config: config),
trustConfiguration: try .init(
config: config,
customCertificateVerificationCallback: customCertificateVerificationCallback
)
)
}
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.TransportSecurity.TLSCredentials {
/// Initialize TLS credentials (certificate chain and private key) from a config reader.
///
/// When `credentialSource` is `"inline"`, the certificate chain and private key are read as PEM strings from the
/// configuration. When `"file"`, they are loaded from disk, optionally reloading at a configured interval.
fileprivate init(config: ConfigSnapshotReader) throws {
let credentialSource = try config.requiredString(
forKey: "credentialSource",
as: NIOHTTPServerConfiguration.TransportSecurity.CredentialSource.self
)
switch credentialSource {
case .inline:
let certificateChainPEMString = try config.requiredString(forKey: "certificateChainPEMString")
let privateKeyPEMString = try config.requiredString(forKey: "privateKeyPEMString", isSecret: true)
self = .inMemory(
certificateChain: try PEMDocument.parseMultiple(pemString: certificateChainPEMString)
.map { try Certificate(pemEncoded: $0.pemString) },
privateKey: try .init(pemEncoded: privateKeyPEMString)
)
case .file:
let certificateChainPEMPath = try config.requiredString(forKey: "certificateChainPEMPath")
let privateKeyPEMPath = try config.requiredString(forKey: "privateKeyPEMPath")
let refreshInterval = config.int(forKey: "refreshInterval")
if let refreshInterval {
self = .reloading(
certificateReloader: TimedCertificateReloader(
refreshInterval: .seconds(refreshInterval),
certificateSource: .init(location: .file(path: certificateChainPEMPath), format: .pem),
privateKeySource: .init(location: .file(path: privateKeyPEMPath), format: .pem)
)
)
} else {
self = .pemFile(
certificateChainPath: certificateChainPEMPath,
privateKeyPath: privateKeyPEMPath
)
}
}
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.TransportSecurity.MTLSTrustConfiguration {
/// Initialize an mTLS trust configuration from a config reader.
///
/// ## Configuration keys:
/// - `trustRootsSource` (string, required): How trust roots are provided (permitted values: `"inline"`, `"file"`,
/// `"systemDefaults"`, `"customCertificateVerificationCallback"`).
/// - `trustRootsPEMString` (string, required for `trustRootsSource: "inline"`): The trusted root certificates as a
/// PEM-encoded string.
/// - `trustRootsPEMPath` (string, required for `trustRootsSource: "file"`): Path to a PEM file containing trusted
/// root certificates.
/// - `certificateVerificationMode` (string, required): The client certificate validation behavior (permitted
/// values: "optionalVerification" or "noHostnameVerification")
///
/// - Parameters:
/// - config: The configuration reader.
/// - customCertificateVerificationCallback: A client certificate verification callback. Must be provided when
/// `trustRootsSource` is `"customCertificateVerificationCallback"`, and must be `nil` otherwise.
///
/// - Throws: `NIOHTTPServerSwiftConfigurationError/trustRootsSourceAndVerificationCallbackMismatch` if:
/// - A verification callback is provided when `trustRootsSource != "customCertificateVerificationCallback"`, or;
/// - A verification callback is *not* provided when `trustRootsSource == "customCertificateVerificationCallback"`.
public init(
config: ConfigSnapshotReader,
customCertificateVerificationCallback: (
@Sendable ([X509.Certificate]) async throws -> CertificateVerificationResult
)?
) throws {
let trustRootsSource = try config.requiredString(forKey: "trustRootsSource", as: TrustRootsSource.self)
let certificateVerificationMode = try config.requiredString(
forKey: "certificateVerificationMode",
as: VerificationMode.self
)
if let _ = customCertificateVerificationCallback, trustRootsSource != .customCertificateVerificationCallback {
throw NIOHTTPServerSwiftConfigurationError.trustRootsSourceAndVerificationCallbackMismatch
}
switch trustRootsSource {
case .inline:
let trustRootsPEMString = try config.requiredString(forKey: "trustRootsPEMString")
self = .inMemory(
trustRoots: try PEMDocument.parseMultiple(pemString: trustRootsPEMString)
.map { try Certificate(pemEncoded: $0.pemString) },
certificateVerification: .init(certificateVerificationMode)
)
case .file:
let trustRootsPEMPath = try config.requiredString(forKey: "trustRootsPEMPath")
self = .pemFile(
path: trustRootsPEMPath,
certificateVerification: .init(certificateVerificationMode)
)
case .systemDefaults:
self = .systemDefaults(certificateVerification: .init(certificateVerificationMode))
case .customCertificateVerificationCallback:
guard let customCertificateVerificationCallback else {
// No custom verification callback provided despite the "trustRootsSource" key being set to
// "customCertificateVerificationCallback".
throw NIOHTTPServerSwiftConfigurationError.trustRootsSourceAndVerificationCallbackMismatch
}
self = .customCertificateVerificationCallback(
customCertificateVerificationCallback,
certificateVerification: .init(certificateVerificationMode)
)
}
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.BackPressureStrategy {
/// Initialize the backpressure strategy configuration from a config reader.
///
/// ## Configuration keys:
/// - `lowWatermark` (int, optional, default: 2): The threshold below which the consumer will ask the producer to
/// produce more elements.
/// - `highWatermark` (int, optional, default: 10): The threshold above which the producer will stop producing
/// elements.
///
/// - Parameter config: The configuration reader.
public init(config: ConfigSnapshotReader) {
self.init(
backing: .watermark(
low: config.int(
forKey: "lowWatermark",
default: NIOHTTPServerConfiguration.BackPressureStrategy.defaultWatermarkLow
),
high: config.int(
forKey: "highWatermark",
default: NIOHTTPServerConfiguration.BackPressureStrategy.defaultWatermarkHigh
)
)
)
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.HTTP2 {
/// Initialize a HTTP/2 configuration from a config reader.
///
/// ## Configuration keys:
/// - `maxFrameSize` (int, optional, default: 2^14): The maximum frame size to be used in an HTTP/2 connection.
/// - `targetWindowSize` (int, optional, default: 2^16 - 1): The target window size to be used in an HTTP/2
/// connection.
/// - `maxConcurrentStreams` (int, optional, default: nil): The maximum number of concurrent streams in an HTTP/2
/// connection.
/// - `gracefulShutdown.maximumDuration` (int, optional, default: nil): The maximum amount of time (in seconds) that
/// the connection has to close gracefully.
///
/// - Parameter config: The configuration reader.
public init(config: ConfigSnapshotReader) {
self.init(
maxFrameSize: config.int(
forKey: "maxFrameSize",
default: NIOHTTPServerConfiguration.HTTP2.defaultMaxFrameSize
),
targetWindowSize: config.int(
forKey: "targetWindowSize",
default: NIOHTTPServerConfiguration.HTTP2.defaultTargetWindowSize
),
/// The default value, ``NIOHTTPServerConfiguration.HTTP2.DEFAULT_TARGET_WINDOW_SIZE``, is `nil`. However,
/// we can only specify a non-nil `default` argument to `config.int(...)`. But `config.int(...)` already
/// defaults to `nil` if it can't find the `"maxConcurrentStreams"` key, so that works for us.
maxConcurrentStreams: config.int(forKey: "maxConcurrentStreams"),
gracefulShutdown: .init(config: config.scoped(to: "gracefulShutdown"))
)
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.HTTP2.GracefulShutdownConfiguration {
/// Initialize a HTTP/2 graceful shutdown configuration from a config reader.
///
/// ## Configuration keys:
/// - `maximumDuration` (int, optional, default: nil): The maximum amount of time (in seconds) that the connection
/// has to close gracefully.
///
/// - Parameter config: The configuration reader.
public init(config: ConfigSnapshotReader) {
self.init(
maximumGracefulShutdownDuration: config.int(forKey: "maximumDuration").map { .seconds($0) }
)
}
}
@available(anyAppleOS 26.0, *)
extension Set where Element == NIOHTTPServerConfiguration.HTTPVersion {
fileprivate enum HTTPVersionKind: String {
case http1_1
case http2
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.TransportSecurity {
fileprivate enum TransportSecurityMode: String {
case plaintext
case tls
case mTLS
}
fileprivate enum CredentialSource: String {
case inline
case file
}
}
@available(anyAppleOS 26.0, *)
extension NIOHTTPServerConfiguration.TransportSecurity.MTLSTrustConfiguration {
/// The supported sources for trust roots.
fileprivate enum TrustRootsSource: String {
case inline
case file
case systemDefaults
case customCertificateVerificationCallback
}
/// A wrapper over ``CertificateVerificationMode``.
fileprivate enum VerificationMode: String {
case optionalVerification
case noHostnameVerification
}
}
@available(anyAppleOS 26.0, *)
extension CertificateVerificationMode {
fileprivate init(_ mode: NIOHTTPServerConfiguration.TransportSecurity.MTLSTrustConfiguration.VerificationMode) {
switch mode {
case .optionalVerification:
self.init(mode: .optionalVerification)
case .noHostnameVerification:
self.init(mode: .noHostnameVerification)
}
}
}
#endif // Configuration