commit 69c1b1eb114bc603fc19e61386f5a27a2e3b2180
parent d6b568213bf8d32fa79d8e94a78076a0b5b0e5d2
Author: triesap <tyson@radroots.org>
Date: Wed, 14 Oct 2026 05:42:06 +0000
files: Refuse invalid application directory components
- Share single-component admission across file roots and local reset.
- Reject invalid names before filesystem access with stable typed errors.
- Retain owned negative, valid, failure and synchronized fixture cases.
- Verify formatting, all 322 tests, exact public API and supply chain.
Diffstat:
4 files changed, 290 insertions(+), 17 deletions(-)
diff --git a/README b/README
@@ -40,6 +40,13 @@ guarded migration overload; a mismatch fails before import or legacy deletion.
Cancelled custody requests cannot use a later successful presence callback to
authorize another effect. Cancellation does not roll back an already committed key.
+## Application directories
+
+File-root construction and local-state reset require a nonempty trimmed app
+identifier containing one Apple filesystem component. Slash, NUL and complete
+`.` or `..` components fail with `invalidRequest` before filesystem access.
+Valid Unicode, spaces, dots within names and literal backslashes are preserved.
+
## Copyright
Except as otherwise noted, all files in the `apple_kit` distribution are
diff --git a/Sources/RadrootsKit/RadrootsAppLocalStateReset.swift b/Sources/RadrootsKit/RadrootsAppLocalStateReset.swift
@@ -23,20 +23,23 @@ public enum RadrootsAppLocalStateReset {
appIdentifier: String,
fileManager: FileManager = .default
) throws {
- let trimmed = appIdentifier.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else {
+ let normalizedAppIdentifier: String
+ do {
+ normalizedAppIdentifier = try RadrootsAppleFileRoots.normalizedAppIdentifier(
+ appIdentifier)
+ } catch {
throw RadrootsAppLocalStateResetError.invalidRequest
}
do {
- let root = try fileManager.url(
- for: .applicationSupportDirectory,
- in: .userDomainMask,
- appropriateFor: nil,
- create: true
- ).appendingPathComponent(trimmed, isDirectory: true)
- if fileManager.fileExists(atPath: root.path) {
- try fileManager.removeItem(at: root)
- }
+ let root = try fileManager.url(
+ for: .applicationSupportDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true
+ ).appendingPathComponent(normalizedAppIdentifier, isDirectory: true)
+ if fileManager.fileExists(atPath: root.path) {
+ try fileManager.removeItem(at: root)
+ }
} catch let error as RadrootsAppLocalStateResetError {
throw error
} catch {
diff --git a/Sources/RadrootsKit/RadrootsAppleFileRoots.swift b/Sources/RadrootsKit/RadrootsAppleFileRoots.swift
@@ -20,7 +20,8 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
let normalizedAppIdentifier = try Self.normalizedAppIdentifier(appIdentifier)
let normalizedDataRoot = try Self.normalizedRootURL(dataRoot, field: "dataRoot")
let normalizedCacheRoot = try Self.normalizedRootURL(cacheRoot, field: "cacheRoot")
- let normalizedTemporaryRoot = try Self.normalizedRootURL(temporaryRoot, field: "temporaryRoot")
+ let normalizedTemporaryRoot = try Self.normalizedRootURL(
+ temporaryRoot, field: "temporaryRoot")
self.appIdentifier = normalizedAppIdentifier
self.dataRoot = normalizedDataRoot
self.cacheRoot = normalizedCacheRoot
@@ -58,7 +59,8 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
create: true
)
)
- let dataRoot = dataBaseURL.appendingPathComponent(normalizedAppIdentifier, isDirectory: true)
+ let dataRoot = dataBaseURL.appendingPathComponent(
+ normalizedAppIdentifier, isDirectory: true)
let cacheRoot = cacheBaseURL.appendingPathComponent(
normalizedAppIdentifier, isDirectory: true
)
@@ -107,7 +109,8 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
}
let components = try Self.normalizedRelativeComponents(trimmedPath)
- let candidateURL = components.isEmpty
+ let candidateURL =
+ components.isEmpty
? rootURL : rootURL.appendingPathComponent(components.joined(separator: "/"))
if candidateURL.path == rootURL.path {
if allowRootDirectory {
@@ -131,7 +134,9 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
guard !components.isEmpty else { throw RadrootsAppleFileError.invalidRequest }
components.removeLast()
} else {
- guard !component.utf8.contains(0) else { throw RadrootsAppleFileError.invalidRequest }
+ guard !component.utf8.contains(0) else {
+ throw RadrootsAppleFileError.invalidRequest
+ }
components.append(String(component))
}
}
@@ -147,7 +152,9 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
public static func normalizedAppIdentifier(_ appIdentifier: String) throws -> String {
let trimmed = appIdentifier.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else {
+ guard !trimmed.isEmpty, trimmed != ".", trimmed != "..",
+ !trimmed.contains("/"), !trimmed.utf8.contains(0)
+ else {
throw RadrootsAppleFileError.invalidRequest
}
return trimmed
@@ -178,7 +185,7 @@ public struct RadrootsAppleFileRoots: Sendable, Equatable {
private static func canonicalExistingDirectory(_ directory: URL) throws -> URL {
guard directory.isFileURL,
- let pointer = directory.path.withCString({ Darwin.realpath($0, nil) })
+ let pointer = directory.path.withCString({ Darwin.realpath($0, nil) })
else {
throw RadrootsAppleFileError.permanentFailure
}
diff --git a/Tests/RadrootsKitTests/RadrootsAppIdentifierAdmissionTests.swift b/Tests/RadrootsKitTests/RadrootsAppIdentifierAdmissionTests.swift
@@ -0,0 +1,256 @@
+import Darwin
+import Foundation
+import Testing
+
+@testable import RadrootsKit
+
+private let invalidAppComponents = [
+ "", " \n", ".", "..", "../retained", "nested/name", "/absolute", "name\0suffix",
+]
+
+@Test(arguments: invalidAppComponents)
+func appIdentifierNormalizerRejectsInvalidComponents(_ identifier: String) {
+ #expect(throws: RadrootsAppleFileError.invalidRequest) {
+ _ = try RadrootsAppleFileRoots.normalizedAppIdentifier(identifier)
+ }
+}
+
+@Test(arguments: invalidAppComponents)
+func appIdentifierConstructorRejectsInvalidComponents(_ identifier: String) {
+ let root = URL(fileURLWithPath: "/owned-app-identifier-fixture", isDirectory: true)
+ #expect(throws: RadrootsAppleFileError.invalidRequest) {
+ _ = try RadrootsAppleFileRoots(
+ appIdentifier: identifier, dataRoot: root, cacheRoot: root, temporaryRoot: root
+ )
+ }
+}
+
+@Test(arguments: invalidAppComponents)
+func appIdentifierContainerRefusesBeforeFilesystemAccess(_ identifier: String) throws {
+ try withOwnedAppIdentifierFixture { manager, _ in
+ #expect(throws: RadrootsAppleFileError.invalidRequest) {
+ _ = try RadrootsAppleFileRoots.appContainer(
+ appIdentifier: identifier, fileManager: manager)
+ }
+ #expect(manager.counts.lookups == 0)
+ #expect(manager.counts.removals == 0)
+ try expectAppIdentifierMarkersPreserved(manager)
+ }
+}
+
+@Test(arguments: invalidAppComponents)
+func appIdentifierResetRefusesBeforeFilesystemAccess(_ identifier: String) throws {
+ try withOwnedAppIdentifierFixture { manager, _ in
+ #expect(throws: RadrootsAppLocalStateResetError.invalidRequest) {
+ try RadrootsAppLocalStateReset.clearApplicationSupport(
+ appIdentifier: identifier, fileManager: manager
+ )
+ }
+ #expect(manager.counts.lookups == 0)
+ #expect(manager.counts.removals == 0)
+ try expectAppIdentifierMarkersPreserved(manager)
+ }
+}
+
+@Test(arguments: [
+ "org.radroots.tests", "valid_app", "a..b", ".owned", "local app", "récolte", "literal\\name",
+])
+func appIdentifierNormalizerPreservesValidComponents(_ identifier: String) throws {
+ #expect(try RadrootsAppleFileRoots.normalizedAppIdentifier(" \(identifier) \n") == identifier)
+}
+
+@Test func appIdentifierContainerPreservesTrimmedSuffixes() throws {
+ try withOwnedAppIdentifierFixture { manager, _ in
+ let roots = try RadrootsAppleFileRoots.appContainer(
+ appIdentifier: " valid_app ", fileManager: manager
+ )
+ #expect(roots.appIdentifier == "valid_app")
+ #expect(
+ roots.dataRoot
+ == manager.supportRoot.appendingPathComponent("valid_app", isDirectory: true))
+ #expect(
+ roots.cacheRoot
+ == manager.cacheRoot.appendingPathComponent("valid_app", isDirectory: true))
+ #expect(
+ roots.temporaryRoot
+ == manager.fixtureRoot.appendingPathComponent("tmp/valid_app", isDirectory: true))
+ #expect(manager.counts.lookups == 3)
+ #expect(manager.counts.removals == 0)
+ try expectAppIdentifierMarkersPreserved(manager)
+ }
+}
+
+@Test func appIdentifierResetRemovesOnlyItsTrimmedChild() throws {
+ try withOwnedAppIdentifierFixture { manager, marker in
+ try RadrootsAppLocalStateReset.clearApplicationSupport(
+ appIdentifier: " valid_app ", fileManager: manager
+ )
+ #expect(!FileManager.default.fileExists(atPath: manager.appMarker.path))
+ #expect(try Data(contentsOf: manager.retainedMarker) == marker)
+ #expect(manager.counts.lookups == 1)
+ #expect(manager.counts.removals == 1)
+ }
+}
+
+@Test func appIdentifierResetClassifiesLookupFailureWithoutRemoval() throws {
+ try withOwnedAppIdentifierFixture(failLookup: true) { manager, _ in
+ #expect(throws: RadrootsAppLocalStateResetError.fileSystemFailure) {
+ try RadrootsAppLocalStateReset.clearApplicationSupport(
+ appIdentifier: "valid_app", fileManager: manager
+ )
+ }
+ #expect(manager.counts.lookups == 1)
+ #expect(manager.counts.removals == 0)
+ try expectAppIdentifierMarkersPreserved(manager)
+ }
+}
+
+@Test func appIdentifierFixtureCountersRemainSynchronized() async throws {
+ // The fake only returns immutable owned URLs; this exercises its counter lock.
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("radroots-app-id-counts-\(UUID().uuidString)", isDirectory: true)
+ let manager = OwnedAppIdentifierFileManager(root: root, failLookup: false)
+ try await withThrowingTaskGroup(of: Void.self) { group in
+ for _ in 0..<32 {
+ group.addTask { @Sendable [manager] in
+ _ = try manager.url(
+ for: .applicationSupportDirectory, in: .userDomainMask,
+ appropriateFor: nil, create: true
+ )
+ }
+ }
+ try await group.waitForAll()
+ }
+ #expect(manager.counts.lookups == 32)
+ #expect(manager.counts.removals == 0)
+}
+
+private final class OwnedAppIdentifierFileManager: FileManager, @unchecked Sendable {
+ // Each case owns its immutable URLs. All mutable counters use this lock,
+ // which is released before Foundation operations; the race case covers it.
+ private let lock = NSLock()
+ private var lookups = 0
+ private var removals = 0
+ private let failLookup: Bool
+ let fixtureRoot: URL
+ let supportRoot: URL
+ let cacheRoot: URL
+
+ init(root: URL, failLookup: Bool) {
+ fixtureRoot = root
+ supportRoot = root.appendingPathComponent("support", isDirectory: true)
+ cacheRoot = root.appendingPathComponent("cache", isDirectory: true)
+ self.failLookup = failLookup
+ super.init()
+ }
+
+ var appMarker: URL { supportRoot.appendingPathComponent("valid_app/marker") }
+ var retainedMarker: URL { fixtureRoot.appendingPathComponent("retained/marker") }
+
+ var counts: (lookups: Int, removals: Int) {
+ lock.lock()
+ defer { lock.unlock() }
+ return (lookups, removals)
+ }
+
+ override var temporaryDirectory: URL {
+ recordLookup()
+ return fixtureRoot.appendingPathComponent("tmp", isDirectory: true)
+ }
+
+ override func url(
+ for directory: SearchPathDirectory, in domain: SearchPathDomainMask,
+ appropriateFor url: URL?, create shouldCreate: Bool
+ ) throws -> URL {
+ recordLookup()
+ guard !failLookup, domain == .userDomainMask, url == nil, shouldCreate else {
+ throw OwnedAppIdentifierFixtureError.refused
+ }
+ switch directory {
+ case .applicationSupportDirectory: return supportRoot
+ case .cachesDirectory: return cacheRoot
+ default: throw OwnedAppIdentifierFixtureError.refused
+ }
+ }
+
+ override func removeItem(at url: URL) throws {
+ let selected = url.standardizedFileURL.path
+ let allowed = [
+ supportRoot.appendingPathComponent("valid_app").standardizedFileURL.path,
+ fixtureRoot.appendingPathComponent("retained").standardizedFileURL.path,
+ ]
+ guard allowed.contains(selected) else { throw OwnedAppIdentifierFixtureError.refused }
+ lock.lock()
+ removals += 1
+ lock.unlock()
+ try super.removeItem(at: url)
+ }
+
+ private func recordLookup() {
+ lock.lock()
+ lookups += 1
+ lock.unlock()
+ }
+}
+
+private enum OwnedAppIdentifierFixtureError: Error { case refused }
+private let appIdentifierMarkerBytes = Data("owned-fixture-v1".utf8)
+
+private func withOwnedAppIdentifierFixture(
+ failLookup: Bool = false,
+ body: (OwnedAppIdentifierFileManager, Data) throws -> Void
+) throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("radroots-app-id-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
+ let canonical = try #require(root.path.withCString { Darwin.realpath($0, nil) })
+ defer { Darwin.free(canonical) }
+ let manager = OwnedAppIdentifierFileManager(
+ root: URL(fileURLWithPath: String(cString: canonical), isDirectory: true),
+ failLookup: failLookup)
+ do {
+ for suffix in ["support/valid_app", "cache", "tmp", "retained"] {
+ try FileManager.default.createDirectory(
+ at: manager.fixtureRoot.appendingPathComponent(suffix, isDirectory: true),
+ withIntermediateDirectories: true
+ )
+ }
+ try appIdentifierMarkerBytes.write(to: manager.appMarker)
+ try appIdentifierMarkerBytes.write(to: manager.retainedMarker)
+ try expectAppIdentifierFixtureBounds(manager.fixtureRoot)
+ try body(manager, appIdentifierMarkerBytes)
+ try expectAppIdentifierFixtureBounds(manager.fixtureRoot)
+ try FileManager.default.removeItem(at: root)
+ } catch {
+ try FileManager.default.removeItem(at: root)
+ throw error
+ }
+ #expect(!FileManager.default.fileExists(atPath: root.path))
+}
+
+private func expectAppIdentifierMarkersPreserved(_ manager: OwnedAppIdentifierFileManager) throws {
+ #expect((try? Data(contentsOf: manager.appMarker)) == appIdentifierMarkerBytes)
+ #expect((try? Data(contentsOf: manager.retainedMarker)) == appIdentifierMarkerBytes)
+}
+
+private func expectAppIdentifierFixtureBounds(_ root: URL) throws {
+ let keys: Set<URLResourceKey> = [.isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey]
+ let entries = try #require(
+ FileManager.default.enumerator(at: root, includingPropertiesForKeys: Array(keys)))
+ var directories = 1
+ var files = 0
+ var bytes = 0
+ for case let url as URL in entries {
+ let values = try url.resourceValues(forKeys: keys)
+ #expect(values.isSymbolicLink == false)
+ if values.isDirectory == true {
+ directories += 1
+ } else {
+ files += 1
+ bytes += values.fileSize ?? 0
+ }
+ }
+ #expect(directories <= 6)
+ #expect(files <= 4)
+ #expect(bytes <= 64)
+}