Files
swift-nio-imap/Examples/IMAPTool/Tests/IMAPToolLibTests/Operations/TestConnection.swift
T
Daniel Eggert 4606da62d2 Validate response text, command tags and namespace delimiters (#866)
* Reject invalid response text when writing

`.no(.init(text: "No mailbox x\r\n* BYE pwned"))` was written verbatim,
injecting an untagged response; likewise tagged, BYE, PREAUTH and
continuation responses.

RFC 9051: `text = 1*(TEXT-CHAR / UTF8-2 / UTF8-3 / UTF8-4)`. `writeText`
now asserts no NUL, CR or LF. Empty stays valid. The parser now accepts
UTF-8 text.

* Add Command.Tag for command and response tags

`TaggedCommand(tag: "A1 NOOP\r\nA2 DELETE INBOX\r\nA3", command: .noop)`
was written verbatim, injecting a command; likewise `APPEND` start.
`TaggedResponse(tag: "* BYE x\r\nA1", …)` injected a response.

RFC 3501: `tag = 1*<any ASTRING-CHAR except "+">`. New `Command.Tag`
replaces the `String` in `TaggedCommand`, `TaggedResponse`, `Response`,
`CommandStreamPart`, `AppendCommand`, `BadCommand` and NIOIMAP's state
machine errors; `init?(_:)` validates, literals trap. The parser already
enforces the production. IMAPCommands converts its numeric tags.

* Validate and escape namespace delimiters

`NamespaceDescription(string: "x", char: "\r\n", …)` wrote a raw CRLF
inside `"…"`, injecting a response. `"\""` encoded as `"""`, and `"\\"`
as `"\"` (unterminated); non-ASCII was accepted.

RFC 2342: `DQUOTE QUOTED-CHAR DQUOTE / nil`. `init(string:delimiter:
responseExtensions:)` (was `char:`) throws `InvalidDelimiterError` for
non-ASCII, CR, LF, NUL; the delimiter is stored as a byte, read-only.
Quoted-specials are escaped on write and parsed when escaped.

* Gate a capturing exit test on Swift 6.3
2026-11-04 17:41:52 +00:00

155 lines
4.8 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import IMAPCommands
import Foundation
@testable import IMAPToolLib
import NIO
import NIOIMAP
extension TestConnection {
struct CommandAndResponses: Hashable, Sendable {
var command: NIOIMAPCore.Command
var responses: [Response]
var completion: TaggedResponse.State
}
}
extension TestConnection.CommandAndResponses {
init(
command: NIOIMAPCore.Command,
untagged: [ResponsePayload],
completion: TaggedResponse.State = .ok(.init(text: "Done"))
) {
self.init(
command: command,
responses: untagged.map { .untagged($0) },
completion: completion
)
}
}
extension TestConnection.CommandAndResponses {
init(
command: NIOIMAPCore.Command,
fetchResponses: [FetchResponse],
completion: TaggedResponse.State = .ok(.init(text: "Done"))
) {
self.init(
command: command,
responses: fetchResponses.map { .fetch($0) },
completion: completion
)
}
}
// MARK: -
/// A simple connection for tests — with expected commands and their responses.
final actor TestConnection: ConnectionProtocol {
init(
expectedOrdering: Ordering = .inOrder,
expectedCommands: [CommandAndResponses]
) {
self.expectedOrdering = expectedOrdering
self.expectedCommands = expectedCommands
}
enum Ordering: Hashable, Sendable {
case inOrder
case anyOrder
}
var _nextTag = IMAPConnection.Tag.first
func makeNextTag() -> IMAPConnection.Tag {
defer { _nextTag = _nextTag.makeNext() }
return _nextTag
}
let expectedOrdering: Ordering
var expectedCommands: [CommandAndResponses]
private var currentContinuations:
[IMAPConnection.Tag: AsyncThrowingStream<Response, any Swift.Error>.Continuation] = [:]
/// Runs in the caller's isolation domain — like `IMAPConnection.send(_:_:)` — rather than on
/// this actor, so that the handler does too. `nonisolated` is explicit because an actor's
/// methods are otherwise isolated to `self`.
nonisolated(nonsending) func send<Result>(
_ command: NIOIMAPCore.Command,
_ handler: nonisolated(nonsending) (IMAPConnection.Tag, IMAPConnection.ResponseStream) async throws -> Result
) async throws -> Result {
let (tag, responses) = try await beginCommand(command)
let r = try await handler(tag, responses)
await finishCommand(tag: tag)
return r
}
private func beginCommand(
_ command: NIOIMAPCore.Command
) throws -> (IMAPConnection.Tag, IMAPConnection.ResponseStream) {
let commandAndResponses: TestConnection.CommandAndResponses
switch expectedOrdering {
case .inOrder:
guard
!expectedCommands.isEmpty,
expectedCommands.first?.command == command
else { throw Error.unexpectedCommand(command) }
commandAndResponses = expectedCommands.removeFirst()
case .anyOrder:
guard
let index = expectedCommands.firstIndex(where: { $0.command == command })
else { throw Error.unexpectedCommand(command) }
commandAndResponses = expectedCommands.remove(at: index)
}
let tag = makeNextTag()
let responses = makeResponseStream(
tag: tag,
commandAndResponses: commandAndResponses
)
return (tag, responses)
}
private func finishCommand(tag: IMAPConnection.Tag) {
currentContinuations.removeValue(forKey: tag)
}
private func makeResponseStream(
tag: IMAPConnection.Tag,
commandAndResponses: CommandAndResponses
) -> IMAPConnection.ResponseStream {
let (stream, continuation) = AsyncThrowingStream<Response, any Swift.Error>.makeStream(of: Response.self)
for r in commandAndResponses.responses {
continuation.yield(r)
}
let state = commandAndResponses.completion
continuation.yield(
.tagged(
TaggedResponse(
tag: Command.Tag(String(tag))!,
state: state
)
)
)
continuation.finish()
return IMAPConnection.ResponseStream(underlying: stream)
}
enum Error: Swift.Error {
case unexpectedCommand(NIOIMAPCore.Command)
}
}