aboutsummaryrefslogtreecommitdiffstats
path: root/packaging-tools/notarize.py
blob: 31d389bac5ea8da0a796c67b8155df353bb59be6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#############################################################################
#
# Copyright (C) 2022 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of the release tools of the Qt Toolkit.
#
# $QT_BEGIN_LICENSE:GPL-EXCEPT$
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# included in the packaging of this file. Please review the following
# information to ensure the GNU General Public License requirements will
# be met: https://www.gnu.org/licenses/gpl-3.0.html.
#
# $QT_END_LICENSE$
#
#############################################################################

import argparse
import json
import shutil
import sys
from pathlib import Path
from platform import mac_ver
from shutil import which
from subprocess import CalledProcessError
from typing import Optional

from bld_utils import is_macos
from logging_util import init_logger
from read_remote_config import get_pkg_value
from runner import run_cmd, run_cmd_silent

log = init_logger(__name__, debug_mode=False)


class NotarizationError(Exception):
    """NotarizationError exception class derived from the Exception class"""


def store_credentials_api_key(profile_name: str, key: str, key_id: str, issuer: str) -> None:
    """
    Store App Store Connect API Keys to keychain and validate them with notarytool.

    Args:
        profile_name: The profile name in keychain to which to save the credentials
        key: App Store Connect API key file system path
        key_id: App Store Connect API Key ID specific to a team (~10 chars)
        issuer: App Store Connect API Issuer ID in UUID format

    Raises:
        NotarizationError: When the command saving and validating the credentials fails

    """
    log.info("Store App Store Connect API Keys to keychain profile '%s'", profile_name)
    cmd = ["xcrun", "notarytool", "store-credentials", profile_name]
    cmd += ["--key", key, "--key-id", key_id, "--issuer", issuer]
    if not run_cmd_silent(cmd=cmd):
        raise NotarizationError("Failed to save or validate API key credentials")


def store_credentials_apple_id(
    profile_name: str, apple_id: str, password: str, team_id: str
) -> None:
    """
    Store Developer Apple ID credentials to keychain and validate them with notarytool.

    Args:
        profile_name: The profile name in keychain to which to save the credentials
        apple_id: The Apple ID login username for accessing Developer ID services
        password: App-specific password generated for the aforementioned Apple ID
        team_id: The Developer Team identifier to use with the credentials (~10 chars)

    Raises:
        NotarizationError: When the command saving and validating the credentials fails

    """
    log.info("Store Developer Apple ID credentials to keychain profile '%s'", profile_name)
    cmd = ["xcrun", "notarytool", "store-credentials", profile_name]
    cmd += ["--apple-id", apple_id, "--password", password, "--team-id", team_id]
    if not run_cmd_silent(cmd=cmd):
        raise NotarizationError("Failed to save or validate Apple ID credentials")


def process_notarize_result(
    json_data: str, profile_name: str, timeout: Optional[int] = None
) -> None:
    """
    Parse and log notarization results from json_data and raise the encountered errors.

    Args:
        json_data: Output data from notarizetool with the --output-format json specified
        profile_name: The keychain profile containing the auth credentials for notarytool
        timeout: Specify a timeout for notarytool command executed via run_cmd

    Raises:
        JSONDecodeError: If json_data formatting is malformed and cannot be decoded to json
        NotarizationError: When the notarization is determined to have failed
        CalledProcessError: When the command requesting additional logs for the UUID fails

    """
    try:
        data = json.loads(json_data)
    except json.JSONDecodeError as err:
        log.exception("Error processing json response")
        raise NotarizationError(f"Notarization failed: {str(err)}") from err
    uuid = data.get("id", "")
    status = data.get("status", "")
    if status != "Accepted":
        log.error("Notarization error: %s, UUID: %s", status, uuid)
        log.error("Gathering more details about the errors...")
        cmd = ["xcrun", "notarytool", "log", uuid, "-p", profile_name]
        try:
            run_cmd(cmd=cmd, timeout=timeout)
        except CalledProcessError as err:
            log.exception("Failed to log additional details", exc_info=err)
        raise NotarizationError(f"Notarization failed, UUID: {uuid}")
    log.info("Notarization complete, UUID: %s", uuid)


def submit_for_notarization(
    path: Path, profile_name: str, timeout: Optional[int] = None, acceleration: bool = True
) -> None:
    """
    Submit a file to Apple's Notary service for notarization.
    Wait for the server to return the result and pass the output to process_notarize_result.

    Args:
        path: The file system path for the file to notarize
        profile_name: The keychain profile containing the auth credentials for notarytool
        timeout: Specify a timeout for the notarytool command and run_cmd
        acceleration: Whether to enable S3 transfer acceleration in the notarytool upload

    """
    cmd = ["xcrun", "notarytool", "submit", str(path), "-p", profile_name]
    cmd += ["--wait", "--timeout", str(timeout), "--output-format", "json"]
    if not acceleration:
        cmd += ["--no-s3-acceleration"]
    try:
        result = run_cmd(cmd=cmd, timeout=timeout)
    except CalledProcessError as err:
        raise NotarizationError("Notarytool command failed, invalid arguments?") from err
    process_notarize_result(result, profile_name, timeout=timeout)


