Skip to content

Commit

Permalink
Keychain error refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
flypaper0 committed Oct 31, 2023
1 parent 8ad09bb commit 9dd5dd0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 13 deletions.
2 changes: 1 addition & 1 deletion Sources/WalletConnectKMS/Crypto/KeyManagementService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public class KeyManagementService: KeyManagementServiceProtocol {
public func getPrivateKey(for publicKey: AgreementPublicKey) throws -> AgreementPrivateKey? {
do {
return try keychain.read(key: publicKey.hexRepresentation) as AgreementPrivateKey
} catch let error where (error as? KeychainError)?.status == errSecItemNotFound {
} catch KeychainError.itemNotFound {
return nil
} catch {
throw error
Expand Down
23 changes: 16 additions & 7 deletions Sources/WalletConnectKMS/Keychain/KeychainError.swift
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
import Foundation

// TODO: Integrate with WalletConnectError
public struct KeychainError: Error, LocalizedError {

public let status: OSStatus
public enum KeychainError: Error, LocalizedError {
case itemNotFound
case other(OSStatus)

public init(_ status: OSStatus) {
self.status = status
switch status {
case errSecItemNotFound:
self = .itemNotFound
default:
self = .other(status)
}
}

public var errorDescription: String? {
return "OSStatus: \(status), message: \(status.message)"
switch self {
case .itemNotFound:
return "Keychain item not found"
case .other(let status):
return "OSStatus: \(status), message: \(status.message)"
}
}
}

extension KeychainError: CustomStringConvertible {

public var description: String {
status.message
return errorDescription ?? ""
}
}

Expand Down
11 changes: 6 additions & 5 deletions Sources/WalletConnectRelay/ClientAuth/ClientIdStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ public struct ClientIdStorage: ClientIdStoring {
do {
let publicPart = try getPublicPart()
return try getPrivatePart(for: publicPart)
} catch {
guard let error = error as? KeychainError, error.status == errSecItemNotFound else {
throw error
}
} catch Errors.privatePartNotFound, Errors.publicPartNotFound {
let privateKey = SigningPrivateKey()
try setPrivatePart(privateKey)
setPublicPart(privateKey.publicKey)
return privateKey
} catch {
throw error
}
}

Expand Down Expand Up @@ -79,8 +78,10 @@ private extension ClientIdStorage {
func getPrivatePart(for publicPart: SigningPublicKey) throws -> SigningPrivateKey {
do {
return try keychain.read(key: publicPart.storageId)
} catch {
} catch KeychainError.itemNotFound {
throw Errors.privatePartNotFound
} catch {
throw error
}
}

Expand Down

0 comments on commit 9dd5dd0

Please sign in to comment.