# iOS Simulator ATS Exception Verification Test

Canonical: https://figment.so/blog/mac-simulator-ats-exception-test

ATS rules come from the app's Info.plist, so build one scheme per configuration, send a URLSession request from an XCTest, and record whether it returned an HTTP status, an ATS block (-1022) or another error. Attach the result as JSON.

**Build one scheme per ATS configuration, drive a `URLSession` request from an XCTest, and record whether the response was an HTTP status, an ATS block (`NSURLErrorDomain` code `-1022`), or a different network error.** App Transport Security (ATS) decisions are read from the running app's `Info.plist`, not toggled at runtime, so a per-scheme test is the only honest way to prove which exception keys permit which loads. This article gives you a compact XCTest and a fill-in worksheet you can paste into a review packet.

## Which ATS keys must the test cover?

Cover one row per key you actually set, plus a control row with no exceptions at all. The authoritative list lives on Apple's [`NSAppTransportSecurity` property-list reference](https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity).

| Key | Scope | Effect worth asserting |
|---|---|---|
| `NSAllowsArbitraryLoads` | Global | Disables ATS for everything that does not have a per-domain entry |
| `NSAllowsArbitraryLoadsInMedia` | Global, `AVFoundation` only | HTTP media loads via `AVFoundation`; does not affect `URLSession` |
| `NSAllowsArbitraryLoadsInWebContent` | Global, `WKWebView` only | HTTP in web views; **does not affect `URLSession`** |
| `NSAllowsLocalNetworking` | Global | Permits unqualified hostnames and `.local` without a per-domain block |
| `NSExceptionDomains` | Container | Dictionary whose keys are domain strings |
| `NSExceptionAllowsInsecureHTTPLoads` | Per-domain | Permits HTTP for the listed domain |
| `NSIncludesSubdomains` | Per-domain | Extends the exception to subdomains of the listed domain |
| `NSExceptionMinimumTLSVersion` | Per-domain | Lowers the minimum TLS version for the listed domain |
| `NSExceptionRequiresForwardSecrecy` | Per-domain | Allows cipher suites without forward secrecy |
| `NSRequiresCertificateTransparency` | Per-domain | Requires CT logs for the listed domain |

Two keys cost the most review time. `NSAllowsArbitraryLoadsInWebContent` is expected to cover `URLSession`, and it does not. Per-domain entries that omit `NSIncludesSubdomains` silently miss API subdomains.

## Which endpoints can I assert against honestly?

Use two endpoints whose reachability you control. Otherwise an ATS block is indistinguishable from a DNS failure, a captive portal or a certificate error. Two options work well on an iOS Simulator running on a Mac:

1. **Local servers on the host**, reached through the Simulator's loopback. Add `NSAllowsLocalNetworking` (or a per-domain exception for `localhost`) when the scheme you are proving needs the local row to succeed.
2. **A domain you own** with a plain-HTTP vhost and a TLS vhost on the same name, published through DNS. This lets you prove the base-domain and subdomain rows for `NSIncludesSubdomains`.

If you use a local HTTPS listener with a self-signed certificate, install the root into the booted Simulator with `xcrun simctl keychain <device> add-root-cert <cert.pem>`, so a `URLSession` failure signals ATS rather than certificate-trust rejection. Record the Simulator runtime version you used. ATS behaviour for local networking has changed across major OS versions, so your evidence should pin each row to a runtime.

## What does the XCTest look like?

The example below is written for Xcode 16.4's XCTest and is **not an executed benchmark**. Replace the placeholders with endpoints your app actually hits, make sure the containing scheme's test-host `Info.plist` has the ATS keys you want to prove, and run the scheme locally before you rely on the asserted outcomes. The async pattern follows Apple's [`XCTestExpectation` reference](https://developer.apple.com/documentation/xctest/xctestexpectation).

