# Safari iframe Sandbox Policy Regression Test

Canonical: https://figment.so/blog/mac-safari-iframe-sandbox-regression

Write a Playwright test.each matrix that maps each iframe sandbox token combination to an expected allow or block result, and run it against WebKit on macOS. Sandbox enforcement is engine-level, so an Intel Mac VM is enough.

**Build the regression suite as a Playwright `test.each`-style matrix, run it against WebKit on a macOS host, and keep one row per sandbox token combination.** Sandbox enforcement is engine-level, not CPU-level, so the same test logic runs on an Intel or an Apple silicon Mac.

## Why does Safari break sandboxed iframes silently?

The [HTML Living Standard](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-sandbox) defines 13 `sandbox` tokens for `<iframe>`. Every current browser implements them, but WebKit's enforcement details diverge from Chromium in ways that surface in production without a dedicated regression suite.

The spec is explicit about two traps:

- Sandbox flags only take effect when the iframe navigates. Removing or changing the `sandbox` attribute on an already-loaded frame has no effect, so your fixture must set the attribute **before** the iframe is inserted or its `src` changes.
- Setting both `allow-scripts` and `allow-same-origin` on a same-origin child lets that child remove the `sandbox` attribute and reload itself, effectively escaping the sandbox. The spec calls this a security antipattern. Cover it as a row in the matrix, and do not rely on it as a default.

A parameterized Playwright run against WebKit on macOS turns this class of bug into a one-line CI failure the moment a token combination regresses.

## Which sandbox tokens need their own row?

Five of the 13 tokens carry most of the regression risk. The spec lists `allow-downloads`, `allow-forms`, `allow-modals`, `allow-orientation-lock`, `allow-pointer-lock`, `allow-popups`, `allow-popups-to-escape-sandbox`, `allow-presentation`, `allow-same-origin`, `allow-scripts`, `allow-top-navigation`, `allow-top-navigation-by-user-activation` and `allow-top-navigation-to-custom-protocols`.

| Token | Re-enables | Why it needs its own row |
|---|---|---|
| `allow-scripts` | JavaScript execution | Parent-context assumptions fail without it |
| `allow-forms` | Form submission | Enforced independently of script permission |
| `allow-same-origin` | Real origin instead of opaque | With `allow-scripts` the sandbox is effectively off; keep it as an explicit row |
| `allow-popups` | `window.open`, `target=_blank` | `window.open` returns `null` when missing |
| `allow-top-navigation-by-user-activation` | Parent navigation on user gesture | Programmatic top navigation stays blocked |

Because post-load changes are a no-op, build the iframe element, set `sandbox`, set `src`, then append, in that order.

## What HTML fixtures do I need?

Serve two static files from the same origin so `allow-same-origin` tests exercise a real same-origin relationship, not an `about:blank` host. Fixture 1 is the iframe content. Fixture 2 is the host page the test loads.

```html
<!-- fixtures/frame.html -->
<!DOCTYPE html>
<html>
<head><title>Sandbox fixture</title></head>
<body>
  <form id="f" action="/echo" method="POST">
    <input name="x" value="1">
    <button type="submit" id="submit-btn">Submit</button>
  </form>
  <script>
    window.parent.postMessage({ event: 'script-executed' }, '*');
  </script>
</body>
</html>
```

```html
<!-- fixtures/host.html -->
<!DOCTYPE html>
<html>
<head><title>Sandbox host</title></head>
<body></body>
</html>
```

The host page is empty on purpose: the test creates the iframe in-page so it controls the exact attribute order.

## How do I write the parameterized matrix?

Give each row the `sandbox` attribute string, whether a `script-executed` postMessage should arrive, and whether a POST to `/echo` should fire. The test clicks the submit button directly instead of calling `form.submit()` from inside the frame, so the form row is not entangled with the script row.

```typescript
// tests/sandbox-regression.spec.ts
import { test, expect } from '@playwright/test';

type SandboxRow = {
  sandbox: string;
  expectScript: boolean;
  expectForm: boolean;
  label: string;
};

const matrix: SandboxRow[] = [
  { sandbox: '',                                            expectScript: true,  expectForm: true,  label: 'no-sandbox'          },
  { sandbox: 'allow-scripts allow-forms',                   expectScript: true,  expectForm: true,  label: 'scripts-and-forms'   },
  { sandbox: 'allow-scripts',                               expectScript: true,  expectForm: false, label: 'scripts-only'        },
  { sandbox: 'allow-forms',                                 expectScript: false, expectForm: true,  label: 'forms-only'          },
  { sandbox: 'allow-same-origin',                           expectScript: false, expectForm: false, label: 'same-origin-only'    },
  { sandbox: 'allow-same-origin allow-scripts',             expectScript: true,  expectForm: false, label: 'same-origin-scripts' },
  { sandbox: 'allow-scripts allow-forms allow-same-origin', expectScript: true,  expectForm: true,  label: 'all-three'           },
];

for (const row of matrix) {
  test(`[${row.label}] script=${row.expectScript} form=${row.expectForm}`, async ({ page }, testInfo) => {
    let formPosted = false;
    await page.route('**/echo', route => {
      formPosted = true;
      return route.fulfill({ status: 200, body: 'ok' });
    });

    await page.goto('http://localhost:3000/host.html');

    const scriptPromise = page.evaluate((sandboxAttr: string) => {
      return new Promise<boolean>(resolve => {
        const handler = (e: MessageEvent) => {
          if ((e.data as { event?: string })?.event === 'script-executed') {
            window.removeEventListener('message', handler);
            resolve(true);
          }
        };
        window.addEventListener('message', handler);

        const iframe = document.createElement('iframe');
        iframe.id = 'sandbox-frame';
        if (sandboxAttr) iframe.setAttribute('sandbox', sandboxAttr);
        iframe.src = '/frame.html';
        document.body.appendChild(iframe);

        setTimeout(() => resolve(false), 2500);
      });
    }, row.sandbox);

    try {
      await page.frameLocator('#sandbox-frame')
        .locator('#submit-btn')
        .click({ timeout: 1500 });
    } catch {
      // A missing allow-forms (or allow-scripts, depending on the row) can block the
      // navigation; formPosted stays false unless the POST actually reaches the route.
    }

    await page.waitForTimeout(500);
    const scriptFired = await scriptPromise;

    expect(scriptFired, `script signal for [${row.label}]`).toBe(row.expectScript);
    expect(formPosted, `form POST for [${row.label}]`).toBe(row.expectForm);

    const screenshotPath = testInfo.outputPath(`${row.label}.png`);
    await page.screenshot({ path: screenshotPath });
    await testInfo.attach(`screenshot-${row.label}`, {
      path: screenshotPath,
      contentType: 'image/png',
    });
  });
}
```