def prepare_payload(path: Path) -> Path:
    """
    Pack payload into a .zip archive if the path does not point to file supported by notarytool.
    The Apple Notary service accepts the following formats:
        - disk images (UDIF format), ending in .dmg
        - signed flat installer packages, ending in .pkg
        - ZIP compressed archives, ending in .zip

    Args:
        path: The file system path to the file or folder to process

    Returns:
        path: The file system path to the created zip file or the path originally passed in

    Raises:
        CalledProcessError: When the compress command via run_cmd returns a non-zero exit status.
        NotarizationError: Raised on CalledProcessError

    """
    if path.suffix not in (".dmg", ".pkg", ".zip"):
        zip_path: Path = path.with_suffix(".zip")
        log.info("Compress to .zip before upload: %s", zip_path)
        ditto_tool = shutil.which("ditto") or "/usr/bin/ditto"
        cmd = [ditto_tool, "-c", "-k", "--keepParent", str(path), str(zip_path)]
        try:
            run_cmd(cmd=cmd)
        except CalledProcessError as err:
            raise NotarizationError(f"Failed to compress {path} to .zip") from err
        path = zip_path
    log.info("Ready to upload: %s", path)
    return path


def embed_notarization(path: Path) -> None:
    """
    Embed the ticket in the notarized package, supported file formats by stapler are:
        - UDIF disk images (.dmg)
        - code-signed executable bundles (.app)
        - signed "flat" installer packages (.pkg)

    Args:
        path: The file system path to the previously notarized file

    Raises:
        CalledProcessError: When the stapler command via run_cmd returns a non-zero exit status.
        NotarizationError: Raised on CalledProcessError on a supported file type.

    """
    log.info("Stapling package: %s", path)
    try:
        cmd = ['xcrun', 'stapler', 'staple', str(path)]
        run_cmd(cmd=cmd)
    except CalledProcessError as err:
        if path.suffix in (".dmg", ".app", ".pkg"):
            raise NotarizationError(f"Error embedding ticket: Stapler failed for {path}") from err
        # Do not raise when file format is not known to support stapling, but log the error instead
        log.exception("Ignored error while stapling %s: %s", str(path), str(err), exc_info=err)


def key_from_remote_env(key: str) -> str:
    """
    Get value from remote environment with get_pkg_value if it exists, or return an empty string

    Args:
        key: The key for the value to look for in the environment

    Returns:
        Returned value from get_pkg_value if no exception was handled or an empty string (str)

    Raises:
        Exception: Raised by get_pkg_value, handled by the function

    """
    try:
        return get_pkg_value(key)
    except Exception:
        return ""


def check_notarize_reqs() -> None:
    """
    Check if the system supports notarization via notarytool and has the required tools installed.

    Raises:
        NotarizationError: If there are missing tools or the platform is not supported.

    """
    if not is_macos():
        raise NotarizationError("Only macOS is supported. For other platforms see Notary API.")
    if not [int(x) for x in mac_ver()[0].split(".")] >= [10, 15, 7]:
        raise NotarizationError("Only macOS version 10.15.7+ is supported by notarytool")
    if not shutil.which("ditto") and not Path("/usr/bin/ditto").exists():
        raise NotarizationError("Couldn't find 'ditto': '/usr/bin/ditto' missing or not in PATH")
    if not which("xcrun"):
        raise NotarizationError("Couldn't find 'xcrun'. Xcode Command Line Tools is required")
    try:
        run_cmd(["xcrun", "--find", "stapler"])
    except CalledProcessError as err:
        raise NotarizationError("Couldn't find 'stapler'. Xcode is required") from err
    try:
        run_cmd(["xcrun", "--find", "notarytool"])
    except CalledProcessError as err:
        raise NotarizationError("Couldn't find 'notarytool'. Xcode 13+ is required") from err


