Files

1612 lines
60 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import NIO
@testable import NIOIMAP
@testable import NIOIMAPCore
import OrderedCollections
import Testing
import Synchronization
@Suite("IMAPClientHandler")
struct IMAPClientHandlerTests {
@Test("basic command and response")
func basicCommandAndResponse() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "a", command: .login(username: "foo", password: "bar"))))
helper.expectOutboundString("a LOGIN \"foo\" \"bar\"\r\n")
helper.writeInbound("a OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "a",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
}
@Test("FETCH literal whose header CRLF is split across reads")
func fetchLiteralWithSplitHeaderCRLF() {
var helper = Helper()
defer {
helper.check()
}
helper.writeInbound("* 1 FETCH (BODY[] {5}\r")
helper.writeInbound("\nabc\r\n)\r\n")
helper.expectInbound(.fetch(.start(1)))
helper.expectInbound(.fetch(.streamingBegin(kind: .body(section: .init(), offset: nil), byteCount: 5)))
helper.expectInbound(.fetch(.streamingBytes("abc\r\n")))
helper.expectInbound(.fetch(.streamingEnd))
helper.expectInbound(.fetch(.finish))
}
@Test("referral URL response")
func referralURLResponse() {
var helper = Helper()
defer {
helper.check()
}
let expectedResponse = Response.tagged(
TaggedResponse(
tag: "A1",
state: .ok(
ResponseText(
code:
.referral(
IMAPURL(
server: IMAPServer(userAuthenticationMechanism: nil, host: "hostname", port: nil),
query: URLCommand.fetch(
path: MessagePath(
mailboxReference: MailboxUIDValidity(
encodeMailbox: "foo/bar",
uidValidity: nil
),
iUID: IUID(uid: 1234),
section: nil,
range: nil
),
authenticatedURL: nil
)
)
),
text: ""
)
)
)
)
helper.writeOutbound(.tagged(.init(tag: "A1", command: .login(username: "foo", password: "bar"))))
helper.expectOutboundString("A1 LOGIN \"foo\" \"bar\"\r\n")
helper.writeInbound("A1 OK [REFERRAL imap://hostname/foo/bar/;UID=1234]\r\n")
helper.expectInbound(expectedResponse)
}
@Test("command that needs to wait for continuation request")
func commandThatNeedsToWaitForContinuationRequest() {
var helper = Helper()
defer {
helper.check()
}
let f = helper.writeOutbound(
CommandStreamPart.tagged(
TaggedCommand(
tag: "x",
command: .rename(
from: .init("å"),
to: .init("to"),
parameters: [:]
)
)
),
wait: false
)
helper.expectOutboundString("x RENAME {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("å \"to\"\r\n")
#expect(throws: Never.self) { try f.wait() }
helper.writeInbound("x OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "x",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
}
@Test("command that needs to wait for two continuation requests")
func commandThatNeedsToWaitForTwoContinuationRequest() {
var helper = Helper()
defer {
helper.check()
}
let f = helper.writeOutbound(
CommandStreamPart.tagged(
TaggedCommand(
tag: "x",
command: .rename(
from: .init("å"),
to: .init("ß"),
parameters: [:]
)
)
),
wait: false
)
helper.expectOutboundString("x RENAME {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("å {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("ß\r\n")
#expect(throws: Never.self) { try f.wait() }
helper.writeInbound("x OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "x",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
}
@Test("two continuation request commands enqueued")
func twoContReqCommandsEnqueued() {
var helper = Helper()
defer {
helper.check()
}
let f1 = helper.writeOutbound(
CommandStreamPart.tagged(
TaggedCommand(
tag: "x",
command: .rename(
from: .init("å"),
to: .init("to"),
parameters: [:]
)
)
),
wait: false
)
let f2 = helper.writeOutbound(
CommandStreamPart.tagged(
TaggedCommand(
tag: "y",
command: .rename(
from: .init("from"),
to: .init("ß"),
parameters: [:]
)
)
),
wait: false
)
helper.expectOutboundString("x RENAME {2}\r\n")
helper.writeInbound("+ OK\r\n")
#expect(throws: Never.self) { try f1.wait() }
helper.expectOutboundString("å \"to\"\r\n")
helper.expectOutboundString("y RENAME \"from\" {2}\r\n")
helper.writeInbound("+ OK\r\n")
#expect(throws: Never.self) { try f2.wait() }
helper.expectOutboundString("ß\r\n")
helper.writeInbound("x OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "x",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
helper.writeInbound("y OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "y",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
}
// This makes sure that we successfully switch from responding to continuation
// requests back to "simple" commands that can be written in one shot. This was a bug
// in a previous implementation, so this test prevents regression.
@Test("three continuation request commands enqueued followed by 2 basic ones")
func threeContReqCommandsEnqueuedFollowedBy2BasicOnes() {
var helper = Helper()
defer {
helper.check()
}
let f1 = helper.writeOutbound(.tagged(.init(tag: "1", command: .create(.init("å"), []))), wait: false)
let f2 = helper.writeOutbound(.tagged(.init(tag: "2", command: .create(.init("ß"), []))), wait: false)
let f3 = helper.writeOutbound(.tagged(.init(tag: "3", command: .create(.init("∂"), []))), wait: false)
let f4 = helper.writeOutbound(.tagged(.init(tag: "4", command: .create(.init("a"), []))), wait: false)
let f5 = helper.writeOutbound(.tagged(.init(tag: "5", command: .create(.init("b"), []))), wait: false)
helper.expectOutboundString("1 CREATE {2}\r\n")
helper.writeInbound("+ OK\r\n")
#expect(throws: Never.self) { try f1.wait() }
helper.expectOutboundString("å\r\n")
helper.expectOutboundString("2 CREATE {2}\r\n")
helper.writeInbound("+ OK\r\n")
#expect(throws: Never.self) { try f2.wait() }
helper.expectOutboundString("ß\r\n")
helper.expectOutboundString("3 CREATE {3}\r\n")
helper.writeInbound("+ OK\r\n")
#expect(throws: Never.self) { try f3.wait() }
helper.expectOutboundString("∂\r\n")
helper.expectOutboundString("4 CREATE \"a\"\r\n")
#expect(throws: Never.self) { try f4.wait() }
helper.expectOutboundString("5 CREATE \"b\"\r\n")
#expect(throws: Never.self) { try f5.wait() }
helper.writeInbound("1 OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "1",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
helper.writeInbound("2 OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "2",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
helper.writeInbound("3 OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "3",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
helper.writeInbound("4 OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "4",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
helper.writeInbound("5 OK ok\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "5",
state: .ok(.init(code: nil, text: "ok"))
)
)
)
}
@Test("unexpected continuation request")
func unexpectedContinuationRequest() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(
CommandStreamPart.tagged(
TaggedCommand(
tag: "x",
command: .rename(
from: .init("from"),
to: .init("to"),
parameters: [:]
)
)
)
)
helper.expectOutboundString("x RENAME \"from\" \"to\"\r\n")
#expect(throws: UnexpectedContinuationRequest.self) {
try helper.channel.writeInbound(helper.buffer(string: "+ OK\r\n+ OK\r\n"))
}
}
@Test("authentication flow")
func authenticationFlow() {
var helper = Helper()
defer {
helper.check()
}
// client starts authentication
helper.writeOutbound(
.tagged(.init(tag: "A1", command: .authenticate(mechanism: .gssAPI, initialResponse: nil)))
)
helper.expectOutboundString("A1 AUTHENTICATE GSSAPI\r\n")
// server sends challenge
let challengeBytes1 = ""
helper.writeInbound("+ \(challengeBytes1)\r\n")
helper.expectInbound(.authenticationChallenge(ByteBuffer()))
// client responds
let responseBytes1 =
"YIIB+wYJKoZIhvcSAQICAQBuggHqMIIB5qADAgEFoQMCAQ6iBwMFACAAAACjggEmYYIBIjCCAR6gAwIBBaESGxB1Lndhc2hpbmd0b24uZWR1oi0wK6ADAgEDoSQwIhsEaW1hcBsac2hpdmFtcy5jYWMud2FzaGluZ3Rvbi5lZHWjgdMwgdCgAwIBAaEDAgEDooHDBIHAcS1GSa5b+fXnPZNmXB9SjL8Ollj2SKyb+3S0iXMljen/jNkpJXAleKTz6BQPzj8duz8EtoOuNfKgweViyn/9B9bccy1uuAE2HI0yC/PHXNNU9ZrBziJ8Lm0tTNc98kUpjXnHZhsMcz5Mx2GR6dGknbI0iaGcRerMUsWOuBmKKKRmVMMdR9T3EZdpqsBd7jZCNMWotjhivd5zovQlFqQ2Wjc2+y46vKP/iXxWIuQJuDiisyXF0Y8+5GTpALpHDc1/pIGmMIGjoAMCAQGigZsEgZg2on5mSuxoDHEA1w9bcW9nFdFxDKpdrQhVGVRDIzcCMCTzvUboqb5KjY1NJKJsfjRQiBYBdENKfzK+g5DlV8nrw81uOcP8NOQCLR5XkoMHC0Dr/80ziQzbNqhxO6652Npft0LQwJvenwDI13YxpwOdMXzkWZN/XrEqOWp6GCgXTBvCyLWLlWnbaUkZdEYbKHBPjd8t/1x5Yg=="
helper.writeOutbound(
.continuationResponse(
ByteBuffer(bytes: [
0x60, 0x82, 0x01, 0xFB, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x12, 0x01, 0x02, 0x02, 0x01,
0x00,
0x6E, 0x82, 0x01, 0xEA, 0x30, 0x82, 0x01, 0xE6, 0xA0, 0x03, 0x02, 0x01, 0x05, 0xA1, 0x03, 0x02,
0x01,
0x0E, 0xA2, 0x07, 0x03, 0x05, 0x00, 0x20, 0x00, 0x00, 0x00, 0xA3, 0x82, 0x01, 0x26, 0x61, 0x82,
0x01,
0x22, 0x30, 0x82, 0x01, 0x1E, 0xA0, 0x03, 0x02, 0x01, 0x05, 0xA1, 0x12, 0x1B, 0x10, 0x75, 0x2E,
0x77,
0x61, 0x73, 0x68, 0x69, 0x6E, 0x67, 0x74, 0x6F, 0x6E, 0x2E, 0x65, 0x64, 0x75, 0xA2, 0x2D, 0x30,
0x2B,
0xA0, 0x03, 0x02, 0x01, 0x03, 0xA1, 0x24, 0x30, 0x22, 0x1B, 0x04, 0x69, 0x6D, 0x61, 0x70, 0x1B,
0x1A,
0x73, 0x68, 0x69, 0x76, 0x61, 0x6D, 0x73, 0x2E, 0x63, 0x61, 0x63, 0x2E, 0x77, 0x61, 0x73, 0x68,
0x69,
0x6E, 0x67, 0x74, 0x6F, 0x6E, 0x2E, 0x65, 0x64, 0x75, 0xA3, 0x81, 0xD3, 0x30, 0x81, 0xD0, 0xA0,
0x03,
0x02, 0x01, 0x01, 0xA1, 0x03, 0x02, 0x01, 0x03, 0xA2, 0x81, 0xC3, 0x04, 0x81, 0xC0, 0x71, 0x2D,
0x46,
0x49, 0xAE, 0x5B, 0xF9, 0xF5, 0xE7, 0x3D, 0x93, 0x66, 0x5C, 0x1F, 0x52, 0x8C, 0xBF, 0x0E, 0x96,
0x58,
0xF6, 0x48, 0xAC, 0x9B, 0xFB, 0x74, 0xB4, 0x89, 0x73, 0x25, 0x8D, 0xE9, 0xFF, 0x8C, 0xD9, 0x29,
0x25,
0x70, 0x25, 0x78, 0xA4, 0xF3, 0xE8, 0x14, 0x0F, 0xCE, 0x3F, 0x1D, 0xBB, 0x3F, 0x04, 0xB6, 0x83,
0xAE,
0x35, 0xF2, 0xA0, 0xC1, 0xE5, 0x62, 0xCA, 0x7F, 0xFD, 0x07, 0xD6, 0xDC, 0x73, 0x2D, 0x6E, 0xB8,
0x01,
0x36, 0x1C, 0x8D, 0x32, 0x0B, 0xF3, 0xC7, 0x5C, 0xD3, 0x54, 0xF5, 0x9A, 0xC1, 0xCE, 0x22, 0x7C,
0x2E,
0x6D, 0x2D, 0x4C, 0xD7, 0x3D, 0xF2, 0x45, 0x29, 0x8D, 0x79, 0xC7, 0x66, 0x1B, 0x0C, 0x73, 0x3E,
0x4C,
0xC7, 0x61, 0x91, 0xE9, 0xD1, 0xA4, 0x9D, 0xB2, 0x34, 0x89, 0xA1, 0x9C, 0x45, 0xEA, 0xCC, 0x52,
0xC5,
0x8E, 0xB8, 0x19, 0x8A, 0x28, 0xA4, 0x66, 0x54, 0xC3, 0x1D, 0x47, 0xD4, 0xF7, 0x11, 0x97, 0x69,
0xAA,
0xC0, 0x5D, 0xEE, 0x36, 0x42, 0x34, 0xC5, 0xA8, 0xB6, 0x38, 0x62, 0xBD, 0xDE, 0x73, 0xA2, 0xF4,
0x25,
0x16, 0xA4, 0x36, 0x5A, 0x37, 0x36, 0xFB, 0x2E, 0x3A, 0xBC, 0xA3, 0xFF, 0x89, 0x7C, 0x56, 0x22,
0xE4,
0x09, 0xB8, 0x38, 0xA2, 0xB3, 0x25, 0xC5, 0xD1, 0x8F, 0x3E, 0xE4, 0x64, 0xE9, 0x00, 0xBA, 0x47,
0x0D,
0xCD, 0x7F, 0xA4, 0x81, 0xA6, 0x30, 0x81, 0xA3, 0xA0, 0x03, 0x02, 0x01, 0x01, 0xA2, 0x81, 0x9B,
0x04,
0x81, 0x98, 0x36, 0xA2, 0x7E, 0x66, 0x4A, 0xEC, 0x68, 0x0C, 0x71, 0x00, 0xD7, 0x0F, 0x5B, 0x71,
0x6F,
0x67, 0x15, 0xD1, 0x71, 0x0C, 0xAA, 0x5D, 0xAD, 0x08, 0x55, 0x19, 0x54, 0x43, 0x23, 0x37, 0x02,
0x30,
0x24, 0xF3, 0xBD, 0x46, 0xE8, 0xA9, 0xBE, 0x4A, 0x8D, 0x8D, 0x4D, 0x24, 0xA2, 0x6C, 0x7E, 0x34,
0x50,
0x88, 0x16, 0x01, 0x74, 0x43, 0x4A, 0x7F, 0x32, 0xBE, 0x83, 0x90, 0xE5, 0x57, 0xC9, 0xEB, 0xC3,
0xCD,
0x6E, 0x39, 0xC3, 0xFC, 0x34, 0xE4, 0x02, 0x2D, 0x1E, 0x57, 0x92, 0x83, 0x07, 0x0B, 0x40, 0xEB,
0xFF,
0xCD, 0x33, 0x89, 0x0C, 0xDB, 0x36, 0xA8, 0x71, 0x3B, 0xAE, 0xB9, 0xD8, 0xDA, 0x5F, 0xB7, 0x42,
0xD0,
0xC0, 0x9B, 0xDE, 0x9F, 0x00, 0xC8, 0xD7, 0x76, 0x31, 0xA7, 0x03, 0x9D, 0x31, 0x7C, 0xE4, 0x59,
0x93,
0x7F, 0x5E, 0xB1, 0x2A, 0x39, 0x6A, 0x7A, 0x18, 0x28, 0x17, 0x4C, 0x1B, 0xC2, 0xC8, 0xB5, 0x8B,
0x95,
0x69, 0xDB, 0x69, 0x49, 0x19, 0x74, 0x46, 0x1B, 0x28, 0x70, 0x4F, 0x8D, 0xDF, 0x2D, 0xFF, 0x5C,
0x79,
0x62,
])
)
)
helper.expectOutboundString("\(responseBytes1)\r\n")
// server challenge 2
let challengeBytes2 =
"YGgGCSqGSIb3EgECAgIAb1kwV6ADAgEFoQMCAQ+iSzBJoAMCAQGiQgRAtHTEuOP2BXb9sBYFR4SJlDZxmg39IxmRBOhXRKdDA0uHTCOT9Bq3OsUTXUlk0CsFLoa8j+gvGDlgHuqzWHPSQg=="
helper.writeInbound("+ \(challengeBytes2)\r\n")
helper.expectInbound(
.authenticationChallenge(
ByteBuffer(bytes: [
0x60, 0x68, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x12, 0x01, 0x02, 0x02, 0x02, 0x00, 0x6F,
0x59,
0x30, 0x57, 0xA0, 0x03, 0x02, 0x01, 0x05, 0xA1, 0x03, 0x02, 0x01, 0x0F, 0xA2, 0x4B, 0x30, 0x49,
0xA0,
0x03, 0x02, 0x01, 0x01, 0xA2, 0x42, 0x04, 0x40, 0xB4, 0x74, 0xC4, 0xB8, 0xE3, 0xF6, 0x05, 0x76,
0xFD,
0xB0, 0x16, 0x05, 0x47, 0x84, 0x89, 0x94, 0x36, 0x71, 0x9A, 0x0D, 0xFD, 0x23, 0x19, 0x91, 0x04,
0xE8,
0x57, 0x44, 0xA7, 0x43, 0x03, 0x4B, 0x87, 0x4C, 0x23, 0x93, 0xF4, 0x1A, 0xB7, 0x3A, 0xC5, 0x13,
0x5D,
0x49, 0x64, 0xD0, 0x2B, 0x05, 0x2E, 0x86, 0xBC, 0x8F, 0xE8, 0x2F, 0x18, 0x39, 0x60, 0x1E, 0xEA,
0xB3,
0x58, 0x73, 0xD2, 0x42,
])
)
)
// client responds
helper.writeOutbound(.continuationResponse(""))
helper.expectOutboundString("\r\n")
// all done
helper.writeInbound("A1 OK Success\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(text: "Success")))))
}
@Test("can change encoding to fixed")
func canChangeEncodingToFixed() {
var helper = Helper()
defer {
helper.check()
}
let f1 = helper.writeOutbound(
.tagged(.init(tag: "A1", command: .login(username: "å", password: "ß"))),
wait: false
)
helper.expectOutboundString("A1 LOGIN {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("å {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("ß\r\n")
#expect(throws: Never.self) { try f1.wait() }
// Change the encoding options:
let f2 = helper.writeOutbound(
.setEncodingOptions(
.fixed(
CommandEncodingOptions(
useSynchronizingLiteral: false,
useNonSynchronizingLiteralPlus: true
)
)
),
wait: false
)
#expect(throws: Never.self) { try f2.wait() }
// now we should have literal+ turned on
let f3 = helper.writeOutbound(
.tagged(.init(tag: "A3", command: .login(username: "å", password: "ß"))),
wait: false
)
helper.expectOutboundString("A3 LOGIN {2+}\r\nå {2+}\r\nß\r\n")
#expect(throws: Never.self) { try f3.wait() }
}
@Test("can change encoding automatically")
func canChangeEncodingAutomatically() {
var helper = Helper()
defer {
helper.check()
}
let f1 = helper.writeOutbound(
.tagged(.init(tag: "A1", command: .login(username: "å", password: "ß"))),
wait: false
)
helper.expectOutboundString("A1 LOGIN {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("å {2}\r\n")
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("ß\r\n")
#expect(throws: Never.self) { try f1.wait() }
// send some capabilities
helper.writeInbound("A1 OK [CAPABILITY IMAP4 LITERAL+]\r\n")
helper.expectInbound(
.tagged(.init(tag: "A1", state: .ok(.init(code: .capability([.imap4, .literalPlus]), text: ""))))
)
// now we should have literal+ turned on
let f3 = helper.writeOutbound(
.tagged(.init(tag: "A3", command: .login(username: "å", password: "ß"))),
wait: false
)
helper.expectOutboundString("A3 LOGIN {2+}\r\nå {2+}\r\nß\r\n")
#expect(throws: Never.self) { try f3.wait() }
}
@Test("continuation requests as user events")
func continuationRequestsAsUserEvents() {
var helper = Helper()
defer {
helper.check()
}
let eventExpectation1 = helper.channel.eventLoop.makePromise(of: Void.self)
let eventExpectation2 = helper.channel.eventLoop.makePromise(of: Void.self)
let eventExpectation3 = helper.channel.eventLoop.makePromise(of: Void.self)
final class UserEventHandler: ChannelDuplexHandler, Sendable {
typealias InboundIn = Response
typealias OutboundIn = CommandStreamPart
let expectation1: EventLoopPromise<Void>
let expectation2: EventLoopPromise<Void>
let expectation3: EventLoopPromise<Void>
init(
expectation1: EventLoopPromise<Void>,
expectation2: EventLoopPromise<Void>,
expectation3: EventLoopPromise<Void>
) {
self.expectation1 = expectation1
self.expectation2 = expectation2
self.expectation3 = expectation3
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
guard let event = event as? ContinuationRequest, case .responseText(let textEvent) = event else {
Issue.record("Unexpected event")
return
}
switch textEvent.text {
case "1": self.expectation1.succeed(())
case "2": self.expectation2.succeed(())
case "3": self.expectation3.succeed(())
default:
Issue.record("Not sure who sent this event, but it wasn't us")
}
}
}
#expect(throws: Never.self) {
try helper.channel.pipeline.addHandler(
UserEventHandler(
expectation1: eventExpectation1,
expectation2: eventExpectation2,
expectation3: eventExpectation3
)
).wait()
}
// confirm it works for literals
helper.writeOutbound(.tagged(.init(tag: "A1", command: .login(username: "å", password: "ß"))), wait: false)
helper.expectOutboundString("A1 LOGIN {2}\r\n")
helper.writeInbound("+ 1\r\n")
#expect(throws: Never.self) { try eventExpectation1.futureResult.wait() }
helper.expectOutboundString("å {2}\r\n")
helper.writeInbound("+ 2\r\n")
#expect(throws: Never.self) { try eventExpectation2.futureResult.wait() }
helper.expectOutboundString("ß\r\n")
helper.writeInbound("A1 OK\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(code: nil, text: "")))))
// now confirm idle
helper.writeOutbound(.tagged(.init(tag: "A2", command: .idleStart)), wait: false)
helper.expectOutboundString("A2 IDLE\r\n")
helper.writeInbound("+ 3\r\n")
#expect(throws: Never.self) { try eventExpectation3.futureResult.wait() }
helper.expectInbound(.idleStarted)
helper.writeOutbound(.idleDone)
helper.expectOutboundString("DONE\r\n")
helper.writeInbound("A2 OK\r\n")
helper.expectInbound(.tagged(.init(tag: "A2", state: .ok(.init(code: nil, text: "")))))
}
@Test("a tagged response after the IDLE confirmation is an error")
func taggedResponseWhileIdlingIsAnError() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
helper.writeInbound("+ idling\r\n")
helper.expectInbound(.idleStarted)
// After its `+`, the server must wait for DONE (RFC 2177 §3).
#expect(throws: UnexpectedResponse.self) {
try helper.channel.writeInbound(ByteBuffer("A1 OK IDLE terminated\r\n"))
}
}
@Test("DONE written before the IDLE confirmation is held until it arrives")
func doneBeforeConfirmationIsHeld() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
// DONE answers the server's `+`, so it can't precede it.
let done = helper.writeOutbound(.idleDone, wait: false)
let noop = helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)), wait: false)
helper.expectNoOutboundString()
#expect(helper.outcome(of: done) == nil)
#expect(helper.outcome(of: noop) == nil)
helper.writeInbound("+ idling\r\n")
helper.expectInbound(.idleStarted)
helper.expectOutboundString("DONE\r\n")
helper.expectOutboundString("A2 NOOP\r\n")
helper.expectSucceeded(done)
helper.expectSucceeded(noop)
helper.writeInbound("A1 OK IDLE terminated\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .ok(.init(code: nil, text: "IDLE terminated")))))
helper.writeInbound("A2 OK\r\n")
helper.expectInbound(.tagged(.init(tag: "A2", state: .ok(.init(code: nil, text: "")))))
}
@Test(
"DONE for a rejected IDLE succeeds without being written",
arguments: zip(
["NO", "BAD"],
[
TaggedResponse.State.no(.init(code: nil, text: "IDLE not permitted")),
.bad(.init(code: nil, text: "IDLE not permitted")),
]
)
)
func doneForRejectedIdleIsNotWritten(status: String, state: TaggedResponse.State) {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
helper.writeInbound("A1 \(status) IDLE not permitted\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: state)))
// The server never sent `+`, so it isn't waiting for DONE.
let done = helper.writeOutbound(.idleDone, wait: false)
helper.expectSucceeded(done)
helper.expectNoOutboundString()
helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)))
helper.expectOutboundString("A2 NOOP\r\n")
helper.writeInbound("A2 OK\r\n")
helper.expectInbound(.tagged(.init(tag: "A2", state: .ok(.init(code: nil, text: "")))))
}
@Test("DONE held for an IDLE that is then rejected succeeds without being written")
func heldDoneForRejectedIdleIsNotWritten() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
let done = helper.writeOutbound(.idleDone, wait: false)
let noop = helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)), wait: false)
helper.expectNoOutboundString()
// The rejection drops the held DONE and releases the command queued behind it.
helper.writeInbound("A1 NO IDLE not permitted\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .no(.init(code: nil, text: "IDLE not permitted")))))
helper.expectSucceeded(done)
helper.expectOutboundString("A2 NOOP\r\n")
helper.expectSucceeded(noop)
helper.writeInbound("A2 OK\r\n")
helper.expectInbound(.tagged(.init(tag: "A2", state: .ok(.init(code: nil, text: "")))))
}
@Test("an unflushed DONE for an IDLE that is then rejected succeeds without being written")
func unflushedDoneForRejectedIdleIsNotWritten() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
let done = helper.channel.write(IMAPClientHandler.Message.part(.idleDone))
helper.writeInbound("A1 NO IDLE not permitted\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .no(.init(code: nil, text: "IDLE not permitted")))))
helper.expectSucceeded(done)
helper.expectNoOutboundString()
}
@Test("KNOWN HAZARD: a late DONE for a rejected IDLE ends a newer IDLE")
func lateDoneForRejectedIdleEndsNewerIdle() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
helper.writeInbound("A1 NO IDLE not permitted\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .no(.init(code: nil, text: "IDLE not permitted")))))
// A second IDLE ends the tolerance for the first one's DONE...
helper.writeOutbound(.tagged(.init(tag: "A2", command: .idleStart)), wait: false)
helper.expectOutboundString("A2 IDLE\r\n")
// ...so that late DONE is taken to be IDLE #2's: held until `+`, then sent, ending IDLE #2 at once.
// Misuse: callers must not send a DONE for an IDLE that was rejected.
let done = helper.writeOutbound(.idleDone, wait: false)
helper.expectNoOutboundString()
helper.writeInbound("+ idling\r\n")
helper.expectInbound(.idleStarted)
helper.expectOutboundString("DONE\r\n")
helper.expectSucceeded(done)
}
@Test(
"a command written in reaction to a response goes out after the commands it released",
arguments: [
("+ idling\r\n", Response.idleStarted, ["DONE\r\n", "A2 NOOP\r\n"]),
(
"A1 NO IDLE not permitted\r\n",
Response.tagged(.init(tag: "A1", state: .no(.init(code: nil, text: "IDLE not permitted")))),
["A2 NOOP\r\n"]
),
]
)
func reactionGoesOutAfterReleasedCommands(response: String, trigger: Response, released: [String]) {
var helper = Helper()
defer {
helper.check()
}
#expect(throws: Never.self) {
try helper.channel.pipeline.syncOperations.addHandler(
WriteOnRead(trigger: trigger, command: .tagged(.init(tag: "A3", command: .noop)))
)
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
helper.writeOutbound(.idleDone, wait: false)
helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)), wait: false)
helper.writeInbound(helper.buffer(string: response))
helper.expectInbound(trigger)
for line in released {
helper.expectOutboundString(line)
}
helper.expectOutboundString("A3 NOOP\r\n")
}
@Test("a command written when a dropped DONE succeeds goes out after the commands it released")
func reactionToDroppedDoneGoesOutAfterReleasedCommands() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
let channel = helper.channel
helper.writeOutbound(.idleDone, wait: false).whenSuccess {
channel.writeAndFlush(
IMAPClientHandler.Message.part(.tagged(.init(tag: "A3", command: .noop))),
promise: nil
)
}
helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)), wait: false)
helper.writeInbound("A1 NO IDLE not permitted\r\n")
helper.expectInbound(.tagged(.init(tag: "A1", state: .no(.init(code: nil, text: "IDLE not permitted")))))
helper.expectOutboundString("A2 NOOP\r\n")
helper.expectOutboundString("A3 NOOP\r\n")
}
@Test("DONE held for the IDLE confirmation goes out when flushed after it")
func heldDoneGoesOutWhenFlushedAfterConfirmation() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
// Written, but not flushed until after the `+` — e.g. `write` and `flush` issued separately.
let done = helper.channel.write(IMAPClientHandler.Message.part(.idleDone))
helper.writeInbound("+ idling\r\n")
helper.expectInbound(.idleStarted)
helper.expectNoOutboundString()
helper.channel.flush()
helper.expectOutboundString("DONE\r\n")
helper.expectSucceeded(done)
}
@Test("DONE held for the IDLE confirmation fails when the channel closes")
func heldDoneFailsOnChannelClose() {
var helper = Helper()
helper.writeOutbound(.tagged(.init(tag: "A1", command: .idleStart)), wait: false)
helper.expectOutboundString("A1 IDLE\r\n")
let done = helper.writeOutbound(.idleDone, wait: false)
#expect(throws: Never.self) { try helper.channel.close().wait() }
guard case .failure = helper.outcome(of: done) else {
Issue.record("DONE should fail, not \(String(describing: helper.outcome(of: done)))")
return
}
}
@Test("promises are failed on channel close")
func promisesAreFailedOnChannelClose() {
var helper = Helper()
defer {
helper.check()
}
// p1 will be the active promise
let p1 = helper.writeOutbound(
.tagged(.init(tag: "A1", command: .login(username: "å", password: "ß"))),
wait: false
)
// p2 is a promise loaded from the queue
let p2 = helper.writeOutbound(.tagged(.init(tag: "A2", command: .noop)), wait: false)
// at this point we'll be held by the continuation requirement for p1
helper.expectOutboundString("A1 LOGIN {2}\r\n")
helper.channel.pipeline.fireChannelInactive()
#expect(throws: ChannelError.self) {
try p1.wait()
}
#expect(throws: ChannelError.self) {
try p2.wait()
}
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
@Test("protect against reentrancy")
func protectAgainstReentrancy() {
var helper = Helper()
defer {
helper.check()
}
struct MyOutboundEvent {}
final class PreTestHandler: ChannelDuplexHandler, Sendable {
typealias InboundIn = ByteBuffer
typealias InboundOut = ByteBuffer
typealias OutboundIn = ByteBuffer
let callCount = Mutex(0)
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
let count = self.callCount.withLock {
$0 += 1
return $0
}
guard count == 1 else { return }
let data = self.wrapInboundOut(ByteBuffer(string: "+ \r\n"))
context.fireChannelRead(data)
promise?.succeed(())
}
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?)
{
#expect(event is MyOutboundEvent)
let data = self.wrapInboundOut(ByteBuffer(string: "A1 OK NOOP complete\r\n"))
context.fireChannelRead(data)
promise?.succeed(())
}
}
final class PostTestHandler: ChannelDuplexHandler, Sendable {
typealias InboundIn = Response
typealias OutboundIn = Response
typealias OutboundOut = IMAPClientHandler.Message
let callCount = Mutex(0)
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let count = self.callCount.withLock {
$0 += 1
return $0
}
guard count == 1 else { return }
context.writeAndFlush(self.wrapOutboundOut(.part(.continuationResponse(""))), promise: nil)
context.triggerUserOutboundEvent(MyOutboundEvent(), promise: nil)
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
Issue.record("Unexpected error \(error)")
}
}
#expect(throws: Never.self) {
try helper.channel.pipeline.syncOperations.addHandlers([
PreTestHandler(),
IMAPClientHandler(),
PostTestHandler(),
])
}
helper.writeOutbound(
.tagged(.init(tag: "A1", command: .authenticate(mechanism: .gssAPI, initialResponse: nil)))
)
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
@Test("write cascades promise failure")
func writeCascadesPromiseFailure() {
var helper = Helper()
defer {
helper.check()
}
struct TestError: Error {}
final class TestOutboundHandlerThatFails: Sendable, ChannelOutboundHandler {
typealias OutboundIn = ByteBuffer
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
#expect(promise != nil)
promise?.fail(TestError())
}
}
#expect(throws: Never.self) {
try helper.channel.pipeline.addHandler(TestOutboundHandlerThatFails(), position: .first).wait()
}
// writing a command that has a continuation
let didComplete = Mutex(false)
helper.writeOutbound(.tagged(.init(tag: "A1", command: .create(.init("å"), []))), wait: false).whenFailure {
error in
#expect(error is TestError)
didComplete.withLock({ $0 = true })
}
let a = didComplete.withLock({ $0 })
#expect(a)
}
@available(macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, *)
@Test("write cascades continuation promise failure")
func writeCascadesContinuationPromiseFailure() {
var helper = Helper()
defer {
helper.check()
}
struct TestError: Error {}
final class TestOutboundHandlerThatFails: Sendable, ChannelOutboundHandler {
let failNextWrite = Mutex(false)
typealias OutboundIn = ByteBuffer
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
guard
!self.failNextWrite.withLock({ $0 })
else {
#expect(promise != nil)
promise?.fail(TestError())
return
}
context.write(data, promise: promise)
}
}
let testHandler = TestOutboundHandlerThatFails()
#expect(throws: Never.self) {
try helper.channel.pipeline.addHandler(testHandler, position: .first).wait()
}
// writing a command that has a continuation
let future = helper.channel.writeAndFlush(
IMAPClientHandler.Message.part(
CommandStreamPart.tagged(
.init(tag: "A1", command: .rename(from: .init("å"), to: .init("ß"), parameters: [:]))
)
)
)
helper.expectOutboundString("A1 RENAME {2}\r\n")
testHandler.failNextWrite.withLock { $0 = true }
helper.writeInbound("+ OK\r\n")
let didComplete = Mutex(false)
future.whenFailure { error in
#expect(error is TestError)
didComplete.withLock({ $0 = true })
}
let a = didComplete.withLock({ $0 })
#expect(a)
}
@Test("append waits for continuation")
func appendWaitsForContinuation() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.append(.start(tag: "A1", appendingTo: .inbox)))
helper.expectOutboundString("A1 APPEND \"INBOX\"")
let literalPromise = helper.writeOutbound(
.append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 5)))),
wait: false
)
helper.expectOutboundString(" {5}\r\n")
#expect(throws: Never.self) { try literalPromise.wait() }
let p1 = helper.writeOutbound(.append(.messageBytes("0")), wait: false)
helper.expectNoOutboundString()
let p2 = helper.writeOutbound(.append(.messageBytes("1")), wait: false)
helper.expectNoOutboundString()
let p3 = helper.writeOutbound(.append(.messageBytes("2")), wait: false)
helper.expectNoOutboundString()
let p4 = helper.writeOutbound(.append(.messageBytes("3")), wait: false)
helper.expectNoOutboundString()
let p5 = helper.writeOutbound(.append(.messageBytes("4")), wait: false)
helper.expectNoOutboundString()
let p6 = helper.writeOutbound(.append(.endMessage), wait: false)
helper.expectNoOutboundString()
let p7 = helper.writeOutbound(.append(.finish), wait: false)
helper.expectNoOutboundString()
// send a continuation, we should now get outbound strings
helper.writeInbound("+ OK\r\n")
helper.expectOutboundString("0")
helper.expectOutboundString("1")
helper.expectOutboundString("2")
helper.expectOutboundString("3")
helper.expectOutboundString("4")
helper.expectOutboundString("")
helper.expectOutboundString("\r\n")
// make sure all the promises are succeeded
#expect(throws: Never.self) { try p1.wait() }
#expect(throws: Never.self) { try p2.wait() }
#expect(throws: Never.self) { try p3.wait() }
#expect(throws: Never.self) { try p4.wait() }
#expect(throws: Never.self) { try p5.wait() }
#expect(throws: Never.self) { try p6.wait() }
#expect(throws: Never.self) { try p7.wait() }
}
@Test("promise is not leaked on unexpected response")
func promiseIsNotLeakedOnUnexpectedResponse() {
var helper = Helper()
defer {
helper.check()
}
// We need to get into a state where we are
// expecting a continuation, but actually
// receive a response.
let promise = helper.writeOutbound(
.tagged(.init(tag: "A1", command: .login(username: "å", password: "test"))),
wait: false
)
helper.expectOutboundBuffer("A1 LOGIN {2}\r\n")
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer("A1 OK\r\n"))
}
#expect(throws: (any Error).self) {
try promise.wait()
}
}
@Test("handles responses split between CR and LF")
func handleResponsesSplitBetweenCRAndLF() {
var helper = Helper()
defer {
helper.check()
}
// Send a command expecting responses
helper.writeOutbound(.tagged(.init(tag: "a", command: .noop)))
helper.expectOutboundString("a NOOP\r\n")
// Write a response where CR and LF are split across two buffers.
// This simulates what happens when a large response is split at
// an 8K buffer boundary right after a carriage return.
// The first buffer ends with \r (carriage return only)
helper.writeInbound("* 1 EXISTS\r")
// The second buffer starts with \n (line feed only), followed by the next response
helper.writeInbound("\n* 0 RECENT\r\n")
// Expect the responses to be parsed successfully
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
helper.expectInbound(.untagged(.mailboxData(.recent(0))))
// Complete the command
helper.writeInbound("a OK NOOP complete\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "a",
state: .ok(.init(code: nil, text: "NOOP complete"))
)
)
)
}
@Test("minimal: split between CR and LF in parser input")
func minimalSplitCRLF() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "t", command: .noop)))
helper.expectOutboundString("t NOOP\r\n")
// Minimal reproducer: send first part ending with CR, then send LF on its own line
helper.writeInbound("* 1 EXISTS\r")
helper.writeInbound("\n")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
helper.writeInbound("t OK\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "t",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
@Test("responses with LF-only line endings (non-split)")
func responsesWithLFOnlyLineEndings() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "a", command: .noop)))
helper.expectOutboundString("a NOOP\r\n")
// Send response with LF-only endings (lenient servers may do this)
// Note: This is the complete LF in one buffer, not split
helper.writeInbound("* 1 EXISTS\n* 0 RECENT\n")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
helper.expectInbound(.untagged(.mailboxData(.recent(0))))
helper.writeInbound("a OK\n")
helper.expectInbound(
.tagged(
.init(
tag: "a",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
@Test("responses with CR-only line endings (non-split)")
func responsesWithCROnlyLineEndings() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "b", command: .noop)))
helper.expectOutboundString("b NOOP\r\n")
// Send response with CR-only endings (lenient servers may do this)
// Note: This is the complete CR in one buffer, not split
helper.writeInbound("* 2 EXISTS\r* 1 RECENT\r")
helper.expectInbound(.untagged(.mailboxData(.exists(2))))
helper.expectInbound(.untagged(.mailboxData(.recent(1))))
helper.writeInbound("b OK\r")
helper.expectInbound(
.tagged(
.init(
tag: "b",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
@Test("rejects buffer starting with empty line (CR CR)")
func rejectsEmptyLineCRCR() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "c", command: .noop)))
helper.expectOutboundString("c NOOP\r\n")
// Empty line: CR CR - This is malformed and should fail
// (This could represent an empty line in the response stream)
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\r\r* 1 EXISTS\r\n"))
}
}
@Test("rejects buffer starting with empty line (LF LF)")
func rejectsEmptyLineLFLF() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "d", command: .noop)))
helper.expectOutboundString("d NOOP\r\n")
// Empty line: LF LF - This is malformed and should fail
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\n\n* 1 EXISTS\r\n"))
}
}
@Test("rejects buffer starting with empty line (CR LF CR)")
func rejectsEmptyLineCRLFCR() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "e", command: .noop)))
helper.expectOutboundString("e NOOP\r\n")
// Empty line: CR LF CR - Valid CRLF followed by orphaned CR
// This represents an empty line which is not valid in IMAP response stream
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\r\n\r* 1 EXISTS\r\n"))
}
}
@Test("rejects buffer starting with empty line (CR LF LF)")
func rejectsEmptyLineCRLFLF() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "f", command: .noop)))
helper.expectOutboundString("f NOOP\r\n")
// Empty line: CR LF LF - Valid CRLF followed by orphaned LF
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\r\n\n* 1 EXISTS\r\n"))
}
}
@Test("rejects buffer starting with empty line (LF CR)")
func rejectsEmptyLineLFCR() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "g", command: .noop)))
helper.expectOutboundString("g NOOP\r\n")
// Empty line: LF CR - This is an unusual sequence and should fail
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\n\r* 1 EXISTS\r\n"))
}
}
@Test("accepts valid CR-only response and continues parsing next response")
func crOnlyResponseFollowedByAnotherResponse() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "h", command: .noop)))
helper.expectOutboundString("h NOOP\r\n")
// First response ends with CR only, then immediately another response
// (both in same buffer to avoid the split case)
helper.writeInbound("* 1 EXISTS\r* 0 RECENT\r")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
helper.expectInbound(.untagged(.mailboxData(.recent(0))))
helper.writeInbound("h OK\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "h",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
@Test("accepts valid CR-only response when it ends the buffer")
func crOnlyResponseEndsBuffer() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "i", command: .noop)))
helper.expectOutboundString("i NOOP\r\n")
// First response ends with CR only at the end of buffer
// This is a complete response that should be accepted
helper.writeInbound("* 2 EXISTS\r")
helper.expectInbound(.untagged(.mailboxData(.exists(2))))
// Send a normal CRLF response next
helper.writeInbound("* 1 RECENT\r\n")
helper.expectInbound(.untagged(.mailboxData(.recent(1))))
helper.writeInbound("i OK\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "i",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
@Test("fails when split CR-LF is followed by malformed data")
func failsWhenSplitCRLFFollowedByMalformedData() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "j", command: .noop)))
helper.expectOutboundString("j NOOP\r\n")
// First response ends with CR only
helper.writeInbound("* 1 EXISTS\r")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
// Next buffer starts with LF (orphaned, will be skipped)
// But then has malformed data that should cause a parse error
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\n!!INVALID\r\n"))
}
}
@Test("rejects CR-only response followed by orphaned LF then another LF (not re-skipped)")
func rejectsCRThenLFThenLFNotReSkipped() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "k", command: .noop)))
helper.expectOutboundString("k NOOP\r\n")
// Response ends with CR only
helper.writeInbound("* 1 EXISTS\r")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
// Next buffer: just orphaned LF (will be skipped, state becomes .crlf)
helper.writeInbound("\n")
// Buffer was empty after skip, so IncompleteMessage - nothing to read
// Next buffer: another LF followed by otherwise valid response
// At this point lastResponseNewlineEnding should be .crlf (not .cr)
// So we should NOT skip this second LF, and the parser should fail
// because \n is not a valid start of a response (even though * 1 EXISTS would be)
#expect(throws: (any Error).self) {
try helper.channel.writeInbound(ByteBuffer(string: "\n* 1 EXISTS\r\n"))
}
}
@Test("accepts CR-only response, orphaned LF, then valid response")
func acceptsCRThenLFThenValidResponse() {
var helper = Helper()
defer {
helper.check()
}
helper.writeOutbound(.tagged(.init(tag: "l", command: .noop)))
helper.expectOutboundString("l NOOP\r\n")
// Response ends with CR only
helper.writeInbound("* 1 EXISTS\r")
helper.expectInbound(.untagged(.mailboxData(.exists(1))))
// Next buffer: orphaned LF (will be skipped)
helper.writeInbound("\n")
// Buffer was empty after skip, so IncompleteMessage
// Next buffer: valid response
helper.writeInbound("* 2 RECENT\r\n")
helper.expectInbound(.untagged(.mailboxData(.recent(2))))
helper.writeInbound("l OK\r\n")
helper.expectInbound(
.tagged(
.init(
tag: "l",
state: .ok(.init(code: nil, text: ""))
)
)
)
}
}
// MARK: - Helper
/// Writes `command` when it reads `trigger`, as a user reacting to that response would.
private final class WriteOnRead: ChannelInboundHandler {
typealias InboundIn = Response
typealias OutboundOut = IMAPClientHandler.Message
let trigger: Response
let command: CommandStreamPart
init(trigger: Response, command: CommandStreamPart) {
self.trigger = trigger
self.command = command
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
if self.unwrapInboundIn(data) == self.trigger {
context.writeAndFlush(self.wrapOutboundOut(.part(self.command)), promise: nil)
}
context.fireChannelRead(data)
}
}
extension IMAPClientHandlerTests {
struct Helper {
var channel: EmbeddedChannel
var clientHandler: IMAPClientHandler
init() {
self.clientHandler = IMAPClientHandler()
self.channel = EmbeddedChannel(handler: self.clientHandler)
self.channel.pipeline.fireChannelActive()
}
func check(
sourceLocation: SourceLocation = #_sourceLocation
) {
var isClean: Bool = false
#expect(throws: Never.self, sourceLocation: sourceLocation) {
isClean = try self.channel.finish().isClean
}
#expect(isClean == true, sourceLocation: sourceLocation)
}
}
}
// MARK: - Helper methods
extension IMAPClientHandlerTests.Helper {
func expectInbound(_ response: Response, sourceLocation: SourceLocation = #_sourceLocation) {
var maybeRead: Response?
#expect(throws: Never.self, sourceLocation: sourceLocation) {
maybeRead = try self.channel.readInbound()
}
guard let read = maybeRead else {
Issue.record("Inbound buffer empty", sourceLocation: sourceLocation)
return
}
#expect(response == read, sourceLocation: sourceLocation)
}
func expectOutboundBuffer(_ buffer: ByteBuffer, sourceLocation: SourceLocation = #_sourceLocation) {
var maybeRead: ByteBuffer?
#expect(throws: Never.self, sourceLocation: sourceLocation) {
maybeRead = try self.channel.readOutbound()
}
guard let read = maybeRead else {
Issue.record("Outbound buffer empty", sourceLocation: sourceLocation)
return
}
#expect(buffer == read, "\(String(buffer: buffer)) != \(String(buffer: read))", sourceLocation: sourceLocation)
}
func expectOutboundString(_ string: String, sourceLocation: SourceLocation = #_sourceLocation) {
var buffer = self.channel.allocator.buffer(capacity: string.utf8.count)
buffer.writeString(string)
self.expectOutboundBuffer(buffer, sourceLocation: sourceLocation)
}
func expectNoOutboundString(sourceLocation: SourceLocation = #_sourceLocation) {
var result: ByteBuffer?
#expect(throws: Never.self, sourceLocation: sourceLocation) {
result = try self.channel.readOutbound(as: ByteBuffer.self)
}
#expect(result == nil, sourceLocation: sourceLocation)
}
mutating func writeInbound(_ string: String, sourceLocation: SourceLocation = #_sourceLocation) {
#expect(throws: Never.self, sourceLocation: sourceLocation) {
try self.channel.writeInbound(self.buffer(string: string))
}
}
mutating func writeInbound(_ bytes: ByteBuffer, sourceLocation: SourceLocation = #_sourceLocation) {
#expect(throws: Never.self, sourceLocation: sourceLocation) {
try self.channel.writeInbound(bytes)
}
}
@discardableResult
mutating func writeOutbound(
_ part: CommandStreamPart,
wait: Bool = true,
sourceLocation: SourceLocation = #_sourceLocation
) -> EventLoopFuture<Void> {
writeOutbound(.part(part), wait: wait, sourceLocation: sourceLocation)
}
@discardableResult
mutating func writeOutbound(
_ outboundIn: IMAPClientHandler.Message,
wait: Bool = true,
sourceLocation: SourceLocation = #_sourceLocation
) -> EventLoopFuture<Void> {
let result = self.channel.writeAndFlush(outboundIn)
if wait {
self.expectSucceeded(result, sourceLocation: sourceLocation)
}
return result
}
/// The outcome of a write, or `nil` while it is pending.
///
/// `EmbeddedChannel` completes writes synchronously, so there is nothing to wait for: a write
/// still pending here would block `wait()` forever instead of failing the test.
func outcome(of future: EventLoopFuture<Void>) -> Result<Void, any Error>? {
let outcome = NIOLoopBoundBox<Result<Void, any Error>?>(nil, eventLoop: self.channel.eventLoop)
future.whenComplete { outcome.value = $0 }
return outcome.value
}
func expectSucceeded(_ future: EventLoopFuture<Void>, sourceLocation: SourceLocation = #_sourceLocation) {
switch self.outcome(of: future) {
case .success:
break
case .failure(let error):
Issue.record(error, "Write failed", sourceLocation: sourceLocation)
case nil:
Issue.record("Write is still pending", sourceLocation: sourceLocation)
}
}
func buffer(string: String) -> ByteBuffer {
var buffer = self.channel.allocator.buffer(capacity: string.utf8.count)
buffer.writeString(string)
return buffer
}
}