import Darwin
import Foundation
import Testing
@testable import ParcelDev
private let interactiveKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
private let interactiveCommit = String(repeating: "a", count: 40)
private let interactiveStub = #"""
#!/bin/bash
set -euo pipefail
name=${0##*/}
printf '%s %s\n' "$name" "$*" >> "$LAUNCH_STUB_LOG"
case "$name" in
security) printf '%s\n' '1) fixture "Developer ID Application: Fixture (FIXTURE123)"' ;;
xcrun) printf '/fixture/notarytool\n' ;;
sleep) ;;
swiftc)
[[ ${LAUNCH_STUB_FAIL_COMPILE:-0} == 0 ]] || exit 70
output=${!#}
[[ -f Scripts/launch-keychain.swift && $output == "$TMPDIR"/launch.*/keychain ]]
[[ $(stat -f '%Lp' "${output%/*}") == 700 ]]
/bin/cat > "${!#}" <<'HELPER'
#!/bin/bash
set -euo pipefail
printf 'helper %s\n' "$*" >> "$LAUNCH_STUB_LOG"
case "$1" in
ensure-update) printf '%s\n' "${LAUNCH_STUB_PUBLIC:-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=}" ;;
get)
[[ ${LAUNCH_STUB_KEYCHAIN_ERROR:-0} == 0 ]] || exit 74
[[ ${LAUNCH_STUB_MISSING_LOCAL:-0} == 0 ]] || exit 44
printf 'hidden-fixture-secret' ;;
put|replace) value=$(/bin/cat); [[ -n $value ]];;
*) exit 99 ;;
esac
HELPER
chmod +x "${!#}" ;;
git)
case "$*" in
'status --porcelain --untracked-files=normal') [[ ${LAUNCH_STUB_DIRTY:-0} == 0 ]] || printf ' M file\n' ;;
'symbolic-ref --quiet --short HEAD') printf '%s\n' "${LAUNCH_STUB_BRANCH:-main}" ;;
'rev-parse HEAD') printf '%s\n' "$LAUNCH_STUB_COMMIT" ;;
'show-ref --verify --quiet refs/tags/'*) [[ ${LAUNCH_STUB_NO_LOCAL_TAG:-0} == 0 ]] ;;
'rev-parse v'*'^{commit}') printf '%s\n' "${LAUNCH_STUB_TAG:-$LAUNCH_STUB_COMMIT}" ;;
'merge-base --is-ancestor '*) [[ ${LAUNCH_STUB_UNTRUSTED:-0} == 0 ]] ;;
'ls-remote '*|'tag -a '*) ;;
'fetch '*)
if [[ ${LAUNCH_STUB_FAIL_FETCH:-0} == 1 ]]; then printf 'refusing existing tag mismatch\n' >&2; exit 1; fi ;;
'push '*) [[ ${LAUNCH_STUB_FAIL_PUSH:-0} == 0 ]] ;;
'-C '*' rev-parse --show-toplevel') printf '%s\n' "${LAUNCH_STUB_SITE_ROOT:-$2}" ;;
*) printf 'Unexpected git stub call: %s\n' "$*" >&2; exit 99 ;;
esac ;;
gh)
case "$*" in
'secret set '*)
if [[ $3 == MIRROR_TOKEN ]]; then [[ $* == *' --env mirror' ]]; else [[ $* == *' --env release' ]]; fi
/bin/cat >/dev/null
[[ ${LAUNCH_STUB_FAIL_SECRET:-0} == 0 ]] ;;
'secret list '*' --env release --json name')
if [[ ${LAUNCH_STUB_MISSING_SECRET:-0} == 1 ]]; then printf '[]\n'; else
printf '[{"name":"DEVELOPER_ID_P12"},{"name":"DEVELOPER_ID_PASSWORD"},{"name":"DEVELOPER_ID_IDENTITY"},{"name":"APPLE_TEAM_ID"},{"name":"ASC_PRIVATE_KEY"},{"name":"ASC_KEY_ID"},{"name":"ASC_ISSUER_ID"},{"name":"SPARKLE_PRIVATE_KEY"}]\n'
fi ;;
'secret list '*' --env mirror --json name')
if [[ ${LAUNCH_STUB_MISSING_MIRROR_SECRET:-0} == 1 ]]; then printf '[]\n'; else printf '[{"name":"MIRROR_TOKEN"}]\n'; fi ;;
'secret list '*' --json name')
[[ ${LAUNCH_STUB_FAIL_REPO_SECRETS:-0} == 0 ]] || exit 75
printf '%s\n' "${LAUNCH_STUB_REPO_SECRETS:-[]}" ;;
'api users/'*) printf '42\n' ;;
'api repos/'*'/environments/release')
if [[ ${LAUNCH_STUB_NO_REVIEW:-0} == 1 ]]; then printf '{"protection_rules":[]}\n'; else
printf '{"can_admins_bypass":false,"protection_rules":[{"type":"required_reviewers","reviewers":[{"type":"User","reviewer":{"id":42}}]}],"deployment_branch_policy":{"protected_branches":false,"custom_branch_policies":true}}\n'
fi ;;
'api repos/'*'/environments/mirror') printf '{"deployment_branch_policy":{"protected_branches":false,"custom_branch_policies":true}}\n' ;;
'api repos/'*'/environments/release/deployment-branch-policies '*)
printf '{"branch_policies":[{"name":"%s","type":"%s"}]}\n' "${LAUNCH_STUB_RELEASE_POLICY:-main}" "${LAUNCH_STUB_POLICY_TYPE:-branch}" ;;
'api repos/'*'/environments/mirror/deployment-branch-policies '*)
printf '{"branch_policies":[{"name":"%s","type":"branch"}]}\n' "${LAUNCH_STUB_MIRROR_POLICY:-main}" ;;
'api repos/'*'/rulesets --paginate '*)
if [[ ${LAUNCH_STUB_BRANCH_RULESET:-0} == 1 ]]; then
printf '[{"id":7,"name":"release-tags","target":"tag","enforcement":"active"},{"id":8,"name":"main","target":"branch","enforcement":"active"}]\n'
elif [[ ${LAUNCH_STUB_DUPLICATE_RULESET:-0} == 1 ]]; then printf '[{"id":7,"name":"release-tags"},{"id":9,"name":"release-tags"}]\n'
else printf '[{"id":7,"name":"release-tags","target":"tag","enforcement":"active"}]\n'; fi ;;
'api repos/'*'/rulesets/7')
printf '{"target":"tag","enforcement":"%s","conditions":{"ref_name":{"include":["refs/tags/v*"],"exclude":[]}},"rules":[{"type":"update"},{"type":"deletion"}],"bypass_actors":[]}\n' "${LAUNCH_STUB_TAG_ENFORCEMENT:-active}" ;;
'api repos/'*'/rulesets/8')
printf '{"target":"branch","enforcement":"active","conditions":{"ref_name":{"include":["%s"],"exclude":[]}},"rules":[{"type":"non_fast_forward"},{"type":"deletion"}],"bypass_actors":[]}\n' "${LAUNCH_STUB_BRANCH_RULE_INCLUDE:-~DEFAULT_BRANCH}" ;;
'api repos/'*'/branches/'*'/protection')
[[ ${LAUNCH_STUB_FAIL_BRANCH_READ:-0} == 0 ]] || exit 76
printf '{"allow_force_pushes":{"enabled":%s},"allow_deletions":{"enabled":false},"enforce_admins":{"enabled":true}}\n' "${LAUNCH_STUB_ALLOW_FORCE:-false}" ;;
'api repos/'*'/commits/v'*' --jq '*) printf '%s\n' "${LAUNCH_STUB_REMOTE_TAG:-$LAUNCH_STUB_COMMIT}" ;;
'api repos/'*'/commits/'*' --jq '*) printf '%s\n' "$LAUNCH_STUB_COMMIT" ;;
'api repos/'*' --jq .default_branch') printf '%s\n' "${LAUNCH_STUB_DEFAULT_BRANCH:-main}" ;;
'run list '*)
previous=0
[[ ! -f $HOME/run-list-count ]] || previous=$(< "$HOME/run-list-count")
printf '%s\n' "$((previous + 1))" > "$HOME/run-list-count"
if [[ ${LAUNCH_STUB_EMPTY_RUNS:-0} == 1 && ! -f $HOME/dispatched && ! ( ${LAUNCH_STUB_RUN_RACE:-0} == 1 && $previous -ge ${PARCEL_LAUNCH_POLL_ATTEMPTS:-60} ) ]]; then printf '[]\n'
else printf '%s\n' "$LAUNCH_STUB_RUNS"; fi ;;
'run view '*' --json attempt '*)
if [[ -f $HOME/rerun && ${LAUNCH_STUB_STUCK_ATTEMPT:-0} == 0 ]]; then printf '2\n'; else printf '1\n'; fi ;;
'run view '*' --json conclusion '*)
if [[ -f $HOME/watched || -f $HOME/rerun ]]; then printf '%s\n' "${LAUNCH_STUB_FINAL_CONCLUSION:-success}"; else printf '%s\n' "${LAUNCH_STUB_CONCLUSION:-success}"; fi ;;
'run rerun '*) touch "$HOME/rerun" ;;
'run watch '*) touch "$HOME/watched"; [[ ${LAUNCH_STUB_FAIL_WATCH:-0} == 0 ]] ;;
'workflow run '*) [[ $* == *' --ref main -f tag=v'* ]]; touch "$HOME/dispatched" ;;
'run download '*)
directory=${!#}
[[ -d $directory && ! -e $directory/appcast.xml ]]
[[ ${LAUNCH_STUB_MISSING_ARTIFACT:-0} == 1 ]] || printf '\n' > "$directory/appcast.xml"
printf 'exit 99\n' > "$directory/parcel-dev" ;;
'release download '*)
directory=${!#}
[[ -d $directory ]]
if [[ ${LAUNCH_STUB_MISSING_ARCHIVE:-0} == 0 ]]; then
printf 'fixture dmg' > "$directory/$LAUNCH_STUB_PRODUCT-$LAUNCH_STUB_VERSION.dmg"
printf 'fixture checksum' > "$directory/SHA256SUMS"
fi ;;
'auth status') ;;
'repo view '*) [[ ${LAUNCH_STUB_FAIL_REPO_VIEW:-0} == 0 ]] ;;
*) printf 'Unexpected gh stub call: %s\n' "$*" >&2; exit 99 ;;
esac ;;
ssh|cloudflared) printf 'Unexpected network command\n' >&2; exit 99 ;;
*) exit 99 ;;
esac
"""#
private let interactiveBinary = #"""
#!/bin/bash
set -euo pipefail
if [[ $1 != launch-feed ]]; then exec "$LAUNCH_REAL_DEV_BINARY" "$@"; fi
shift
[[ $# == 9 && $PWD == "$PARCEL_DEV_ROOT" && ${!#} == "$PWD" ]]
[[ ${1%/*} != ${6%/*} && -f $1 && -f $6 && -f $7 ]]
[[ $5 == */v"$4"/"${6##*/}" ]]
printf 'feed %s\n' "$*" >> "$LAUNCH_STUB_LOG"
[[ ${LAUNCH_STUB_FAIL_FEED:-0} == 0 ]] || { printf 'fixture feed verification failed\n' >&2; exit 1; }
"""#
private struct InteractiveResult {
let status: Int32
let text: String
let log: String
}
@Suite(.timeLimit(.minutes(5))) struct InteractiveLaunchTests {
private func runs(title: String = "Release v0.1.0", id: DevJSON = .number(42)) throws -> String {
let value: DevJSON = .array([
.object([
"databaseId": id, "headSha": .string(String(repeating: "b", count: 40)), "headBranch": .string("main"),
"displayTitle": .string(title), "event": .string("workflow_dispatch"),
])
])
return String(decoding: try value.encoded(), as: UTF8.self)
}
private func run(
_ accept: [String] = [], _ overrides: [String: String] = [:], arguments: [String] = [],
repeated: String = "hidden-fixture-secret", interrupt: String? = nil,
product: [String: String] = [:], credential: String = "regular",
pauseBeforeSecretRead: Bool = false, interruptHiddenInput: Bool = false, initialEchoEnabled: Bool = true
) throws -> InteractiveResult {
let created = try PolicyTestSupport.temporary("launch-interactive")
let physical = try #require(realpath(created.path, nil))
let root = URL(fileURLWithPath: String(cString: physical))
free(physical)
defer { #expect(throws: Never.self) { try FileManager.default.removeItem(at: root) } }
let scripts = root.appendingPathComponent("project/Scripts")
try FileManager.default.createDirectory(at: scripts, withIntermediateDirectories: true)
for name in ["launch.sh", "product.env", "version.sh", "parcel-dev.sh", "launch-keychain.swift"] {
try FileManager.default.copyItem(
at: PolicyTestSupport.root.appendingPathComponent("Scripts/" + name),
to: scripts.appendingPathComponent(name))
}
if pauseBeforeSecretRead {
let launch = scripts.appendingPathComponent("launch.sh")
let source = try String(contentsOf: launch, encoding: .utf8)
let prompt = #"printf '%s (hidden): ' "$name" >&2"#
try #require(source.components(separatedBy: prompt).count == 2)
// Keep scheduling from hiding an echo race after the prompt.
try PolicyTestSupport.write(
source.replacingOccurrences(of: prompt, with: prompt + "\n kill -STOP $$"), to: launch)
}
var chosen = [
"PRODUCT_NAME": "Parcel", "PRODUCT_GITHUB_REPO": "vinnymac/parcel", "PRODUCT_DEFAULT_BRANCH": "main",
]
chosen.merge(product) { _, new in new }
let productPath = scripts.appendingPathComponent("product.env")
var settings = try String(contentsOf: productPath, encoding: .utf8)
settings += "\nexport PRODUCT_UPDATE_PUBLIC_KEY=" + interactiveKey + "\n"
for (key, value) in chosen { settings += "export \(key)=\(value)\n" }
try PolicyTestSupport.write(settings, to: productPath)
let bin = root.appendingPathComponent("bin")
try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
func executable(_ path: URL, _ content: String) throws {
try PolicyTestSupport.write(content, to: path)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path)
}
for name in ["git", "gh", "security", "xcrun", "swiftc", "ssh", "cloudflared", "sleep"] {
try executable(bin.appendingPathComponent(name), interactiveStub)
}
let dev = bin.appendingPathComponent("fixture-dev")
try executable(dev, interactiveBinary)
let cached = root.appendingPathComponent(".local/share/parcel/launch/keychain")
try FileManager.default.createDirectory(
at: cached.deletingLastPathComponent(), withIntermediateDirectories: true)
try executable(cached, "#!/bin/bash\ntouch \"$HOME/cached-used\"\nexit 99\n")
try FileManager.default.setAttributes(
[.modificationDate: Date(timeIntervalSince1970: 4_000_000_000)], ofItemAtPath: cached.path)
let temporary = root.appendingPathComponent("tmp")
let site = root.appendingPathComponent("site with spaces")
for path in [temporary, site] {
try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true)
}
let credentialPath = root.appendingPathComponent("fixture credential")
if credential == "regular" {
try PolicyTestSupport.write("hidden-fixture-secret", to: credentialPath)
} else if credential == "symlink" {
try FileManager.default.createSymbolicLink(at: credentialPath, withDestinationURL: cached)
}
let log = root.appendingPathComponent("commands.log")
try PolicyTestSupport.write("", to: log)
var version = "0.1.0"
if let index = arguments.firstIndex(of: "--version"), index + 1 < arguments.count {
version = arguments[index + 1]
}
var env = ProcessInfo.processInfo.environment
env["PATH"] = bin.path + ":" + (env["PATH"] ?? "/usr/bin:/bin")
env["HOME"] = root.path
env["TMPDIR"] = temporary.path
env["LAUNCH_STUB_LOG"] = log.path
env["LAUNCH_STUB_COMMIT"] = interactiveCommit
env["LAUNCH_STUB_RUNS"] = try runs()
env["LAUNCH_STUB_PRODUCT"] = chosen["PRODUCT_NAME"]
env["LAUNCH_STUB_VERSION"] = version
env["PARCEL_LAUNCH_POLL_ATTEMPTS"] = "2"
env["PARCEL_DEV_BINARY"] = dev.path
env["LAUNCH_REAL_DEV_BINARY"] = try PolicyTestSupport.binary.path
env.removeValue(forKey: "BASH_ENV")
env.removeValue(forKey: "ENV")
env.merge(overrides) { _, new in new }
var master: Int32 = -1
var slave: Int32 = -1
guard openpty(&master, &slave, nil, nil, nil) == 0 else { throw DevError("openpty failed: \(errno)") }
defer { close(master) }
let terminal = FileHandle(fileDescriptor: slave, closeOnDealloc: true)
var initialAttributes = termios()
guard tcgetattr(master, &initialAttributes) == 0 else { throw DevError("PTY attributes failed: \(errno)") }
if !initialEchoEnabled {
initialAttributes.c_lflag &= ~tcflag_t(ECHO)
guard tcsetattr(master, TCSANOW, &initialAttributes) == 0 else {
throw DevError("Could not set PTY attributes: \(errno)")
}
}
let process = Process()
let termination = DispatchSemaphore(value: 0)
process.terminationHandler = { _ in termination.signal() }
process.executableURL = URL(fileURLWithPath: "/bin/bash")
process.arguments = [scripts.appendingPathComponent("launch.sh").path, "--site-repo", site.path] + arguments
process.environment = env
process.standardInput = terminal
process.standardOutput = terminal
process.standardError = terminal
try process.run()
defer {
if process.isRunning { kill(process.processIdentifier, SIGKILL) }
process.waitUntilExit()
}
try terminal.close()
var output = Data()
var pending = ""
var declined: [String] = []
var stoppedAtSecretPrompt = false
while true {
try Task.checkCancellation()
var descriptor = pollfd(fd: master, events: Int16(POLLIN | POLLHUP), revents: 0)
let ready = poll(&descriptor, 1, 100)
if ready < 0 {
if errno == EINTR { continue }
throw DevError("PTY poll failed: \(errno)")
}
if ready == 0 { continue }
var buffer = [UInt8](repeating: 0, count: 8192)
let size = read(master, &buffer, buffer.count)
if size <= 0 {
if size < 0 && errno != EIO { throw DevError("PTY read failed: \(errno)") }
break
}
let chunk = Data(buffer.prefix(size))
output.append(chunk)
pending += String(decoding: chunk, as: UTF8.self)
func send(_ value: String) throws {
let bytes = Array((value + "\n").utf8)
let written = bytes.withUnsafeBytes { Darwin.write(master, $0.baseAddress, $0.count) }
guard written == bytes.count else { throw DevError("PTY write failed: \(errno)") }
}
if let range = pending.range(of: "[y/N] ") {
let prompt =
(String(pending[..> 8 == SIGSTOP else {
throw DevError("Launch did not pause at the hidden input prompt")
}
stoppedAtSecretPrompt = true
}
var attributes = termios()
guard tcgetattr(master, &attributes) == 0 else { throw DevError("PTY attributes failed: \(errno)") }
guard attributes.c_lflag & tcflag_t(ECHO) == 0 else {
throw DevError("Hidden input prompt appeared before terminal echo was disabled")
}
if paused, kill(process.processIdentifier, SIGCONT) != 0 {
throw DevError("Could not resume launch: \(errno)")
}
if interruptHiddenInput {
guard kill(process.processIdentifier, SIGTERM) == 0 else {
throw DevError("Could not interrupt launch: \(errno)")
}
} else {
try send(pending.contains("Repeat ") ? repeated : "hidden-fixture-secret")
}
pending = ""
} else if pending.contains("Path to the exported credential file: ") {
try send(credentialPath.path)
pending = ""
}
}
while termination.wait(timeout: .now() + .milliseconds(100)) == .timedOut {
try Task.checkCancellation()
}
var finalAttributes = termios()
guard tcgetattr(master, &finalAttributes) == 0 else { throw DevError("PTY attributes failed: \(errno)") }
#expect(finalAttributes.c_lflag & tcflag_t(ECHO) == initialAttributes.c_lflag & tcflag_t(ECHO))
let text = String(decoding: output, as: UTF8.self)
let commands = try String(contentsOf: log, encoding: .utf8)
#expect(!(text + commands).contains("hidden-fixture-secret"))
#expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("cached-used").path))
#expect(try FileManager.default.contentsOfDirectory(atPath: temporary.path).isEmpty)
for prompt in declined { #expect(text.contains("Skipped: " + prompt), "\(prompt)\n\(text)") }
for command in ["git remote ", "gh api --method ", "gh secret delete ", "gh repo create "] {
#expect(!commands.contains(command))
}
if commands.contains("swiftc ") {
#expect(commands.components(separatedBy: "swiftc ").count == 2 && !commands.contains(cached.path))
}
return InteractiveResult(status: process.terminationStatus, text: text, log: commands)
}
private func expect(
_ result: InteractiveResult, _ status: Int32, _ text: String = "", log: String? = nil, absent: String? = nil
) {
#expect(result.status == status, "\(result.text)\n\(result.log)")
#expect(text.isEmpty || result.text.contains(text), "Expected: \(text)\nOutput: \(result.text)\n\(result.log)")
if let log { #expect(result.log.contains(log), "\(result.log)") }
if let absent { #expect(!result.log.contains(absent), "\(result.log)") }
}
@Test func hiddenPromptDisablesEchoBeforeAcceptingInput() throws {
let result = try run(
["Prepare DEVELOPER_ID_PASSWORD"], ["LAUNCH_STUB_MISSING_LOCAL": "1"], pauseBeforeSecretRead: true)
expect(result, 3, log: "helper put ")
}
@Test func hiddenInputPreservesDisabledEcho() throws {
let result = try run(
["Prepare DEVELOPER_ID_PASSWORD"], ["LAUNCH_STUB_MISSING_LOCAL": "1"], initialEchoEnabled: false)
expect(result, 3, log: "helper put ")
}
@Test(arguments: [false, true]) func interruptingHiddenInputRestoresTerminalEcho(initialEchoEnabled: Bool) throws {
let result = try run(
["Prepare DEVELOPER_ID_PASSWORD"], ["LAUNCH_STUB_MISSING_LOCAL": "1"],
interruptHiddenInput: true, initialEchoEnabled: initialEchoEnabled)
expect(result, 143, "Launch summary", absent: "helper put ")
}
@Test func confirmationsSecretsAndResume() throws {
for attempts in ["", "0", "-1", "61", "1.5", "01", "999999999999999999999999"] {
let result = try run([], ["PARCEL_LAUNCH_POLL_ATTEMPTS": attempts])
expect(result, 1, "Polling attempts must be an integer from 1 to 60")
#expect(result.log.isEmpty)
}
let skipped = try run()
expect(skipped, 3, "Launch incomplete (exit 3)", absent: "gh ")
#expect(!skipped.text.contains("Launch complete."))
#expect(skipped.text.components(separatedBy: "Incomplete (required):").count == 5)
for step in [
"Set DEVELOPER_ID_P12 in GitHub environment release (local preparation skipped)",
"Set MIRROR_TOKEN in GitHub environment mirror (local preparation skipped)",
"Download signed release evidence (release CI wait skipped)",
] { #expect(skipped.text.contains(step)) }
let accept = ["Prepare DEVELOPER_ID_PASSWORD", "Set DEVELOPER_ID_PASSWORD"]
let uploaded = try run(accept)
expect(uploaded, 3, log: "gh secret set DEVELOPER_ID_PASSWORD", absent: "git push ")
#expect(uploaded.log.contains("--env release"))
for override in [["LAUNCH_STUB_NO_REVIEW": "1"], ["LAUNCH_STUB_RELEASE_POLICY": "*"]] {
expect(try run(accept, override), 1, absent: "gh secret set ")
}
expect(
try run(accept, ["LAUNCH_STUB_FAIL_SECRET": "1"]), 1, "run the same command to resume", absent: "git push ")
expect(
try run(accept, ["LAUNCH_STUB_KEYCHAIN_ERROR": "1"]), 1, "Could not read DEVELOPER_ID_PASSWORD",
absent: "gh secret set ")
let prompted = try run(accept, ["LAUNCH_STUB_MISSING_LOCAL": "1"])
expect(prompted, 3, log: "helper put ")
#expect(prompted.log.contains("gh secret set "))
expect(
try run(accept, ["LAUNCH_STUB_MISSING_LOCAL": "1"], repeated: "wrong"), 1, "Values do not match",
absent: "helper put ")
expect(try run(["Prepare DEVELOPER_ID_PASSWORD"]), 3, absent: "gh secret set ")
for same in [true, false] {
expect(
try run(["Create release tag"], ["LAUNCH_STUB_TAG": same ? interactiveCommit : "different"]),
same ? 3 : 1, same ? "" : "Existing tag points to another commit", absent: "git push ")
}
expect(try run(["Create release tag"], ["LAUNCH_STUB_NO_LOCAL_TAG": "1"]), 3, log: "git tag -a v0.1.0")
let replace = ["Prepare DEVELOPER_ID_PASSWORD", "Replace DEVELOPER_ID_PASSWORD", "Set DEVELOPER_ID_PASSWORD"]
let replacement = try run(replace, arguments: ["--replace-secret", "DEVELOPER_ID_PASSWORD"])
expect(replacement, 3, log: "helper replace ")
#expect(replacement.log.contains("gh secret set "))
expect(
try run(replace, arguments: ["--replace-secret", "DEVELOPER_ID_PASSWORD"], repeated: "wrong"), 1,
"Values do not match", absent: "helper replace ")
expect(
try run(["Prepare DEVELOPER_ID_PASSWORD"], arguments: ["--replace-secret", "DEVELOPER_ID_PASSWORD"]), 1,
"Replacement cancelled", absent: "helper replace ")
expect(
try run(["Create or reuse the Sparkle key"], ["LAUNCH_STUB_PUBLIC": "different"]), 1, "refusing rotation",
absent: "gh secret set ")
let sparkle = try run(["Create or reuse the Sparkle key", "Set SPARKLE_PRIVATE_KEY"])
expect(sparkle, 3, log: "helper get https://sparkle-project.org")
#expect(sparkle.log.contains("--env release"))
let mirror = try run(["Prepare MIRROR_TOKEN", "Set MIRROR_TOKEN"])
expect(
mirror, 3, log: "gh secret set MIRROR_TOKEN --repo vinnymac/parcel --env mirror", absent: "--env release")
#expect(!mirror.text.contains("Pipelines/Secrets"))
#expect(
try #require(mirror.log.range(of: "/environments/mirror/deployment-branch-policies")).lowerBound
< #require(mirror.log.range(of: "gh secret set MIRROR_TOKEN")).lowerBound)
expect(
try run(["Prepare MIRROR_TOKEN", "Set MIRROR_TOKEN"], ["LAUNCH_STUB_MIRROR_POLICY": "*"]), 1,
absent: "gh secret set ")
for name in ["DEVELOPER_ID_P12", "ASC_PRIVATE_KEY"] {
for credential in ["regular", "symlink", "missing"] {
let result = try run(
["Prepare " + name, "Set " + name], ["LAUNCH_STUB_MISSING_LOCAL": "1"], credential: credential)
expect(result, credential == "regular" ? 3 : 1)
#expect(result.log.contains("helper put ") == (credential == "regular"))
if name == "DEVELOPER_ID_P12" && credential == "regular" {
#expect(result.text.contains("Skipped: Delete the exported .p12"))
}
}
}
}
@Test func releasePoliciesBlockPublicationUntilVerified() throws {
let failures: [([String: String], String)] = [
(["LAUNCH_STUB_MISSING_SECRET": "1"], "Missing"),
(["LAUNCH_STUB_MISSING_MIRROR_SECRET": "1"], "MIRROR_TOKEN"),
(["LAUNCH_STUB_UNTRUSTED": "1"], "ancestor of GitHub main"),
(["LAUNCH_STUB_FAIL_FETCH": "1"], "refusing existing tag mismatch"),
(["LAUNCH_STUB_NO_REVIEW": "1"], "require the repository owner"),
(["LAUNCH_STUB_RELEASE_POLICY": "v*", "LAUNCH_STUB_POLICY_TYPE": "tag"], "only branch main"),
(["LAUNCH_STUB_MIRROR_POLICY": "*"], "only branch main"), (["LAUNCH_STUB_ALLOW_FORCE": "true"], "force"),
(["LAUNCH_STUB_FAIL_BRANCH_READ": "1"], "Could not read default branch protection"),
(["LAUNCH_STUB_TAG_ENFORCEMENT": "disabled"], "tag ruleset"),
(["LAUNCH_STUB_DUPLICATE_RULESET": "1"], "exactly one release-tags"),
(
["LAUNCH_STUB_DEFAULT_BRANCH": "other", "LAUNCH_STUB_BRANCH_RULESET": "1"],
"default branch must be main"
),
(["LAUNCH_STUB_FAIL_REPO_SECRETS": "1"], "Launch stopped"),
]
for (override, message) in failures {
let result = try run(["Push v"], override)
#expect(result.status != 0 && result.status != 3)
#expect(result.text.contains(message), "\(result.text)")
#expect(!result.log.contains("git push "))
#expect(result.text.contains("run the same command to resume"))
}
let pushed = try run(["Push v"])
expect(pushed, 3, log: "git push ")
let push = try #require(pushed.log.range(of: "git push"))
for check in [
"--env release --json name", "--env mirror --json name", "--repo vinnymac/parcel --json name",
"merge-base --is-ancestor", "/branches/main/protection",
] {
#expect(try #require(pushed.log.range(of: check)).lowerBound < push.lowerBound)
}
let fetch = try #require(pushed.log.split(separator: "\n").first(where: { $0.hasPrefix("git fetch ") }))
#expect(
fetch.contains("refs/heads/main:refs/remotes/github/main refs/tags/v*:refs/tags/v*")
&& !fetch.contains("--force"))
expect(
try run(["Push v"], ["LAUNCH_STUB_BRANCH_RULESET": "1", "LAUNCH_STUB_FAIL_BRANCH_READ": "1"]), 3,
log: "git push ", absent: "/branches/main/protection")
expect(
try run(
["Push v"], ["LAUNCH_STUB_BRANCH_RULESET": "1", "LAUNCH_STUB_BRANCH_RULE_INCLUDE": "refs/heads/other"]),
3, "not sufficient default branch protection", log: "/branches/main/protection")
for name in [
"DEVELOPER_ID_P12", "DEVELOPER_ID_PASSWORD", "DEVELOPER_ID_IDENTITY", "APPLE_TEAM_ID", "ASC_PRIVATE_KEY",
"ASC_KEY_ID", "ASC_ISSUER_ID", "SPARKLE_PRIVATE_KEY", "APPLE_ID", "APPLE_APP_PASSWORD",
"SPARKLE_PUBLIC_KEY", "MIRROR_TOKEN",
] {
let result = try run(["Push v"], ["LAUNCH_STUB_REPO_SECRETS": "[{\"name\":\"\(name)\"}]"])
expect(result, 1, name, absent: "git push ")
#expect(!result.text.contains("WARNING:"))
}
expect(
try run(["Inspect repository-level"], ["LAUNCH_STUB_REPO_SECRETS": #"[{"name":"MIRROR_TOKEN"}]"#]), 1,
"MIRROR_TOKEN", absent: "gh secret delete ")
}
@Test func releaseRunsMatchAndDispatchWithoutDuplicates() throws {
let wait = ["Wait for GitHub release"]
let rerun = try run(wait + ["Rerun failed jobs"], ["LAUNCH_STUB_CONCLUSION": "failure"])
expect(rerun, 3, log: "gh run rerun 42")
let rerunRange = try #require(rerun.log.range(of: "gh run rerun"))
let attemptRange = try #require(rerun.log.range(of: "--json attempt", options: .backwards))
let watchRange = try #require(rerun.log.range(of: "gh run watch"))
#expect(rerunRange.lowerBound < attemptRange.lowerBound && attemptRange.lowerBound < watchRange.lowerBound)
for conclusion in ["failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale"] {
expect(try run(wait, ["LAUNCH_STUB_CONCLUSION": conclusion]), 1, absent: "gh run rerun ")
}
for (override, message) in [
(["LAUNCH_STUB_FAIL_WATCH": "1"], "Launch stopped"),
(["LAUNCH_STUB_FINAL_CONCLUSION": "failure"], "has not succeeded"),
(["LAUNCH_STUB_CONCLUSION": "unexpected"], "Unexpected release CI conclusion"),
(["LAUNCH_STUB_REMOTE_TAG": "different"], "GitHub release tag must match"),
] {
expect(try run(wait, override), 1, message, absent: "gh run download ")
}
expect(
try run(
wait + ["Rerun failed jobs"], ["LAUNCH_STUB_CONCLUSION": "failure", "LAUNCH_STUB_STUCK_ATTEMPT": "1"]),
1, "new attempt did not start", absent: "gh run watch ")
var wrong = try PolicyTestSupport.json(runs()).requireArray()
let base = try #require(wrong.first).requireObject()
for (id, key, value): (Double, String, String) in [
(1, "displayTitle", "Release v0.1.1"), (2, "headBranch", "v0.1.0"), (3, "event", "push"),
] {
var record = base
record["databaseId"] = .number(id)
record[key] = .string(value)
wrong.insert(.object(record), at: 0)
}
let matched = try run(
wait, ["LAUNCH_STUB_RUNS": String(decoding: DevJSON.array(wrong).encoded(), as: UTF8.self)])
expect(matched, 3, log: "gh run watch 42", absent: "gh run watch 1 ")
let listing = try #require(matched.log.split(separator: "\n").first(where: { $0.hasPrefix("gh run list ") }))
#expect(
listing.contains("--event workflow_dispatch --branch main") && !listing.contains("--commit")
&& listing.contains("displayTitle"))
expect(
try run(wait, ["LAUNCH_STUB_RUNS": runs(id: .bool(true))]), 1, "invalid database ID",
absent: "gh run watch ")
expect(try run(wait, ["LAUNCH_STUB_EMPTY_RUNS": "1"]), 1, "did not appear", absent: "gh workflow run ")
let dispatch = wait + ["Dispatch "]
let dispatched = try run(dispatch, ["LAUNCH_STUB_EMPTY_RUNS": "1"])
expect(dispatched, 3, log: "gh workflow run release.yml --repo vinnymac/parcel --ref main -f tag=v0.1.0")
let dispatchRange = try #require(dispatched.log.range(of: "gh workflow run"))
for check in ["--env mirror --json name", "merge-base --is-ancestor"] {
#expect(try #require(dispatched.log.range(of: check)).lowerBound < dispatchRange.lowerBound)
}
expect(
try run(dispatch, ["LAUNCH_STUB_EMPTY_RUNS": "1", "LAUNCH_STUB_RUN_RACE": "1"]), 3,
"no duplicate was dispatched", absent: "gh workflow run ")
expect(
try run(
dispatch, ["LAUNCH_STUB_EMPTY_RUNS": "1", "LAUNCH_STUB_REPO_SECRETS": #"[{"name":"MIRROR_TOKEN"}]"#]),
1, "MIRROR_TOKEN", absent: "gh workflow run ")
}
@Test func requiredSummaryEvidenceAndCleanup() throws {
let complete = ["Push v", "Wait for GitHub release", "Download the signed", "Publish the appcast"]
let finished = try run(complete)
expect(finished, 0, "Launch complete.", log: "feed ", absent: "gh workflow run ")
#expect(
!finished.text.contains("Incomplete (required):")
&& finished.text.components(separatedBy: "Completed:").count == 5)
#expect(finished.text.contains("Skipped: Prepare DEVELOPER_ID_PASSWORD"))
for (prefixes, message) in [
(Array(complete.dropLast()), "Publish the verified appcast"),
(Array(complete.prefix(2)), "Download signed release evidence"),
(Array(complete.dropFirst()), "Publish the release tag"),
] {
let result = try run(prefixes)
expect(result, 3, "Incomplete (required): " + message)
#expect(!result.text.contains("Launch complete."))
}
for (override, message) in [
(["LAUNCH_STUB_MISSING_ARTIFACT": "1"], "no appcast.xml"),
(["LAUNCH_STUB_MISSING_ARCHIVE": "1"], "lacks its DMG"),
(["LAUNCH_STUB_FAIL_FEED": "1"], "fixture feed verification failed"),
(["LAUNCH_STUB_SITE_ROOT": "/elsewhere"], "own repository root"),
(["LAUNCH_STUB_FAIL_PUSH": "1"], "Launch stopped"),
] {
let result = try run(complete, override)
expect(result, 1, message)
#expect(!result.text.contains("Launch complete."))
}
let renamed = try run(
complete, ["LAUNCH_STUB_RUNS": runs(title: "Release v2.3.4")], arguments: ["--version", "2.3.4"],
product: [
"PRODUCT_NAME": "Crate", "PRODUCT_GITHUB_REPO": "example/crate",
"PRODUCT_BUNDLE_ID": "org.example.crate",
])
expect(renamed, 0, "v2.3.4", log: "Crate-2.3.4.dmg")
#expect(renamed.log.contains("--repo example/crate"))
expect(try run([], ["LAUNCH_STUB_FAIL_COMPILE": "1"]), 70, "Launch summary", absent: "helper ")
expect(try run(interrupt: "Prepare DEVELOPER_ID_PASSWORD"), 143, "Launch summary", absent: "git push ")
expect(
try run(["Inspect the GitHub mirror"], ["LAUNCH_STUB_FAIL_REPO_VIEW": "1"]), 1, "no repository was created")
expect(try run(["Inspect release/mirror"]), 3, log: "/environments/mirror", absent: "git push ")
let access = try run(["Check GitHub login", "Push main"])
expect(access, 3, log: "gh auth status")
#expect(access.log.contains("git ls-remote ") && access.log.contains("HEAD:refs/heads/main"))
}
}