RadrootsAppIdentifierAdmissionTests.swift (10136B)
1 import Darwin 2 import Foundation 3 import Testing 4 5 @testable import RadrootsKit 6 7 private let invalidAppComponents = [ 8 "", " \n", ".", "..", "../retained", "nested/name", "/absolute", "name\0suffix", 9 ] 10 11 @Test(arguments: invalidAppComponents) 12 func appIdentifierNormalizerRejectsInvalidComponents(_ identifier: String) { 13 #expect(throws: RadrootsAppleFileError.invalidRequest) { 14 _ = try RadrootsAppleFileRoots.normalizedAppIdentifier(identifier) 15 } 16 } 17 18 @Test(arguments: invalidAppComponents) 19 func appIdentifierConstructorRejectsInvalidComponents(_ identifier: String) { 20 let root = URL(fileURLWithPath: "/owned-app-identifier-fixture", isDirectory: true) 21 #expect(throws: RadrootsAppleFileError.invalidRequest) { 22 _ = try RadrootsAppleFileRoots( 23 appIdentifier: identifier, dataRoot: root, cacheRoot: root, temporaryRoot: root 24 ) 25 } 26 } 27 28 @Test(arguments: invalidAppComponents) 29 func appIdentifierContainerRefusesBeforeFilesystemAccess(_ identifier: String) throws { 30 try withOwnedAppIdentifierFixture { manager, _ in 31 #expect(throws: RadrootsAppleFileError.invalidRequest) { 32 _ = try RadrootsAppleFileRoots.appContainer( 33 appIdentifier: identifier, fileManager: manager) 34 } 35 #expect(manager.counts.lookups == 0) 36 #expect(manager.counts.removals == 0) 37 try expectAppIdentifierMarkersPreserved(manager) 38 } 39 } 40 41 @Test(arguments: invalidAppComponents) 42 func appIdentifierResetRefusesBeforeFilesystemAccess(_ identifier: String) throws { 43 try withOwnedAppIdentifierFixture { manager, _ in 44 #expect(throws: RadrootsAppLocalStateResetError.invalidRequest) { 45 try RadrootsAppLocalStateReset.clearApplicationSupport( 46 appIdentifier: identifier, fileManager: manager 47 ) 48 } 49 #expect(manager.counts.lookups == 0) 50 #expect(manager.counts.removals == 0) 51 try expectAppIdentifierMarkersPreserved(manager) 52 } 53 } 54 55 @Test(arguments: [ 56 "org.radroots.tests", "valid_app", "a..b", ".owned", "local app", "récolte", "literal\\name", 57 ]) 58 func appIdentifierNormalizerPreservesValidComponents(_ identifier: String) throws { 59 #expect(try RadrootsAppleFileRoots.normalizedAppIdentifier(" \(identifier) \n") == identifier) 60 } 61 62 @Test func appIdentifierContainerPreservesTrimmedSuffixes() throws { 63 try withOwnedAppIdentifierFixture { manager, _ in 64 let roots = try RadrootsAppleFileRoots.appContainer( 65 appIdentifier: " valid_app ", fileManager: manager 66 ) 67 #expect(roots.appIdentifier == "valid_app") 68 #expect( 69 roots.dataRoot 70 == manager.supportRoot.appendingPathComponent("valid_app", isDirectory: true)) 71 #expect( 72 roots.cacheRoot 73 == manager.cacheRoot.appendingPathComponent("valid_app", isDirectory: true)) 74 #expect( 75 roots.temporaryRoot 76 == manager.fixtureRoot.appendingPathComponent("tmp/valid_app", isDirectory: true)) 77 #expect(manager.counts.lookups == 3) 78 #expect(manager.counts.removals == 0) 79 try expectAppIdentifierMarkersPreserved(manager) 80 } 81 } 82 83 @Test func appIdentifierResetRemovesOnlyItsTrimmedChild() throws { 84 try withOwnedAppIdentifierFixture { manager, marker in 85 try RadrootsAppLocalStateReset.clearApplicationSupport( 86 appIdentifier: " valid_app ", fileManager: manager 87 ) 88 #expect(!FileManager.default.fileExists(atPath: manager.appMarker.path)) 89 #expect(try Data(contentsOf: manager.retainedMarker) == marker) 90 #expect(manager.counts.lookups == 1) 91 #expect(manager.counts.removals == 1) 92 } 93 } 94 95 @Test func appIdentifierResetClassifiesLookupFailureWithoutRemoval() throws { 96 try withOwnedAppIdentifierFixture(failLookup: true) { manager, _ in 97 #expect(throws: RadrootsAppLocalStateResetError.fileSystemFailure) { 98 try RadrootsAppLocalStateReset.clearApplicationSupport( 99 appIdentifier: "valid_app", fileManager: manager 100 ) 101 } 102 #expect(manager.counts.lookups == 1) 103 #expect(manager.counts.removals == 0) 104 try expectAppIdentifierMarkersPreserved(manager) 105 } 106 } 107 108 @Test func appIdentifierFixtureCountersRemainSynchronized() async throws { 109 // The fake only returns immutable owned URLs; this exercises its counter lock. 110 let root = FileManager.default.temporaryDirectory 111 .appendingPathComponent("radroots-app-id-counts-\(UUID().uuidString)", isDirectory: true) 112 let manager = OwnedAppIdentifierFileManager(root: root, failLookup: false) 113 try await withThrowingTaskGroup(of: Void.self) { group in 114 for _ in 0..<32 { 115 group.addTask { @Sendable [manager] in 116 _ = try manager.url( 117 for: .applicationSupportDirectory, in: .userDomainMask, 118 appropriateFor: nil, create: true 119 ) 120 } 121 } 122 try await group.waitForAll() 123 } 124 #expect(manager.counts.lookups == 32) 125 #expect(manager.counts.removals == 0) 126 } 127 128 private final class OwnedAppIdentifierFileManager: FileManager, @unchecked Sendable { 129 // Each case owns its immutable URLs. All mutable counters use this lock, 130 // which is released before Foundation operations; the race case covers it. 131 private let lock = NSLock() 132 private var lookups = 0 133 private var removals = 0 134 private let failLookup: Bool 135 let fixtureRoot: URL 136 let supportRoot: URL 137 let cacheRoot: URL 138 139 init(root: URL, failLookup: Bool) { 140 fixtureRoot = root 141 supportRoot = root.appendingPathComponent("support", isDirectory: true) 142 cacheRoot = root.appendingPathComponent("cache", isDirectory: true) 143 self.failLookup = failLookup 144 super.init() 145 } 146 147 var appMarker: URL { supportRoot.appendingPathComponent("valid_app/marker") } 148 var retainedMarker: URL { fixtureRoot.appendingPathComponent("retained/marker") } 149 150 var counts: (lookups: Int, removals: Int) { 151 lock.lock() 152 defer { lock.unlock() } 153 return (lookups, removals) 154 } 155 156 override var temporaryDirectory: URL { 157 recordLookup() 158 return fixtureRoot.appendingPathComponent("tmp", isDirectory: true) 159 } 160 161 override func url( 162 for directory: SearchPathDirectory, in domain: SearchPathDomainMask, 163 appropriateFor url: URL?, create shouldCreate: Bool 164 ) throws -> URL { 165 recordLookup() 166 guard !failLookup, domain == .userDomainMask, url == nil, shouldCreate else { 167 throw OwnedAppIdentifierFixtureError.refused 168 } 169 switch directory { 170 case .applicationSupportDirectory: return supportRoot 171 case .cachesDirectory: return cacheRoot 172 default: throw OwnedAppIdentifierFixtureError.refused 173 } 174 } 175 176 override func removeItem(at url: URL) throws { 177 let selected = url.standardizedFileURL.path 178 let allowed = [ 179 supportRoot.appendingPathComponent("valid_app").standardizedFileURL.path, 180 fixtureRoot.appendingPathComponent("retained").standardizedFileURL.path, 181 ] 182 guard allowed.contains(selected) else { throw OwnedAppIdentifierFixtureError.refused } 183 lock.lock() 184 removals += 1 185 lock.unlock() 186 try super.removeItem(at: url) 187 } 188 189 private func recordLookup() { 190 lock.lock() 191 lookups += 1 192 lock.unlock() 193 } 194 } 195 196 private enum OwnedAppIdentifierFixtureError: Error { case refused } 197 private let appIdentifierMarkerBytes = Data("owned-fixture-v1".utf8) 198 199 private func withOwnedAppIdentifierFixture( 200 failLookup: Bool = false, 201 body: (OwnedAppIdentifierFileManager, Data) throws -> Void 202 ) throws { 203 let root = FileManager.default.temporaryDirectory 204 .appendingPathComponent("radroots-app-id-\(UUID().uuidString)", isDirectory: true) 205 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) 206 let canonical = try #require(root.path.withCString { Darwin.realpath($0, nil) }) 207 defer { Darwin.free(canonical) } 208 let manager = OwnedAppIdentifierFileManager( 209 root: URL(fileURLWithPath: String(cString: canonical), isDirectory: true), 210 failLookup: failLookup) 211 do { 212 for suffix in ["support/valid_app", "cache", "tmp", "retained"] { 213 try FileManager.default.createDirectory( 214 at: manager.fixtureRoot.appendingPathComponent(suffix, isDirectory: true), 215 withIntermediateDirectories: true 216 ) 217 } 218 try appIdentifierMarkerBytes.write(to: manager.appMarker) 219 try appIdentifierMarkerBytes.write(to: manager.retainedMarker) 220 try expectAppIdentifierFixtureBounds(manager.fixtureRoot) 221 try body(manager, appIdentifierMarkerBytes) 222 try expectAppIdentifierFixtureBounds(manager.fixtureRoot) 223 try FileManager.default.removeItem(at: root) 224 } catch { 225 try FileManager.default.removeItem(at: root) 226 throw error 227 } 228 #expect(!FileManager.default.fileExists(atPath: root.path)) 229 } 230 231 private func expectAppIdentifierMarkersPreserved(_ manager: OwnedAppIdentifierFileManager) throws { 232 #expect((try? Data(contentsOf: manager.appMarker)) == appIdentifierMarkerBytes) 233 #expect((try? Data(contentsOf: manager.retainedMarker)) == appIdentifierMarkerBytes) 234 } 235 236 private func expectAppIdentifierFixtureBounds(_ root: URL) throws { 237 let keys: Set<URLResourceKey> = [.isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey] 238 let entries = try #require( 239 FileManager.default.enumerator(at: root, includingPropertiesForKeys: Array(keys))) 240 var directories = 1 241 var files = 0 242 var bytes = 0 243 for case let url as URL in entries { 244 let values = try url.resourceValues(forKeys: keys) 245 #expect(values.isSymbolicLink == false) 246 if values.isDirectory == true { 247 directories += 1 248 } else { 249 files += 1 250 bytes += values.fileSize ?? 0 251 } 252 } 253 #expect(directories <= 6) 254 #expect(files <= 4) 255 #expect(bytes <= 64) 256 }