179 lines
8.8 KiB
Python
179 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|||
|
|
"""One-time App Store signing setup through the App Store Connect API.
|
||
|
|
|
||
|
|
Why: Apple's cloud-managed distribution signing writes the certificate name
|
||
|
|
into each binary's designated requirement in Unicode-decomposed form
|
||
|
|
("Sági"), while the certificate itself holds the composed form ("Sági").
|
||
|
|
The requirement then never matches and App Store Connect rejects the upload
|
||
|
|
(ITMS-90035). Signing locally with our own distribution certificate and an
|
||
|
|
explicit, ASCII-only requirement avoids that (see scripts/ios_release.sh).
|
||
|
|
|
||
|
|
This script:
|
||
|
|
1. checks the app record and bundle ID exist,
|
||
|
|
2. creates a local key + Apple Distribution certificate (reuses it if present),
|
||
|
|
3. creates an App Store provisioning profile for it,
|
||
|
|
4. puts key + certificate into a dedicated keychain (not the login keychain).
|
||
|
|
|
||
|
|
Secrets stay outside the repo in ~/.appstoreconnect/skycontour/.
|
||
|
|
Usage: python3 scripts/asc_signing_setup.py --key-id KEY --issuer ISSUER
|
||
|
|
"""
|
||
|
|
import argparse
|
||
|
|
import base64
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import secrets
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
import time
|
||
|
|
import urllib.error
|
||
|
|
import urllib.request
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from cryptography import x509
|
||
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
||
|
|
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||
|
|
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
|
||
|
|
from cryptography.x509.oid import NameOID
|
||
|
|
|
||
|
|
BUNDLE_ID = 'com.sagifer.skycontour.ios'
|
||
|
|
TEAM_ID = '8EQZ487TY9'
|
||
|
|
API = 'https://api.appstoreconnect.apple.com/v1'
|
||
|
|
HOME = Path.home() / '.appstoreconnect'
|
||
|
|
OUT = HOME / 'skycontour'
|
||
|
|
KEYCHAIN = Path.home() / 'Library/Keychains/skycontour-signing.keychain-db'
|
||
|
|
|
||
|
|
|
||
|
|
def b64url(b):
|
||
|
|
return base64.urlsafe_b64encode(b).rstrip(b'=').decode()
|
||
|
|
|
||
|
|
|
||
|
|
def jwt(key_id, issuer):
|
||
|
|
key = serialization.load_pem_private_key((HOME / f'private_keys/AuthKey_{key_id}.p8').read_bytes(), None)
|
||
|
|
now = int(time.time())
|
||
|
|
head = b64url(json.dumps({'alg': 'ES256', 'kid': key_id, 'typ': 'JWT'}).encode())
|
||
|
|
body = b64url(json.dumps({'iss': issuer, 'iat': now, 'exp': now + 900, 'aud': 'appstoreconnect-v1'}).encode())
|
||
|
|
r, s = decode_dss_signature(key.sign(f'{head}.{body}'.encode(), ec.ECDSA(hashes.SHA256())))
|
||
|
|
return f'{head}.{body}.{b64url(r.to_bytes(32, "big") + s.to_bytes(32, "big"))}'
|
||
|
|
|
||
|
|
|
||
|
|
class Api:
|
||
|
|
def __init__(self, key_id, issuer):
|
||
|
|
self.token = jwt(key_id, issuer)
|
||
|
|
|
||
|
|
def call(self, method, path, body=None):
|
||
|
|
req = urllib.request.Request(API + path, method=method, data=json.dumps(body).encode() if body else None,
|
||
|
|
headers={'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json'})
|
||
|
|
try:
|
||
|
|
with urllib.request.urlopen(req, timeout=60) as r:
|
||
|
|
return json.loads(r.read() or b'{}')
|
||
|
|
except urllib.error.HTTPError as e:
|
||
|
|
sys.exit(f'{method} {path} → HTTP {e.code}: {e.read().decode()[:600]}')
|
||
|
|
|
||
|
|
|
||
|
|
def sh(*args, check=True):
|
||
|
|
return subprocess.run(args, check=check, capture_output=True, text=True)
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
ap = argparse.ArgumentParser()
|
||
|
|
ap.add_argument('--key-id', required=True)
|
||
|
|
ap.add_argument('--issuer', required=True)
|
||
|
|
a = ap.parse_args()
|
||
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
||
|
|
os.chmod(OUT, 0o700)
|
||
|
|
api = Api(a.key_id, a.issuer)
|
||
|
|
|
||
|
|
# 1. App record + bundle ID
|
||
|
|
bid = [b for b in api.call('GET', f'/bundleIds?filter[identifier]={BUNDLE_ID}&limit=50')['data']
|
||
|
|
if b['attributes']['identifier'] == BUNDLE_ID]
|
||
|
|
if not bid:
|
||
|
|
sys.exit(f'Bundle ID {BUNDLE_ID} is not registered for this team')
|
||
|
|
bundle_id = bid[0]['id']
|
||
|
|
apps = api.call('GET', f'/apps?filter[bundleId]={BUNDLE_ID}')['data']
|
||
|
|
print('app record:', apps[0]['attributes']['name'] if apps else 'MISSING (create it in App Store Connect)')
|
||
|
|
|
||
|
|
# 2. Distribution certificate (reuse ours if the key is still here)
|
||
|
|
key_path, cert_path, meta_path = OUT / 'distribution.key.pem', OUT / 'distribution.cer', OUT / 'meta.json'
|
||
|
|
meta = json.loads(meta_path.read_text()) if meta_path.exists() else {}
|
||
|
|
if key_path.exists() and cert_path.exists() and meta.get('certificateId'):
|
||
|
|
print('reusing local distribution certificate', meta['certificateId'])
|
||
|
|
key = serialization.load_pem_private_key(key_path.read_bytes(), None)
|
||
|
|
cert = x509.load_der_x509_certificate(cert_path.read_bytes())
|
||
|
|
else:
|
||
|
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||
|
|
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||
|
|
serialization.NoEncryption()))
|
||
|
|
os.chmod(key_path, 0o600)
|
||
|
|
csr = (x509.CertificateSigningRequestBuilder()
|
||
|
|
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'SkyContour distribution')]))
|
||
|
|
.sign(key, hashes.SHA256()))
|
||
|
|
res = api.call('POST', '/certificates', {'data': {'type': 'certificates', 'attributes': {
|
||
|
|
'certificateType': 'DISTRIBUTION', 'csrContent': csr.public_bytes(serialization.Encoding.PEM).decode()}}})
|
||
|
|
der = base64.b64decode(res['data']['attributes']['certificateContent'])
|
||
|
|
cert_path.write_bytes(der)
|
||
|
|
cert = x509.load_der_x509_certificate(der)
|
||
|
|
meta['certificateId'] = res['data']['id']
|
||
|
|
print('created distribution certificate', meta['certificateId'], 'expires', cert.not_valid_after_utc.date())
|
||
|
|
|
||
|
|
meta['certificateSha1'] = cert.fingerprint(hashes.SHA1()).hex().upper()
|
||
|
|
meta_path.write_text(json.dumps(meta, indent=2))
|
||
|
|
|
||
|
|
# 3. App Store profile bound to this certificate (reused while it exists)
|
||
|
|
prof = OUT / 'appstore.mobileprovision'
|
||
|
|
if prof.exists() and meta.get('profileId'):
|
||
|
|
print('reusing App Store profile', meta['profileId'])
|
||
|
|
else:
|
||
|
|
res = api.call('POST', '/profiles', {'data': {'type': 'profiles',
|
||
|
|
'attributes': {'name': f'SkyContour App Store {time.strftime("%Y%m%d-%H%M%S")}', 'profileType': 'IOS_APP_STORE'},
|
||
|
|
'relationships': {'bundleId': {'data': {'type': 'bundleIds', 'id': bundle_id}},
|
||
|
|
'certificates': {'data': [{'type': 'certificates', 'id': meta['certificateId']}]}}}})
|
||
|
|
prof.write_bytes(base64.b64decode(res['data']['attributes']['profileContent']))
|
||
|
|
meta['profileId'] = res['data']['id']
|
||
|
|
meta_path.write_text(json.dumps(meta, indent=2))
|
||
|
|
print('created App Store profile', res['data']['attributes']['name'])
|
||
|
|
|
||
|
|
# 4. Dedicated keychain with key + certificate (codesign can use it without prompts)
|
||
|
|
pw_path = OUT / 'keychain.password'
|
||
|
|
if not pw_path.exists():
|
||
|
|
pw_path.write_text(secrets.token_urlsafe(24))
|
||
|
|
os.chmod(pw_path, 0o600)
|
||
|
|
pw = pw_path.read_text().strip()
|
||
|
|
if not KEYCHAIN.exists():
|
||
|
|
sh('security', 'create-keychain', '-p', pw, str(KEYCHAIN))
|
||
|
|
sh('security', 'unlock-keychain', '-p', pw, str(KEYCHAIN))
|
||
|
|
sh('security', 'set-keychain-settings', str(KEYCHAIN)) # no auto-lock
|
||
|
|
# Key and certificate separately: macOS `security` cannot read the modern
|
||
|
|
# (AES/PBKDF2) PKCS#12 files that Python/OpenSSL 3 write by default.
|
||
|
|
(OUT / 'distribution.p12').unlink(missing_ok=True) # left over by an older version
|
||
|
|
if not sh('security', 'find-identity', '-v', '-p', 'codesigning', str(KEYCHAIN)).stdout.count(')') :
|
||
|
|
# `security` wants the traditional "BEGIN RSA PRIVATE KEY" form, not PKCS#8.
|
||
|
|
legacy = OUT / 'distribution.rsa.pem'
|
||
|
|
legacy.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
|
||
|
|
serialization.NoEncryption()))
|
||
|
|
os.chmod(legacy, 0o600)
|
||
|
|
try:
|
||
|
|
for path, kind, fmt in ((legacy, 'priv', 'openssl'), (cert_path, 'cert', 'x509')):
|
||
|
|
r = sh('security', 'import', str(path), '-k', str(KEYCHAIN), '-t', kind, '-f', fmt,
|
||
|
|
'-T', '/usr/bin/codesign', check=False)
|
||
|
|
if r.returncode != 0 and 'already exists' not in r.stderr:
|
||
|
|
sys.exit(f'keychain import of {path.name} failed: {r.stderr.strip()}')
|
||
|
|
finally:
|
||
|
|
legacy.unlink(missing_ok=True)
|
||
|
|
r = sh('security', 'set-key-partition-list', '-S', 'apple-tool:,apple:,codesign:', '-s', '-k', pw,
|
||
|
|
str(KEYCHAIN), check=False)
|
||
|
|
if r.returncode != 0:
|
||
|
|
sys.exit('set-key-partition-list failed: ' + r.stderr.strip())
|
||
|
|
listed = sh('security', 'list-keychains', '-d', 'user').stdout.split()
|
||
|
|
listed = [k.strip('"') for k in listed]
|
||
|
|
if str(KEYCHAIN) not in listed:
|
||
|
|
sh('security', 'list-keychains', '-d', 'user', '-s', *listed, str(KEYCHAIN))
|
||
|
|
ident = sh('security', 'find-identity', '-v', '-p', 'codesigning', str(KEYCHAIN)).stdout.strip()
|
||
|
|
print(ident)
|
||
|
|
if meta['certificateSha1'] not in ident:
|
||
|
|
sys.exit('the distribution identity is not usable in the signing keychain')
|
||
|
|
print('signing identity SHA1:', meta['certificateSha1'], '| team', TEAM_ID)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
main()
|