import Foundation import NIOSSL import PostgresNIO /// A parsed `postgres://user:password@host:port/database?sslmode=…` URL. /// /// PostgresNIO has no URL initializer, so the URL the Go service read from /// `EFFEM_DATABASE_URL` is parsed here and turned into a client configuration. /// `sslmode` follows libpq: `disable` sends no TLS, `require` encrypts without /// checking the certificate, `verify-ca` and `verify-full` check it, and /// anything else prefers TLS when the server offers it. struct DatabaseURL: Sendable, Equatable { enum SSLMode: String, Sendable { case disable case allow case prefer case require case verifyCA = "verify-ca" case verifyFull = "verify-full" } enum ParseError: Error, Equatable, Sendable { case invalidURL(String) case unsupportedScheme(String) case missingUser case invalidSSLMode(String) } let host: String let port: Int let username: String let password: String? let database: String? let sslMode: SSLMode init(_ string: String) throws { guard let components = URLComponents(string: string) else { throw ParseError.invalidURL(string) } guard let scheme = components.scheme, scheme == "postgres" || scheme == "postgresql" else { throw ParseError.unsupportedScheme(components.scheme ?? "") } guard let host = components.host, !host.isEmpty else { throw ParseError.invalidURL(string) } guard let username = components.user, !username.isEmpty else { throw ParseError.missingUser } self.host = host self.port = components.port ?? 5432 self.username = username self.password = components.password let path = components.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")) self.database = path.isEmpty ? nil : path if let raw = components.queryItems?.first(where: { $0.name == "sslmode" })?.value { guard let mode = SSLMode(rawValue: raw) else { throw ParseError.invalidSSLMode(raw) } self.sslMode = mode } else { self.sslMode = .prefer } } /// Hosts that may skip TLS: loopback, the compose and CI service names, /// mDNS `.local` names and `.internal`, the reserved private-use domain /// (Docker's `host.docker.internal` and Railway's private network /// among them). Anything else must at least require it, because it is /// reached over the public internet. var isLocalHost: Bool { ["localhost", "127.0.0.1", "::1", "postgres", "db"].contains(host.lowercased()) || host.hasSuffix(".local") || host.hasSuffix(".internal") } func clientConfiguration(maximumConnections: Int, minimumConnections: Int, idleTimeout: Duration) throws -> PostgresClient.Configuration { let tls: PostgresClient.Configuration.TLS switch sslMode { case .disable: tls = .disable case .allow, .prefer: tls = .prefer(try Self.tlsConfiguration(verifying: false)) case .require: tls = .require(try Self.tlsConfiguration(verifying: false)) case .verifyCA, .verifyFull: tls = .require(try Self.tlsConfiguration(verifying: true)) } var configuration = PostgresClient.Configuration(host: host, port: port, username: username, password: password, database: database, tls: tls) configuration.options.maximumConnections = maximumConnections configuration.options.minimumConnections = minimumConnections configuration.options.connectionIdleTimeout = idleTimeout configuration.options.tlsServerName = host return configuration } /// The configuration for a single connection outside the pool, such as /// the one that listens for notifications. func connectionConfiguration() throws -> PostgresConnection.Configuration { let tls: PostgresConnection.Configuration.TLS switch sslMode { case .disable: tls = .disable case .allow, .prefer: tls = .prefer(try NIOSSLContext(configuration: Self.tlsConfiguration(verifying: false))) case .require: tls = .require(try NIOSSLContext(configuration: Self.tlsConfiguration(verifying: false))) case .verifyCA, .verifyFull: tls = .require(try NIOSSLContext(configuration: Self.tlsConfiguration(verifying: true))) } var configuration = PostgresConnection.Configuration(host: host, port: port, username: username, password: password, database: database, tls: tls) configuration.options.tlsServerName = host return configuration } private static func tlsConfiguration(verifying: Bool) throws -> TLSConfiguration { var configuration = TLSConfiguration.makeClientConfiguration() configuration.certificateVerification = verifying ? .fullVerification : .none return configuration } }