def notarize(
    path: Path,
    apple_id: str = key_from_remote_env("AC_USERNAME"),
    password: str = key_from_remote_env("AC_PASSWORD"),
    team_id: str = key_from_remote_env("QT_CODESIGN_IDENTITY_KEY"),
    key: str = key_from_remote_env("AC_KEY"),
    key_id: str = key_from_remote_env("AC_KEYID"),
    issuer: str = key_from_remote_env("AC_ISSUER"),
    profile: str = key_from_remote_env("AC_NOTARY") or "AC_NOTARY",
    timeout: Optional[int] = 60 * 60 * 3,
    acceleration: bool = True
) -> None:
    """
    Run notarize and staple actions for the given file with arguments specified
    Notarytool authentication options:
        - apple_id, password, team_id -> saved to profile
        - key, key_id, issuer -> saved to profile
        - profile -> use from profile directly

    Args:
        path: The file system path to the file or folder to notarize
        apple_id: The Apple ID login username to save
        password: App-specific password to save
        team_id: The Developer Team identifier to save
        key: App Store Connect API key file system path to save
        key_id: App Store Connect API Key ID to save
        issuer: App Store Connect API Issuer UUID to save
        profile: Profile name in keychain for saving and accessing credentials
        timeout: Timeout for all of the notarytool commands executed
        acceleration: Whether to enable transfer acceleration in notarytool uploads

    Raises:
        NotarizationError: When conditions required for notarization are not met or it fails

    """
    # Check system requirements
    check_notarize_reqs()
    # Store credentials for later
    if not profile:
        raise NotarizationError("Keychain profile name is empty?")
    if key and key_id and issuer:
        store_credentials_api_key(profile, key, key_id, issuer)
    elif apple_id and password and team_id:
        store_credentials_apple_id(profile, apple_id, password, team_id)
    else:
        log.warning("App Store Connect API keys or Apple ID credentials not provided.")
        log.info("Attempting to use previously saved credentials from profile '%s'", profile)
    # Pack the file if necessary, return the new path
    notarize_path = prepare_payload(path)
    # Submit payload for notarization and wait for it to complete
    log.info("Notarize %s", notarize_path)
    submit_for_notarization(notarize_path, profile, timeout, acceleration)
    # Embed the notarization ticket to the file if file type supports it (DMG, PKG)
    # If required, stapler needs to be run separately for each file inside the ZIP archive
    if notarize_path.suffix != ".zip":
        embed_notarization(notarize_path)
    # Remove the zipped archive as this is no longer needed, keeping only the original data
    if path != notarize_path:
        notarize_path.unlink()


def main() -> None:
    """Main function, parse arguments with ArgumentParser and call the notarize function."""
    parser = argparse.ArgumentParser(prog="Helper script to notarize content from given path")
    parser.add_argument(
        "--bundle-id",  # TODO: remove
        dest="bundle_id", required=False, type=str, help="Deprecated"
    )
    parser.add_argument(
        "--path",
        "--dmg",  # TODO: remove
        dest="path", required=True, type=str, help="Path to a file or a folder"
    )
    parser.add_argument(
        "--apple-id",
        "--user",  # TODO: remove
        dest="apple_id", type=str, default=key_from_remote_env("AC_USERNAME"),
        help="Developer Apple ID login username"
    )
    parser.add_argument(
        "--password",
        "--passwd",  # TODO: remove
        dest="password", type=str, default=key_from_remote_env("AC_PASSWORD"),
        help="App-specific password for Apple ID"
    )
    parser.add_argument(
        "--team-id", dest="team_id", type=str,
        default=key_from_remote_env("QT_CODESIGN_IDENTITY_KEY"), help="Developer Team identifier"
    )
    parser.add_argument(
        "--key", dest="key", type=str, default=key_from_remote_env("AC_KEY"),
        help="Path for App Store Connect API key"
    )
    parser.add_argument(
        "--key-id", dest="key_id", type=str, default=key_from_remote_env("AC_KEYID"),
        help="App Store Connect API Key ID"
    )
    parser.add_argument(
        "--issuer", dest="issuer", type=str, default=key_from_remote_env("AC_ISSUER"),
        help="App Store Connect API Issuer UUID"
    )
    parser.add_argument(
        "--timeout", dest="timeout", type=int, default=10800,
        help="Timeout value for remote requests"
    )
    parser.add_argument(
        "--profile", dest="profile", type=str,
        default=key_from_remote_env("AC_NOTARY") or "AC_NOTARY",
        help="Notarytool profile name for saved credentials"
    )
    parser.add_argument(
        "--acceleration", dest="acceleration", action="store_true", default=True,
        help="Enable S3 Acceleration"
    )
    args = parser.parse_args(sys.argv[1:])
    try:
        notarize(
            path=Path(args.path),
            apple_id=args.apple_id,
            password=args.password,
            team_id=args.team_id,
            key=args.key,
            key_id=args.key_id,
            issuer=args.issuer,
            timeout=args.timeout,
            profile=args.profile,
            acceleration=args.acceleration,
        )
    except NotarizationError as err:
        log.exception("Notarize script failed: %s", str(err), exc_info=err)
        raise SystemExit from err


if __name__ == "__main__":
    main()