certs: match certificates whose serial starts with 0 (#306)
- Commit
316a11e523b383b6acf740858e5768b1693946c3- Author
- Chintan Patel <[email protected]>
- When
- 2026-10-15 20:44 UTC (1 month ago)
- Parents
b50173f
## What does this PR do? Fixes #305 (thanks @0x53 for the detailed diagnosis). `Certificate.serialNumber()` stripped leading `0` *characters* from the hex string, so a serial like `0337…` became `337…` and never matched the `serialNumber` returned by the API. xtool then treated its stored certificate as missing: free teams are prompted to revoke a valid certificate on every run, and paid teams take the same path and try to create another certificate, which @McoreD confirmed fails with `409 … You already have a current Development certificate or a pending certificate request.` The character-level `drop` predates b6a40ca, which switched to fixed-width `%02hhX` formatting; since then it removes the significant zero of any first byte below `0x10`. swift-certificates already strips leading zero bytes (including DER sign padding) when parsing, so the `drop` isn't needed for padding. - `serialNumber()` now drops only leading zero *bytes*, matching the API and `openssl x509 -serial`. - The stored-certificate lookup uses a new `Certificate.hasSerialNumber(_:)`, which compares serials numerically (ignoring case and leading zeros), so it doesn't depend on Apple's exact formatting. - Profile creation no longer finds the signing certificate with `filter[serialNumber]`. The API lists serials with the leading zero (`0E41…`), but the filter only matches them without it (`E41…`), so once `serialNumber()` kept the zero the filter matched nothing and profile creation failed with a 409 ([details](https://github.com/xtool-org/xtool/pull/306#issuecomment-6181157860)). It now fetches all pages of certificates and matches them with `hasSerialNumber(_:)`. Fix by @McoreD, with pagination added so a certificate on a later page isn't missed. ## How was it tested? - Added `Tests/XToolTests/CertificateTests.swift`: builds a cert with the serial from #305, round-trips it through DER, and checks `serialNumber()` and `hasSerialNumber(_:)`, plus a high-bit serial so DER sign padding doesn't leak into the string. The leading-zero test fails on `main` (returns `33742570D6F9684A23311711956A084`) and passes with this change. - `swift test` (17 tests) and `make lint` pass on macOS (Xcode 27, Swift 6.4, `XTL_CI=1`). - @McoreD tested on Linux (Arch, Swift 6.4.1, Xcode 27 SDK, on top of 1.22.2) with a paid team whose certificate serial starts with `0`: the stored certificate is reused, and provisioning, signing and install to an iPhone (iOS 27) succeed end to end (tested before pagination was added). `CertificateTests` also pass on Linux. - Not tested with a free team. To generate test certificates, the test target now depends on `Crypto` and `X509`, which XKit already uses. ## AI tool usage How much of this PR was AI-assisted? (check one) - [ ] **0** - No AI was used to write code - [x] **1** - I was assisted by AI. I reviewed the finished result. - [ ] **2** - I set the AI going and left it to it; nobody has read the result - no review, or AI review only <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Certificate serial numbers now preserve leading zero nibbles while omitting unnecessary padding. * Certificate matching now ignores letter case and leading zeros, and profile lookups find matching certificates even when the API’s serial-number filter treats leading-zero values differently. * Certificate lookups continue to use the existing fallback when no matching certificate is found. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: McoreD <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Diff
Package.swift
diff --git a/Package.swift b/Package.swiftindex 4a7766f..199a142 100644--- a/Package.swift+++ b/Package.swift@@ -166,6 +166,8 @@ let package = Package( "XKit", "XToolSupport", "PackLib",+ .product(name: "Crypto", package: "swift-crypto"),+ .product(name: "X509", package: "swift-certificates"), ], swiftSettings: swiftSettings, ),
Sources/XKit/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift
diff --git a/Sources/XKit/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift b/Sources/XKit/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swiftindex 980cb9c..2ca1787 100644--- a/Sources/XKit/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift+++ b/Sources/XKit/DeveloperServices/Certificates/DeveloperServicesFetchCertificateOperation.swift@@ -100,8 +100,9 @@ public struct DeveloperServicesFetchCertificateOperation: DeveloperServicesOpera return try await self.replaceCertificates(certificates, requireConfirmation: true) } - let knownSerialNumber = signingInfo.certificate.serialNumber()- guard let certificate = certificates.first(where: { $0.attributes?.serialNumber == knownSerialNumber }) else {+ guard let certificate = certificates.first(where: {+ $0.attributes?.serialNumber.map(signingInfo.certificate.hasSerialNumber) == true+ }) else { // we need to revoke existing certs, otherwise it doesn't always let us make a new one return try await self.replaceCertificates(certificates, requireConfirmation: true) }
Sources/XKit/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift
diff --git a/Sources/XKit/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift b/Sources/XKit/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swiftindex 23ea7a6..c9ac8a3 100644--- a/Sources/XKit/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift+++ b/Sources/XKit/DeveloperServices/Profiles/DeveloperServicesFetchProfileOperation.swift@@ -61,13 +61,16 @@ public struct DeveloperServicesFetchProfileOperation: DeveloperServicesOperation break } - let serialNumber = signingInfo.certificate.serialNumber()- let certs = try await context.developerAPIClient.certificatesGetCollection(- query: .init(- filter_lbrack_serialNumber_rbrack_: [serialNumber]- )- )- .ok.body.json.data+ // Match locally rather than with filter[serialNumber]: the API lists serials with a+ // leading zero nibble ("0E41…") but its filter only matches them without it ("E41…").+ let certs = try await DeveloperAPIPages {+ try await context.developerAPIClient.certificatesGetCollection().ok.body.json+ } next: {+ $0.links.next+ }+ .map(\.data)+ .reduce(into: [], +=)+ .filter { $0.attributes?.serialNumber.map(signingInfo.certificate.hasSerialNumber) == true } let allDevices = try await context.developerAPIClient.devicesGetCollection() .ok.body.json.data
Sources/XKit/Model/Certificate.swift
diff --git a/Sources/XKit/Model/Certificate.swift b/Sources/XKit/Model/Certificate.swiftindex 7cf2fb9..e6d6a1e 100644--- a/Sources/XKit/Model/Certificate.swift+++ b/Sources/XKit/Model/Certificate.swift@@ -57,12 +57,23 @@ public struct Certificate: Codable, Sendable { } public func serialNumber() -> String {- // big endian, hex-encoded- let content = raw.serialNumber.bytes.lazy+ // big endian, hex-encoded. Leading zero bytes are dropped, but not leading zero+ // nibbles: Apple formats serials like "03AB…", not "3AB…" (#305).+ raw.serialNumber.bytes+ .drop { $0 == 0 } .map { String(format: "%02hhX", $0) } .joined()- .drop { $0 == "0" }- return String(content)+ }++ /// Whether `serialNumber` (hex-encoded, e.g. by the App Store Connect API)+ /// is this certificate's serial number.+ ///+ /// Compares numerically, so case and leading zeros don't matter.+ public func hasSerialNumber(_ serialNumber: String) -> Bool {+ func normalized(_ hex: String) -> Substring {+ hex.uppercased().drop { $0 == "0" }+ }+ return normalized(serialNumber) == normalized(self.serialNumber()) } public func wasIssuedBefore(_ other: Certificate) -> Bool {
Tests/XToolTests/CertificateTests.swift
diff --git a/Tests/XToolTests/CertificateTests.swift b/Tests/XToolTests/CertificateTests.swiftnew file mode 100644index 0000000..0230a43--- /dev/null+++ b/Tests/XToolTests/CertificateTests.swift@@ -0,0 +1,57 @@+import Foundation+import Testing+import Crypto+import X509+import XKit++// serial number from https://github.com/xtool-org/xtool/issues/305+private let leadingZeroSerial: [UInt8] = [+ 0x03, 0x37, 0x42, 0x57, 0x0D, 0x6F, 0x96, 0x84,+ 0xA2, 0x33, 0x11, 0x71, 0x19, 0x56, 0xA0, 0x84,+]++@Test func serialNumberKeepsLeadingZeroNibble() throws {+ let certificate = try makeCertificate(serialNumber: leadingZeroSerial)+ #expect(certificate.serialNumber() == "033742570D6F9684A23311711956A084")+}++@Test func serialNumberOmitsDERSignPadding() throws {+ // the high bit is set, so DER encodes this serial with a leading 0x00 byte+ var serial = leadingZeroSerial+ serial[0] = 0x83+ let certificate = try makeCertificate(serialNumber: serial)+ #expect(certificate.serialNumber() == "833742570D6F9684A23311711956A084")+}++@Test func hasSerialNumberIgnoresCaseAndLeadingZeros() throws {+ let certificate = try makeCertificate(serialNumber: leadingZeroSerial)+ #expect(certificate.hasSerialNumber("033742570D6F9684A23311711956A084"))+ #expect(certificate.hasSerialNumber("033742570d6f9684a23311711956a084"))+ #expect(certificate.hasSerialNumber("33742570D6F9684A23311711956A084"))+ #expect(certificate.hasSerialNumber("0033742570D6F9684A23311711956A084"))+ #expect(!certificate.hasSerialNumber("133742570D6F9684A23311711956A084"))+ #expect(!certificate.hasSerialNumber(""))+}++/// Creates a self-signed certificate and round-trips it through DER,+/// like the certificates we get from the developer API.+private func makeCertificate(serialNumber: [UInt8]) throws -> XKit.Certificate {+ let key = P256.Signing.PrivateKey()+ let name = try DistinguishedName {+ CommonName("xtool tests")+ }+ let now = Date()+ let certificate = try X509.Certificate(+ version: .v3,+ serialNumber: .init(bytes: serialNumber),+ publicKey: .init(key.publicKey),+ notValidBefore: now,+ notValidAfter: now + 3600,+ issuer: name,+ subject: name,+ signatureAlgorithm: .ecdsaWithSHA256,+ extensions: .init(),+ issuerPrivateKey: .init(key)+ )+ return try XKit.Certificate(data: XKit.Certificate(raw: certificate).data())+}