Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(validation): adds domain validation to client #42

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Sources/ImgixSwift/ImgixClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import Foundation

// regex pattern used to determine if a domain is valid
let _domainRegex = #"^(?:[a-z\d\-_]{1,62}\.){0,125}(?:[a-z\d](?:\-(?=\-*[a-z\d])|[a-z]|\d){0,62}\.)[a-z\d]{1,63}$"#;

@objc open class ImgixClient: NSObject {
@objc static public let VERSION = "1.1.3"

Expand All @@ -13,22 +16,30 @@ import Foundation
@objc open var secureUrlToken: String?
@objc open var includeLibraryParam: Bool = true

enum ClientError: Error {
case invalidDomain(host: String, _ reason: String)
}

@objc public init(host: String) {
let _ = try! ImgixClient.validateDomain(host)
self.host = host
}

@objc public init(host: String, useHttps: Bool) {
let _ = try! ImgixClient.validateDomain(host)
self.host = host
self.useHttps = useHttps
}

@objc public init(host: String, useHttps: Bool, secureUrlToken: String) {
let _ = try! ImgixClient.validateDomain(host)
self.host = host
self.useHttps = useHttps
self.secureUrlToken = secureUrlToken
}

@objc public init(host: String, secureUrlToken: String) {
let _ = try! ImgixClient.validateDomain(host)
self.host = host
self.secureUrlToken = secureUrlToken
}
Expand Down Expand Up @@ -156,4 +167,19 @@ import Foundation

return URLQueryItem.init(name: "s", value: signature)
}

class public func validateDomain(_ host: String) throws -> String {
let regex = try! NSRegularExpression(pattern: _domainRegex)
let range = NSRange(location: 0, length: host.count)
let match = regex.firstMatch(in: host, options: [], range: range) != nil
if !match{
throw ClientError.invalidDomain(host:host, """
Domain must be passed in as fully-qualified \
domain name and should not include a protocol or any path \
element, i.e. 'example.imgix.net'.
""")
}
return host
}
}

5 changes: 5 additions & 0 deletions Tests/ImgixSwiftTests/BuildUrlTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,9 @@ class BuildUrlTests: XCTestCase {
print(generatedUrl)
XCTAssert(generatedUrl.absoluteString == expectedUrl)
}

func testValidatesDomain() {
let malformedHost = "http://www.imgix.com"
XCTAssertThrowsError(try ImgixClient.validateDomain(malformedHost))
}
}