mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-26 04:57:51 +00:00
* Reject invalid URLAUTH mechanisms
`.resetKey(mailbox: .inbox, mechanisms: [.init("X\r\nA2 DELETE INBOX")])`
was written verbatim, injecting a command into RESETKEY / GENURLAUTH.
RFC 4467: `mechanism = "INTERNAL" / 1*(ALPHA / DIGIT / "-" / ".")`.
`init(_:)` becomes `init?(_:)`; literals trap on invalid input. The
parser already enforces the production.
* Reject invalid mailbox attributes
`MailboxInfo.Attribute("\\X)\r\n* BYE")` was written verbatim, injecting
an untagged response into LIST. It also feeds CREATE … USE via
`UseAttribute(_:)`.
RFC 3501: `mbx-list-flag` is `"\" atom` in every branch. `init(_:)`
becomes `init?(_:)`; literals trap on invalid input. Constants become
`static let` literals; storage is `let`. Fix the `String.init` doc,
which claimed lowercase storage.
* Reject invalid use attributes
`UseAttribute("\\All))\r\nA2 DELETE INBOX\r\nA3 NOOP ((")` was written
verbatim, injecting a command into CREATE … (USE (…)). It also feeds
`GmailLabel(useAttribute:)`.
RFC 6154: `use-attr-ext = "\" atom`. `init(_:)` becomes `init?(_:)`;
literals trap on invalid input. `init(_: MailboxInfo.Attribute)` stays
non-failable: same production. Fix docs that claimed lowercase storage.
* Reject invalid attribute flags
`AttributeFlag("x\" all 1\r\nA2 DELETE INBOX\r\nA3 NOOP \"")` was
written verbatim inside SEARCH MODSEQ "/flags/…", injecting a command.
RFC 7162: `attr-flag = "\\" atom / atom`, where `"\\"` is two literal
backslashes (the stored form is already escaped). `init(_:)` becomes
`init?(_:)`, validating after lowercasing; literals trap on invalid
input. Fix docs that claimed casing is preserved.
* Add FilterName for SEARCH FILTER
`.filter("x\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into SEARCH.
RFC 5466: `filter-name = 1*<any ATOM-CHAR except "/">`. New `FilterName`
type replaces the `String` payload of `SearchKey.filter`; `init?(_:)`
validates, literals trap on invalid input.
* Reject invalid compression kinds
`.compress(.init("DEFLATE\r\nA2 DELETE INBOX"))` was written verbatim,
injecting a command after COMPRESS.
RFC 4978: `algorithm = "DEFLATE"`, an atom. `init(_:)` becomes
`init?(_:)`, validating after uppercasing; literals trap on invalid
input. Add `String.init(_:)`.
* Reject invalid capabilities
`Capability("X\r\nA2 DELETE INBOX")` was written verbatim, injecting a
command into ENABLE, or (`"X\r\n* OK [ALERT] hi"`) a response into
CAPABILITY / ENABLED. Same for the kinds a capability is built from,
e.g. `.context(.init("X\r\n…"))`.
RFC 3501: `capability = ("AUTH=" auth-type) / atom`. `init(_:)` becomes
`init?(_:)` for `Capability` and each kind (kinds validate after
uppercasing); literals trap on invalid input. Storage is `let`. Add
`String.init(_:)` for the kinds.
* Add validated LIST option tag types
`.standard("X)\r\nA2 DELETE INBOX\r\nA3 LIST (")` was written verbatim,
injecting a command into LIST select/return options. Same for
`.vendor(KeyValue<String, String>)`.
RFC 5258: `option-standard-tag = atom`, `option-vendor-tag =
vendor-token "-" atom`. New `OptionExtensionKind.Standard` and
`.Vendor` replace the payloads; `init?(_:)` validates, literals trap.
`Vendor` stores `ACME-SORT` and derives `token` / `name`.
* Add CharacterSetName for SEARCH, SORT, and BADCHARSET
`.sort(…, charset: "UTF-8 ALL\r\nA2 DELETE INBOX\r\nA3 SEARCH", …)` was
written verbatim, injecting a command into SORT / SEARCH / ESEARCH.
`.badCharset(["a)] x\r\n* BYE"])` injected a response. Quoted names
also didn't round-trip: `"a b"` parsed, then encoded bare.
RFC 3501: `charset = atom / quoted`. New `CharacterSetName` replaces
`String`; valid = non-empty `TEXT-CHAR`. Written as an atom where it is
one (`CHARSET UTF-8` unchanged), quoted otherwise, never a literal. The
parser rejects quoted names it couldn't write back.
* Assert keyword validity when writing a flag keyword
`writeFlagKeyword` wrote verbatim with no check. `writeAtom` would be
wrong: Gmail keywords contain `]`, which no atom does. Assert the
keyword's own production instead; test that a `]` keyword encodes.
* Hoist a #require the compiler flagged as redundant
152 lines
6.0 KiB
Swift
152 lines
6.0 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 struct NIO.ByteBuffer
|
||
|
||
/// A special-use mailbox attribute from RFC 6154.
|
||
///
|
||
/// The `SPECIAL-USE` extension allows servers to advertise the special purpose of certain mailboxes.
|
||
/// Helps clients automatically identify important mailboxes like Drafts, Sent, Trash, and Junk
|
||
/// without relying on localized mailbox names or user configuration.
|
||
///
|
||
/// The attribute values are compared case-insensitively, but keep their original casing.
|
||
/// Servers can advertise these attributes in `LIST` responses, and clients can create mailboxes
|
||
/// with these attributes using the `CREATE-SPECIAL-USE` extension.
|
||
///
|
||
/// ## Validity
|
||
///
|
||
/// An attribute is written to the wire verbatim, so anything that isn't a `"\" atom` is
|
||
/// rejected: ``init(_:)`` returns `nil`, ``init(stringLiteral:)`` traps.
|
||
///
|
||
/// - SeeAlso: [RFC 6154 IMAP Special-Use Mailbox Attributes](https://datatracker.ietf.org/doc/html/rfc6154)
|
||
public struct UseAttribute: Hashable, Sendable {
|
||
/// A mailbox that presents all messages in the user's store.
|
||
public static let all: Self = "\\All"
|
||
|
||
/// Used to archive messages - note that the meaning of "archived" will vary from server to server.
|
||
public static let archive: Self = "\\Archive"
|
||
|
||
/// Used to store draft messages that have not been sent.
|
||
public static let drafts: Self = "\\Drafts"
|
||
|
||
/// Stores messages that have been marked as "important" for some reason.
|
||
public static let flagged: Self = "\\Flagged"
|
||
|
||
/// Stores messages deemed to be spam or junk mail, for example, from a mailing list.
|
||
public static let junk: Self = "\\Junk"
|
||
|
||
/// Holds copies of messages that have been sent.
|
||
public static let sent: Self = "\\Sent"
|
||
|
||
/// Holds messages that have been deleted or marked for deletion.
|
||
public static let trash: Self = "\\Trash"
|
||
|
||
/// Holds messages that have been temporarily removed from the user's
|
||
/// attention and scheduled to reappear at a later "awaken" time.
|
||
///
|
||
/// - SeeAlso: [RFC 9979 Section 8.1](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.1)
|
||
public static let snoozed: Self = "\\Snoozed"
|
||
|
||
/// Holds messages that have been composed but are scheduled to be sent at a
|
||
/// future time rather than immediately.
|
||
///
|
||
/// - SeeAlso: [RFC 9979 Section 8.2](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.2)
|
||
public static let scheduled: Self = "\\Scheduled"
|
||
|
||
/// Holds messages bearing the ``Flag/Keyword/memo`` keyword: user-created
|
||
/// notes or annotations regarding other messages.
|
||
///
|
||
/// - SeeAlso: [RFC 9979 Section 8.3](https://www.rfc-editor.org/rfc/rfc9979.html#section-8.3)
|
||
public static let memos: Self = "\\Memos"
|
||
|
||
internal let stringValue: String
|
||
|
||
/// Creates a `UseAttribute` from a string, if the string is a valid attribute. Note that
|
||
/// usually it should be sufficient to just use the predefined attributes, for example `.drafts`.
|
||
///
|
||
/// A string literal resolves to ``init(stringLiteral:)`` instead, which traps rather than
|
||
/// returning `nil`.
|
||
///
|
||
/// - parameter stringValue: The attribute, for example `\Drafts`.
|
||
/// - returns: A new attribute, or `nil` if `stringValue` is not a `"\" atom`.
|
||
public init?(_ stringValue: String) {
|
||
guard Self.isValidAttribute(stringValue) else { return nil }
|
||
self.stringValue = stringValue
|
||
}
|
||
|
||
init(unchecked stringValue: String) {
|
||
assert(Self.isValidAttribute(stringValue))
|
||
self.stringValue = stringValue
|
||
}
|
||
|
||
/// Whether the given string is a `use-attr`
|
||
/// ([RFC 6154 Section 6](https://datatracker.ietf.org/doc/html/rfc6154#section-6)):
|
||
/// ```
|
||
/// use-attr = "\All" / "\Archive" / "\Drafts" / "\Flagged" /
|
||
/// "\Junk" / "\Sent" / "\Trash" / use-attr-ext
|
||
/// use-attr-ext = "\" atom
|
||
/// ```
|
||
static func isValidAttribute(_ string: String) -> Bool {
|
||
string.hasPrefix("\\") && string.dropFirst().isIMAPAtom
|
||
}
|
||
|
||
public static func == (lhs: Self, rhs: Self) -> Bool {
|
||
lhs.stringValue.lowercased() == rhs.stringValue.lowercased()
|
||
}
|
||
|
||
public func hash(into hasher: inout Hasher) {
|
||
self.stringValue.lowercased().hash(into: &hasher)
|
||
}
|
||
}
|
||
|
||
extension UseAttribute {
|
||
/// Special Use can be returned as part of the `LIST` response. They’ll then be
|
||
/// wrapped in `MailboxInfo.Attribute`.
|
||
public init(_ other: MailboxInfo.Attribute) {
|
||
// Both are `"\" atom`.
|
||
self.init(unchecked: String(other))
|
||
}
|
||
}
|
||
|
||
extension String {
|
||
/// The raw value of the attribute, for example `\Trash`, in its original casing.
|
||
public init(_ other: UseAttribute) {
|
||
self = other.stringValue
|
||
}
|
||
}
|
||
|
||
// MARK: - Encoding
|
||
|
||
extension UseAttribute: ExpressibleByStringLiteral {
|
||
/// Creates an attribute from a string literal.
|
||
///
|
||
/// A literal is written by the programmer, so an invalid one is a bug to be caught on first
|
||
/// run rather than handled. Use ``init(_:)`` for anything else.
|
||
///
|
||
/// - parameter value: The string literal.
|
||
/// - Precondition: `value` is a `"\" atom`; this traps if it isn't.
|
||
public init(stringLiteral value: String) {
|
||
precondition(Self.isValidAttribute(value), "Invalid use attribute: \(String(reflecting: value))")
|
||
self.init(unchecked: value)
|
||
}
|
||
}
|
||
|
||
extension EncodeBuffer {
|
||
@discardableResult mutating func writeUseAttribute(_ att: UseAttribute) -> Int {
|
||
// Verbatim: `"\" atom` needs no quoting.
|
||
assert(UseAttribute.isValidAttribute(att.stringValue))
|
||
return self.writeString(att.stringValue)
|
||
}
|
||
}
|