```swift
// ATSTruthTableTests.swift
import XCTest

final class ATSTruthTableTests: XCTestCase {

    struct ATSRow: Encodable {
        let scheme: String
        let label: String
        let url: String
        let expected: String   // "allow" or "block"
        let observed: String   // "allow", "ats-block", or "other-error"
        let httpStatus: Int?
        let errorDomain: String?
        let errorCode: Int?
    }

    // Supply these from the scheme's environment variables.
    // Each scheme supplies its own matrix matching its Info.plist keys.
    private func matrix() -> [(label: String, url: String, expectAllow: Bool)] {
        let env = ProcessInfo.processInfo.environment
        let httpHost  = env["ATS_HTTP_HOST"]  ?? "localhost:8080"
        let httpsHost = env["ATS_HTTPS_HOST"] ?? "localhost:8443"
        return [
            ("control-https", "https://\(httpsHost)/ping", true),
            ("control-http",  "http://\(httpHost)/ping",   false),
        ]
    }

    func testATSTruthTable() throws {
        let schemeName = ProcessInfo.processInfo.environment["ATS_SCHEME"] ?? "ATSDefault"
        let session = URLSession(configuration: .ephemeral)
        var rows: [ATSRow] = []

        for tc in matrix() {
            guard let url = URL(string: tc.url) else {
                XCTFail("Invalid URL: \(tc.url)"); continue
            }
            let done = XCTestExpectation(description: "load \(tc.label)")
            var observed = "other-error"
            var status: Int? = nil
            var errDomain: String? = nil
            var errCode: Int? = nil

            let task = session.dataTask(with: url) { _, response, error in
                defer { done.fulfill() }
                if let http = response as? HTTPURLResponse {
                    observed = "allow"
                    status = http.statusCode
                } else if let e = error as NSError? {
                    errDomain = e.domain
                    errCode = e.code
                    if e.domain == NSURLErrorDomain && e.code == -1022 {
                        observed = "ats-block"
                    }
                }
            }
            task.resume()
            wait(for: [done], timeout: 15)

            rows.append(ATSRow(
                scheme: schemeName, label: tc.label, url: tc.url,
                expected: tc.expectAllow ? "allow" : "block",
                observed: observed, httpStatus: status,
                errorDomain: errDomain, errorCode: errCode
            ))

            // Only assert ATS behaviour. An "other-error" row is logged but
            // neither passes nor fails: fix the endpoint and re-run.
            if observed != "other-error" {
                XCTAssertEqual(
                    observed == "allow", tc.expectAllow,
                    "ATS mismatch [\(tc.label)]: expected \(tc.expectAllow ? "allow" : "block"), observed \(observed)"
                )
            }
        }

        let encoder = JSONEncoder()
        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
        let data = try encoder.encode(rows)
        let attachment = XCTAttachment(
            uniformTypeIdentifier: "public.json",
            name: "ats-truth-table-\(schemeName).json",
            payload: data
        )
        attachment.lifetime = .keepAlways
        add(attachment)
    }
}
```

Read these points twice:

- The `other-error` branch means the row is not usable evidence. A DNS failure, a TLS trust failure and a timeout all land there. Fix the endpoint before you claim ATS proved anything.
- Only `-1022` in `NSURLErrorDomain` counts as an ATS block. Other codes (for example `-1200` secure-connection-failed) can be a trust-store or TLS-negotiation problem rather than an ATS decision.
- A per-scheme `ATS_SCHEME` variable keeps the attachment filenames distinct, so `xcrun xcresulttool merge` output is easy to diff.

## How do I cover the key matrix and fill in the worksheet?

Build one scheme per configuration and reuse the same test class, because ATS keys live in the app's `Info.plist`. For each scheme, run the test once on your target Simulator runtime and paste the filled worksheet into the review packet.

| Scheme | Test-host `Info.plist` keys | Row to prove |
|---|---|---|
| `ATSDefault` | none | `control-http` → `ats-block` ; `control-https` → `allow` |
| `ATSArbitraryLoads` | `NSAllowsArbitraryLoads = true` | `control-http` → `allow` |
| `ATSPerDomain` | `NSExceptionDomains[your.host].NSExceptionAllowsInsecureHTTPLoads = true` | `http://your.host` → `allow` ; `http://other.host` → `ats-block` |
| `ATSSubdomains` | Above plus `NSIncludesSubdomains = true` | `http://api.your.host` → `allow` |
| `ATSWebContentOnly` | `NSAllowsArbitraryLoadsInWebContent = true` | `URLSession` HTTP → still `ats-block` |
| `ATSTLSFloor` | `NSExceptionMinimumTLSVersion = TLSv1.2` for `your.host` | TLS 1.1 endpoint → `ats-block` ; TLS 1.2 → `allow` |

Fill these worksheet rows per run and attach them beside the `xcresult`:

- Xcode version and build (`xcodebuild -version`): _______
- Simulator runtime (device + iOS version): _______
- Scheme name: _______
- `ATS_HTTP_HOST` / `ATS_HTTPS_HOST`: _______
- For each matrix row (label, observed, httpStatus, errorDomain, errorCode): _______
- Reviewer sign-off and date: _______

Run each scheme in CI, merge the attached JSON with `xcrun xcresulttool merge`, and commit the merged truth table alongside your review notes. The merged JSON and a signed worksheet are the artifact reviewers can diff between releases.

## When does the Intel Mac VM fit an ATS Simulator test?

The Intel Mac VM ($25 a month, $2 a day) fits when your project builds with Xcode 26.3 or earlier and a Simulator runtime that still supports Intel. Per Apple's [porting-to-Apple-silicon guide](https://developer.apple.com/documentation/apple-silicon/porting-your-macos-apps-to-apple-silicon.md), Xcode on an Intel processor stops at an earlier release, and not every current Simulator runtime supports Intel, so check the Xcode release notes for the exact pair. The Apple Silicon Mac VM ($39 a month, $6 a day) is the fit for Xcode 26.4 or later, visionOS or arm64-only runtimes. Both VMs use shared vCPUs and give you administrator access to your own VM, and macOS versions are shown before purchase. See the [Mac hosting plans](/mac-hosting).

**Related testing guides:**
- [Safari and Firefox Regression Matrix](/blog/mac-safari-firefox-regression-matrix)
- [Safari Crash Log Evidence Collection](/blog/mac-safari-crash-log-evidence)
- [GitHub Actions Self-Hosted Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
