Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Refactor DeveloperServices operations and add tests

kabiroberai3da2181f9bd8
diff --git a/Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAddAppGroupRequest.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAddAppGroupRequest.swift
rename to Supersign/DeveloperServices/App Groups/DeveloperServicesAddAppGroupRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAppGroup.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAppGroup.swift
rename to Supersign/DeveloperServices/App Groups/DeveloperServicesAppGroup.swift
diff --git a/Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAssignAppGroupRequest.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesAssignAppGroupRequest.swift
rename to Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupRequest.swift
diff --git a/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
new file mode 100644
index 0000000..ee7cacf
--- /dev/null
+++ b/Supersign/DeveloperServices/App Groups/DeveloperServicesAssignAppGroupsOperation.swift
@@ -0,0 +1,77 @@
+//
+// DeveloperServicesAssignAppGroupsOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 14/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct DeveloperServicesAssignAppGroupsOperation: DeveloperServicesOperation {
+
+ public let context: SigningContext
+ public let groupIDs: [DeveloperServicesAppGroup.GroupID]
+ public let appID: DeveloperServicesAppID
+ public init(context: SigningContext, groupIDs: [DeveloperServicesAppGroup.GroupID], appID: DeveloperServicesAppID) {
+ self.context = context
+ self.groupIDs = groupIDs
+ self.appID = appID
+ }
+
+ private func assignAppGroup(
+ _ group: DeveloperServicesAppGroup,
+ appID: DeveloperServicesAppID,
+ completion: @escaping (Result<DeveloperServicesAppGroup.GroupID, Swift.Error>) -> Void
+ ) {
+ let request = DeveloperServicesAssignAppGroupRequest(
+ platform: context.platform, teamID: context.team.id, appIDID: appID.id, groupID: group.id
+ )
+ context.client.send(request) { result in
+ guard result.get(withErrorHandler: completion) != nil else { return }
+ completion(.success(group.groupID))
+ }
+ }
+
+ private func addOrAssignAppGroup(
+ _ groupID: DeveloperServicesAppGroup.GroupID,
+ existingGroups: [DeveloperServicesAppGroup],
+ appID: DeveloperServicesAppID,
+ completion: @escaping (Result<DeveloperServicesAppGroup.GroupID, Swift.Error>) -> Void
+ ) {
+ let sanitized = ProvisioningIdentifiers.sanitize(groupID: groupID)
+ if let group = existingGroups.first(where: {
+ ProvisioningIdentifiers.sanitize(groupID: $0.groupID) == sanitized
+ }) {
+ assignAppGroup(group, appID: appID, completion: completion)
+ } else {
+ let groupID = ProvisioningIdentifiers.groupID(fromSanitized: sanitized)
+ let name = ProvisioningIdentifiers.groupName(fromSanitized: sanitized)
+ let request = DeveloperServicesAddAppGroupRequest(
+ platform: context.platform, teamID: context.team.id, name: name, groupID: groupID
+ )
+ context.client.send(request) { result in
+ guard let group = result.get(withErrorHandler: completion) else { return }
+ self.assignAppGroup(group, appID: appID, completion: completion)
+ }
+ }
+ }
+
+ public func perform(completion: @escaping (Result<[DeveloperServicesAppGroup.GroupID], Error>) -> Void) {
+ let request = DeveloperServicesListAppGroupsRequest(platform: context.platform, teamID: context.team.id)
+ context.client.send(request) { result in
+ guard let existingGroups = result.get(withErrorHandler: completion) else { return }
+
+ let grouper = RequestGrouper<DeveloperServicesAppGroup.GroupID, Error>()
+ for groupID in self.groupIDs {
+ grouper.add { completion in
+ self.addOrAssignAppGroup(
+ groupID, existingGroups: existingGroups, appID: self.appID, completion: completion
+ )
+ }
+ }
+ grouper.onComplete(completion)
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesListAppGroupsRequest.swift b/Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App Groups/DeveloperServicesListAppGroupsRequest.swift
rename to Supersign/DeveloperServices/App Groups/DeveloperServicesListAppGroupsRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAddAppIDRequest.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAddAppIDRequest.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
new file mode 100644
index 0000000..2cc1121
--- /dev/null
+++ b/Supersign/DeveloperServices/App IDs/DeveloperServicesAddAppOperation.swift
@@ -0,0 +1,185 @@
+//
+// DeveloperServicesAddAppOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 14/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct DeveloperServicesAddAppOperation: DeveloperServicesOperation {
+
+ public enum Error: LocalizedError {
+ case invalidApp(URL)
+
+ public var errorDescription: String? {
+ switch self {
+ case .invalidApp(let url):
+ return String.localizedStringWithFormat(
+ NSLocalizedString(
+ "app_id_request_helper.error.invalid_app", value: "Invalid app: %@", comment: ""
+ ), url.path
+ )
+ }
+ }
+ }
+
+ public let context: SigningContext
+ public let root: URL
+ public init(context: SigningContext, root: URL) {
+ self.context = context
+ self.root = root
+ }
+
+ /// Registers the app with the given entitlements
+ private func addOrFetchApp(
+ bundleID: String,
+ entitlements: Entitlements,
+ completion: @escaping (Result<DeveloperServicesAppID, Swift.Error>) -> Void
+ ) {
+ let request = DeveloperServicesListAppIDsRequest(platform: context.platform, teamID: context.team.id)
+ context.client.send(request) { result in
+ guard let appIDs = result.get(withErrorHandler: completion) else { return }
+ if let appID = appIDs.first(where: {
+ bundleID == ProvisioningIdentifiers.sanitize(identifier: $0.bundleID)
+ }) {
+ let request = DeveloperServicesUpdateAppIDRequest(
+ platform: self.context.platform,
+ teamID: self.context.team.id,
+ appIDID: appID.id,
+ entitlements: entitlements,
+ additionalFeatures: [],
+ isFree: self.context.team.isFree
+ )
+ self.context.client.send(request, completion: completion)
+ } else {
+ let newBundleID = ProvisioningIdentifiers.identifier(fromSanitized: bundleID)
+ let name = ProvisioningIdentifiers.appName(fromSanitized: bundleID)
+ let request = DeveloperServicesAddAppIDRequest(
+ platform: self.context.platform,
+ teamID: self.context.team.id,
+ bundleID: newBundleID,
+ appName: name,
+ entitlements: entitlements,
+ additionalFeatures: [],
+ isFree: self.context.team.isFree
+ )
+ self.context.client.send(request, completion: completion)
+ }
+ }
+ }
+
+ /// Registers the app and returns the resultant entitlements
+ private func addAppAndGetEntitlements(
+ app: URL,
+ // old bundle id, app id, ents
+ completion: @escaping (Result<(DeveloperServicesAppID, Entitlements), Swift.Error>) -> Void
+ ) {
+ let infoURL = app.appendingPathComponent("Info.plist")
+ guard let dict = NSDictionary(contentsOf: infoURL),
+ let bundleID = dict[kCFBundleIdentifierKey as String] as? String,
+ let executable = dict[kCFBundleExecutableKey as String] as? String else {
+ return completion(.failure(Error.invalidApp(app)))
+ }
+ let executableURL = app.appendingPathComponent(executable)
+
+ var entitlements: Entitlements
+ // if the executable doesn't already have entitlements, that's
+ // okay. We don't have to throw an error.
+ if let entitlementsData = context.signerImpl.analyze(executable: executableURL),
+ let decodedEntitlements = try? PropertyListDecoder().decode(Entitlements.self, from: entitlementsData) {
+ entitlements = decodedEntitlements
+
+ if context.team.isFree {
+ do {
+ // re-assign rather than using updateEntitlements since the latter will
+ // retain unrecognized entitlements
+ let filtered = try entitlements.entitlements().filter { type(of: $0).isFree }
+ entitlements = try Entitlements(entitlements: filtered)
+ } catch {
+ return completion(.failure(error))
+ }
+ }
+ } else {
+ do {
+ entitlements = try Entitlements(entitlements: [])
+ } catch {
+ return completion(.failure(error))
+ }
+ }
+
+ addOrFetchApp(bundleID: bundleID, entitlements: entitlements) { result in
+ guard let appID = result.get(withErrorHandler: completion) else { return }
+
+ do {
+ try entitlements.update(teamID: self.context.team.id, bundleID: appID.bundleID)
+ } catch {
+ return completion(.failure(error))
+ }
+
+ if var entitlementsArray = try? entitlements.entitlements(),
+ let groupsIdx = entitlementsArray.firstIndex(where: { $0 is AppGroupEntitlement }),
+ let groupsEntitlement = entitlementsArray[groupsIdx] as? AppGroupEntitlement {
+ let groups = groupsEntitlement.rawValue
+
+ DeveloperServicesAssignAppGroupsOperation(
+ context: self.context,
+ groupIDs: groups,
+ appID: appID
+ ).perform { result in
+ guard let newGroups = result.get(withErrorHandler: completion) else { return }
+ entitlementsArray[groupsIdx] = AppGroupEntitlement(rawValue: newGroups)
+
+ do {
+ try entitlements.setEntitlements(entitlementsArray)
+ } catch {
+ return completion(.failure(error))
+ }
+
+ completion(.success((appID, entitlements)))
+ }
+ } else {
+ completion(.success((appID, entitlements)))
+ }
+ }
+ }
+
+ /// Registers the app and creates a profile. Returns the resultant entitlements as well as
+ /// the profile (note that the profile does not necessarily include all of the entitlements
+ /// that the app has).
+ private func addApp(
+ _ app: URL,
+ completion: @escaping (Result<ProvisioningInfo, Swift.Error>) -> Void
+ ) {
+ addAppAndGetEntitlements(app: app) { result in
+ guard let (appID, entitlements) = result.get(withErrorHandler: completion) else { return }
+ DeveloperServicesFetchProfileOperation(context: self.context, appID: appID).perform { result in
+ guard let profile = result.get(withErrorHandler: completion) else { return }
+ guard let mobileprovision = profile.mobileprovision
+ else { return completion(.failure(Mobileprovision.Error.invalidProfile)) }
+ completion(.success(ProvisioningInfo(
+ newBundleID: appID.bundleID, entitlements: entitlements, mobileprovision: mobileprovision
+ )))
+ }
+ }
+ }
+
+ /// Registers the app + its extensions, returning the profile and entitlements of each
+ public func perform(completion: @escaping (Result<[URL: ProvisioningInfo], Swift.Error>) -> Void) {
+ var apps: [URL] = [root]
+ let plugins = root.appendingPathComponent("PlugIns")
+ if plugins.dirExists {
+ apps += plugins.implicitContents.filter { $0.pathExtension.lowercased() == "appex" }
+ }
+
+ let grouper = RequestGrouper<(URL, ProvisioningInfo), Swift.Error>()
+ for app in apps {
+ grouper.add { completion in
+ addApp(app) { completion($0.map { (app, $0) }) }
+ }
+ }
+ grouper.onComplete { completion($0.map(Dictionary.init(uniqueKeysWithValues:))) }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAppID.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAppID.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesAppID.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAppIDRequestApplier.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
similarity index 99%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAppIDRequestApplier.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
index 6edb688..651fe79 100644
--- a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesAppIDRequestApplier.swift
+++ b/Supersign/DeveloperServices/App IDs/DeveloperServicesAppIDRequestApplier.swift
@@ -9,6 +9,7 @@
import Foundation
enum DeveloperServicesAppIDRequestApplier {
+
static func apply(
entitlements: Entitlements, additionalFeatures: [DeveloperServicesFeature],
to dict: inout [String: Any], isFree: Bool
@@ -28,4 +29,5 @@ enum DeveloperServicesAppIDRequestApplier {
else { return }
dict.merge(features) { a, _ in a }
}
+
}
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesDeleteAppIDRequest.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesDeleteAppIDRequest.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesDeleteAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesListAppIDsRequest.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesListAppIDsRequest.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesListAppIDsRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesUpdateAppIDRequest.swift b/Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/DeveloperServicesUpdateAppIDRequest.swift
rename to Supersign/DeveloperServices/App IDs/DeveloperServicesUpdateAppIDRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift b/Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
rename to Supersign/DeveloperServices/App IDs/Entitlements/Entitlement+DeveloperServicesFeature.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift b/Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
rename to Supersign/DeveloperServices/App IDs/Entitlements/EntitlementWithTeamOrBundleID.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeature.swift b/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeature.swift
rename to Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeature.swift
diff --git a/Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeatureTypes.swift b/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
similarity index 95%
rename from Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeatureTypes.swift
rename to Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
index d8e0c76..c71a182 100644
--- a/Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeatureTypes.swift
+++ b/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatureTypes.swift
@@ -87,7 +87,7 @@ public struct DeveloperServicesAppGroupFeature: DeveloperServicesFeature, RawRep
}
extension AppGroupEntitlement: EntitlementWithFeature {
func typedFeature() -> DeveloperServicesAppGroupFeature {
- return .init(rawValue: !rawValue.isEmpty)
+ .init(rawValue: !rawValue.isEmpty)
}
}
@@ -104,6 +104,11 @@ public struct DeveloperServicesAssociatedDomainsFeature: DeveloperServicesFeatur
public let rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
}
+extension AssociatedDomainsEntitlement: EntitlementWithFeature {
+ func typedFeature() -> DeveloperServicesAssociatedDomainsFeature {
+ .init(rawValue: true)
+ }
+}
public struct DeveloperServicesClassKitFeature: DeveloperServicesFeature, RawRepresentable {
public static let identifier = "PKTJAN2017"
@@ -224,6 +229,11 @@ public struct DeveloperServicesPushNotificationFeature: DeveloperServicesFeature
public let rawValue: Bool
public init(rawValue: Bool) { self.rawValue = rawValue }
}
+extension APSEnvironmentEntitlement: EntitlementWithFeature {
+ func typedFeature() -> DeveloperServicesPushNotificationFeature {
+ .init(rawValue: true)
+ }
+}
public struct DeveloperServicesSiriKitFeature: DeveloperServicesFeature, RawRepresentable {
public static let identifier = "SI015DKUHP"
diff --git a/Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeatures.swift b/Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/App IDs/Features/DeveloperServicesFeatures.swift
rename to Supersign/DeveloperServices/App IDs/Features/DeveloperServicesFeatures.swift
diff --git a/Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesCSRResponse.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesCSRResponse.swift
rename to Supersign/DeveloperServices/Certificates/DeveloperServicesCSRResponse.swift
diff --git a/Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesCertificate.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesCertificate.swift
rename to Supersign/DeveloperServices/Certificates/DeveloperServicesCertificate.swift
diff --git a/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
new file mode 100644
index 0000000..a16acb7
--- /dev/null
+++ b/Supersign/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
@@ -0,0 +1,116 @@
+//
+// DeveloperServicesFetchCertificateOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 13/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct DeveloperServicesFetchCertificateOperation: DeveloperServicesOperation {
+
+ public enum Error: LocalizedError {
+ case csrFailed
+
+ public var errorDescription: String? {
+ switch self {
+ case .csrFailed:
+ return NSLocalizedString(
+ "certificate_request_helper.error.csr_failed", value: "CSR request failed", comment: ""
+ )
+ }
+ }
+ }
+
+ public let context: SigningContext
+ public init(context: SigningContext) {
+ self.context = context
+ }
+
+ private func createCertificate(
+ completion: @escaping (Result<SigningInfo, Swift.Error>) -> Void
+ ) {
+ let csr: CSR
+ let privateKey: PrivateKey
+ do {
+ let keypair = try Keypair()
+ csr = try keypair.generateCSR()
+ privateKey = try keypair.privateKey()
+ } catch {
+ return completion(.failure(error))
+ }
+
+ let request = DeveloperServicesSubmitCSRRequest(
+ platform: context.platform,
+ teamID: context.team.id,
+ csr: csr,
+ machineName: context.deviceName,
+ machineID: context.udid
+ )
+ context.client.send(request) { result in
+ guard let partialCert = result.get(withErrorHandler: completion) else { return }
+ let serialNumber = partialCert.serialNumber
+
+ let request = DeveloperServicesListCertificatesRequest(
+ platform: self.context.platform,
+ teamID: self.context.team.id
+ )
+ self.context.client.send(request) { result in
+ guard let certificates = result.get(withErrorHandler: completion) else { return }
+ guard let fullCert = certificates.first(where: { $0.serialNumber == serialNumber })
+ else { return completion(.failure(Error.csrFailed)) }
+ completion(.success(.init(privateKey: privateKey, certificate: fullCert.content)))
+ }
+ }
+ }
+
+ private func createAndSaveCertificate(
+ completion: @escaping (Result<SigningInfo, Swift.Error>) -> Void
+ ) {
+ createCertificate { result in
+ guard let value = result.get(withErrorHandler: completion) else { return }
+ SigningKeychain[self.context.team.id] = value
+ completion(.success(value))
+ }
+ }
+
+ private func revokeCreateSaveCertificate(
+ certificate: DeveloperServicesCertificate,
+ completion: @escaping (Result<SigningInfo, Swift.Error>) -> Void
+ ) {
+ let request = DeveloperServicesRevokeCertificateRequest(
+ platform: context.platform,
+ teamID: context.team.id,
+ serialNumber: certificate.serialNumber
+ )
+ context.client.send(request) { result in
+ guard result.get(withErrorHandler: completion) != nil else { return }
+ self.createAndSaveCertificate(completion: completion)
+ }
+ }
+
+ public func perform(completion: @escaping (Result<SigningInfo, Swift.Error>) -> Void) {
+ let request = DeveloperServicesListCertificatesRequest(
+ platform: context.platform, teamID: context.team.id
+ )
+ context.client.send(request) { result in
+ guard let certificates = result.get(withErrorHandler: completion) else { return }
+
+ guard let certificate = certificates.first(where: { $0.machineID == self.context.udid }) else {
+ return self.createAndSaveCertificate(completion: completion)
+ }
+
+ guard let signingInfo = SigningKeychain[self.context.team.id],
+ let serialNumber = try? signingInfo.certificate.serialNumber(),
+ certificate.serialNumber.rawValue == serialNumber,
+ certificate.expiry > Date()
+ else { return self.revokeCreateSaveCertificate(
+ certificate: certificate, completion: completion
+ ) }
+
+ completion(.success(signingInfo))
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesListCertificatesRequest.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesListCertificatesRequest.swift
rename to Supersign/DeveloperServices/Certificates/DeveloperServicesListCertificatesRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesRevokeCertificateRequest.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesRevokeCertificateRequest.swift
rename to Supersign/DeveloperServices/Certificates/DeveloperServicesRevokeCertificateRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesSubmitCSRRequest.swift b/Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Certificates/DeveloperServicesSubmitCSRRequest.swift
rename to Supersign/DeveloperServices/Certificates/DeveloperServicesSubmitCSRRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Developer/DeveloperServicesViewDeveloperRequest.swift b/Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Developer/DeveloperServicesViewDeveloperRequest.swift
rename to Supersign/DeveloperServices/Developer/DeveloperServicesViewDeveloperRequest.swift
diff --git a/Supersign/DeveloperServices/DeveloperServicesOperation.swift b/Supersign/DeveloperServices/DeveloperServicesOperation.swift
new file mode 100644
index 0000000..e091492
--- /dev/null
+++ b/Supersign/DeveloperServices/DeveloperServicesOperation.swift
@@ -0,0 +1,17 @@
+//
+// DeveloperServicesOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 13/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public protocol DeveloperServicesOperation {
+ associatedtype Response
+
+ var context: SigningContext { get }
+
+ func perform(completion: @escaping (Result<Response, Error>) -> Void)
+}
diff --git a/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift b/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
index e202b30..f815eae 100644
--- a/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
+++ b/Supersign/DeveloperServices/DeveloperServicesPlatformRequest.swift
@@ -26,6 +26,16 @@ public enum DeveloperServicesPlatform: String, Decodable {
case .tvOS: return "tvOS"
}
}
+
+ public static let current: DeveloperServicesPlatform = {
+ #if os(tvOS)
+ return .tvOS
+ #elseif os(watchOS)
+ return .watchOS
+ #else
+ return .iOS
+ #endif
+ }()
}
protocol DeveloperServicesPlatformRequest: DeveloperServicesRequest {
diff --git a/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift b/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
new file mode 100644
index 0000000..5e91dc8
--- /dev/null
+++ b/Supersign/DeveloperServices/DeveloperServicesProvisioningOperation.swift
@@ -0,0 +1,44 @@
+//
+// DeveloperServicesProvisioningOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 12/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct ProvisioningInfo {
+ public let newBundleID: String
+ public let entitlements: Entitlements
+ public let mobileprovision: Mobileprovision
+}
+
+public struct DeveloperServicesProvisioningOperation: DeveloperServicesOperation {
+
+ public struct Response {
+ public let signingInfo: SigningInfo
+ public let provisioningDict: [URL: ProvisioningInfo]
+ }
+
+ public let context: SigningContext
+ public let app: URL
+ public init(context: SigningContext, app: URL) {
+ self.context = context
+ self.app = app
+ }
+
+ public func perform(completion: @escaping (Result<Response, Error>) -> Void) {
+ DeveloperServicesFetchDeviceOperation(context: context).perform { result in
+ guard result.get(withErrorHandler: completion) != nil else { return }
+ DeveloperServicesFetchCertificateOperation(context: self.context).perform { result in
+ guard let signingInfo = result.get(withErrorHandler: completion) else { return }
+ DeveloperServicesAddAppOperation(context: self.context, root: self.app).perform { result in
+ guard let provisioningDict = result.get(withErrorHandler: completion) else { return }
+ completion(.success(.init(signingInfo: signingInfo, provisioningDict: provisioningDict)))
+ }
+ }
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/Devices/DeveloperServicesAddDeviceRequest.swift b/Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Devices/DeveloperServicesAddDeviceRequest.swift
rename to Supersign/DeveloperServices/Devices/DeveloperServicesAddDeviceRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Devices/DeveloperServicesDevice.swift b/Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Devices/DeveloperServicesDevice.swift
rename to Supersign/DeveloperServices/Devices/DeveloperServicesDevice.swift
diff --git a/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift b/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift
new file mode 100644
index 0000000..00e48bd
--- /dev/null
+++ b/Supersign/DeveloperServices/Devices/DeveloperServicesFetchDeviceOperation.swift
@@ -0,0 +1,36 @@
+//
+// DeveloperServicesFetchDeviceOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 13/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct DeveloperServicesFetchDeviceOperation: DeveloperServicesOperation {
+
+ public let context: SigningContext
+ public init(context: SigningContext) {
+ self.context = context
+ }
+
+ public func perform(completion: @escaping (Result<DeveloperServicesDevice, Error>) -> Void) {
+ let request = DeveloperServicesListDevicesRequest(platform: context.platform, teamID: context.team.id)
+ context.client.send(request) { result in
+ guard let devices = result.get(withErrorHandler: completion) else { return }
+ if let device = devices.first(where: { $0.udid == self.context.udid }) {
+ return completion(.success(device))
+ }
+
+ let addRequest = DeveloperServicesAddDeviceRequest(
+ platform: self.context.platform,
+ teamID: self.context.team.id,
+ udid: self.context.udid,
+ name: self.context.deviceName
+ )
+ self.context.client.send(addRequest, completion: completion)
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/Devices/DeveloperServicesListDevicesRequest.swift b/Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Devices/DeveloperServicesListDevicesRequest.swift
rename to Supersign/DeveloperServices/Devices/DeveloperServicesListDevicesRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesDeleteProfileRequest.swift b/Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesDeleteProfileRequest.swift
rename to Supersign/DeveloperServices/Profiles/DeveloperServicesDeleteProfileRequest.swift
diff --git a/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift b/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
new file mode 100644
index 0000000..eb58ad3
--- /dev/null
+++ b/Supersign/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
@@ -0,0 +1,48 @@
+//
+// DeveloperServicesFetchProfileOperation.swift
+// Supersign
+//
+// Created by Kabir Oberai on 13/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct DeveloperServicesFetchProfileOperation: DeveloperServicesOperation {
+
+ public let context: SigningContext
+ public let appID: DeveloperServicesAppID
+ public init(context: SigningContext, appID: DeveloperServicesAppID) {
+ self.context = context
+ self.appID = appID
+ }
+
+ private func createProfile(
+ appID: DeveloperServicesAppID,
+ completion: @escaping (Result<DeveloperServicesProfile, Swift.Error>) -> Void
+ ) {
+ let request = DeveloperServicesGetProfileRequest(
+ platform: context.platform, teamID: context.team.id, appIDID: appID.id
+ )
+ context.client.send(request, completion: completion)
+ }
+
+ public func perform(completion: @escaping (Result<DeveloperServicesProfile, Error>) -> Void) {
+ let request = DeveloperServicesListProfilesRequest(platform: context.platform, teamID: context.team.id)
+ context.client.send(request) { result in
+ guard let profiles = result.get(withErrorHandler: completion) else { return }
+ if let profile = profiles.first(where: { $0.appID.id == self.appID.id }) {
+ let request = DeveloperServicesDeleteProfileRequest(
+ platform: self.context.platform, teamID: self.context.team.id, profileID: profile.id
+ )
+ self.context.client.send(request) { result in
+ guard result.get(withErrorHandler: completion) != nil else { return }
+ self.createProfile(appID: self.appID, completion: completion)
+ }
+ } else {
+ self.createProfile(appID: self.appID, completion: completion)
+ }
+ }
+ }
+
+}
diff --git a/Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesGetProfileRequest.swift b/Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesGetProfileRequest.swift
rename to Supersign/DeveloperServices/Profiles/DeveloperServicesGetProfileRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesListProfilesRequest.swift b/Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesListProfilesRequest.swift
rename to Supersign/DeveloperServices/Profiles/DeveloperServicesListProfilesRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesProfile.swift b/Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Profiles/DeveloperServicesProfile.swift
rename to Supersign/DeveloperServices/Profiles/DeveloperServicesProfile.swift
diff --git a/Supersign/DeveloperServices/Requests/Teams/DeveloperServicesListTeamsRequest.swift b/Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Teams/DeveloperServicesListTeamsRequest.swift
rename to Supersign/DeveloperServices/Teams/DeveloperServicesListTeamsRequest.swift
diff --git a/Supersign/DeveloperServices/Requests/Teams/DeveloperServicesTeam.swift b/Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift
similarity index 100%
rename from Supersign/DeveloperServices/Requests/Teams/DeveloperServicesTeam.swift
rename to Supersign/DeveloperServices/Teams/DeveloperServicesTeam.swift
diff --git a/Supersign/Model/Entitlements/EntitlementTypes.swift b/Supersign/Model/Entitlements/EntitlementTypes.swift
index 06e1a6d..4d93743 100644
--- a/Supersign/Model/Entitlements/EntitlementTypes.swift
+++ b/Supersign/Model/Entitlements/EntitlementTypes.swift
@@ -17,6 +17,8 @@ extension EntitlementContainer {
TeamIdentifierEntitlement.self,
KeychainAccessGroupsEntitlement.self,
GetTaskAllowEntitlement.self,
+ AssociatedDomainsEntitlement.self,
+ APSEnvironmentEntitlement.self,
AppGroupEntitlement.self,
NetworkExtensionEntitlement.self,
MultipathEntitlement.self,
@@ -29,8 +31,6 @@ extension EntitlementContainer {
]
}
-// MARK: - Entitlements without Features
-
public struct ApplicationIdentifierEntitlement: Entitlement, RawRepresentable {
public static let identifier = "application-identifier"
public static let isFree = true
@@ -89,6 +89,30 @@ public struct GetTaskAllowEntitlement: Entitlement, RawRepresentable {
public init(rawValue: Bool) { self.rawValue = rawValue }
}
+public struct AssociatedDomainsEntitlement: Entitlement, RawRepresentable {
+ public static let identifier = "com.apple.developer.associated-domains"
+ public static let isFree = false
+
+ public var rawValue: [String]
+ public init(rawValue: [String]) { self.rawValue = rawValue }
+
+ public init(from decoder: Decoder) throws {
+ rawValue = try decoder.singleValueContainer().decode([String].self)
+ }
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(rawValue)
+ }
+}
+
+public enum APSEnvironmentEntitlement: String, Entitlement {
+ public static let identifier = "aps-environment"
+ public static let isFree = false
+
+ case development
+ case production
+}
+
public enum DataProtectionEntitlement: String, Entitlement {
public static let identifier = "com.apple.developer.default-data-protection"
public static let isFree = true
diff --git a/Supersign/Signer/Signer.swift b/Supersign/Signer/Signer.swift
index 616a3ee..3cf45ea 100644
--- a/Supersign/Signer/Signer.swift
+++ b/Supersign/Signer/Signer.swift
@@ -36,11 +36,8 @@ public struct Signer {
}
public let context: SigningContext
- public let provisioner: Provisioner
-
public init(context: SigningContext) {
self.context = context
- self.provisioner = Provisioner(context: context)
}
private func sign(
@@ -48,16 +45,16 @@ public struct Signer {
signingInfo: SigningInfo,
provisioningDict: [URL: ProvisioningInfo],
progress: @escaping (Double) -> Void,
- completion: @escaping (Result<Void, Swift.Error>) -> Void
+ completion: @escaping (Result<(), Swift.Error>) -> Void
) {
for (url, info) in provisioningDict {
let infoPlist = url.appendingPathComponent("Info.plist")
guard let dict = NSMutableDictionary(contentsOf: infoPlist) else {
- return completion(.failure(Error.errorReading("Info.plist")))
+ return completion(.failure(Error.errorReading(infoPlist.lastPathComponent)))
}
dict[kCFBundleIdentifierKey as String] = info.newBundleID
guard dict.write(to: infoPlist, atomically: true) else {
- return completion(.failure(Error.errorWriting("Info.plist")))
+ return completion(.failure(Error.errorWriting(infoPlist.lastPathComponent)))
}
do {
@@ -72,7 +69,6 @@ public struct Signer {
}
let entitlements = provisioningDict.mapValues { $0.entitlements }
-
context.signerImpl.sign(
app: app,
certificate: signingInfo.certificate,
@@ -86,14 +82,14 @@ public struct Signer {
public func sign(
app: URL,
progress: @escaping (Double) -> Void,
- completion: @escaping (Result<Void, Swift.Error>) -> Void
+ completion: @escaping (Result<(), Swift.Error>) -> Void
) {
- provisioner.provision(app: app) { r in
- guard let (signingInfo, provisioningDict) = r.get(withErrorHandler: completion) else { return }
+ DeveloperServicesProvisioningOperation(context: context, app: app).perform { result in
+ guard let response = result.get(withErrorHandler: completion) else { return }
self.sign(
app: app,
- signingInfo: signingInfo,
- provisioningDict: provisioningDict,
+ signingInfo: response.signingInfo,
+ provisioningDict: response.provisioningDict,
progress: progress,
completion: completion
)
diff --git a/Supersign/Signer/SigningContext.swift b/Supersign/Signer/SigningContext.swift
index 32e6f24..7a12220 100644
--- a/Supersign/Signer/SigningContext.swift
+++ b/Supersign/Signer/SigningContext.swift
@@ -8,10 +8,6 @@
import Foundation
-#if canImport(UIKit)
-import UIKit
-#endif
-
public struct SigningContext {
public let udid: String
@@ -24,7 +20,7 @@ public struct SigningContext {
udid: String,
team: DeveloperServicesTeam,
signerImpl: SignerImpl? = nil,
- platform: DeveloperServicesPlatform = .iOS,
+ platform: DeveloperServicesPlatform = .current,
client: DeveloperServicesClient = .shared
) throws {
self.udid = udid
@@ -34,6 +30,12 @@ public struct SigningContext {
self.client = client
}
+}
+
+#if canImport(UIKit)
+import UIKit
+#endif
+extension SigningContext {
public var deviceName: String {
#if targetEnvironment(simulator)
return "Simulator"
@@ -45,5 +47,4 @@ public struct SigningContext {
return "Supercharge Client"
#endif
}
-
}
diff --git a/Supersign/SignerImpl/SignerImpl.swift b/Supersign/SignerImpl/SignerImpl.swift
index 6e71dc7..1a00a75 100644
--- a/Supersign/SignerImpl/SignerImpl.swift
+++ b/Supersign/SignerImpl/SignerImpl.swift
@@ -21,8 +21,7 @@ public struct SignerImpl {
public enum Error: LocalizedError {
case notFound
- case signer(String)
- case unknown
+ case signer(String?)
public var errorDescription: String? {
switch self {
@@ -30,9 +29,9 @@ public struct SignerImpl {
return NSLocalizedString(
"signer_impl.error.not_found", value: "No signer implementation found", comment: ""
)
- case .signer(let error):
+ case .signer(let error?):
return error
- case .unknown:
+ case .signer(nil):
return NSLocalizedString(
"signer_impl.error.unknown", value: "An unknown signing error occurred", comment: ""
)
@@ -85,7 +84,9 @@ public struct SignerImpl {
let privBound = privBytes.bindMemory(to: Int8.self)
var exception: UnsafeMutablePointer<Int8>?
- let ret = sign(
+ defer { exception.map { free($0) } }
+
+ guard sign(
app.path,
certBound.baseAddress,
certBound.count,
@@ -95,16 +96,9 @@ public struct SignerImpl {
ents.count,
progress,
&exception
- )
- guard ret == 0 else {
- defer { free(exception) }
- throw exception
- .map { UnsafePointer($0) }
- .map(String.init(cString:))
- .map(Error.signer)
- ?? .unknown
+ ) == 0 else {
+ throw Error.signer(exception.map { String(cString: $0) })
}
- if let exception = exception { free(exception) }
}
}
}
@@ -116,7 +110,7 @@ public struct SignerImpl {
privateKey: PrivateKey,
entitlementMapping: [URL: Entitlements],
progress: @escaping (Double) -> Void,
- completion: @escaping (Result<Void, Swift.Error>) -> Void
+ completion: @escaping (Result<(), Swift.Error>) -> Void
) {
Self.signingQueue.async {
do {
diff --git a/Supersign/Utilities/ProvisioningIdentifiers.swift b/Supersign/Utilities/ProvisioningIdentifiers.swift
new file mode 100644
index 0000000..5ec97fa
--- /dev/null
+++ b/Supersign/Utilities/ProvisioningIdentifiers.swift
@@ -0,0 +1,50 @@
+//
+// ProvisioningIdentifiers.swift
+// Supersign
+//
+// Created by Kabir Oberai on 14/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+enum ProvisioningIdentifiers {}
+
+extension ProvisioningIdentifiers {
+
+ static let idPrefix = "SC-"
+ static let groupPrefix = "group."
+ static let namePrefix = "Supercharge "
+
+ static func sanitize(identifier: String) -> String {
+ guard identifier.hasPrefix(Self.idPrefix) else { return identifier }
+ return identifier.split(separator: ".").dropFirst().joined(separator: ".")
+ }
+
+ static func identifier(fromSanitized sanitized: String) -> String {
+ "\(Self.idPrefix)\(UUID().uuidString.split(separator: "-")[0]).\(sanitized)"
+ }
+
+ static func safeify(identifier: String) -> String {
+ identifier.replacingOccurrences(of: ".", with: " ")
+ }
+
+ static func sanitize(groupID: DeveloperServicesAppGroup.GroupID) -> String {
+ var id = groupID.rawValue
+ if id.hasPrefix(Self.groupPrefix) { id.removeFirst(Self.groupPrefix.count) }
+ return sanitize(identifier: id)
+ }
+
+ static func groupID(fromSanitized sanitized: String) -> DeveloperServicesAppGroup.GroupID {
+ .init(rawValue: "\(Self.groupPrefix)\(identifier(fromSanitized: sanitized))")
+ }
+
+ static func groupName(fromSanitized sanitized: String) -> String {
+ "\(Self.namePrefix)group \(safeify(identifier: sanitized))"
+ }
+
+ static func appName(fromSanitized sanitized: String) -> String {
+ "\(Self.namePrefix)\(safeify(identifier: sanitized))"
+ }
+
+}
diff --git a/Supersign/Utilities/RequestGrouper.swift b/Supersign/Utilities/RequestGrouper.swift
new file mode 100644
index 0000000..0f00f8e
--- /dev/null
+++ b/Supersign/Utilities/RequestGrouper.swift
@@ -0,0 +1,54 @@
+//
+// RequestGrouper.swift
+// Supersign
+//
+// Created by Kabir Oberai on 14/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+public struct ErrorList<E: Error>: LocalizedError {
+
+ public let errors: [E]
+ public init(_ errors: [E]) {
+ self.errors = errors
+ }
+
+ public var errorDescription: String? {
+ return errors.map { $0.legibleLocalizedDescription }.joined(separator: ", ")
+ }
+
+}
+
+class RequestGrouper<T, E: Error> {
+
+ private let waitQueue = DispatchQueue(label: "request-wait-queue", attributes: .concurrent)
+ private let group = DispatchGroup()
+
+ private var values: [T] = []
+ private var errors: [E] = []
+
+ func add(request: (_ completion: @escaping (Result<T, E>) -> Void) -> Void) {
+ group.enter()
+ request { result in
+ defer { self.group.leave() }
+ switch result {
+ case .failure(let error): self.errors.append(error)
+ case .success(let value): self.values.append(value)
+ }
+ }
+ }
+
+ func onComplete(_ completion: @escaping (Result<[T], Error>) -> Void) {
+ waitQueue.async {
+ self.group.wait()
+ switch self.errors.count {
+ case 0: completion(.success(self.values))
+ case 1: completion(.failure(self.errors[0]))
+ default: completion(.failure(ErrorList(self.errors)))
+ }
+ }
+ }
+
+}
diff --git a/SupersignTests/Tests/SupersignDeveloperServicesTests.swift b/SupersignTests/Tests/SupersignDeveloperServicesTests.swift
new file mode 100644
index 0000000..122efb4
--- /dev/null
+++ b/SupersignTests/Tests/SupersignDeveloperServicesTests.swift
@@ -0,0 +1,45 @@
+//
+// SupersignDeveloperServicesTests.swift
+// SupersignTests
+//
+// Created by Kabir Oberai on 30/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import XCTest
+import Supersign
+
+class SupersignDeveloperServicesTests: XCTestCase {
+
+ var client: DeveloperServicesClient!
+
+ override func setUp() {
+ super.setUp()
+ client = .test()
+ }
+
+ override func tearDown() {
+ super.tearDown()
+ client = nil
+ }
+
+ // integration test for provisioning
+ func testProvisioningIntegration() throws {
+
+ }
+
+ func testListTeams() throws {
+ let listTeams = DeveloperServicesListTeamsRequest()
+ let teams = try XCTTry(client.sendTest(listTeams))
+ XCTAssertFalse(teams.isEmpty, "No teams found")
+
+ let team = try XCTUnwrap(
+ teams.first { $0.id.rawValue == Config.current.preferredTeam },
+ "Could not find preferred team"
+ )
+
+ XCTAssertEqual(team.status, "active", "Expected team status active. Got: \(team.status)")
+ XCTAssert(team.memberships.contains { $0.platform == .iOS }, "Team does not have iOS membership")
+ }
+
+}
diff --git a/SupersignTests/Tests/SupersignSigningTests.swift b/SupersignTests/Tests/SupersignSigningTests.swift
new file mode 100644
index 0000000..8e4ba76
--- /dev/null
+++ b/SupersignTests/Tests/SupersignSigningTests.swift
@@ -0,0 +1,80 @@
+//
+// SupersignSigningTests.swift
+// SupersignTests
+//
+// Created by Kabir Oberai on 06/11/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import XCTest
+import Supersign
+
+class SupersignSigningTests: XCTestCase {
+
+ var client: DeveloperServicesClient!
+ var signerImpl: SignerImpl!
+ var app: URL!
+
+ // swiftlint:disable force_try
+ override func setUp() {
+ super.setUp()
+ client = .test()
+ signerImpl = try! SignerImpl.first()
+
+ let bundle = Bundle(for: Self.self)
+ let source = try! XCTUnwrap(bundle.url(forResource: "test", withExtension: "app"))
+ let tmp = FileManager.default.temporaryDirectory
+ app = tmp.appendingPathComponent(source.lastPathComponent)
+ if FileManager.default.fileExists(atPath: app.path) {
+ try! FileManager.default.removeItem(at: app)
+ }
+ try! FileManager.default.copyItem(at: source, to: app)
+ }
+
+ override func tearDown() {
+ super.tearDown()
+ client = nil
+ signerImpl = nil
+ try! FileManager.default.removeItem(at: app)
+ app = nil
+ }
+ // swiftlint:enable force_try
+
+ // integration test for signing
+ func testSigningIntegration() throws {
+ let listTeams = DeveloperServicesListTeamsRequest()
+ let teams = try XCTTry(client.sendTest(listTeams))
+ let team = teams.first { $0.status == "active" && $0.memberships.contains { $0.platform == .iOS } }!
+
+ let context = try XCTTry(SigningContext(
+ udid: "00008030-001409AA0298802E", team: team, signerImpl: signerImpl, client: client
+ ))
+ let signer = Signer(context: context)
+
+ let signingWaiter = ResultWaiter<()>(description: "Failed to sign app")
+ signer.sign(app: app, progress: { _ in }, completion: signingWaiter.completion)
+ try signingWaiter.wait(timeout: 10000)
+
+ // TODO: Ensure entitlements are correct in new app, also codesign -vvvv
+ }
+
+ func testAnalyze() throws {
+ let infoURL = app.appendingPathComponent("Info.plist")
+ let info = try XCTUnwrap(NSDictionary(contentsOf: infoURL))
+ let execName = try XCTUnwrap(info[kCFBundleExecutableKey as String] as? String)
+ let exec = app.appendingPathComponent(execName)
+
+ let ents = try XCTUnwrap(signerImpl.analyze(executable: exec))
+ let entsPlist = try XCTTry(PropertyListDecoder().decode(Entitlements.self, from: ents))
+
+ XCTAssertFalse(try XCTTry(entsPlist.entitlements().isEmpty))
+ }
+
+ func testSign() throws {
+ let signingWaiter = ResultWaiter<()>(description: "Failed to sign app")
+ // TODO: Get cert, key, ents from fixtures
+// signerImpl.sign(app: app, certificate: <#T##Certificate#>, privateKey: <#T##PrivateKey#>, entitlementMapping: <#T##[URL : Entitlements]#>, progress: { _ in }, completion: signingWaiter.completion)
+// try signingWaiter.wait(timeout: 10000)
+ }
+
+}
diff --git a/SupersignTests/Utilities/Config.swift b/SupersignTests/Utilities/Config.swift
new file mode 100644
index 0000000..8397aa8
--- /dev/null
+++ b/SupersignTests/Utilities/Config.swift
@@ -0,0 +1,30 @@
+//
+// Config.swift
+// SupersignTests
+//
+// Created by Kabir Oberai on 05/11/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+
+struct Config: Decodable {
+ struct AppleID: Decodable {
+ let username: String
+ let password: String
+ /// for non-login tests, just provide a token already so that the 2fa prompt isn't invoked
+ let token: String
+ }
+ let appleID: AppleID
+
+ let preferredTeam: String
+
+ static let current: Config = {
+ class ConfigDummy {}
+ let url = Bundle(for: ConfigDummy.self).url(forResource: "config", withExtension: "json")!
+ // swiftlint:disable:next force_try
+ let data = try! Data(contentsOf: url)
+ // swiftlint:disable:next force_try
+ return try! JSONDecoder().decode(Config.self, from: data)
+ }()
+}
diff --git a/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift b/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift
new file mode 100644
index 0000000..d50f1fb
--- /dev/null
+++ b/SupersignTests/Utilities/DeveloperServicesClient+Testing.swift
@@ -0,0 +1,34 @@
+//
+// DeveloperServicesTestClient.swift
+// SupersignTests
+//
+// Created by Kabir Oberai on 06/11/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+import XCTest
+import Supersign
+
+struct CredentialsManagerMock: DeveloperServicesCredentialsManagerProtocol {
+ // store login in memory
+ public var token: DeveloperServicesCredentialsToken?
+}
+
+extension DeveloperServicesClient {
+
+ static func test() -> DeveloperServicesClient {
+ let client = DeveloperServicesClient(credentialsManager: CredentialsManagerMock())
+ client.credentialsManager.token = .init(rawValue: Config.current.appleID.token)
+ return client
+ }
+
+ func sendTest<T: DeveloperServicesRequest>(
+ _ request: T, file: StaticString = #file, line: UInt = #line
+ ) throws -> T.Value {
+ let waiter = ResultWaiter<T.Value>(description: "Could not finish request: \(request.action)")
+ send(request, completion: waiter.completion)
+ return try waiter.wait(timeout: 10, file: file, line: line)
+ }
+
+}
diff --git a/SupersignTests/Utilities/ResultWaiter.swift b/SupersignTests/Utilities/ResultWaiter.swift
new file mode 100644
index 0000000..3b78b2c
--- /dev/null
+++ b/SupersignTests/Utilities/ResultWaiter.swift
@@ -0,0 +1,36 @@
+//
+// ResultWaiter.swift
+// SupersignTests
+//
+// Created by Kabir Oberai on 30/10/19.
+// Copyright © 2019 Kabir Oberai. All rights reserved.
+//
+
+import Foundation
+import XCTest
+
+class ResultWaiter<T> {
+
+ private let waiter = XCTWaiter()
+ private let expectation: XCTestExpectation
+ private(set) var completion: ((Result<T, Error>) -> Void)
+ private var result: Result<T, Error>?
+
+ init(description: String) {
+ let expectation = XCTestExpectation(description: description)
+ self.expectation = expectation
+ // this stub is needed to allow the initialization phase to finish,
+ // since we can't access self.result until that's done
+ self.completion = { _ in }
+ self.completion = { result in
+ self.result = result
+ expectation.fulfill()
+ }
+ }
+
+ func wait(timeout: TimeInterval, file: StaticString = #file, line: UInt = #line) throws -> T {
+ waiter.wait(for: [expectation], timeout: timeout)
+ return try XCTUnwrap(result, file: file, line: line).get()
+ }
+
+}
diff --git a/SupersignTests/config/config-template.json b/SupersignTests/config/config-template.json
new file mode 100644
index 0000000..91a4b85
--- /dev/null
+++ b/SupersignTests/config/config-template.json
@@ -0,0 +1,8 @@
+{
+ "appleID": {
+ "username": "",
+ "password": "",
+ "token": ""
+ },
+ "preferredTeam": ""
+}