Skip to content

Commit 92ff97d

Browse files
authored
fix: use non-failable UTF8View Data init when converting from String (#3430)
1 parent 006e045 commit 92ff97d

File tree

58 files changed

+125
-184
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+125
-184
lines changed

Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift

+1-8
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,7 @@ extension Model where Self: Codable {
3333
resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy)
3434
}
3535

36-
guard let data = json.data(using: .utf8) else {
37-
throw DataStoreError.decodingError(
38-
"Invalid JSON string. Could not convert the passed JSON string into a UTF-8 Data object",
39-
"Ensure the JSON doesn't contain any invalid UTF-8 data:\n\n\(json)"
40-
)
41-
}
42-
43-
return try resolvedDecoder.decode(Self.self, from: data)
36+
return try resolvedDecoder.decode(Self.self, from: Data(json.utf8))
4437
}
4538

4639
/// De-serialize a `Dictionary` into an instance of the concrete type that conforms

Amplify/Categories/DataStore/Model/Internal/Schema/ModelValueConverter.swift

+1-4
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,6 @@ extension ModelValueConverter {
6363
/// application making any change to these `public` types should be backward compatible, otherwise it will be a
6464
/// breaking change.
6565
public static func fromJSON(_ value: String) throws -> Any? {
66-
guard let data = value.data(using: .utf8) else {
67-
return nil
68-
}
69-
return try JSONSerialization.jsonObject(with: data)
66+
return try JSONSerialization.jsonObject(with: Data(value.utf8))
7067
}
7168
}

AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class AmplifyConfigurationInitFromFileTests: XCTestCase {
2222
}
2323
"""
2424

25-
let configData = configString.data(using: .utf8)!
25+
let configData = Data(configString.utf8)
2626
let configURL = FileManager
2727
.default
2828
.temporaryDirectory

AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthenticationTokenAuthInterceptor.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ class AuthenticationTokenAuthInterceptor: AuthInterceptorAsync {
5555
let authHeader = TokenAuthHeader(token: authToken, host: host)
5656
let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader)
5757

58-
let payloadData = SubscriptionConstants.emptyPayload.data(using: .utf8)
59-
let payloadBase64 = payloadData?.base64EncodedString()
58+
let payloadData = Data(SubscriptionConstants.emptyPayload.utf8)
59+
let payloadBase64 = payloadData.base64EncodedString()
6060

6161
guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else {
6262
return request

AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ class IAMAuthInterceptor: AuthInterceptorAsync {
5454
}
5555
let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader)
5656

57-
let payloadData = payloadString.data(using: .utf8)
58-
let payloadBase64 = payloadData?.base64EncodedString()
57+
let payloadData = Data(payloadString.utf8)
58+
let payloadBase64 = payloadData.base64EncodedString()
5959

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

9696
/// 2. The request is SigV4 signed by using all the available headers on the request. By signing the request, the signature is added to
9797
/// the request headers as authorization and security token.

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import XCTest
1111
class AWSHTTPURLResponseTests: XCTestCase {
1212

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

3737
func testAWSHTTPURLResponseNSCoding() {
38-
let body = "responseBody".data(using: .utf8)
38+
let body = Data("responseBody".utf8)
3939
let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!,
4040
statusCode: 200,
4141
httpVersion: "1.1",

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class GraphQLMutateCombineTests: OperationTestBase {
1616

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

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

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

5858
let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class GraphQLQueryCombineTests: OperationTestBase {
1616

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

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

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

5858
let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self)

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift

+5-5
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
7272
receivedDataValueError.isInverted = true
7373

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

7777
try await subscribe(expecting: testJSON)
7878
await fulfillment(of: [onSubscribeInvoked], timeout: 0.05)
@@ -117,7 +117,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
117117
}
118118

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

@@ -134,7 +134,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase {
134134

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

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

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift

+5-5
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
7676
receivedDataValueError.isInverted = true
7777

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

8181
try await subscribe(expecting: testJSON)
8282
await fulfillment(of: [onSubscribeInvoked], timeout: 0.05)
@@ -169,7 +169,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
169169
}
170170

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

@@ -186,7 +186,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
186186

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

191191
receivedCompletionFailure.isInverted = true
192192
receivedDataValueError.isInverted = true
@@ -205,8 +205,8 @@ class GraphQLSubscribeTasksTests: OperationTestBase {
205205
}
206206

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

211211
receivedCompletionFailure.isInverted = true
212212
receivedDataValueSuccess.expectedFulfillmentCount = 2

AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift

+5-5
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class GraphQLSubscribeTests: OperationTestBase {
6464
/// - The completion handler is invoked with a normal termination
6565
func testHappyPath() throws {
6666
let testJSON: JSONValue = ["foo": true]
67-
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
67+
let testData = Data(#"{"data": {"foo": true}}"#.utf8)
6868
receivedCompletionFinish.shouldTrigger = true
6969
receivedCompletionFailure.shouldTrigger = false
7070
receivedConnected.shouldTrigger = true
@@ -152,7 +152,7 @@ class GraphQLSubscribeTests: OperationTestBase {
152152
/// - The value handler is invoked with a disconnection message
153153
/// - The completion handler is invoked with a normal termination
154154
func testDecodingError() throws {
155-
let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
155+
let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
156156
receivedCompletionFinish.shouldTrigger = true
157157
receivedCompletionFailure.shouldTrigger = false
158158
receivedConnected.shouldTrigger = true
@@ -173,7 +173,7 @@ class GraphQLSubscribeTests: OperationTestBase {
173173

174174
func testMultipleSuccessValues() throws {
175175
let testJSON: JSONValue = ["foo": true]
176-
let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
176+
let testData = Data(#"{"data": {"foo": true}}"#.utf8)
177177
receivedCompletionFinish.shouldTrigger = true
178178
receivedCompletionFailure.shouldTrigger = false
179179
receivedConnected.shouldTrigger = true
@@ -195,8 +195,8 @@ class GraphQLSubscribeTests: OperationTestBase {
195195
}
196196

197197
func testMixedSuccessAndErrorValues() throws {
198-
let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)!
199-
let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)!
198+
let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8)
199+
let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8)
200200
receivedCompletionFinish.shouldTrigger = true
201201
receivedCompletionFailure.shouldTrigger = false
202202
receivedConnected.shouldTrigger = true

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift

+2-6
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior {
103103
}
104104
let key = SymmetricKey(data: keyData)
105105
let content = "\(Self.asfVersion)\(contextJson)"
106-
guard let data = content.data(using: .utf8) else {
107-
throw ASFError.hashData
108-
}
106+
let data = Data(content.utf8)
109107
let hmac = HMAC<SHA256>.authenticationCode(for: data, using: key)
110108
let hmacData = Data(hmac)
111109
return hmacData.base64EncodedString()
@@ -121,9 +119,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior {
121119
guard let jsonString = String(data: jsonData, encoding: .utf8) else {
122120
throw ASFError.stringConversion
123121
}
124-
guard let data = jsonString.data(using: .utf8) else {
125-
throw ASFError.dataConversion
126-
}
122+
let data = Data(jsonString.utf8)
127123
return data.base64EncodedString()
128124
}
129125
}

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,10 @@ extension VerifyDevicePasswordSRP {
8686
serviceSecretBlock: Data) -> Data {
8787
let key = SymmetricKey(data: authenticationKey)
8888
var hmac = HMAC<SHA256>.init(key: key)
89-
hmac.update(data: deviceGroupKey.data(using: .utf8)!)
90-
hmac.update(data: deviceKey.data(using: .utf8)!)
89+
hmac.update(data: Data(deviceGroupKey.utf8))
90+
hmac.update(data: Data(deviceKey.utf8))
9191
hmac.update(data: serviceSecretBlock)
92-
hmac.update(data: srpTimeStamp.data(using: .utf8)!)
92+
hmac.update(data: Data(srpTimeStamp.utf8))
9393
return Data(hmac.finalize())
9494
}
9595
}

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift

+3-3
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,10 @@ extension VerifyPasswordSRP {
9393
serviceSecretBlock: Data) -> Data {
9494
let key = SymmetricKey(data: authenticationKey)
9595
var hmac = HMAC<SHA256>.init(key: key)
96-
hmac.update(data: poolName.data(using: .utf8)!)
97-
hmac.update(data: srpUserName.data(using: .utf8)!)
96+
hmac.update(data: Data(poolName.utf8))
97+
hmac.update(data: Data(srpUserName.utf8))
9898
hmac.update(data: serviceSecretBlock)
99-
hmac.update(data: srpTimeStamp.data(using: .utf8)!)
99+
hmac.update(data: Data(srpTimeStamp.utf8))
100100
return Data(hmac.finalize())
101101
}
102102
}

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift

+7-12
Original file line numberDiff line numberDiff line change
@@ -49,20 +49,15 @@ extension RespondToAuthChallenge {
4949

5050
/// Helper method to extract MFA types from parameters
5151
private func getMFATypes(forKey key: String) -> Set<MFAType> {
52-
var mfaTypes = Set<MFAType>()
53-
guard let mfaTypeParametersData = parameters?[key]?.data(using: .utf8),
52+
guard let mfaTypeParameters = parameters?[key],
5453
let mfaTypesArray = try? JSONDecoder().decode(
55-
[String].self, from: mfaTypeParametersData) else {
56-
return mfaTypes
57-
}
58-
59-
for mfaTypeValue in mfaTypesArray {
60-
if let mfaType = MFAType(rawValue: String(mfaTypeValue)) {
61-
mfaTypes.insert(mfaType)
62-
}
63-
}
54+
[String].self,
55+
from: Data(mfaTypeParameters.utf8)
56+
)
57+
else { return .init() }
6458

65-
return mfaTypes
59+
let mfaTypes = mfaTypesArray.compactMap(MFAType.init(rawValue:))
60+
return Set(mfaTypes)
6661
}
6762

6863
var debugDictionary: [String: Any] {

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,11 @@ enum ClientSecretHelper {
3131
userPoolClientId: String,
3232
clientSecret: String
3333
) -> String {
34-
let clientSecretData = clientSecret.data(using: .utf8)!
34+
let clientSecretData = Data(clientSecret.utf8)
3535
let clientSecretByteArray = [UInt8](clientSecretData)
3636
let key = SymmetricKey(data: clientSecretByteArray)
3737

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

4040
let mac = HMAC<SHA256>.authenticationCode(for: clientData, using: key)
4141
let macBase64 = Data(mac).base64EncodedString()

AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift

+4-5
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ struct HostedUIRequestHelper {
115115

116116
var urlRequest = URLRequest(url: url)
117117
urlRequest.httpMethod = "POST"
118-
urlRequest.httpBody = body.data(using: .utf8)
118+
urlRequest.httpBody = Data(body.utf8)
119119
urlRequest.addHeaders(using: configuration)
120120
return urlRequest
121121
}
@@ -145,7 +145,7 @@ struct HostedUIRequestHelper {
145145

146146
var urlRequest = URLRequest(url: url)
147147
urlRequest.httpMethod = "POST"
148-
urlRequest.httpBody = body.data(using: .utf8)
148+
urlRequest.httpBody = Data(body.utf8)
149149
urlRequest.addHeaders(using: configuration)
150150
return urlRequest
151151
}
@@ -159,11 +159,10 @@ struct HostedUIRequestHelper {
159159

160160
private extension URLRequest {
161161
mutating func addHeaders(using configuration: HostedUIConfigurationData) {
162-
guard let clientSecret = configuration.clientSecret,
163-
let value = "\(configuration.clientId):\(clientSecret)".data(using: .utf8) else {
162+
guard let clientSecret = configuration.clientSecret else {
164163
return
165164
}
166-
165+
let value = Data("\(configuration.clientId):\(clientSecret)".utf8)
167166
setValue("Basic \(value.base64EncodedString())", forHTTPHeaderField: "Authorization")
168167
}
169168
}

AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift

+3-4
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public enum HMACKeyDerivationFunction {
2323
outputLength: outputLength)
2424
} else {
2525
let pseudoRandomKey = extractPseudoRandomKey(salt: salt, inputKeyMaterial: keyingMaterial)
26-
return expand(pseudoRandomKey: pseudoRandomKey, info: info?.data(using: .utf8), outputLength: outputLength)
26+
return expand(pseudoRandomKey: pseudoRandomKey, info: info.map { Data($0.utf8) }, outputLength: outputLength)
2727
}
2828
}
2929

@@ -34,11 +34,10 @@ public enum HMACKeyDerivationFunction {
3434
outputLength: Int) -> Data {
3535
let key = SymmetricKey(data: keyingMaterial)
3636
var hkdf: SymmetricKey
37-
if let infoData = info?.data(using: .utf8) {
37+
if let info {
3838
hkdf = HKDF<SHA256>.deriveKey(inputKeyMaterial: key,
39-
salt: salt, info: infoData,
39+
salt: salt, info: Data(info.utf8),
4040
outputByteCount: outputLength)
41-
4241
} else {
4342
hkdf = HKDF<SHA256>.deriveKey(inputKeyMaterial: key,
4443
salt: salt,

AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior {
2828
}
2929

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

3434
func _set(_ value: String, key: String) throws { }

0 commit comments

Comments
 (0)