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:
@@ -18,4 +18,10 @@ enum InputValidationError: Error {
|
||||
case inputIsEmpty
|
||||
/// An input is nil.
|
||||
case inputIsNil
|
||||
/// An input does not comply with the consumer key requirements.
|
||||
case inputNotConsumerKey
|
||||
/// An input does not comply with the consumer secret requirements.
|
||||
case inputNotConsumerSecret
|
||||
/// An input does not comply with the user token requirements.
|
||||
case inputNotUserToken
|
||||
}
|
||||
|
||||
@@ -26,13 +26,8 @@ extension String {
|
||||
static let token = "token"
|
||||
}
|
||||
/// A namespaces assigned for the formats of string values.
|
||||
enum Format {
|
||||
/// A format for the consumer authentication header.
|
||||
static let authConsumer = "Discogs \(String.Parameter.key)=%@, \(String.Parameter.secret)=%@"
|
||||
/// A format for the user authentication header.
|
||||
static let authUser = "Discogs \(String.Parameter.token)=%@"
|
||||
/// A format for the user agent header.
|
||||
static let userAgent = "%@/%@ +%@"
|
||||
}
|
||||
enum Format {}
|
||||
|
||||
/// A namespaces assigned for the formats of regular expression patterns.
|
||||
enum Pattern {}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,17 @@ struct NotEmptyValidationRule: InputValidationRule {
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Definitions
|
||||
|
||||
extension InputValidationRule where Self == NotEmptyValidationRule {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
/// A validation rule that checks whether an input is empty or not.
|
||||
static var notEmpty: Self { .init() }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension NotEmptyValidationRule {
|
||||
@@ -54,10 +65,3 @@ private extension NotEmptyValidationRule {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
extension InputValidationRule where Self == NotEmptyValidationRule {
|
||||
/// A validation rule that checks whether an input is empty or not.
|
||||
static var notEmpty: Self { .init() }
|
||||
}
|
||||
|
||||
@@ -29,6 +29,17 @@ struct NotNilValidationRule: InputValidationRule {
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Definitions
|
||||
|
||||
extension InputValidationRule where Self == NotNilValidationRule {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
/// A validation rule that checks whether an input is nil or not.
|
||||
static var notNil: Self { .init() }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension NotNilValidationRule {
|
||||
@@ -43,7 +54,7 @@ private extension NotNilValidationRule {
|
||||
/// - Returns: A flag that indicates whether a given input has been validated or not.
|
||||
/// - Throws: An error of type ``InputValidatorError`` in case the validation failed.
|
||||
func validate(input: String?) throws -> Bool {
|
||||
guard let input else {
|
||||
guard input != nil else {
|
||||
throw InputValidationError.inputIsNil
|
||||
}
|
||||
|
||||
@@ -51,10 +62,3 @@ private extension NotNilValidationRule {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
extension InputValidationRule where Self == NotNilValidationRule {
|
||||
/// A validation rule that checks whether an input is nil or not.
|
||||
static var notNil: Self { .init() }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// This source file is part of the DiscogsService open source project
|
||||
//
|
||||
// Copyright (c) 2025 Röck+Cöde VoF. and the DiscogsService project authors
|
||||
// Licensed under Apache license v2.0
|
||||
//
|
||||
// See LICENSE for license information
|
||||
// See CONTRIBUTORS for the list of DiscogsService project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A validation rule type that checks whether an input is secure or not.
|
||||
struct SecureValidationRule: InputValidationRule {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// A representation of the available security input types.
|
||||
private let inputType: SecurityInput
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Initializes this validation rule.
|
||||
/// - Parameter inputType: A representation of the available security input types.
|
||||
init(inputType: SecurityInput) {
|
||||
self.inputType = inputType
|
||||
}
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
#if swift(>=6.0)
|
||||
func validate(_ input: String?) throws(InputValidationError) -> Bool {
|
||||
try validate(input: input)
|
||||
}
|
||||
#else
|
||||
func validate(_ input: String?) throws -> Bool {
|
||||
try validate(input: input)
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Definitions
|
||||
|
||||
extension InputValidationRule where Self == SecureValidationRule {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// A validation rule that checks whether an input is secure or not.
|
||||
/// - Parameter securityInput: A representation of the security input type to validate
|
||||
/// - Returns: A validation rule that has been configured and it is ready to use.
|
||||
static func secure(_ securityInput: SecurityInput) -> Self {
|
||||
.init(inputType: securityInput)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Enumerations
|
||||
|
||||
/// A representation of all the possible security input types, based on their respective character length expectations.
|
||||
enum SecurityInput: Int {
|
||||
/// A consumer key is 20 characters long.
|
||||
case consumerKey = 20
|
||||
/// A consumer key is 32 characters long.
|
||||
case consumerSecret = 32
|
||||
/// A consumer key is 40 characters long.
|
||||
case userToken = 40
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension SecureValidationRule {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Checks if a given input is valid,
|
||||
/// - Parameter input: An input to validate.
|
||||
/// - Returns: A flag that indicates whether a given input is valid or not.
|
||||
func isValid(_ input: String) -> Bool {
|
||||
let regexPattern = String(format: .Pattern.securityInput, inputType.rawValue)
|
||||
|
||||
do {
|
||||
if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 6.0, *) {
|
||||
let securityInput = try Regex(regexPattern)
|
||||
let matches = input.matches(of: securityInput)
|
||||
|
||||
return !matches.isEmpty
|
||||
} else {
|
||||
let securityInput = try NSRegularExpression(pattern: regexPattern)
|
||||
let matches = securityInput.matches(
|
||||
in: input,
|
||||
range: .init(location: 0, length: input.count)
|
||||
)
|
||||
|
||||
return !matches.isEmpty
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a given input.
|
||||
///
|
||||
/// > note: This helper function would not be necessary when support for *Swift 5.10* is discontinued.
|
||||
///
|
||||
/// - Parameter input: An input to be validated.
|
||||
/// - Returns: A flag that indicates whether a given input has been validated or not.
|
||||
/// - Throws: An error of type ``InputValidatorError`` in case the validation failed.
|
||||
func validate(input: String?) throws -> Bool {
|
||||
guard let input else {
|
||||
return false
|
||||
}
|
||||
guard isValid(input) else {
|
||||
switch inputType {
|
||||
case .consumerKey: throw InputValidationError.inputNotConsumerKey
|
||||
case .consumerSecret: throw InputValidationError.inputNotConsumerSecret
|
||||
case .userToken: throw InputValidationError.inputNotUserToken
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Pattern {
|
||||
/// A regular expression pattern to match the security inputs against.
|
||||
static let securityInput = "^([a-z]|[A-Z]){%d}$"
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A representation of the available transport options to send credentials in authenticated requests.
|
||||
public enum AuthTransport: Sendable {
|
||||
public enum AuthTransport: CaseIterable, Sendable {
|
||||
/// Authentication credential are sent in a request as an `Authentication` header.
|
||||
///
|
||||
/// This means that the header will be added to any existing header in a request, like this:
|
||||
|
||||
@@ -19,23 +19,24 @@ import protocol OpenAPIRuntime.ClientMiddleware
|
||||
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
|
||||
|
||||
/// A middleware that attaches any defined authentication credentials into the requests for the service.
|
||||
/// A middleware that attaches any defined authentication credentials into the requests to the service.
|
||||
///
|
||||
/// Please refer to the [Discogs documentation](https://www.discogs.com/developers#page:authentication) for further information.
|
||||
public struct AuthMiddleware {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// A representation of an authentication method to use to authenticate requests.
|
||||
private let method: AuthMethod
|
||||
|
||||
/// A representation of a transport option to send credentials in requests.
|
||||
private let transport: AuthTransport
|
||||
/// A header field that contains the authentication information.
|
||||
let authField: HTTPField?
|
||||
|
||||
/// A list of query items that contains the authentication information.
|
||||
let authItems: [URLQueryItem]?
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Initializes this middleware.
|
||||
@@ -45,9 +46,59 @@ public struct AuthMiddleware {
|
||||
public init(
|
||||
method: AuthMethod = .none,
|
||||
transport: AuthTransport
|
||||
) {
|
||||
self.method = method
|
||||
self.transport = transport
|
||||
) throws {
|
||||
switch method {
|
||||
case let .consumer(key, secret):
|
||||
let validateKey = ValidateInputUseCase(rules: .notNil, .notEmpty, .secure(.consumerKey))
|
||||
let validateSecret = ValidateInputUseCase(rules: .notNil, .notEmpty, .secure(.consumerSecret))
|
||||
|
||||
try validateKey(key)
|
||||
try validateSecret(secret)
|
||||
|
||||
self.authField = switch transport {
|
||||
case .onQuery: nil
|
||||
case .onHeader: .init(
|
||||
name: .authorization,
|
||||
value: .init(format: .Format.authConsumer, key, secret)
|
||||
)}
|
||||
|
||||
self.authItems = switch transport {
|
||||
case .onHeader: nil
|
||||
case .onQuery: [
|
||||
.init(name: .Parameter.key, value: key),
|
||||
.init(name: .Parameter.secret, value: secret)
|
||||
]}
|
||||
|
||||
case let .user(token):
|
||||
let validateToken = ValidateInputUseCase(rules: .notNil, .notEmpty, .secure(.userToken))
|
||||
|
||||
try validateToken(token)
|
||||
|
||||
self.authField = switch transport {
|
||||
case .onQuery: nil
|
||||
case .onHeader: .init(
|
||||
name: .authorization,
|
||||
value: .init(format: .Format.authUser, token)
|
||||
)}
|
||||
|
||||
self.authItems = switch transport {
|
||||
case .onHeader: nil
|
||||
case .onQuery: [
|
||||
.init(name: .Parameter.token, value: token)
|
||||
]
|
||||
}
|
||||
|
||||
case .none:
|
||||
self.authField = nil
|
||||
self.authItems = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// A flag that indicates whether the middleware should authenticate the intercepted request or not.
|
||||
var shouldAuthenticate: Bool {
|
||||
authField != nil || authItems != nil
|
||||
}
|
||||
|
||||
}
|
||||
@@ -65,29 +116,17 @@ extension AuthMiddleware: ClientMiddleware {
|
||||
operationID: String,
|
||||
next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
|
||||
) async throws -> (HTTPResponse, HTTPBody?) {
|
||||
guard method != .none else {
|
||||
guard shouldAuthenticate else {
|
||||
return try await next(request, body, baseURL)
|
||||
}
|
||||
|
||||
let headerFields = if transport == .onHeader {
|
||||
authenticateHeader(request.headerFields)
|
||||
} else {
|
||||
request.headerFields
|
||||
}
|
||||
|
||||
let path = if transport == .onQuery {
|
||||
authenticatePath(request.path)
|
||||
} else {
|
||||
request.path
|
||||
}
|
||||
|
||||
return try await next(
|
||||
.init(
|
||||
method: request.method,
|
||||
scheme: request.scheme,
|
||||
authority: request.authority,
|
||||
path: path,
|
||||
headerFields: headerFields
|
||||
path: authenticatePath(request.path),
|
||||
headerFields: authenticateHeader(request.headerFields)
|
||||
),
|
||||
body,
|
||||
baseURL
|
||||
@@ -104,21 +143,14 @@ private extension AuthMiddleware {
|
||||
|
||||
/// Adds an authorization header to the existing header fields.
|
||||
/// - Parameter fields: A set of header fields to update.
|
||||
/// - Returns: An updated set of header fields.
|
||||
/// - Returns: An updated set of header fields including the authorization header.
|
||||
func authenticateHeader(_ fields: HTTPFields) -> HTTPFields {
|
||||
var fields = fields
|
||||
|
||||
let authorization: String = switch method {
|
||||
case let .consumer(key, secret): .init(format: .Format.authConsumer, key, secret)
|
||||
case let .user(token): .init(format: .Format.authUser, token)
|
||||
default: .empty
|
||||
|
||||
if let authField {
|
||||
fields.append(authField)
|
||||
}
|
||||
|
||||
fields.append(.init(
|
||||
name: .authorization,
|
||||
value: authorization
|
||||
))
|
||||
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -127,23 +159,13 @@ private extension AuthMiddleware {
|
||||
/// - Returns: An updated request path including the authentication parameters.
|
||||
func authenticatePath(_ path: String?) -> String? {
|
||||
guard
|
||||
let authItems,
|
||||
let path,
|
||||
var urlComponents = URLComponents(string: path)
|
||||
else {
|
||||
return path
|
||||
}
|
||||
|
||||
let authItems: [URLQueryItem] = switch method {
|
||||
case let .consumer(key, secret): [
|
||||
.init(name: .Parameter.key, value: key),
|
||||
.init(name: .Parameter.secret, value: secret)
|
||||
]
|
||||
case let .user(token): [
|
||||
.init(name: .Parameter.token, value: token)
|
||||
]
|
||||
default: []
|
||||
}
|
||||
|
||||
|
||||
var queryItems = urlComponents.queryItems ?? []
|
||||
|
||||
queryItems.append(contentsOf: authItems)
|
||||
@@ -158,3 +180,12 @@ private extension AuthMiddleware {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Format {
|
||||
/// A format for the consumer authentication header.
|
||||
static let authConsumer = "Discogs \(String.Parameter.key)=%@, \(String.Parameter.secret)=%@"
|
||||
/// A format for the user authentication header.
|
||||
static let authUser = "Discogs \(String.Parameter.token)=%@"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user