Skip to content

Commit

Permalink
fix: use non-failable UTF8View Data init when converting from String (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
atierian authored Dec 20, 2023
1 parent 006e045 commit 92ff97d
Show file tree
Hide file tree
Showing 58 changed files with 125 additions and 184 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,7 @@ extension Model where Self: Codable {
resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy)
}

guard let data = json.data(using: .utf8) else {
throw DataStoreError.decodingError(
"Invalid JSON string. Could not convert the passed JSON string into a UTF-8 Data object",
"Ensure the JSON doesn't contain any invalid UTF-8 data:\n\n\(json)"
)
}

return try resolvedDecoder.decode(Self.self, from: data)
return try resolvedDecoder.decode(Self.self, from: Data(json.utf8))
}

/// De-serialize a `Dictionary` into an instance of the concrete type that conforms
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,6 @@ extension ModelValueConverter {
/// application making any change to these `public` types should be backward compatible, otherwise it will be a
/// breaking change.
public static func fromJSON(_ value: String) throws -> Any? {
guard let data = value.data(using: .utf8) else {
return nil
}
return try JSONSerialization.jsonObject(with: data)
return try JSONSerialization.jsonObject(with: Data(value.utf8))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class AmplifyConfigurationInitFromFileTests: XCTestCase {
}
"""

let configData = configString.data(using: .utf8)!
let configData = Data(configString.utf8)
let configURL = FileManager
.default
.temporaryDirectory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ class AuthenticationTokenAuthInterceptor: AuthInterceptorAsync {
let authHeader = TokenAuthHeader(token: authToken, host: host)
let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader)

let payloadData = SubscriptionConstants.emptyPayload.data(using: .utf8)
let payloadBase64 = payloadData?.base64EncodedString()
let payloadData = Data(SubscriptionConstants.emptyPayload.utf8)
let payloadBase64 = payloadData.base64EncodedString()

guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else {
return request
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ class IAMAuthInterceptor: AuthInterceptorAsync {
}
let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader)

let payloadData = payloadString.data(using: .utf8)
let payloadBase64 = payloadData?.base64EncodedString()
let payloadData = Data(payloadString.utf8)
let payloadBase64 = payloadData.base64EncodedString()

guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else {
return request
Expand Down Expand Up @@ -91,7 +91,7 @@ class IAMAuthInterceptor: AuthInterceptorAsync {
.withHeader(name: RealtimeProviderConstants.contentEncodingKey, value: RealtimeProviderConstants.iamEncoding)
.withHeader(name: URLRequestConstants.Header.contentType, value: RealtimeProviderConstants.iamConentType)
.withHeader(name: URLRequestConstants.Header.host, value: host)
.withBody(.data(payload.data(using: .utf8)))
.withBody(.data(Data(payload.utf8)))

/// 2. The request is SigV4 signed by using all the available headers on the request. By signing the request, the signature is added to
/// the request headers as authorization and security token.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import XCTest
class AWSHTTPURLResponseTests: XCTestCase {

func testAWSHTTPURLResponse() throws {
let body = "responseBody".data(using: .utf8)
let body = Data("responseBody".utf8)
let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!,
statusCode: 200,
httpVersion: "1.1",
Expand All @@ -35,7 +35,7 @@ class AWSHTTPURLResponseTests: XCTestCase {
}

func testAWSHTTPURLResponseNSCoding() {
let body = "responseBody".data(using: .utf8)
let body = Data("responseBody".utf8)
let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!,
statusCode: 200,
httpVersion: "1.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class GraphQLMutateCombineTests: OperationTestBase {

func testMutateSucceeds() throws {
let testJSONData: JSONValue = ["foo": true]
let sentData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let sentData = Data(#"{"data": {"foo": true}}"#.utf8)
try setUpPluginForSingleResponse(sending: sentData, for: .graphQL)

let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)
Expand Down Expand Up @@ -52,7 +52,7 @@ class GraphQLMutateCombineTests: OperationTestBase {
}

func testMutateHandlesResponseError() throws {
let sentData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let sentData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
try setUpPluginForSingleResponse(sending: sentData, for: .graphQL)

let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class GraphQLQueryCombineTests: OperationTestBase {

func testQuerySucceeds() throws {
let testJSONData: JSONValue = ["foo": true]
let sentData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let sentData = Data(#"{"data": {"foo": true}}"#.utf8)
try setUpPluginForSingleResponse(sending: sentData, for: .graphQL)

let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)
Expand Down Expand Up @@ -52,7 +52,7 @@ class GraphQLQueryCombineTests: OperationTestBase {
}

func testQueryHandlesResponseError() throws {
let sentData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let sentData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
try setUpPluginForSingleResponse(sending: sentData, for: .graphQL)

let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
receivedDataValueError.isInverted = true

let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)

try await subscribe(expecting: testJSON)
await fulfillment(of: [onSubscribeInvoked], timeout: 0.05)
Expand Down Expand Up @@ -117,7 +117,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
}

func testDecodingError() async throws {
let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
receivedCompletionFailure.isInverted = true
receivedDataValueSuccess.isInverted = true

Expand All @@ -134,7 +134,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {

func testMultipleSuccessValues() async throws {
let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)
receivedCompletionFailure.isInverted = true
receivedDataValueError.isInverted = true
receivedDataValueSuccess.expectedFulfillmentCount = 2
Expand All @@ -152,8 +152,8 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
}

func testMixedSuccessAndErrorValues() async throws {
let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8)
let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
receivedCompletionFailure.isInverted = true
receivedDataValueSuccess.expectedFulfillmentCount = 2

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
receivedDataValueError.isInverted = true

let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)

try await subscribe(expecting: testJSON)
await fulfillment(of: [onSubscribeInvoked], timeout: 0.05)
Expand Down Expand Up @@ -169,7 +169,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
}

func testDecodingError() async throws {
let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
receivedCompletionFailure.isInverted = true
receivedDataValueSuccess.isInverted = true

Expand All @@ -186,7 +186,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {

func testMultipleSuccessValues() async throws {
let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)

receivedCompletionFailure.isInverted = true
receivedDataValueError.isInverted = true
Expand All @@ -205,8 +205,8 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
}

func testMixedSuccessAndErrorValues() async throws {
let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8)
let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)

receivedCompletionFailure.isInverted = true
receivedDataValueSuccess.expectedFulfillmentCount = 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class GraphQLSubscribeTests: OperationTestBase {
/// - The completion handler is invoked with a normal termination
func testHappyPath() throws {
let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)
receivedCompletionFinish.shouldTrigger = true
receivedCompletionFailure.shouldTrigger = false
receivedConnected.shouldTrigger = true
Expand Down Expand Up @@ -152,7 +152,7 @@ class GraphQLSubscribeTests: OperationTestBase {
/// - The value handler is invoked with a disconnection message
/// - The completion handler is invoked with a normal termination
func testDecodingError() throws {
let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
receivedCompletionFinish.shouldTrigger = true
receivedCompletionFailure.shouldTrigger = false
receivedConnected.shouldTrigger = true
Expand All @@ -173,7 +173,7 @@ class GraphQLSubscribeTests: OperationTestBase {

func testMultipleSuccessValues() throws {
let testJSON: JSONValue = ["foo": true]
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let testData = Data(#"{"data": {"foo": true}}"#.utf8)
receivedCompletionFinish.shouldTrigger = true
receivedCompletionFailure.shouldTrigger = false
receivedConnected.shouldTrigger = true
Expand All @@ -195,8 +195,8 @@ class GraphQLSubscribeTests: OperationTestBase {
}

func testMixedSuccessAndErrorValues() throws {
let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8)
let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
receivedCompletionFinish.shouldTrigger = true
receivedCompletionFailure.shouldTrigger = false
receivedConnected.shouldTrigger = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior {
}
let key = SymmetricKey(data: keyData)
let content = "\(Self.asfVersion)\(contextJson)"
guard let data = content.data(using: .utf8) else {
throw ASFError.hashData
}
let data = Data(content.utf8)
let hmac = HMAC<SHA256>.authenticationCode(for: data, using: key)
let hmacData = Data(hmac)
return hmacData.base64EncodedString()
Expand All @@ -121,9 +119,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior {
guard let jsonString = String(data: jsonData, encoding: .utf8) else {
throw ASFError.stringConversion
}
guard let data = jsonString.data(using: .utf8) else {
throw ASFError.dataConversion
}
let data = Data(jsonString.utf8)
return data.base64EncodedString()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ extension VerifyDevicePasswordSRP {
serviceSecretBlock: Data) -> Data {
let key = SymmetricKey(data: authenticationKey)
var hmac = HMAC<SHA256>.init(key: key)
hmac.update(data: deviceGroupKey.data(using: .utf8)!)
hmac.update(data: deviceKey.data(using: .utf8)!)
hmac.update(data: Data(deviceGroupKey.utf8))
hmac.update(data: Data(deviceKey.utf8))
hmac.update(data: serviceSecretBlock)
hmac.update(data: srpTimeStamp.data(using: .utf8)!)
hmac.update(data: Data(srpTimeStamp.utf8))
return Data(hmac.finalize())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,10 @@ extension VerifyPasswordSRP {
serviceSecretBlock: Data) -> Data {
let key = SymmetricKey(data: authenticationKey)
var hmac = HMAC<SHA256>.init(key: key)
hmac.update(data: poolName.data(using: .utf8)!)
hmac.update(data: srpUserName.data(using: .utf8)!)
hmac.update(data: Data(poolName.utf8))
hmac.update(data: Data(srpUserName.utf8))
hmac.update(data: serviceSecretBlock)
hmac.update(data: srpTimeStamp.data(using: .utf8)!)
hmac.update(data: Data(srpTimeStamp.utf8))
return Data(hmac.finalize())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,15 @@ extension RespondToAuthChallenge {

/// Helper method to extract MFA types from parameters
private func getMFATypes(forKey key: String) -> Set<MFAType> {
var mfaTypes = Set<MFAType>()
guard let mfaTypeParametersData = parameters?[key]?.data(using: .utf8),
guard let mfaTypeParameters = parameters?[key],
let mfaTypesArray = try? JSONDecoder().decode(
[String].self, from: mfaTypeParametersData) else {
return mfaTypes
}

for mfaTypeValue in mfaTypesArray {
if let mfaType = MFAType(rawValue: String(mfaTypeValue)) {
mfaTypes.insert(mfaType)
}
}
[String].self,
from: Data(mfaTypeParameters.utf8)
)
else { return .init() }

return mfaTypes
let mfaTypes = mfaTypesArray.compactMap(MFAType.init(rawValue:))
return Set(mfaTypes)
}

var debugDictionary: [String: Any] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ enum ClientSecretHelper {
userPoolClientId: String,
clientSecret: String
) -> String {
let clientSecretData = clientSecret.data(using: .utf8)!
let clientSecretData = Data(clientSecret.utf8)
let clientSecretByteArray = [UInt8](clientSecretData)
let key = SymmetricKey(data: clientSecretByteArray)

let clientData = (username + userPoolClientId).data(using: .utf8)!
let clientData = Data((username + userPoolClientId).utf8)

let mac = HMAC<SHA256>.authenticationCode(for: clientData, using: key)
let macBase64 = Data(mac).base64EncodedString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ struct HostedUIRequestHelper {

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = body.data(using: .utf8)
urlRequest.httpBody = Data(body.utf8)
urlRequest.addHeaders(using: configuration)
return urlRequest
}
Expand Down Expand Up @@ -145,7 +145,7 @@ struct HostedUIRequestHelper {

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = body.data(using: .utf8)
urlRequest.httpBody = Data(body.utf8)
urlRequest.addHeaders(using: configuration)
return urlRequest
}
Expand All @@ -159,11 +159,10 @@ struct HostedUIRequestHelper {

private extension URLRequest {
mutating func addHeaders(using configuration: HostedUIConfigurationData) {
guard let clientSecret = configuration.clientSecret,
let value = "\(configuration.clientId):\(clientSecret)".data(using: .utf8) else {
guard let clientSecret = configuration.clientSecret else {
return
}

let value = Data("\(configuration.clientId):\(clientSecret)".utf8)
setValue("Basic \(value.base64EncodedString())", forHTTPHeaderField: "Authorization")
}
}
7 changes: 3 additions & 4 deletions AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public enum HMACKeyDerivationFunction {
outputLength: outputLength)
} else {
let pseudoRandomKey = extractPseudoRandomKey(salt: salt, inputKeyMaterial: keyingMaterial)
return expand(pseudoRandomKey: pseudoRandomKey, info: info?.data(using: .utf8), outputLength: outputLength)
return expand(pseudoRandomKey: pseudoRandomKey, info: info.map { Data($0.utf8) }, outputLength: outputLength)
}
}

Expand All @@ -34,11 +34,10 @@ public enum HMACKeyDerivationFunction {
outputLength: Int) -> Data {
let key = SymmetricKey(data: keyingMaterial)
var hkdf: SymmetricKey
if let infoData = info?.data(using: .utf8) {
if let info {
hkdf = HKDF<SHA256>.deriveKey(inputKeyMaterial: key,
salt: salt, info: infoData,
salt: salt, info: Data(info.utf8),
outputByteCount: outputLength)

} else {
hkdf = HKDF<SHA256>.deriveKey(inputKeyMaterial: key,
salt: salt,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior {
}

func _getData(_ key: String) throws -> Data {
return data.data(using: .utf8)!
return Data(data.utf8)
}

func _set(_ value: String, key: String) throws { }
Expand Down
Loading

0 comments on commit 92ff97d

Please sign in to comment.