This is reference code to adapt, not a benchmark we executed. Run it against your real fixtures and change expectations only when your installed WebKit version demonstrably disagrees. The rows encode the spec, which is the correct starting point, and any deviation you observe is the regression this suite exists to catch.

## How do I configure Playwright for WebKit on macOS?

Target the `webkit` project on macOS. Per [Playwright's browsers documentation](https://playwright.dev/docs/browsers), Playwright's WebKit is built from the upstream WebKit main branch with Playwright patches. It is not the branded Safari binary, and Playwright recommends running WebKit on macOS for the closest-to-Safari behavior because media codecs and platform integrations differ by OS. If you need the exact shipping Safari (for example to reproduce a bug a customer only sees in Safari.app), drive the real Safari binary on the same Mac over WebDriver and keep the Playwright suite as your fast first line.

Pin the Playwright version in `package.json` and record `npx playwright --version` in each CI log so a WebKit bump is visible when a matrix row flips.

```typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  webServer: {
    command: 'npx serve ./fixtures -p 3000',
    port: 3000,
    reuseExistingServer: !process.env.CI,
  },
  projects: [
    { name: 'webkit-macos', use: { ...devices['Desktop Safari'] } },
  ],
});
```

Install the WebKit browser once with `npx playwright install webkit`. A Linux WebKit run is useful as a smoke check but is not a substitute for macOS, because platform-level WebKit behavior is what breaks Safari users.

## How do I check one row by hand?

Walk one row manually in Safari before you trust the automated matrix, so you have a human baseline:

1. Serve the `fixtures/` directory on `http://localhost:3000/` and open it in Safari in a remote desktop session on the Mac.
2. Load `host.html`. Open the Web Inspector console (Develop menu).
3. Paste the iframe-creation snippet for `sandbox="allow-same-origin"` and press Enter. Confirm no `script-executed` postMessage logs and the form submit button does not navigate when clicked.
4. Repeat for `allow-scripts allow-forms`. Confirm the message does log and the submit button triggers a POST. The Playwright route is not active here, so you will see a 404 to `/echo`, and that 404 is the signal the POST fired.
5. Save a screenshot of each Web Inspector run and compare it to the Playwright per-row screenshots. Any row where manual Safari and Playwright WebKit disagree is a lead on a Playwright-versus-Safari divergence worth filing.

## Which failures does the matrix catch first?

Two rows usually fail first.

**Row `allow-same-origin` with no `allow-scripts`.** Parent-page handlers that assume they can drive the iframe through same-origin DOM access fail here. Fix: add `allow-scripts` if the parent legitimately needs scripted interaction, or stop reaching into `contentDocument` and use `postMessage` with `allow-scripts`.

**Row `allow-scripts` without `allow-forms`.** Inline scripts run, but a programmatic `form.submit()` and a user click on the submit button both stop at the navigation boundary. Fix: add `allow-forms`, or POST via `fetch` from the parent frame on the child's behalf.

Add a new row every time your app embeds a new third-party widget, such as a payment iframe, survey or comment thread. Each embed gets its own token combination, so a vendor change cannot regress your form flow silently.

## How do I run the suite in CI?

Run it from a self-hosted Mac runner and upload the HTML report on every run:

```yaml
# .github/workflows/safari-sandbox.yml
name: Safari sandbox regression
on: [push, pull_request]
jobs:
  webkit:
    runs-on: [self-hosted, macos]   # your Figment Mac runner
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx playwright install webkit
      - run: npx playwright test --project=webkit-macos --reporter=html
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
```

The HTML report uploads on every run, including failures, with per-row screenshots. Keep this runner behind a private repo or restrict `pull_request` triggers to trusted forks. A self-hosted macOS runner executes whatever workflow a PR brings in, so public-repo exposure is a direct code-execution risk on the Mac. If the repo must be public, prefer ephemeral runners that are destroyed after each job.

## How much Mac does a WebKit iframe sandbox matrix need?

The Intel Mac VM ($25 a month, $2 a day) runs macOS Sequoia and is enough for a WebKit sandbox matrix. Choose the Apple Silicon Mac VM ($39 a month, $6 a day) if the same machine must also run the iOS Simulator with Xcode 26.4 or later, which needs macOS Tahoe. Both VMs use shared vCPUs and give you administrator access to your own VM. We have not measured this suite on any plan. See the [Mac hosting plans](/mac-hosting).

**Related testing guides:**
- [Safari ITP Cookie Block Test](/blog/mac-safari-itp-cookie-block-test)
- [macOS Notification Permission UITest](/blog/mac-notification-permission-uitest)
- [GitHub Actions Self-Hosted Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
