diff --git a/Sources/NIOIMAPCore/Grammar/EncodedUrlAuth.swift b/Sources/NIOIMAPCore/Grammar/EncodedUrlAuth.swift index e9c5b43c..ae0b9472 100644 --- a/Sources/NIOIMAPCore/Grammar/EncodedUrlAuth.swift +++ b/Sources/NIOIMAPCore/Grammar/EncodedUrlAuth.swift @@ -39,7 +39,7 @@ import struct NIO.ByteBuffer /// The final hexadecimal string `91354a473744909de610943775f92038` is the token, /// wrapped as: /// ``` -/// EncodedAuthenticatedURL(data: "91354a473744909de610943775f92038") +/// EncodedAuthenticatedURL("91354a473744909de610943775f92038") /// ``` /// /// When a client later uses this URL with URLFETCH, the server re-calculates the token @@ -51,26 +51,75 @@ import struct NIO.ByteBuffer /// for the complete mechanism and token pair, and ``AuthenticatedURL`` for the full /// authorization structure. /// +/// ## Validity +/// +/// The token is written to the wire verbatim, so anything that isn't an `enc-urlauth` is rejected: +/// +/// - ``init(_:)`` returns `nil`. Use it for a token derived from input. +/// - ``init(stringLiteral:)`` traps. A literal is written by the programmer, so an invalid one is a +/// bug to be caught on first run rather than handled. +/// /// - SeeAlso: [RFC 4467 Section 2.5](https://datatracker.ietf.org/doc/html/rfc4467#section-2.5) - Authorization Token /// - SeeAlso: [RFC 4467 Section 5](https://datatracker.ietf.org/doc/html/rfc4467#section-5) - Generation of URLAUTH-Authorized URLs /// - SeeAlso: [RFC 4467 Section 6](https://datatracker.ietf.org/doc/html/rfc4467#section-6) - Validation of URLAUTH-authorized URLs public struct EncodedAuthenticatedURL: Hashable, Sendable { - /// The hexadecimal-encoded authorization token string. - /// - /// An ASCII-encoded hexadecimal representation of the token bytes. The RFC 4467 - /// specification recommends using hexadecimal instead of Base64 to avoid URL-problematic - /// padding characters. - public var data: String + let stringValue: String - /// Creates a new hexadecimal-encoded URLAUTH verification token. - /// - parameter data: The hexadecimal-encoded token string. - public init(data: String) { - self.data = data + /// Creates a token from a hexadecimal string, if the string is a valid `enc-urlauth`. + /// + /// A string literal resolves to ``init(stringLiteral:)`` instead, which traps rather than + /// returning `nil`. + /// + /// - parameter stringValue: The token, for example `91354a473744909de610943775f92038`. + /// - returns: A new token, or `nil` if `stringValue` is not 32 or more hexadecimal digits. + public init?(_ stringValue: String) { + guard Self.isValidToken(stringValue) else { return nil } + self.stringValue = stringValue + } + + init(unchecked stringValue: String) { + assert(Self.isValidToken(stringValue)) + self.stringValue = stringValue + } + + /// The minimum token length: 128 bits. + static let minimumLength = 32 + + /// Whether the given string is an `enc-urlauth` + /// ([RFC 4467 Section 9](https://datatracker.ietf.org/doc/html/rfc4467#section-9)): + /// ``` + /// enc-urlauth = 32*HEXDIG + /// ``` + static func isValidToken(_ string: String) -> Bool { + string.utf8.count >= Self.minimumLength && string.utf8.allSatisfy(\.isHexCharacter) + } +} + +extension String { + /// Creates a `String` from an ``EncodedAuthenticatedURL``. + /// + /// - parameter other: The token to convert. + public init(_ other: EncodedAuthenticatedURL) { + self = other.stringValue + } +} + +extension EncodedAuthenticatedURL: ExpressibleByStringLiteral { + /// Creates a token 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 valid `enc-urlauth`; this traps if it isn't. + public init(stringLiteral value: String) { + precondition(Self.isValidToken(value), "Invalid URLAUTH token: \(String(reflecting: value))") + self.init(unchecked: value) } } extension EncodeBuffer { @discardableResult mutating func writeEncodedAuthenticationURL(_ data: EncodedAuthenticatedURL) -> Int { - self.writeString(data.data) + self.writeString(data.stringValue) } } diff --git a/Sources/NIOIMAPCore/Grammar/URLAuthenticationMechanism.swift b/Sources/NIOIMAPCore/Grammar/URLAuthenticationMechanism.swift index 3b114c31..a3972be7 100644 --- a/Sources/NIOIMAPCore/Grammar/URLAuthenticationMechanism.swift +++ b/Sources/NIOIMAPCore/Grammar/URLAuthenticationMechanism.swift @@ -43,7 +43,7 @@ /// ``` /// AuthenticatedURLVerifier( /// urlAuthenticationMechanism: URLAuthenticationMechanism("INTERNAL"), -/// encodedAuthenticationURL: EncodedAuthenticatedURL(data: "91354a473744909de610943775f92038") +/// encodedAuthenticationURL: "91354a473744909de610943775f92038" /// ) /// // Represents: :internal:91354a473744909de610943775f92038 /// ``` diff --git a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift index bf23e063..95c48843 100644 --- a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift +++ b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser.swift @@ -569,13 +569,12 @@ extension GrammarParser { func parseEncodedURLAuth(buffer: inout ParseBuffer, tracker: StackTracker) throws -> EncodedAuthenticatedURL { try PL.composite(buffer: &buffer, tracker: tracker) { buffer, tracker -> EncodedAuthenticatedURL in - let bytes = try PL.parseBytes(buffer: &buffer, tracker: tracker, length: 32) - guard bytes.readableBytesView.allSatisfy(\.isHexCharacter) else { - throw ParserError(hint: "Found invalid character in \(String(buffer: bytes))") + // `32*HEXDIG` + let bytes = try PL.parseOneOrMoreCharacters(buffer: &buffer, tracker: tracker, where: \.isHexCharacter) + guard bytes.readableBytes >= EncodedAuthenticatedURL.minimumLength else { + throw ParserError(hint: "Expected at least 32 hex digits, got \(String(buffer: bytes))") } - - // can used the unsafe String.init here as we've already validated everything is valid hex - return .init(data: String(buffer: bytes)) + return .init(unchecked: String(buffer: bytes)) } } diff --git a/Tests/NIOIMAPCoreTests/Grammar/AuthImapUrlFull+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/AuthImapUrlFull+Tests.swift index 067cc771..3fba77a8 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/AuthImapUrlFull+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/AuthImapUrlFull+Tests.swift @@ -30,10 +30,13 @@ struct FullAuthenticatedURLTests { ), authenticatedURL: .init( authenticatedURL: .init(access: .anonymous), - verifier: .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "data")) + verifier: .init( + urlAuthMechanism: .internal, + encodedAuthenticationURL: "ffffffffffffffffffffffffffffffff" + ) ) ), - "imap://localhost/test/;UID=123;URLAUTH=anonymous:INTERNAL:data" + "imap://localhost/test/;UID=123;URLAUTH=anonymous:INTERNAL:ffffffffffffffffffffffffffffffff" ), EncodeFixture.fullAuthenticatedURL( .init( @@ -46,10 +49,13 @@ struct FullAuthenticatedURLTests { ), authenticatedURL: .init( authenticatedURL: .init(access: .user("alice")), - verifier: .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "verifier123")) + verifier: .init( + urlAuthMechanism: .internal, + encodedAuthenticationURL: "0123456789ABCDEF0123456789ABCDEF" + ) ) ), - "imap://mail.example.com/INBOX/;UID=789;URLAUTH=user+alice:INTERNAL:verifier123" + "imap://mail.example.com/INBOX/;UID=789;URLAUTH=user+alice:INTERNAL:0123456789ABCDEF0123456789ABCDEF" ), ]) func encode(_ fixture: EncodeFixture) { @@ -73,7 +79,7 @@ struct FullAuthenticatedURLTests { authenticatedURL: .init(access: .anonymous), verifier: .init( urlAuthMechanism: .internal, - encodedAuthenticationURL: .init(data: "01234567890123456789012345678901") + encodedAuthenticationURL: "01234567890123456789012345678901" ) ) ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/EncodedUrlAuth+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/EncodedUrlAuth+Tests.swift index 488543f9..9ff9a22d 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/EncodedUrlAuth+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/EncodedUrlAuth+Tests.swift @@ -18,9 +18,40 @@ import Testing @Suite("EncodedAuthenticatedURL") struct EncodedAuthenticatedURLTests { + /// A token is written to the wire verbatim, inside a URL that is itself written bare. + @Test( + "invalid tokens are rejected", + arguments: [ + "", + "0123456789abcdef0123456789abcde", // `32*HEXDIG`: 31 digits. + "0123456789abcdef0123456789abcdeg", + "0123456789abcdef0123456789abcdef ", + "0123456789abcdef0123456789abcdef\r\n* BYE", // Would inject a whole response. + ] + ) + func invalidTokens(_ string: String) { + #expect(EncodedAuthenticatedURL(string) == nil) + } + + @Test("valid tokens", arguments: validTokenStrings) + func validTokens(_ string: String) { + #expect(EncodedAuthenticatedURL(string).map { String($0) } == string) + } + + @Test("valid tokens round-trip", arguments: validTokenStrings) + func validTokensRoundTrip(_ string: String) throws { + TestUtilities.expectRoundTrip( + try #require(EncodedAuthenticatedURL(string)), + encoder: { $0.writeEncodedAuthenticationURL($1) }, + parser: GrammarParser().parseEncodedURLAuth + ) + } + @Test(arguments: [ - EncodeFixture.encodedAuthenticationURL(.init(data: "1F"), "1F"), - EncodeFixture.encodedAuthenticationURL(.init(data: "ABC123"), "ABC123"), + EncodeFixture.encodedAuthenticationURL( + "0123456789ABCDEF0123456789ABCDEF", + "0123456789ABCDEF0123456789ABCDEF" + ) ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() @@ -29,8 +60,19 @@ struct EncodedAuthenticatedURLTests { @Test(arguments: [ ParseFixture.encodedAuthenticationURL( "0123456789abcdef01234567890abcde", - "", - expected: .success(.init(data: "0123456789abcdef01234567890abcde")) + " ", + expected: .success("0123456789abcdef01234567890abcde") + ), + // `32*HEXDIG`: reads past 32. + ParseFixture.encodedAuthenticationURL( + "0123456789abcdef01234567890abcdef0", + " ", + expected: .success("0123456789abcdef01234567890abcdef0") + ), + ParseFixture.encodedAuthenticationURL( + "0123456789abcdef01234567890abcd", + " ", + expected: .failure ), ParseFixture.encodedAuthenticationURL( "0123456789zbcdef01234567890abcde", @@ -46,8 +88,29 @@ struct EncodedAuthenticatedURLTests { func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + #if !os(iOS) && !os(watchOS) && !os(tvOS) && !os(visionOS) && !os(Android) + @Test("an invalid string literal traps") func stringLiteralPreconditionFailure() async { + let result = await #expect( + processExitsWith: .failure, + observing: [\.standardErrorContent], + performing: { + let token: EncodedAuthenticatedURL = "1F" + _ = token + } + ) + TestUtilities.expectTrapMessage(result, "Invalid URLAUTH token") + } + #endif } +// MARK: - + +private let validTokenStrings = [ + "0123456789abcdef0123456789abcdef", + "0123456789ABCDEF0123456789ABCDEF0123", +] + extension EncodeFixture { fileprivate static func encodedAuthenticationURL(_ input: T, _ expectedString: String) -> Self { .init( diff --git a/Tests/NIOIMAPCoreTests/Grammar/ICommand+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ICommand+Tests.swift index 717eddf0..8d47ca9e 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ICommand+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ICommand+Tests.swift @@ -37,7 +37,7 @@ struct URLCommandTests { authenticatedURL: .init(access: .anonymous), verifier: .init( urlAuthMechanism: .internal, - encodedAuthenticationURL: .init(data: "01234567890123456789012345678901") + encodedAuthenticationURL: "01234567890123456789012345678901" ) ) ), @@ -82,7 +82,7 @@ struct URLCommandTests { authenticatedURL: .init(access: .anonymous), verifier: .init( urlAuthMechanism: .internal, - encodedAuthenticationURL: .init(data: "01234567890123456789012345678901") + encodedAuthenticationURL: "01234567890123456789012345678901" ) ) ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/IUAVerifier+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/IUAVerifier+Tests.swift index b56ad27a..649fde8b 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/IUAVerifier+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/IUAVerifier+Tests.swift @@ -20,12 +20,12 @@ import Testing struct AuthenticatedURLVerifierTests { @Test(arguments: [ EncodeFixture.authenticatedURLVerifier( - .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "test")), - ":INTERNAL:test" + .init(urlAuthMechanism: .internal, encodedAuthenticationURL: "0123456789abcdef0123456789abcdef"), + ":INTERNAL:0123456789abcdef0123456789abcdef" ), EncodeFixture.authenticatedURLVerifier( - .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "verifier123")), - ":INTERNAL:verifier123" + .init(urlAuthMechanism: .internal, encodedAuthenticationURL: "0123456789ABCDEF0123456789ABCDEF"), + ":INTERNAL:0123456789ABCDEF0123456789ABCDEF" ), ]) func encode(_ fixture: EncodeFixture) { @@ -39,7 +39,7 @@ struct AuthenticatedURLVerifierTests { expected: .success( .init( urlAuthMechanism: .internal, - encodedAuthenticationURL: .init(data: "01234567890123456789012345678901") + encodedAuthenticationURL: "01234567890123456789012345678901" ) ) ) diff --git a/Tests/NIOIMAPCoreTests/Grammar/IUrlAuth+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/IUrlAuth+Tests.swift index 8a9c9571..4654fc5c 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/IUrlAuth+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/IUrlAuth+Tests.swift @@ -22,16 +22,22 @@ struct AuthenticatedURLTests { EncodeFixture.authenticatedURL( .init( authenticatedURL: .init(access: .anonymous), - verifier: .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "test")) + verifier: .init( + urlAuthMechanism: .internal, + encodedAuthenticationURL: "0123456789abcdef0123456789abcdef" + ) ), - ";URLAUTH=anonymous:INTERNAL:test" + ";URLAUTH=anonymous:INTERNAL:0123456789abcdef0123456789abcdef" ), EncodeFixture.authenticatedURL( .init( authenticatedURL: .init(access: .user("alice")), - verifier: .init(urlAuthMechanism: .internal, encodedAuthenticationURL: .init(data: "verifier456")) + verifier: .init( + urlAuthMechanism: .internal, + encodedAuthenticationURL: "0123456789abcdef0123456789abcdef0123" + ) ), - ";URLAUTH=user+alice:INTERNAL:verifier456" + ";URLAUTH=user+alice:INTERNAL:0123456789abcdef0123456789abcdef0123" ), ]) func encode(_ fixture: EncodeFixture) { @@ -47,7 +53,7 @@ struct AuthenticatedURLTests { authenticatedURL: .init(access: .anonymous), verifier: .init( urlAuthMechanism: .internal, - encodedAuthenticationURL: .init(data: "01234567890123456789012345678901") + encodedAuthenticationURL: "01234567890123456789012345678901" ) ) )