import Foundation import DeveloperAPI import Dependencies import XKit import XCLIUtils import Subprocess /// App Store distribution signing for `xtool dev build --distribution app-store`. /// /// Inputs come from the release-pipeline env contract: /// `XTOOL_DIST_P12_PATH` + `XTOOL_DIST_P12_PASSWORD` (a pre-made Apple /// Distribution identity) and the App Store Connect API key (see /// `resolveASCKey()`). The distribution certificate is extracted from the /// P12 with `openssl`, an `IOS_APP_STORE` provisioning profile for the app's /// bundle id is fetched (or created) via the ASC API, embedded, and the app /// is signed with that identity and the profile's entitlements. enum DistributionSigning { struct Identity { var certificate: Certificate var privateKey: PrivateKey /// Files holding decrypted key material; deleted after signing. var tempDir: URL } static func resolveIdentity() async throws -> Identity { let env = ProcessInfo.processInfo.environment guard let p12Path = env["XTOOL_DIST_P12_PATH"], let password = env["XTOOL_DIST_P12_PASSWORD"] else { throw Console.Error(""" --distribution app-store requires XTOOL_DIST_P12_PATH and \ XTOOL_DIST_P12_PASSWORD (an Apple Distribution .p12). """) } return try await extractIdentity(p12Path: p12Path, password: password) } /// Extracts (cert DER, key PEM) from a PKCS12 using the `openssl` CLI. /// `openssl` is present on Linux builders and macOS; parsing PKCS12 in ///-process would need an OpenSSL binding xtool does not have. static func extractIdentity(p12Path: String, password: String) async throws -> Identity { let tempDir = FileManager.default.temporaryDirectory .appendingPathComponent("xtool-dist-\(UUID().uuidString)", isDirectory: true) try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: tempDir.path) func runOpenSSL(_ arguments: [String]) async throws { try await Subprocess.run( .name("openssl"), arguments: .init(arguments), output: .discarded, error: .discarded ).checkSuccess() } let certPEM = tempDir.appendingPathComponent("cert.pem") let keyPEM = tempDir.appendingPathComponent("key.pem") let certDER = tempDir.appendingPathComponent("cert.der") // OpenSSL 3 may need -legacy for PKCS12 files made by older tooling. func extract(_ base: [String]) async throws { do { try await runOpenSSL(base) } catch { try await runOpenSSL(base + ["-legacy"]) } } try await extract([ "pkcs12", "-in", p12Path, "-clcerts", "-nokeys", "-out", certPEM.path, "-passin", "pass:\(password)", ]) try await extract([ "pkcs12", "-in", p12Path, "-nocerts", "-nodes", "-out", keyPEM.path, "-passin", "pass:\(password)", ]) try await runOpenSSL(["x509", "-in", certPEM.path, "-outform", "DER", "-out", certDER.path]) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: keyPEM.path) let certificate = try Certificate(data: Data(contentsOf: certDER)) let privateKey = PrivateKey(data: try Data(contentsOf: keyPEM)) return Identity(certificate: certificate, privateKey: privateKey, tempDir: tempDir) } /// Signs `app` for App Store distribution in place. static func signAppStore(_ app: URL) async throws { let identity = try await resolveIdentity() defer { try? FileManager.default.removeItem(at: identity.tempDir) } let infoURL = app.appendingPathComponent("Info.plist") let infoData = try Data(contentsOf: infoURL) guard let info = try PropertyListSerialization.propertyList(from: infoData, format: nil) as? [String: Any], let bundleID = info["CFBundleIdentifier"] as? String else { throw Console.Error("Could not read CFBundleIdentifier from '\(infoURL.path)'") } let key = try resolveASCKey() let client = DeveloperAPIClient(auth: .appStoreConnect(key)) let profile = try await fetchOrCreateAppStoreProfile( client: client, bundleID: bundleID, certificate: identity.certificate ) let digest = try profile.digest() let embedded = app.appendingPathComponent("embedded.mobileprovision") try? FileManager.default.removeItem(at: embedded) try profile.data().write(to: embedded) @Dependency(\.signer) var signer let encoder = PropertyListEncoder() encoder.outputFormat = .xml try await signer.sign( app: app, identity: .real(identity.certificate, identity.privateKey), entitlementMapping: [app: try encoder.encode(digest.entitlements)], deep: true, progress: { _ in } ) } private static func fetchOrCreateAppStoreProfile( client: DeveloperAPIClient, bundleID: String, certificate: Certificate ) async throws -> Mobileprovision { let bundleIDs = try await client.bundleIdsGetCollection(query: .init( filter_lbrack_identifier_rbrack_: [bundleID] )).ok.body.json guard let bundleResource = bundleIDs.data.first(where: { $0.attributes?.identifier == bundleID }) else { throw Console.Error("No bundle id '\(bundleID)' registered in App Store Connect") } // Find the ASC resource for the P12's certificate (matched by serial). let certificates = try await DeveloperAPIPages { try await client.certificatesGetCollection().ok.body.json } next: { $0.links.next }.map(\.data).reduce(into: [], +=) guard let certResource = certificates.first(where: { $0.attributes?.serialNumber.map(certificate.hasSerialNumber) == true }) else { throw Console.Error("Distribution certificate from the P12 is not registered in App Store Connect") } // Reuse an active app-store profile for this bundle id when one exists. let profiles = try await DeveloperAPIPages { try await client.profilesGetCollection().ok.body.json } next: { $0.links.next }.map(\.data).reduce(into: [], +=) for profile in profiles { // The list response omits relationships unless included, so the // deterministic name we create with is the reliable reuse key. let isOurs = profile.attributes?.name == "xtool app-store \(bundleID)" let matchesBundle = profile.relationships?.bundleId?.data?.id == bundleResource.id guard profile.attributes?.profileType?.value1 == .iosAppStore, profile.attributes?.profileState?.value1 == .active, isOurs || matchesBundle, let content = profile.attributes?.profileContent, let data = Data(base64Encoded: content) else { continue } return try Mobileprovision(data: data) } let created = try await client.profilesCreateInstance(body: .json(.init( data: .init( _type: .profiles, attributes: .init( name: "xtool app-store \(bundleID)", profileType: .init(.iosAppStore) ), relationships: .init( bundleId: .init(data: .init(_type: .bundleIds, id: bundleResource.id)), certificates: .init(data: [.init(_type: .certificates, id: certResource.id)]) ) ) ))).created.body.json.data guard let content = created.attributes?.profileContent, let data = Data(base64Encoded: content) else { throw Console.Error("Created app-store profile had no profileContent") } return try Mobileprovision(data: data) } }