Search code examples
objective-cmacoscocoaappkitappstore-sandbox

Internal sandbox error in a document-based app


I have a sandboxed document-based (NSDocument) app. When saving files, I get weird sandboxing errors:

[scoped] handle 0: sandbox_extension_release error [22: Invalid argument]
[scoped] <0x600001278f00 file:///Users/username/Testi%203.exampletext>: internal sandbox error for <StopAccessing>

I'm also fetching file attributes for recent files using recentDocumentURLs in document controller, and display them in NSOutlineView. When I've accessed enough files, I start getting a new sandbox error, sandbox_extension_consume returned 12, and after that sandbox sometimes blocks the app from accessing any files.

This even happens when creating a minimal document-based app from the Xcode template. Things get saved correctly, and I can access the files I want, but errors start stacking up.

Here is a sample project which reproduces the behavior:
https://www.dropbox.com/s/9v0v65jbqkjb7ra/Sandboxed%20Doc%20App.zip?dl=1

Create a new document (window only shows the basic template, to keep it minimal) and save it. Sandbox error is immediately logged.

Document subclass in the sample is as bare bones as possible:

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
    return [_string dataUsingEncoding:NSUTF8StringEncoding];
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
    _string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return YES;
}

AFAIK, NSDocumentController should support sandboxing without any subclassing. Also, trying to manually stop accessing scoped bookmark of the document URL (after saving or on document close) produces an error.

Similar sandbox bug is referred to on Twitter, but I'm hardly accessing couple of files, and not over 4000.

What am I doing wrong, or is this a macOS Big Sur bug? And if not, how can it be present even in the document-based app template?


Solution

  • The issue here was that my app was requesting the list of recent files from NSDocumentController, and checking the edited dated by once again requesting that same list.

    There seems to be a limit for how many files the app can rapidly access outside its sandbox, even if it has the permission to do so, and sandbox quickly runs out of extensions.

    To fix the issue, check your code for anything that runs through a list of files and accesses them.