Xcode 9.2: Keychain error when running unit test

Number:rdar://36809637 Date Originated:24/08/2018
Status:Open Resolved:
Product:Xcode Product Version:9.2
Classification:Security Reproducible:Always

I have the following code in a framework target for my app:

let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault,                                            

var attributes: [String: Any] = [
    kSecAttrKeyType as String: encryptionType,
    kSecAttrKeySizeInBits as String: encryptionBits,
    kSecPrivateKeyAttrs as String: [
       kSecAttrIsPermanent as String: true,
       kSecAttrApplicationTag as String: "abc".data(using: .utf8) as Any,
       kSecAttrAccessControl as String: access,

if Device.hasSecureEnclave {
    attributes[kSecAttrTokenID as String] = kSecAttrTokenIDSecureEnclave

var error: Unmanaged<CFError>?
SecKeyCreateRandomKey(attributes as CFDictionary, &error)

When I run this code on the device or in the simulator it works fine. When I run this code from a unit test it fails, reporting: Error Domain=NSOSStatusErrorDomain Code=-50 
"Key generation failed, error -50" UserInfo={NSDescription=Key generation failed, error -50}

Steps to Reproduce:

1. Cut and paste the above code into a method in an app. Run the app in the simulator to verify a key pair is created and errSecSuccess (0) is returned from the call to SecKeyCreateRandomKey.

2. Setup a unit test totes the framework containing this test. ie. No host application.

3. Run the test. 

Expected Results:

Code should succeed, returning a key and a success code of errSecSuccess (0)

Actual Results:

Instead, a nil is returned and a success code of errSecParam(-50)


Xcode Version 9.2 (9C40b)


I can verify that this behavior still exists as of Xcode 9.4.1. Also, the code doesn't work even if it's directly a part of the test bundle code itself (i.e. a class/method authored within the test bundle), suggesting that the issue is with the test bundle's ability to access the keychain for this functionality.

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!