Added input validation to the Authentication middleware (#5)

This PR contains the work done to improve the existing `AuthMiddleware` type to provide input validations with the `SecureValidationRule` validation rule and also, by generating the authentication information at initialization time.

Reviewed-on: #5
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit was merged in pull request #5.
This commit is contained in:
2025-10-12 19:33:45 +00:00
committed by Javier Cicchelli
parent a1a649838c
commit 24d703b967
10 changed files with 638 additions and 98 deletions
@@ -16,33 +16,147 @@ import Testing
@testable import DiscogsService
@Suite("Validate Input Use Cases")
@Suite("Validate Input Use Cases", .tags(.useCase))
struct ValidateInputUseCaseTests {
// MARK: Functions
#if swift(>=6.2)
@Test(arguments: zip(
Input.inputsToValidate,
Output.inputsToValidate
)) func `validate`(
Input.inputsNotEmpty,
Output.inputsNotEmpty
)) func `validates not empty`(
input: String,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .notEmpty,
input: input,
expects: error
)
}
@Test(arguments: zip(
Input.inputsNotNil,
Output.inputsNotNil
)) func `validate not nil`(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .notNil,
input: input,
expects: error
)
}
@Test(arguments: zip(
Input.inputsSecureConsumerKey,
Output.inputsSecureConsumerKey
)) func `validate secure (consumer key)`(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.consumerKey),
input: input,
expects: error
)
}
@Test(arguments: zip(
Input.inputsSecureConsumerSecret,
Output.inputsSecureConsumerSecret
)) func `validate secure (consumer secret)`(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.consumerSecret),
input: input,
expects: error
)
}
@Test(arguments: zip(
Input.inputsSecureUserToken,
Output.inputsSecureUserToken
)) func `validate secure (user token)`(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.userToken),
input: input,
expects: error
)
}
#else
@Test("validate", arguments: zip(
Input.inputsToValidate,
Output.inputsToValidate
)) func validate(
@Test("validate not empty", arguments: zip(
Input.inputsNotEmpty,
Output.inputsNotEmpty
)) func validateNotEmpty(
input: String,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .notEmpty,
input: input,
expects: error
)
}
@Test("validate not nil", arguments: zip(
Input.inputsNotNil,
Output.inputsNotNil
)) func validateNotNil(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .notNil,
input: input,
expects: error
)
}
@Test("validate secure (consumer key)", arguments: zip(
Input.inputsSecureConsumerKey,
Output.inputsSecureConsumerKey
)) func validateSecureConsumerKey(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.consumerKey),
input: input,
expects: error
)
}
@Test("validate secure (consumer secret)", arguments: zip(
Input.inputsSecureConsumerSecret,
Output.inputsSecureConsumerSecret
)) func validateSecureConsumerSecret(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.consumerSecret),
input: input,
expects: error
)
}
@Test("validate secure (user token)", arguments: zip(
Input.inputsSecureUserToken,
Output.inputsSecureUserToken
)) func validateSecureUserToken(
input: String?,
expects error: InputValidationError?
) async throws {
try assertValidate(
rule: .secure(.userToken),
input: input,
expects: error
)
@@ -59,15 +173,17 @@ private extension ValidateInputUseCaseTests {
/// Asserts an input validation of a ``ValidateInputUseCase`` use case.
/// - Parameters:
/// - rule: A validation rule to test.
/// - input: An input to validate, if any.
/// - error: An expected error, if any.
/// - Throws: An error of type ``InputValidationError`` in case of an unexpected test case scenario.
func assertValidate(
rule: InputValidationRule,
input: String?,
expects error: InputValidationError?
) throws {
// GIVEN
let validate = ValidateInputUseCase(rules: .notNil, .notEmpty)
let validate = ValidateInputUseCase(rules: rule)
// WHEN
// THEN
@@ -87,11 +203,27 @@ private extension ValidateInputUseCaseTests {
// MARK: - Constants
private extension Input {
/// A list of inputs to validate against a set of validation rules.
static let inputsToValidate: [String?] = [nil, .empty, "SomeInput"]
/// A list of inputs to validate against the not empty validation rule.
static let inputsNotEmpty: [String] = ["Something", .empty]
/// A list of inputs to validate against the not nil validation rule.
static let inputsNotNil: [String?] = [.empty, nil]
/// A list of inputs to validate against the secure (consumer key) validation rule.
static let inputsSecureConsumerKey: [String] = ["aAbBcCdDeEfFgGhHiIjJ", "aAbBcCdDeEfFgGhH", "aAbBcCdDeEfFgGhHiIjJkK", "a4bBcCdDe3fFg6hH1Ij7"]
/// A list of inputs to validate against the secure (consumer secret) validation rule.
static let inputsSecureConsumerSecret: [String] = ["aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoO", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQ", "a4bBcCdDe3fFg6hH1IjJkK1LmMnNo0p9"]
/// A list of inputs to validate against the secure (user token) validation rule.
static let inputsSecureUserToken: [String] = ["aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStT", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsS", "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuU", "a4bBcCdDe3fFg6hH1IjJkK1LmMnNo0p9qQrRs5t7"]
}
private extension Output {
/// A list of expected input validation errors to be thrown (if necessary).
static let inputsToValidate: [InputValidationError?] = [.inputIsNil, .inputIsEmpty, nil]
/// A list of expected input validation errors to be thrown after validating inputs against the not empty validation rule.
static let inputsNotEmpty: [InputValidationError?] = [nil, .inputIsEmpty]
/// A list of expected input validation errors to be thrown after validating inputs against the not nil validation rule.
static let inputsNotNil: [InputValidationError?] = [nil, .inputIsNil]
/// A list of expected input validation errors to be thrown after validating inputs against the secure (consumer key) validation rule.
static let inputsSecureConsumerKey: [InputValidationError?] = [nil, .inputNotConsumerKey, .inputNotConsumerKey, .inputNotConsumerKey]
/// A list of expected input validation errors to be thrown after validating inputs against the secure (consumer secret) validation rule.
static let inputsSecureConsumerSecret: [InputValidationError?] = [nil, .inputNotConsumerSecret, .inputNotConsumerSecret, .inputNotConsumerSecret]
/// A list of expected input validation errors to be thrown after validating inputs against the secure (user token) validation rule.
static let inputsSecureUserToken: [InputValidationError?] = [nil, .inputNotUserToken, .inputNotUserToken, .inputNotUserToken]
}
@@ -14,6 +14,8 @@
import struct Foundation.URL
import struct Foundation.URLComponents
import struct Foundation.URLQueryItem
import struct HTTPTypes.HTTPField
import struct HTTPTypes.HTTPFields
import struct HTTPTypes.HTTPRequest
import struct HTTPTypes.HTTPResponse
@@ -25,6 +27,92 @@ import Testing
@Suite("Auth Middleware", .tags(.middleware))
struct AuthMiddlewareTests {
// MARK: Initializers tests
#if swift(>=6.2)
@Test(arguments: Input.authMethods)
func `initialize`(
_ authMethod: AuthMethod
) async throws {
try assertInit(
authMethod: authMethod,
authTransport: try randomTransport
)
}
@Test(arguments: zip(
Input.authMethodsThrows,
Output.authMethodsThrows
))
func `initialize throws`(
_ authMethod: AuthMethod,
expects error: InputValidationError?
) async throws {
try assertInitThrows(
authMethod: authMethod,
authTransport: try randomTransport,
expects: error
)
}
#else
@Test("initialize", arguments: Input.authMethods)
func initialize(
_ authMethod: AuthMethod
) throws {
try assertInit(
authMethod: authMethod,
authTransport: try randomTransport
)
}
@Test("initialize throws", arguments: zip(
Input.authMethodsThrows,
Output.authMethodsThrows
))
func initializeThrows(
_ authMethod: AuthMethod,
expects error: InputValidationError?
) throws {
assertInitThrows(
authMethod: authMethod,
authTransport: try randomTransport,
expects: error
)
}
#endif
// MARK: Properties tests
#if swift(>=6.2)
@Test(arguments: zip(
Input.authMethods,
Output.authMethodsShouldAuthenticate
))
func `should authenticate`(
_ authMethod: AuthMethod,
expects flag: Bool
) throws {
try assertShouldAuthenticate(
authMethod: authMethod,
authTransport: try randomTransport,
expects: flag
)
}
#else
@Test("should authenticate", arguments: zip(
Input.authMethods,
Output.authMethodsShouldAuthenticate
))
func shouldAuthenticate(
_ authMethod: AuthMethod,
expects flag: Bool
) throws {
try assertShouldAuthenticate(
authMethod: authMethod,
authTransport: try randomTransport,
expects: flag
)
}
#endif
// MARK: Functions tests
#if swift(>=6.2)
@@ -134,12 +222,94 @@ private extension AuthMiddlewareTests {
// MARK: Functions
/// Asserts the initialization of the middleware, especially the assignment of its properties.
/// - Parameters:
/// - authMethod: A representation of an authentication method.
/// - authTransport: A representation of an authentication transport.
/// - Throws: an error of type ``InputValidationError`` in case of an unexpected error occurs while running test cases.
func assertInit(
authMethod: AuthMethod,
authTransport: AuthTransport,
) throws {
// GIVEN
// WHEN
let middleware = try AuthMiddleware(
method: authMethod,
transport: authTransport
)
// THEN
switch (authMethod, authTransport) {
case let (.consumer(key, secret), .onHeader):
#expect(middleware.authItems == nil)
#expect(middleware.authField == .init(
name: .authorization,
value: "Discogs \(String.Parameter.key)=\(key), \(String.Parameter.secret)=\(secret)"
))
case let (.consumer(key, secret), .onQuery):
#expect(middleware.authField == nil)
#expect(middleware.authItems == [
.init(name: .Parameter.key, value: key),
.init(name: .Parameter.secret, value: secret)
])
case let (.user(token), .onHeader):
#expect(middleware.authItems == nil)
#expect(middleware.authField == .init(
name: .authorization,
value: "Discogs \(String.Parameter.token)=\(token)"
))
case let (.user(token), .onQuery):
#expect(middleware.authField == nil)
#expect(middleware.authItems == [
.init(name: .Parameter.token, value: token)
])
case (.none, _):
#expect(middleware.authField == nil)
#expect(middleware.authItems == nil)
}
}
/// Asserts the error throwing (if justified) during the initialization of the middleware.
/// - Parameters:
/// - authMethod: A representation of an authentication method.
/// - authTransport: A representation of an authentication transport.
/// - error: An expected error of type ``InputValidationError`` during the initialization of the middleware.
func assertInitThrows(
authMethod: AuthMethod,
authTransport: AuthTransport,
expects error: InputValidationError?
) {
// GIVEN
// WHEN
// THEN
if let error {
#expect(throws: error) {
try AuthMiddleware(
method: authMethod,
transport: authTransport
)
}
} else {
#expect(throws: Never.self) {
try AuthMiddleware(
method: authMethod,
transport: authTransport
)
}
}
}
/// Asserts the interception of a request to add its authentication.
/// - Parameters:
/// - authMethod: A representation of an authentication method.
/// - authTransport: A representation of an authentication transport.
/// - path: A URI path for a request.
/// - headerFields: A set of header fields for a request.
/// - Throws:An error in case of an unexpected issue encountered while running a test case.
func assertIntercept(
authMethod: AuthMethod,
authTransport: AuthTransport,
@@ -147,7 +317,7 @@ private extension AuthMiddlewareTests {
headerFields: HTTPFields = [:],
) async throws {
// GIVEN
let middleware = AuthMiddleware(
let middleware = try AuthMiddleware(
method: authMethod,
transport: authTransport
)
@@ -166,22 +336,24 @@ private extension AuthMiddlewareTests {
) { request, _, _ in
// THEN
switch (authMethod, authTransport) {
case let (.consumer(key, secret), .onHeader):
case (.consumer, .onHeader):
#expect(request.path == path)
#expect(request.headerFields != headerFields)
#expect(request.headerFields[.authorization] == "Discogs key=\(key), secret=\(secret)")
#expect(request.headerFields.contains(where: { $0.name == .authorization }))
case (.consumer, .onQuery):
#expect(request.path != path)
try assertAuthInPath(request.path, authMethod)
#expect(request.headerFields == headerFields)
case let (.user(token), .onHeader):
try assertAuthInPath(request.path, authMethod)
case (.user, .onHeader):
#expect(request.path == path)
#expect(request.headerFields != headerFields)
#expect(request.headerFields[.authorization] == "Discogs token=\(token)")
#expect(request.headerFields.contains(where: { $0.name == .authorization }))
case (.user, .onQuery):
#expect(request.path != path)
try assertAuthInPath(request.path, authMethod)
#expect(request.headerFields == headerFields)
try assertAuthInPath(request.path, authMethod)
case (.none, _):
#expect(request.path == path)
#expect(request.headerFields == headerFields)
@@ -194,10 +366,33 @@ private extension AuthMiddlewareTests {
}
}
/// Asserts the value of `shouldAuthenticate` flag after an initialization of a middleware.
/// - Parameters:
/// - authMethod: A representation of an authentication method.
/// - authTransport: A representation of an authentication transport.
/// - flag: An expected flag that indicates whether the middleware should authenticate its requests or not.
/// - Throws: An error of type ``InputValidationError`` in case of an unexpected issue occurs while running test cases.
func assertShouldAuthenticate(
authMethod: AuthMethod,
authTransport: AuthTransport,
expects flag: Bool
) throws {
// GIVEN
// WHEN
let middleware = try AuthMiddleware(
method: authMethod,
transport: authTransport
)
// THEN
#expect(middleware.shouldAuthenticate == flag)
}
/// Asserts a request path to contain authentication parameters in its query.
/// - Parameters:
/// - path: A request path
/// - authMethod: A representation of an authentication method.
/// - Throws:An error in case of an unexpected issue encountered while unwrapping the optionals.
func assertAuthInPath(
_ path: String?,
_ authMethod: AuthMethod
@@ -222,6 +417,19 @@ private extension AuthMiddlewareTests {
// MARK: - Helpers
private extension AuthMiddlewareTests {
// MARK: Properties
/// Provides a random authentication transport representation.
var randomTransport: AuthTransport {
get throws {
try #require(AuthTransport.allCases.randomElement())
}
}
}
private extension HTTPRequest {
// MARK: Initializers
@@ -250,12 +458,34 @@ private extension HTTPRequest {
// MARK: - Constants
private extension Input {
/// A list of authentication methods for a request.
/// A list of authentication methods to use in most of the test cases.
static let authMethods: [AuthMethod] = [
.consumer(key: "SomeKey", secret: "SomeSecret"),
.user(token: "SomeToken"),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJ", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP"),
.user(token: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStT"),
.none
]
/// A list of authentication methods to tests for the initialization throw test cases.
static let authMethodsThrows: [AuthMethod] = authMethods + [
.consumer(key: .empty, secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP"),
.consumer(key: "aAbBcCdDeEfFgGhHiI", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP"),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJkK", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP"),
.consumer(key: "a4bBcCdDe3fFg6hH1Ij7", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpP"),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJ", secret: .empty),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJ", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoO"),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJ", secret: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQ"),
.consumer(key: "aAbBcCdDeEfFgGhHiIjJ", secret: "a4bBcCdDe3fFg6hH1IjJkK1LmMnNo0p9"),
.user(token: .empty),
.user(token: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsS"),
.user(token: "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuU"),
.user(token: "a4bBcCdDe3fFg6hH1IjJkK1LmMnNo0p9qQrRs5t7"),
]
}
private extension Output {
/// A list of expected input validation errors (if thrown) coming from the initialization throw test cases.
static let authMethodsThrows: [InputValidationError?] = [nil, nil, nil, .inputIsEmpty, .inputNotConsumerKey, .inputNotConsumerKey, .inputNotConsumerKey, .inputIsEmpty, .inputNotConsumerSecret, .inputNotConsumerSecret, .inputNotConsumerSecret, .inputIsEmpty, .inputNotUserToken, .inputNotUserToken, .inputNotUserToken]
/// A list of expected boolean flags coming from the should authenticate test cases.
static let authMethodsShouldAuthenticate: [Bool] = [true, true, false]
}
private extension String {
@@ -21,4 +21,7 @@ extension Tag {
/// A tag that indicates tests for a middleware type.
@Tag static var middleware: Self
/// A tag that indicates tests for a use case type.
@Tag static var useCase: Self
}