Implemented the User Agent middleware (#6)
This PR contains the work done to implement the `UserAgentMiddleware` middleware that includes user agent information into a header of the requests sent by the `Client` type, as defined in the [Discogs documentation](https://www.discogs.com/developers/#page:home,header:home-general-information). For this purpose, the `CamelCaseValidationRule`, `SemanticVersionValidationRule` and `URLValidationRule` types were implemented and integrated into the existing `ValidateInputUseCase` type. Reviewed-on: #6 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 #6.
This commit is contained in:
@@ -22,6 +22,12 @@
|
||||
- ``AuthMethod``
|
||||
- ``AuthTransport``
|
||||
|
||||
### User Agent
|
||||
|
||||
- ``UserAgentMiddleware``
|
||||
- ``Product``
|
||||
- ``InputValidationError``
|
||||
|
||||
### Types
|
||||
|
||||
- ``Components``
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// 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
|
||||
|
||||
extension String {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Checks whether a regular expression pattern fully matches a string or not.
|
||||
/// - Parameter pattern: A regular expression pattern to match a string against.
|
||||
/// - Returns: A flag that indicates whether a given pattern fully matches a string or not.
|
||||
func fullyMatch(pattern: String) -> Bool {
|
||||
do {
|
||||
if #available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 6.0, *) {
|
||||
let securityInput = try Regex(pattern)
|
||||
let matches = self.wholeMatch(of: securityInput)
|
||||
|
||||
return matches != nil
|
||||
} else {
|
||||
let securityInput = try NSRegularExpression(pattern: pattern)
|
||||
let matches = securityInput.matches(
|
||||
in: self,
|
||||
range: .init(location: 0, length: count)
|
||||
)
|
||||
|
||||
return !matches.isEmpty
|
||||
}
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A validation rule type that checks whether an input is camel-case or not.
|
||||
struct CamelCaseValidationRule: InputValidationRule {
|
||||
|
||||
// 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 == CamelCaseValidationRule {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
/// A validation rule that checks whether an input is camel-cased or not.
|
||||
static var camelCase: Self { .init() }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension CamelCaseValidationRule {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// 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 input.fullyMatch(
|
||||
pattern: .init(format: .Pattern.camelCase)
|
||||
) else {
|
||||
throw InputValidationError.inputNotCamelCase
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Pattern {
|
||||
/// A regular expression pattern that represents camel-cased inputs.
|
||||
static let camelCase = "([A-Z]([a-z]|[0-9])+)+"
|
||||
}
|
||||
@@ -77,32 +77,6 @@ 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.
|
||||
@@ -114,7 +88,10 @@ private extension SecureValidationRule {
|
||||
guard let input else {
|
||||
return false
|
||||
}
|
||||
guard isValid(input) else {
|
||||
|
||||
guard input.fullyMatch(
|
||||
pattern: .init(format: .Pattern.securityInput, inputType.rawValue)
|
||||
) else {
|
||||
switch inputType {
|
||||
case .consumerKey: throw InputValidationError.inputNotConsumerKey
|
||||
case .consumerSecret: throw InputValidationError.inputNotConsumerSecret
|
||||
@@ -130,6 +107,6 @@ private extension SecureValidationRule {
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Pattern {
|
||||
/// A regular expression pattern to match the security inputs against.
|
||||
/// A regular expression pattern that represents security inputs.
|
||||
static let securityInput = "^([a-z]|[A-Z]){%d}$"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A validation rule type that checks whether an input is a semantic version or not.
|
||||
///
|
||||
/// This validation rules follows the principles defined in the [Semantic Versioning 2.0.0 documentation](https://semver.org/spec/v2.0.0.html)
|
||||
struct SemanticVersionValidationRule: InputValidationRule {
|
||||
|
||||
// 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 == SemanticVersionValidationRule {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
/// A validation rule that checks whether an input is semantic version or not.
|
||||
static var semanticVersion: Self { .init() }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension SemanticVersionValidationRule {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// 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 input.fullyMatch(
|
||||
pattern: .init(format: .Pattern.semanticVersioning)
|
||||
) else {
|
||||
throw InputValidationError.inputNotSemanticVersion
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Pattern {
|
||||
/// A regular expression pattern that represents semantic version inputs.
|
||||
///
|
||||
/// This regular expression is based on the [suggested regular expression](https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string) of the *Semantic Versioning 2.0.0* documentation.
|
||||
static let semanticVersioning = "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$"
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A validation rule type that checks whether an input is a URL or not.
|
||||
///
|
||||
/// This validation rule doesn't necessarily follow the [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) standard.
|
||||
/// Thus it doesn't implement a complex regular expression pattern such as [this one](https://rgxdb.com/r/5JXUI5A2).
|
||||
/// Instead this validation implements a regular expression sufficient enough to satisfy the requirements for a [user agent definition](https://www.discogs.com/developers/#page:home,header:home-general-information).
|
||||
struct URLValidationRule: InputValidationRule {
|
||||
|
||||
// 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 == URLValidationRule {
|
||||
|
||||
// MARK: Constants
|
||||
|
||||
/// A validation rule that checks whether an input is a URL or not.
|
||||
static var url: Self { .init() }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension URLValidationRule {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// 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 input.fullyMatch(
|
||||
pattern: .init(format: .Pattern.url)
|
||||
) else {
|
||||
throw InputValidationError.inputNotURL
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Pattern {
|
||||
/// A regular expression pattern that represents URL inputs.
|
||||
///
|
||||
/// This regular expression is based on [this regular expression](https://regex101.com/r/3fYy3x/1) found while researching the topic.
|
||||
static let url = "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"
|
||||
}
|
||||
+7
-1
@@ -13,15 +13,21 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
|
||||
/// A representation of all the possible validation error that could be thrown while validating an input.
|
||||
enum InputValidationError: Error {
|
||||
public enum InputValidationError: Error {
|
||||
/// An input is empty.
|
||||
case inputIsEmpty
|
||||
/// An input is nil.
|
||||
case inputIsNil
|
||||
/// An input is not camel-case.
|
||||
case inputNotCamelCase
|
||||
/// 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 is not a semantic version.
|
||||
case inputNotSemanticVersion
|
||||
/// An input is not a URL.
|
||||
case inputNotURL
|
||||
/// An input does not comply with the user token requirements.
|
||||
case inputNotUserToken
|
||||
}
|
||||
@@ -43,6 +43,7 @@ public struct AuthMiddleware {
|
||||
/// - Parameters:
|
||||
/// - method: A representation of an authentication method to use to authenticate requests.
|
||||
/// - transport: A representation of a transport option to send credentials in requests.
|
||||
/// - Throws: An error of type ``InputValidationError`` in case an input failed any validation.
|
||||
public init(
|
||||
method: AuthMethod = .none,
|
||||
transport: AuthTransport
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// ===----------------------------------------------------------------------===
|
||||
//
|
||||
// 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 class OpenAPIRuntime.HTTPBody
|
||||
|
||||
import protocol OpenAPIRuntime.ClientMiddleware
|
||||
|
||||
import struct Foundation.URL
|
||||
import struct HTTPTypes.HTTPField
|
||||
import struct HTTPTypes.HTTPFields
|
||||
import struct HTTPTypes.HTTPRequest
|
||||
import struct HTTPTypes.HTTPResponse
|
||||
|
||||
/// A middleware that attaches the user agent header into the requests to the service.
|
||||
///
|
||||
/// Please refer to the [Discogs documentation](https://www.discogs.com/developers/#page:home,header:home-general-information) for further information.
|
||||
public struct UserAgentMiddleware {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// A formatted value for the user agent header.
|
||||
let agentField: HTTPField
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Initializes this middleware.
|
||||
/// - Parameter product: A product from which the user agent will be generated from.
|
||||
/// - Throws: An error of type ``InputValidationError`` in case an input failed any validation.
|
||||
public init(product: Product) throws {
|
||||
let agentName = ValidateInputUseCase(rules: .notNil, .notEmpty, .camelCase)
|
||||
let agentVersion = ValidateInputUseCase(rules: .notNil, .notEmpty, .semanticVersion)
|
||||
let agentURL = ValidateInputUseCase(rules: .notNil, .notEmpty, .url)
|
||||
|
||||
try agentName(product.name)
|
||||
try agentVersion(product.version)
|
||||
try agentURL(product.url)
|
||||
|
||||
self.agentField = .init(
|
||||
name: .userAgent,
|
||||
value: .init(format: .Format.userAgent, product.name, product.version, product.url)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - ClientMiddleware
|
||||
|
||||
extension UserAgentMiddleware: ClientMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
public func intercept(
|
||||
_ request: HTTPRequest,
|
||||
body: HTTPBody?,
|
||||
baseURL: URL,
|
||||
operationID: String,
|
||||
next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
|
||||
) async throws -> (HTTPResponse, HTTPBody?) {
|
||||
return try await next(
|
||||
.init(
|
||||
method: request.method,
|
||||
scheme: request.scheme,
|
||||
authority: request.authority,
|
||||
path: request.path,
|
||||
headerFields: userAgentHeader(request.headerFields)
|
||||
),
|
||||
body,
|
||||
baseURL
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension UserAgentMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Adds a user agent header to the existing header fields.
|
||||
/// - Parameter fields: A set of header fields to update.
|
||||
/// - Returns: An updated set of header fields including the user agent header.
|
||||
func userAgentHeader(_ fields: HTTPFields) -> HTTPFields {
|
||||
var fields = fields
|
||||
|
||||
fields.append(agentField)
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private extension String.Format {
|
||||
/// A format for the user agent header.
|
||||
static let userAgent = "%@/%@ +%@"
|
||||
}
|
||||
@@ -33,8 +33,8 @@ public struct Product: Sendable {
|
||||
/// Initializes this model.
|
||||
/// - Parameters:
|
||||
/// - name: A camel-cased name of a product.
|
||||
/// - version: A URI link related to a product.
|
||||
/// - url: A semantic version of a product.
|
||||
/// - version: A semantic version of a product.
|
||||
/// - url: A URI link related to a product.
|
||||
public init(
|
||||
name: String,
|
||||
version: String,
|
||||
|
||||
Reference in New Issue
Block a user