Atomic save in the Mac App Sandbox: the sibling temp file fails
If you save safely in a sandboxed Mac app by writing a temp file next to the target and swapping it into place, the sandbox refuses to create the temp file. In my testing that held in Downloads, Desktop, Documents, and every other folder I picked. In Purrchiver the error read “Could not open … for writing”. The same code passes every test, because the tests don’t run in the sandbox. This is how saving an edited archive in Purrchiver went from truncating files, to failing outright, to working.
The first bug: libarchive truncates on open
Purrchiver can edit an existing archive and save it back over the original.
The writer is libarchive, and archive_write_open_filename opens its output
with O_WRONLY | O_CREAT | O_TRUNC as soon as the writer is created. Two
problems came from that:
- An interrupted save destroys the original. A crash, a cancel, a full disk: whatever had been flushed so far is all that’s left of the file.
- Saving over the archive you’re reading from yields empty entries. To keep the entries you didn’t touch, Purrchiver copies them straight from the source archive into the new one. The writer opened, and so truncated, the output before the reader had read anything. When output and source were the same file, the reader found a zero-byte file and the new archive came out with zero-byte entries.
The answer was the textbook one: write the new archive somewhere else, check it, then replace the original in one step.
The textbook fix: a sibling temp file
The usual way to do that is a hidden temp file in the same directory, then
FileManager.replaceItemAt(_:withItemAt:). The same directory keeps both
files on one volume, so the swap is a single atomic rename, not a copy and
delete. Purrchiver also ran its verify step on the temp file before swapping,
so a bad write never replaced a good archive. Four tests covered it: a failed
verify leaves the original untouched, a good write replaces it, a new path
still gets a file, and a failure leaves no temp file behind. All green.
Then I tried it in the app.
Why it fails in the sandbox
In the App Sandbox, NSSavePanel and NSOpenPanel extend access to the
exact file the user picked. Not its folder. A sibling such as
.purrchiver-save-<uuid>-Archive.zip was never granted, so libarchive’s
open() on it was denied, and saving to Downloads, Desktop, or Documents
failed every time.
The tests missed it because Swift package tests run in an unsandboxed test host. There, any folder you can write to in Terminal is writable, and a sibling temp file is fine.
What works: the item replacement directory
Foundation has a directory made for this:
let dir = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: destination, // a temp location on the same volume
create: true
)
let temp = dir.appendingPathComponent(destination.lastPathComponent)Asking for .itemReplacementDirectory appropriate for the destination gives
you a temporary directory on the same volume, which is what replaceItemAt
needs for an atomic swap. In the sandboxed app, writing there worked where the
sibling didn’t. I haven’t found Apple documentation that spells out the
sandbox rule. All I can say is that it holds for every folder I tested.
The save now plans its write in three cases:
- Overwriting an existing file: write to the item replacement directory,
run verify on the temp,
replaceItemAtonto the destination, then remove the temp directory.replaceItemAtconsumes the temp file but leaves its directory behind, so a cleanup step removes the directory whether the save succeeded or not. - Creating a new file: write straight to the path the user picked. That path is granted, and there’s no original to protect, so a temp file and swap would add nothing. If the write fails, the partial file is deleted. That’s safe only because it didn’t exist before the save.
- Split volumes (
Archive.7z.001,.002, …): written directly too. A set of files can’t be swapped atomically, and splitting is only offered when creating a new archive, so again there’s no original to lose.
A unit test now checks the plan itself: in the overwrite case, the temp file must not be in the destination’s folder. That test fails under the old design whether or not the test host is sandboxed.
A related trap: don’t touch the save panel’s URL
A few days earlier, the plain Create Archive flow failed with the same “Could
not open … for writing” message. The save panel had been shown with a name
like Archive, and the code then called appendPathExtension("zip") on the
URL it returned. Archive.zip isn’t the path the user confirmed, so the
sandbox didn’t cover it.
The fix is to put the full name in the panel before showing it, and to use the returned URL exactly as it comes back:
panel.nameFieldStringValue = "\(baseName).\(ext)"
// ...
if panel.runModal() == .OK, let url = panel.url {
try write(to: url) // never append, rename, or rebuild this URL
}If the user deletes the extension in the panel, they get a file without one. Purrchiver picks the format from your choice in the sheet, not from the filename, so the file still writes correctly.
What to take away
- In the sandbox, a save or open panel grants access to one exact path. Any path you derive from it, whether a sibling, a renamed copy, or an added extension, isn’t granted.
- For atomic replace, write into
.itemReplacementDirectoryappropriate for the destination, thenreplaceItemAt. Remove the directory afterwards. - If there’s no original to protect, write directly. A temp file and swap only adds places to fail.
- Package tests run unsandboxed. Anything that touches the file system outside your container needs a check that doesn’t depend on the test host, or a run in the signed, sandboxed app.