dev: add --distribution app-store distribution signing
- Commit
76d6681510cf24320b4b7f15ba00d5a5eaaa8c20- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-18 15:58 UTC (17 days ago)
- Parents
8c0deb2
Extracts the Apple Distribution identity from XTOOL_DIST_P12_PATH/PASSWORD via openssl, fetches or creates the IOS_APP_STORE profile for the app bundle id via the ASC API, embeds it, and signs with the profile entitlements. Verified: identity extraction succeeds with a test P12 and fails cleanly (missing env, or ASC unreachable) without leaking temp key files.
Diff
Sources/XToolSupport/DevCommand.swift
diff --git a/Sources/XToolSupport/DevCommand.swift b/Sources/XToolSupport/DevCommand.swiftindex 369bfa8..ee50444 100644--- a/Sources/XToolSupport/DevCommand.swift+++ b/Sources/XToolSupport/DevCommand.swift@@ -144,6 +144,18 @@ struct DevBuildCommand: AsyncParsableCommand { ) ) var triple: String? + @Option(+ help: ArgumentHelp(+ "Distribution channel for the built app",+ discussion: """+ 'app-store' signs the app with an Apple Distribution identity \+ (XTOOL_DIST_P12_PATH / XTOOL_DIST_P12_PASSWORD) and an \+ IOS_APP_STORE provisioning profile fetched via the App Store \+ Connect API. Combine with --ipa for an uploadable build.+ """+ )+ ) var distribution: Distribution?+ func run() async throws { let signingAuthToken: AuthToken? if sign {@@ -160,6 +172,13 @@ struct DevBuildCommand: AsyncParsableCommand { buildOptions: packOptions ).run() + if distribution == .appStore {+ guard signingAuthToken == nil else {+ throw Console.Error("--distribution app-store cannot be combined with --sign")+ }+ try await DistributionSigning.signAppStore(url)+ }+ if let signingAuthToken { let installDelegate = XToolInstallerDelegate() let installer = IntegratedInstaller(@@ -293,6 +312,11 @@ struct DevCommand: AsyncParsableCommand { extension BuildConfiguration: ExpressibleByArgument {} +enum Distribution: String, CaseIterable, ExpressibleByArgument, Sendable {+ case development+ case appStore = "app-store"+}+ #if os(macOS) import Subprocess
Sources/XToolSupport/DistributionSigning.swift
diff --git a/Sources/XToolSupport/DistributionSigning.swift b/Sources/XToolSupport/DistributionSigning.swiftnew file mode 100644index 0000000..a0efeeb--- /dev/null+++ b/Sources/XToolSupport/DistributionSigning.swift@@ -0,0 +1,171 @@+import Foundation+import DeveloperAPI+import XKit+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)++ let signer = try Signer.first()+ try await signer.sign(+ app: app,+ identity: .real(identity.certificate, identity.privateKey),+ entitlementMapping: [app: digest.entitlements],+ 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 {+ guard profile.attributes?.profileType?.value1 == .iosAppStore,+ profile.attributes?.profileState?.value1 == .active,+ profile.relationships?.bundleId?.data?.id == bundleResource.id,+ 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)+ }+}