From 53d6fbdaa1520cd89193c9e7a5e69194c2068a09 Mon Sep 17 00:00:00 2001 From: Gabor Sajo Date: Sat, 7 Nov 2026 00:18:13 -0600 Subject: [PATCH 1/7] Fix hybrid expiry, unsafe folder names and lock contention - An object in hybrid storage has one expiry, so the copy in memory can't outlive the file. MemoryConfig.expiry is only used by memory-only storage. - Refuse DiskConfig names that aren't a single folder, because purging or removeAll() could delete files outside the cache. - Encode and decode outside the locks, and serve memory hits without waiting for another object's disk access. - Document that objects should be read with the type they were written as. - Add tests that compare all kinds of storage, cover the config's default expiry and use storage from many threads. Run Thread Sanitizer in CI. --- .github/workflows/ci.yml | 8 + CHANGELOG.md | 16 ++ README.md | 8 +- Sources/Cache/Configuration/DiskConfig.swift | 1 + .../Cache/Configuration/MemoryConfig.swift | 3 +- Sources/Cache/Storage/DiskStorage.swift | 96 ++++--- Sources/Cache/Storage/HybridStorage.swift | 54 ++-- Sources/Cache/Storage/Storage.swift | 7 +- Tests/CacheTests/ConcurrencyTests.swift | 158 +++++++++++ Tests/CacheTests/ParityTests.swift | 266 ++++++++++++++++++ Tests/CacheTests/StorageTests.swift | 15 - Tests/CacheTests/TestSupport.swift | 116 +++++++- 12 files changed, 658 insertions(+), 90 deletions(-) create mode 100644 Tests/CacheTests/ConcurrencyTests.swift create mode 100644 Tests/CacheTests/ParityTests.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e92d36..0ca996c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,14 @@ jobs: - uses: actions/checkout@v7 - run: swift test + test-thread-sanitizer: + name: Test with Thread Sanitizer + runs-on: macos-26 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + - run: swift test --sanitize=thread + # File protection is only compiled for iOS and tvOS, so its tests only run here. test-ios: name: Test on the iOS Simulator diff --git a/CHANGELOG.md b/CHANGELOG.md index 143a0da..17b2a8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 5.0.1 + +Bug fixes +- With both disk and memory, an object could stay readable after its file expired, because the copy in memory used `MemoryConfig.expiry`. An object now has one expiry, and `entry(ofType:forKey:)` reports the same one from memory and from disk. +- A `DiskConfig` name that isn't a single folder is refused, because purging or `removeAll()` could delete files outside the cache. With an empty name, they emptied `directory` itself. `Storage` now throws `CocoaError(.fileWriteInvalidFileName)`. +- An object in memory no longer waits for disk access or encoding of another object. +- Encoding and decoding no longer hold any lock, so a slow `Codable` type doesn't hold up other objects, and its code can use the storage it's being saved in. + +Behaviour changes +- `MemoryConfig.expiry` is now only used by memory-only storage. With a disk, objects use the expiry from `DiskConfig`. +- A `DiskConfig` name with a `/`, like `"Images/Thumbnails"`, used to create nested folders and now throws. Pass the parent folder as `directory` instead. Use the same full path to keep what's already cached there. + +Other +- Documented that objects should be read with the type they were written as. On disk, `Data` returns a file's bytes without checking what was written, so an object written as `Data?` comes back as JSON. +- Added tests that compare all kinds of storage, cover the config's default expiry and use storage from many threads. CI also runs the tests with Thread Sanitizer. + ## 5.0.0 Removed diff --git a/README.md b/README.md index 25cd7ab..5ca0a7b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Stores `Codable & Sendable` values on disk, in memory, or both, with expiry. Thread safe. -Requires iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1. +Requires Swift 6.2, and iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1. ## Installation @@ -40,6 +40,8 @@ try storage.removeAll() let bytes = try storage.diskSize() ``` +Read an object with the type it was written as. With any other type, the result depends on the kind of storage. Files don't record their type, so a file may decode as another type if its JSON fits, and asking for `Data` returns the file's bytes as they are. That includes an object written as `Data?`, whose file holds JSON rather than the original bytes. + ## Configuration ```swift @@ -56,12 +58,16 @@ MemoryConfig( ) ``` +The name must be a single folder name. An empty name, `.`, `..` and anything with a `/` make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. + The folder must be used only by the storage: `removeExpiredObjects()` deletes every file in it that isn't one of its objects, whatever its age and hidden files included. ## Expiry `.never`, `.seconds(TimeInterval)` or `.date(Date)`. It's set by the config, or per object in `setObject`. +With both disk and memory, an object has one expiry, and the config's default comes from `DiskConfig`. `MemoryConfig.expiry` is only used by memory-only storage. + An expired object counts as missing, but its file stays on disk until `removeExpiredObjects()`. ## Errors diff --git a/Sources/Cache/Configuration/DiskConfig.swift b/Sources/Cache/Configuration/DiskConfig.swift index 0fb6e1a..0d42b68 100644 --- a/Sources/Cache/Configuration/DiskConfig.swift +++ b/Sources/Cache/Configuration/DiskConfig.swift @@ -2,6 +2,7 @@ import Foundation public struct DiskConfig: Sendable { /// The name of disk storage, this will be used as folder name within directory. + /// It must be a single folder name: `Storage` refuses an empty name, `.`, `..`, and anything with a `/`. /// The folder must be used only by this storage: `removeExpiredObjects()` deletes anything else in it. public let name: String /// Expiry date that will be applied by default for every added object diff --git a/Sources/Cache/Configuration/MemoryConfig.swift b/Sources/Cache/Configuration/MemoryConfig.swift index 40ce8a5..6032982 100644 --- a/Sources/Cache/Configuration/MemoryConfig.swift +++ b/Sources/Cache/Configuration/MemoryConfig.swift @@ -11,7 +11,8 @@ public struct MemoryConfig: Sendable { // MARK: Public /// Expiry date that will be applied by default for every added object - /// if it's not overridden in the `setObject(_:forKey:expiry:)` method + /// if it's not overridden in the `setObject(_:forKey:expiry:)` method. + /// Only used by memory-only storage. With a disk, objects use the expiry from `DiskConfig`. public let expiry: Expiry /// The maximum number of objects in memory the cache should hold. 0 means no limit. public let countLimit: UInt diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index 1f3ca39..6e428a4 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -6,6 +6,11 @@ final class DiskStorage: Sendable { // MARK: Lifecycle init(config: DiskConfig, fileManager: FileManager = FileManager.default) throws { + // First, because the folder gets emptied later on, and these names could point at someone else's + guard Self.isSingleFolderName(config.name) else { + throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: config.name]) + } + self.config = config self.fileManager = fileManager @@ -29,6 +34,9 @@ final class DiskStorage: Sendable { /// format can't be read any more, so it's never looked up and `removeExpiredObjects()` removes it. static let fileExtension = "cache" + /// Configuration + let config: DiskConfig + // MARK: Private private enum Error: Swift.Error { @@ -37,17 +45,16 @@ final class DiskStorage: Sendable { /// File manager to read/write to the disk (access protected by lock) private nonisolated(unsafe) let fileManager: FileManager - /// Configuration - private let config: DiskConfig /// The computed path `directory+name` private let path: String - /// Lock protecting all file I/O operations + /// Lock protecting all file I/O operations. Encoding and decoding stay outside of it, because + /// they run the type's own code, which may be slow or use this storage. private let lock = OSAllocatedUnfairLock() } extension DiskStorage: StorageAware { func entry(ofType type: T.Type, forKey key: String) throws -> Entry { - try self.lock.withLockUnchecked { + let (data, date) = try self.lock.withLockUnchecked { let filePath = makeFilePath(for: key) do { // The expiry comes first, so that an expired object isn't read or decoded @@ -59,38 +66,19 @@ extension DiskStorage: StorageAware { throw StorageError.notFound(key: key) } - let data = try Data(contentsOf: URL(fileURLWithPath: filePath)) - let object: T = if T.self == Data.self, let data = data as? T { - data - } - else { - try decode(data, forKey: key) - } - - return Entry(object: object, expiry: Expiry.date(date)) + return (try Data(contentsOf: URL(fileURLWithPath: filePath)), date) } catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { throw StorageError.notFound(key: key) } } + + let object: T = try decode(data, forKey: key) + return Entry(object: object, expiry: Expiry.date(date)) } func setObject(_ object: T, forKey key: String, expiry: Expiry? = nil) throws { - try self.lock.withLockUnchecked { - let expiry = expiry ?? self.config.expiry - - // Exactly `Data`, like when reading. `as? Data` alone would also unwrap a `Data?`. - let data: Data = if T.self == Data.self, let rawData = object as? Data { - rawData - } - else { - try encode(object, forKey: key) - } - - let filePath = makeFilePath(for: key) - try writeFile(data, atPath: filePath) - try self.fileManager.setAttributes([.modificationDate: expiry.date], ofItemAtPath: filePath) - } + try self.write(self.encode(object, forKey: key), forKey: key, expiry: expiry) } func existsObject(forKey key: String) throws -> Bool { @@ -154,7 +142,42 @@ extension DiskStorage: StorageAware { } } +/// The two halves of `setObject`, so that hybrid storage can encode before taking its own lock. +extension DiskStorage { + /// Wraps encoding failures in a `StorageError`, unless the type's own `Codable` code already threw one. + func encode(_ object: T, forKey key: String) throws -> Data { + // Exactly `Data`, like when reading. `as? Data` alone would also unwrap a `Data?`. + if T.self == Data.self, let data = object as? Data { + return data + } + + do { + return try DataSerializer.serialize(object: object) + } + catch let error as StorageError { + throw error + } + catch { + throw StorageError.encodingFailed(context: "DiskStorage: failed to encode object for key: \(key)", underlyingError: error) + } + } + + func write(_ data: Data, forKey key: String, expiry: Expiry?) throws { + try self.lock.withLockUnchecked { + let expiry = expiry ?? self.config.expiry + let filePath = makeFilePath(for: key) + try writeFile(data, atPath: filePath) + try self.fileManager.setAttributes([.modificationDate: expiry.date], ofItemAtPath: filePath) + } + } +} + private extension DiskStorage { + /// Whether the name is one folder inside the directory, rather than the directory itself or a path out of it. + static func isSingleFolderName(_ name: String) -> Bool { + !name.isEmpty && name != "." && name != ".." && !name.contains("/") + } + /** Lists the files in the cache directory, hidden ones included, keeping the first failure instead of stopping at it. A file that vanished during the scan is skipped. Must be called while holding the lock. @@ -281,21 +304,12 @@ private extension DiskStorage { } } - /// Wraps encoding failures in a `StorageError`, unless the type's own `Codable` code already threw one. - func encode(_ object: some Encodable, forKey key: String) throws -> Data { - do { - return try DataSerializer.serialize(object: object) - } - catch let error as StorageError { - throw error - } - catch { - throw StorageError.encodingFailed(context: "DiskStorage: failed to encode object for key: \(key)", underlyingError: error) - } - } - /// Wraps decoding failures in a `StorageError`, unless the type's own `Codable` code already threw one. func decode(_ data: Data, forKey key: String) throws -> T { + if T.self == Data.self, let data = data as? T { + return data + } + do { return try DataSerializer.deserialize(data: data) } diff --git a/Sources/Cache/Storage/HybridStorage.swift b/Sources/Cache/Storage/HybridStorage.swift index 9c84dd9..3386d1e 100644 --- a/Sources/Cache/Storage/HybridStorage.swift +++ b/Sources/Cache/Storage/HybridStorage.swift @@ -14,66 +14,74 @@ final class HybridStorage: Sendable { private let memoryStorage: MemoryStorage private let diskStorage: DiskStorage - /// Lock for atomic cross-storage operations - private let lock = OSAllocatedUnfairLock() + /// Keeps memory and disk in step when changing them, and counts those changes. The count lets + /// a read notice that the object it just decoded may be out of date. + private let lock = OSAllocatedUnfairLock(initialState: 0) } extension HybridStorage: StorageAware { func entry(ofType type: T.Type, forKey key: String) throws -> Entry { - try self.lock.withLockUnchecked { - do { - return try self.memoryStorage.entry(ofType: type, forKey: key) - } - catch { - let entry = try diskStorage.entry(ofType: type, forKey: key) - // set back to memoryStorage + // Without the lock, so that a hit doesn't wait for another object's disk access + if let entry = try? self.memoryStorage.entry(ofType: type, forKey: key) { + return entry + } + + // Decoding happens without the lock too, so the object may be removed or replaced meanwhile. + // Memory is only filled if nothing changed, or this would bring back the old object. + let changeCount = self.lock.withLockUnchecked { $0 } + let entry = try diskStorage.entry(ofType: type, forKey: key) + self.lock.withLockUnchecked { currentCount in + if currentCount == changeCount { self.memoryStorage.setObject(entry.object, forKey: key, expiry: entry.expiry) - return entry } } + return entry } func existsObject(forKey key: String) throws -> Bool { - try lock.withLockUnchecked { - if memoryStorage.existsObject(forKey: key) { - return true - } - return try diskStorage.existsObject(forKey: key) + if self.memoryStorage.existsObject(forKey: key) { + return true } + return try self.diskStorage.existsObject(forKey: key) } func removeObject(forKey key: String) throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 self.memoryStorage.removeObject(forKey: key) try self.diskStorage.removeObject(forKey: key) } } func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry? = nil) throws { - try self.lock.withLockUnchecked { + let data = try diskStorage.encode(object, forKey: key) + // An object has one expiry, worked out once, so the copy in memory can't outlive the file + let expiry = Expiry.date((expiry ?? self.diskStorage.config.expiry).date) + + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 // Disk first, because it's the one that can fail. Memory then never holds what wasn't saved. - try self.diskStorage.setObject(object, forKey: key, expiry: expiry) + try self.diskStorage.write(data, forKey: key, expiry: expiry) self.memoryStorage.setObject(object, forKey: key, expiry: expiry) } } func removeAll() throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 self.memoryStorage.removeAll() try self.diskStorage.removeAll() } } func removeExpiredObjects() throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { _ in self.memoryStorage.removeExpiredObjects() try self.diskStorage.removeExpiredObjects() } } func diskSize() throws -> UInt64 { - try self.lock.withLockUnchecked { - try self.diskStorage.diskSize() - } + try self.diskStorage.diskSize() } } diff --git a/Sources/Cache/Storage/Storage.swift b/Sources/Cache/Storage/Storage.swift index eb4ad7f..e3389d6 100644 --- a/Sources/Cache/Storage/Storage.swift +++ b/Sources/Cache/Storage/Storage.swift @@ -9,7 +9,8 @@ public final class Storage: Sendable { /// - Parameters: /// - diskConfig: Configuration for disk storage /// - memoryConfig: Optional. Pass config to add an in-memory layer - /// - Throws: Throw StorageError if any. + /// - Throws: `CocoaError(.fileWriteInvalidFileName)` if the config's name isn't a single folder name, + /// or the file system's error if the folder can't be created. public init(diskConfig: DiskConfig, memoryConfig: MemoryConfig? = nil) throws { let disk = try DiskStorage(config: diskConfig) @@ -37,7 +38,9 @@ public final class Storage: Sendable { extension Storage: StorageAware { /** - Tries to retrieve the object from the storage. + Tries to retrieve the object from the storage. Use the type the object was written as: with + any other type, the kinds of storage can give different results, including the file's raw + bytes when asking for `Data`. - Parameter key: Unique key to identify the object in the cache - Returns: Cached object - Throws: `StorageError.notFound` if there's no object for the key, or it has expired diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift new file mode 100644 index 0000000..9bb5d3e --- /dev/null +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -0,0 +1,158 @@ +import Foundation +import os +import Testing +@testable import Cache + +@Suite("Concurrency") +struct ConcurrencyTests { + // MARK: Using it from many threads + + /// Mostly here for Thread Sanitizer, which CI runs it under. Values carry their key, to catch mix-ups. + @Test("Many threads can use a storage at once", arguments: Sandbox.Mode.allCases) + func manyThreads(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + // A small limit, so that NSCache evicts while this runs + let storage = try sandbox.storage(mode, countLimit: 5) + let failures = OSAllocatedUnfairLock(initialState: [String]()) + + DispatchQueue.concurrentPerform(iterations: 8) { thread in + for iteration in 0 ..< 300 { + let keyNumber = (iteration + thread) % 10 + let key = "key\(keyNumber)" + do { + try storage.setObject(iteration * 10 + keyNumber, forKey: key, + expiry: iteration % 3 == 0 ? .seconds(-1) : .seconds(60)) + _ = try storage.existsObject(forKey: key) + do { + let value = try storage.object(ofType: Int.self, forKey: key) + if value % 10 != keyNumber { + failures.withLock { $0.append("\(key) held \(value)") } + } + } + catch StorageError.notFound { + // It expired, or another thread removed it + } + if iteration % 20 == 0 { try storage.removeObject(forKey: key) } + if iteration % 50 == 0 { + try storage.removeExpiredObjects() + _ = try storage.diskSize() + } + if iteration % 120 == 0 { try storage.removeAll() } + } + catch { + failures.withLock { $0.append("\(error)") } + } + } + } + + #expect(failures.withLock { $0 } == []) + } + + // MARK: Not waiting for each other + + /// Runs the code on another thread while `write` is stuck at the gate. + private func whileHeldUp(at gate: Gate, write: @escaping @Sendable () -> Void, _ code: () throws -> Void) throws { + let finished = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + write() + finished.signal() + } + gate.waitUntilEntered() + defer { + gate.release() + finished.wait() + #expect(!gate.timedOut, "The code had to wait for the write to finish") + } + try code() + } + + @Test("A slow encode doesn't hold up other objects", arguments: [Sandbox.Mode.disk, .hybrid]) + func slowEncode(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + try storage.setObject(1, forKey: "existing") + let gate = Gate() + + try whileHeldUp(at: gate, write: { try? storage.setObject(HeldUpWhileEncoding(gate: gate), forKey: "slow") }) { + #expect(try storage.object(ofType: Int.self, forKey: "existing") == 1) + try storage.setObject(2, forKey: "other") + #expect(try storage.object(ofType: Int.self, forKey: "other") == 2) + try storage.removeObject(forKey: "other") + } + } + + @Test("A slow disk doesn't hold up an object that's in memory") + func slowDisk() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + try storage.setObject(1, forKey: "inMemory", expiry: nil) + let gate = Gate() + fileManager.beforeSettingAttributes = { gate.enter() } + + try whileHeldUp(at: gate, write: { try? storage.setObject(2, forKey: "slow", expiry: nil) }) { + let value = try storage.object(ofType: Int.self, forKey: "inMemory") + let exists = try storage.existsObject(forKey: "inMemory") + #expect(value == 1) + #expect(exists) + } + } + + // MARK: Using the storage from Codable code + + @Test("A type's Codable code can use the storage it's being saved in", arguments: [Sandbox.Mode.disk, .hybrid]) + func codableCodeUsesStorage(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + // A new instance, because hybrid storage would otherwise answer from memory without decoding + let reader = try sandbox.storage(mode) + let writerRan = OSAllocatedUnfairLock(initialState: false) + let readerRan = OSAllocatedUnfairLock(initialState: false) + + try RunsCodeInCodable.$code.withValue({ + try? storage.setObject(1, forKey: "other") + writerRan.withLock { $0 = true } + }) { + try storage.setObject(RunsCodeInCodable(), forKey: "key") + } + _ = try RunsCodeInCodable.$code.withValue({ + _ = try? reader.object(ofType: Int.self, forKey: "other") + readerRan.withLock { $0 = true } + }) { + try reader.object(ofType: RunsCodeInCodable.self, forKey: "key") + } + + #expect(writerRan.withLock { $0 }) + #expect(readerRan.withLock { $0 }) + } + + // MARK: Filling memory from disk + + @Test("An object removed during decoding doesn't come back into memory") + func removedWhileDecoding() throws { + let sandbox = try Sandbox() + try sandbox.storage(.hybrid).setObject(RunsCodeInCodable(), forKey: "key") + let storage = try sandbox.storage(.hybrid) + + _ = try RunsCodeInCodable.$code.withValue({ + try? storage.removeObject(forKey: "key") + }) { + try storage.object(ofType: RunsCodeInCodable.self, forKey: "key") + } + + #expect(try storage.existsObject(forKey: "key") == false) + } + + @Test("An object from disk is kept in memory after reading it") + func readingFillsMemory() throws { + let sandbox = try Sandbox() + try sandbox.storage(.hybrid).setObject(1, forKey: "key") + let storage = try sandbox.storage(.hybrid) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + try FileManager.default.removeItem(at: sandbox.folder()) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + } +} diff --git a/Tests/CacheTests/ParityTests.swift b/Tests/CacheTests/ParityTests.swift new file mode 100644 index 0000000..bcaba77 --- /dev/null +++ b/Tests/CacheTests/ParityTests.swift @@ -0,0 +1,266 @@ +import Foundation +import Testing +@testable import Cache + +/// What a read came to, in a form that can be compared between kinds of storage. +enum ReadOutcome: Hashable { + /// The value as JSON, which shows the bytes of a `Data` too + case value(String) + case notFound + /// `typeNotMatch` from memory and `decodingFailed` from disk mean the same thing to the caller + case wrongType + case otherError(String) +} + +/// Writes a value, and reads it back as some type. +struct ReadCase: Sendable, CustomTestStringConvertible { + // MARK: Internal + + let testDescription: String + let write: @Sendable (Storage) throws -> Void + let read: @Sendable (Storage) throws -> String + let expected: ReadOutcome? + + /// Written and read as the same type, which must give back the same value. + static func same(_ value: T, _ name: String = "\(T.self)") -> ReadCase { + ReadCase(testDescription: name, write: self.writing(value), read: self.reading(T.self), + expected: .value(self.json(value))) + } + + /// Read as a type that doesn't fit what was written. + static func mismatch(_ value: T, as _: U.Type) -> ReadCase { + ReadCase(testDescription: "\(T.self) as \(U.self)", write: self.writing(value), read: self.reading(U.self), + expected: .wrongType) + } + + /// Read as a different type, where the kinds of storage are known to disagree. + static func disagreeing(_ value: T, as _: U.Type) -> ReadCase { + ReadCase(testDescription: "\(T.self) as \(U.self)", write: self.writing(value), read: self.reading(U.self), + expected: nil) + } + + // MARK: Private + + private static func writing(_ value: some Codable & Sendable) -> @Sendable (Storage) throws -> Void { + { try $0.setObject(value, forKey: "key") } + } + + private static func reading(_: T.Type) -> @Sendable (Storage) throws -> String { + { try self.json($0.object(ofType: T.self, forKey: "key")) } + } + + private static func json(_ value: some Encodable) -> String { + (try? JSONEncoder().encode(value)).map { String(decoding: $0, as: UTF8.self) } ?? "can't be encoded" + } +} + +/// Every way of reading: from the instance that wrote the object, which for hybrid means from +/// memory, and from a new instance, which for disk and hybrid means from the file. +private func outcomes(of readCase: ReadCase) throws -> [String: ReadOutcome] { + var outcomes = [String: ReadOutcome]() + for (mode, reopened) in [(Sandbox.Mode.disk, true), (.memory, false), (.hybrid, false), (.hybrid, true)] { + let sandbox = try Sandbox() + let writer = try sandbox.storage(mode) + try readCase.write(writer) + let reader = reopened ? try sandbox.storage(mode) : writer + + let name = "\(mode)\(reopened ? " reopened" : "")" + do { + outcomes[name] = try .value(readCase.read(reader)) + } + catch StorageError.notFound { + outcomes[name] = .notFound + } + catch StorageError.typeNotMatch, StorageError.decodingFailed { + outcomes[name] = .wrongType + } + catch { + outcomes[name] = .otherError("\(error)") + } + } + return outcomes +} + +@Suite("All kinds of storage agree") +struct ParityTests { + static let sameTypeCases: [ReadCase] = [ + .same(42), + .same(-1.5), + .same(true), + .same("text"), + .same(""), + .same(Date(timeIntervalSince1970: 1000)), + .same(Person(name: "Ada")), + .same([1, 2, 3]), + .same(["a": 1]), + .same(Data([0, 255, 254, 1]), "Data"), + .same(Data(), "empty Data"), + .same([Data([0, 255])]), + .same(Data?(Data([0, 255, 254, 1])), "Data? with a value"), + .same(Data?.none, "Data? without a value"), + .same(Int?(1), "Int? with a value"), + .same(Int?.none, "Int? without a value"), + ] + + static let mismatchCases: [ReadCase] = [ + .mismatch(1, as: Person.self), + .mismatch("text", as: Int.self), + .mismatch(Person(name: "Ada"), as: String.self), + .mismatch(Int?.none, as: Int.self), + ] + + /// Files don't record the type they were written with. `Data` is read as it is without looking + /// inside, and anything else is decoded if its JSON happens to fit, while memory compares types. + /// The README tells callers to read with the type they wrote. If one of these starts passing, + /// that's good news: move it up to `sameTypeCases` or `mismatchCases`. + static let disagreeingCases: [ReadCase] = [ + .disagreeing(Data?(Data([0, 255])), as: Data.self), + .disagreeing(Data([0, 255]), as: Data?.self), + .disagreeing(Person(name: "Ada"), as: Data.self), + .disagreeing(1, as: Double.self), + ] + + @Test("Reading with the type that was written gives back the value", arguments: sameTypeCases) + func sameType(readCase: ReadCase) throws { + for (reader, outcome) in try outcomes(of: readCase) { + #expect(outcome == readCase.expected, "Read by \(reader)") + } + } + + @Test("Reading with a type that doesn't fit is an error", arguments: mismatchCases) + func mismatch(readCase: ReadCase) throws { + for (reader, outcome) in try outcomes(of: readCase) { + #expect(outcome == readCase.expected, "Read by \(reader)") + } + } + + @Test("Reading with another type that happens to fit depends on the storage", arguments: disagreeingCases) + func knownDisagreement(readCase: ReadCase) throws { + let results = try outcomes(of: readCase) + withKnownIssue("Files don't record the type they were written with") { + #expect(Set(results.values).count == 1, "\(results)") + } + } + + // MARK: The config's default expiry + + @Test("The config's expiry applies when an object has none of its own", arguments: Sandbox.Mode.allCases) + func configExpiry(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(-10)) + + try storage.setObject(1, forKey: "key") + + #expect(try storage.existsObject(forKey: "key") == false) + #expect(throws: StorageError.self) { + try storage.object(ofType: Int.self, forKey: "key") + } + } + + @Test("The config's expiry is reported in the entry", arguments: Sandbox.Mode.allCases) + func configExpiryInEntry(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(3600)) + + try storage.setObject(1, forKey: "key") + + let expiry = try storage.entry(ofType: Int.self, forKey: "key").expiry.date + #expect(abs(expiry.timeIntervalSinceNow - 3600) < 60) + } + + @Test("An object's own expiry beats an expired config", arguments: Sandbox.Mode.allCases) + func objectExpiryOverridesExpiredConfig(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(-10)) + + try storage.setObject(1, forKey: "key", expiry: .seconds(3600)) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + } + + @Test("An object's own expiry beats a config that never expires", arguments: Sandbox.Mode.allCases) + func objectExpiryOverridesLastingConfig(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .never) + + try storage.setObject(1, forKey: "key", expiry: .seconds(-10)) + + #expect(try storage.existsObject(forKey: "key") == false) + } +} + +@Suite("Hybrid storage's expiry") +struct HybridExpiryTests { + private func makeStorage(in sandbox: Sandbox, disk: Expiry, memory: Expiry) throws -> Storage { + try Storage(diskConfig: DiskConfig(name: "cache", expiry: disk, directory: sandbox.root), + memoryConfig: MemoryConfig(expiry: memory)) + } + + @Test("The copy in memory doesn't outlive the file") + func memoryDoesNotOutliveDisk() throws { + let sandbox = try Sandbox() + let storage = try makeStorage(in: sandbox, disk: .seconds(-10), memory: .never) + + try storage.setObject("stale", forKey: "key") + + #expect(try storage.existsObject(forKey: "key") == false) + #expect(throws: StorageError.self) { + try storage.object(ofType: String.self, forKey: "key") + } + } + + @Test("MemoryConfig's expiry doesn't cut an object short") + func memoryExpiryIsNotUsed() throws { + let sandbox = try Sandbox() + let storage = try makeStorage(in: sandbox, disk: .never, memory: .seconds(-10)) + + try storage.setObject("kept", forKey: "key") + + #expect(try storage.object(ofType: String.self, forKey: "key") == "kept") + } + + @Test("An entry reports the same expiry from memory and from disk") + func sameExpiryFromMemoryAndDisk() throws { + let sandbox = try Sandbox() + let writer = try makeStorage(in: sandbox, disk: .seconds(3600), memory: .seconds(60)) + try writer.setObject("value", forKey: "key") + + let fromMemory = try writer.entry(ofType: String.self, forKey: "key").expiry.date + let reader = try makeStorage(in: sandbox, disk: .seconds(3600), memory: .seconds(60)) + let fromDisk = try reader.entry(ofType: String.self, forKey: "key").expiry.date + let refilled = try reader.entry(ofType: String.self, forKey: "key").expiry.date + + #expect(abs(fromMemory.timeIntervalSince(fromDisk)) < 1) + #expect(abs(fromDisk.timeIntervalSince(refilled)) < 1) + #expect(abs(fromDisk.timeIntervalSinceNow - 3600) < 60) + } +} + +@Suite("Folder names") +struct FolderNameTests { + @Test("A name that isn't a single folder is refused, with nothing touched", + arguments: ["", ".", "..", "../escaped", "a/b", "/absolute", "a/"]) + func refused(name: String) throws { + let sandbox = try Sandbox() + let bystander = sandbox.root.appendingPathComponent("bystander.txt") + try Data([1]).write(to: bystander) + + let error = try #require(throws: CocoaError.self) { + try Storage(diskConfig: DiskConfig(name: name, directory: sandbox.root)) + } + + #expect(error.code == .fileWriteInvalidFileName) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) + } + + @Test("Other names work", arguments: ["Floppy", "with space", "a.b", ".hidden", "..dots", "…", "日本語"]) + func accepted(name: String) throws { + let sandbox = try Sandbox() + let storage = try Storage(diskConfig: DiskConfig(name: name, directory: sandbox.root)) + + try storage.setObject(1, forKey: "key") + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == [name]) + } +} diff --git a/Tests/CacheTests/StorageTests.swift b/Tests/CacheTests/StorageTests.swift index e7e29b8..8fbced1 100644 --- a/Tests/CacheTests/StorageTests.swift +++ b/Tests/CacheTests/StorageTests.swift @@ -446,21 +446,6 @@ struct MemoryStorageTests { } } -/// Runs a hook before each removal, which can fail it or delete the file first. -private final class HookedFileManager: FileManager, @unchecked Sendable { - var beforeRemoving: (String) throws -> Void = { _ in } - - override func removeItem(atPath path: String) throws { - try self.beforeRemoving(path) - try super.removeItem(atPath: path) - } - - override func removeItem(at url: URL) throws { - try self.beforeRemoving(url.path) - try super.removeItem(at: url) - } -} - @Suite("Purging with failures") struct PurgeFailureTests { struct RemovalFailed: Error {} diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index c8dc571..68617df 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -1,4 +1,5 @@ import Foundation +import os @testable import Cache /// A folder that lasts as long as a test, with the three kinds of storage inside it. @@ -25,13 +26,14 @@ final class Sandbox { let root: URL - func folder(named name: String = "cache") -> URL { - self.root.appendingPathComponent(name, isDirectory: true) + func folder() -> URL { + self.root.appendingPathComponent("cache", isDirectory: true) } - func storage(_ mode: Mode, name: String = "cache", countLimit: UInt = 0) throws -> Storage { - let disk = DiskConfig(name: name, directory: self.root) - let memory = MemoryConfig(countLimit: countLimit) + /// - Parameter expiry: The default expiry, in the config of whichever kinds of storage are used + func storage(_ mode: Mode, expiry: Expiry = .never, countLimit: UInt = 0) throws -> Storage { + let disk = DiskConfig(name: "cache", expiry: expiry, directory: self.root) + let memory = MemoryConfig(expiry: expiry, countLimit: countLimit) return switch mode { case .disk: try Storage(diskConfig: disk) @@ -42,8 +44,8 @@ final class Sandbox { } } - func files(named name: String = "cache") throws -> [String] { - try FileManager.default.contentsOfDirectory(atPath: self.folder(named: name).path) + func files() throws -> [String] { + try FileManager.default.contentsOfDirectory(atPath: self.folder().path) } } @@ -71,3 +73,103 @@ struct UnencodableWithStorageError: Codable, Sendable { throw StorageError.encodingFailed(context: "inner", underlyingError: nil) } } + +/// Runs hooks during file operations, which can fail them, delete the file first, or hold them up. +final class HookedFileManager: FileManager, @unchecked Sendable { + var beforeRemoving: (String) throws -> Void = { _ in } + var beforeSettingAttributes: () -> Void = {} + + override func removeItem(atPath path: String) throws { + try self.beforeRemoving(path) + try super.removeItem(atPath: path) + } + + override func removeItem(at url: URL) throws { + try self.beforeRemoving(url.path) + try super.removeItem(at: url) + } + + override func setAttributes(_ attributes: [FileAttributeKey: Any], ofItemAtPath path: String) throws { + self.beforeSettingAttributes() + try super.setAttributes(attributes, ofItemAtPath: path) + } +} + +/// Holds one thread up until another has done something. Gives up after a while and remembers +/// that it did, so that a test fails if the other thread was stuck behind it, rather than hanging. +final class Gate: Sendable { + // MARK: Internal + + var timedOut: Bool { + self.didTimeOut.withLock { $0 } + } + + /// Called by the thread being held up. + func enter() { + self.entered.signal() + if self.released.wait(timeout: .now() + 5) == .timedOut { + self.didTimeOut.withLock { $0 = true } + } + } + + func waitUntilEntered() { + self.entered.wait() + } + + func release() { + self.released.signal() + } + + // MARK: Private + + private let entered = DispatchSemaphore(value: 0) + private let released = DispatchSemaphore(value: 0) + private let didTimeOut = OSAllocatedUnfairLock(initialState: false) +} + +/// Waits at a gate while it's being encoded. +struct HeldUpWhileEncoding: Codable, Sendable { + // MARK: Lifecycle + + init(gate: Gate) { + self.gate = gate + } + + init(from _: Decoder) throws { + self.gate = nil + } + + // MARK: Internal + + func encode(to encoder: Encoder) throws { + self.gate?.enter() + var container = encoder.singleValueContainer() + try container.encode(1) + } + + // MARK: Private + + private let gate: Gate? +} + +/// Runs some code of the test's while it's being encoded or decoded, like a type whose `Codable` +/// code uses the storage it's being saved in. +struct RunsCodeInCodable: Codable, Sendable { + // MARK: Lifecycle + + init() {} + + init(from _: Decoder) throws { + Self.code?() + } + + // MARK: Internal + + @TaskLocal static var code: (@Sendable () -> Void)? + + func encode(to encoder: Encoder) throws { + Self.code?() + var container = encoder.singleValueContainer() + try container.encode(1) + } +} From 6a3cf206edc680c674946a8fcdd46071c616f63f Mon Sep 17 00:00:00 2001 From: Gabor Sajo Date: Sat, 7 Nov 2026 00:27:46 -0600 Subject: [PATCH 2/7] Work out hybrid expiry after taking the lock A relative expiry was turned into a date before waiting for the lock, so a slow write to another key used up the object's lifetime, and could leave it expired by the time it was saved. --- Sources/Cache/Storage/HybridStorage.swift | 5 ++-- Tests/CacheTests/ConcurrencyTests.swift | 35 ++++++++++++++++++++++- Tests/CacheTests/TestSupport.swift | 4 +-- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/Sources/Cache/Storage/HybridStorage.swift b/Sources/Cache/Storage/HybridStorage.swift index 3386d1e..c734e17 100644 --- a/Sources/Cache/Storage/HybridStorage.swift +++ b/Sources/Cache/Storage/HybridStorage.swift @@ -55,11 +55,12 @@ extension HybridStorage: StorageAware { func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry? = nil) throws { let data = try diskStorage.encode(object, forKey: key) - // An object has one expiry, worked out once, so the copy in memory can't outlive the file - let expiry = Expiry.date((expiry ?? self.diskStorage.config.expiry).date) try self.lock.withLockUnchecked { changeCount in changeCount += 1 + // An object has one expiry, worked out once, so the copy in memory can't outlive the file. + // Worked out here, so that waiting for the lock doesn't use up the object's lifetime. + let expiry = Expiry.date((expiry ?? self.diskStorage.config.expiry).date) // Disk first, because it's the one that can fail. Memory then never holds what wasn't saved. try self.diskStorage.write(data, forKey: key, expiry: expiry) self.memoryStorage.setObject(object, forKey: key, expiry: expiry) diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift index 9bb5d3e..e7dfa05 100644 --- a/Tests/CacheTests/ConcurrencyTests.swift +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -89,7 +89,7 @@ struct ConcurrencyTests { let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) try storage.setObject(1, forKey: "inMemory", expiry: nil) let gate = Gate() - fileManager.beforeSettingAttributes = { gate.enter() } + fileManager.beforeSettingAttributes = { _ in gate.enter() } try whileHeldUp(at: gate, write: { try? storage.setObject(2, forKey: "slow", expiry: nil) }) { let value = try storage.object(ofType: Int.self, forKey: "inMemory") @@ -99,6 +99,39 @@ struct ConcurrencyTests { } } + @Test("Waiting for another write doesn't use up an object's expiry") + func expiryStartsAfterWaiting() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + let gate = Gate() + let slowFile = fileName(for: "slow") + fileManager.beforeSettingAttributes = { path in + if path.hasSuffix(slowFile) { + gate.enter() + } + } + let finished = DispatchSemaphore(value: 0) + var endOfWait = Date.distantFuture + + try whileHeldUp(at: gate, write: { try? storage.setObject(1, forKey: "slow", expiry: nil) }) { + DispatchQueue.global().async { + try? storage.setObject(2, forKey: "short", expiry: .seconds(0.1)) + finished.signal() + } + // Longer than the object's expiry + Thread.sleep(forTimeInterval: 0.3) + endOfWait = Date() + } + finished.wait() + + // The file's date rather than a read, which would depend on how quickly this gets there + let file = sandbox.folder().appendingPathComponent(fileName(for: "short")) + let expiry = try FileManager.default.attributesOfItem(atPath: file.path)[.modificationDate] as? Date + #expect(try #require(expiry) > endOfWait) + } + // MARK: Using the storage from Codable code @Test("A type's Codable code can use the storage it's being saved in", arguments: [Sandbox.Mode.disk, .hybrid]) diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index 68617df..cdeb6ec 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -77,7 +77,7 @@ struct UnencodableWithStorageError: Codable, Sendable { /// Runs hooks during file operations, which can fail them, delete the file first, or hold them up. final class HookedFileManager: FileManager, @unchecked Sendable { var beforeRemoving: (String) throws -> Void = { _ in } - var beforeSettingAttributes: () -> Void = {} + var beforeSettingAttributes: (String) -> Void = { _ in } override func removeItem(atPath path: String) throws { try self.beforeRemoving(path) @@ -90,7 +90,7 @@ final class HookedFileManager: FileManager, @unchecked Sendable { } override func setAttributes(_ attributes: [FileAttributeKey: Any], ofItemAtPath path: String) throws { - self.beforeSettingAttributes() + self.beforeSettingAttributes(path) try super.setAttributes(attributes, ofItemAtPath: path) } } From cb6ad4cb966148302277c4696bd0cdadd8e4e67b Mon Sep 17 00:00:00 2001 From: Gabor Shaio Date: Sat, 7 Nov 2026 15:44:06 -0600 Subject: [PATCH 3/7] Only ever delete the cache's own files A DiskConfig name with a NUL passed the folder-name check. File system calls stop reading a path at a NUL, so purging could act on files far outside the cache, and it deleted every non-.cache file it found, subfolders included. - Refuse names with control characters, and a directory with a NUL - Purging and removeAll() only delete hash-named files directly in the cache folder, checking each one is really inside it - removeAll() deletes those files instead of the whole folder - Don't look inside subfolders Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ README.md | 4 +- Sources/Cache/Configuration/DiskConfig.swift | 5 +- Sources/Cache/Storage/DiskStorage.swift | 56 +++++++++++++++++--- Sources/Cache/Storage/Storage.swift | 9 ++-- Tests/CacheTests/ParityTests.swift | 18 ++++++- Tests/CacheTests/StorageTests.swift | 38 +++++++++---- 7 files changed, 107 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17b2a8e..1e45da5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,14 @@ Bug fixes - With both disk and memory, an object could stay readable after its file expired, because the copy in memory used `MemoryConfig.expiry`. An object now has one expiry, and `entry(ofType:forKey:)` reports the same one from memory and from disk. - A `DiskConfig` name that isn't a single folder is refused, because purging or `removeAll()` could delete files outside the cache. With an empty name, they emptied `directory` itself. `Storage` now throws `CocoaError(.fileWriteInvalidFileName)`. +- A `DiskConfig` name with a control character such as NUL is refused too, and so is a `directory` with a NUL in it. File system calls stop reading a path at a NUL, so purging could act on files far outside the cache. +- `removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Purging used to delete every other file in the folder and in its subfolders, and `removeAll()` deleted the whole folder, so a wrong path could cost files that had nothing to do with the cache. - An object in memory no longer waits for disk access or encoding of another object. - Encoding and decoding no longer hold any lock, so a slow `Codable` type doesn't hold up other objects, and its code can use the storage it's being saved in. Behaviour changes - `MemoryConfig.expiry` is now only used by memory-only storage. With a disk, objects use the expiry from `DiskConfig`. +- Files in the cache folder that aren't the storage's, hidden ones included, are no longer deleted by `removeExpiredObjects()` or `removeAll()`. They still count toward `diskSize()`. - A `DiskConfig` name with a `/`, like `"Images/Thumbnails"`, used to create nested folders and now throws. Pass the parent folder as `directory` instead. Use the same full path to keep what's already cached there. Other diff --git a/README.md b/README.md index 5ca0a7b..2bfd719 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,9 @@ MemoryConfig( ) ``` -The name must be a single folder name. An empty name, `.`, `..` and anything with a `/` make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. +The name must be a single folder name. An empty name, `.`, `..`, and anything with a `/` or a control character such as NUL make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. So does a `directory` with a NUL in it. -The folder must be used only by the storage: `removeExpiredObjects()` deletes every file in it that isn't one of its objects, whatever its age and hidden files included. +`removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Anything else in the folder, including subfolders, is left alone. ## Expiry diff --git a/Sources/Cache/Configuration/DiskConfig.swift b/Sources/Cache/Configuration/DiskConfig.swift index 0d42b68..0f1782f 100644 --- a/Sources/Cache/Configuration/DiskConfig.swift +++ b/Sources/Cache/Configuration/DiskConfig.swift @@ -2,8 +2,9 @@ import Foundation public struct DiskConfig: Sendable { /// The name of disk storage, this will be used as folder name within directory. - /// It must be a single folder name: `Storage` refuses an empty name, `.`, `..`, and anything with a `/`. - /// The folder must be used only by this storage: `removeExpiredObjects()` deletes anything else in it. + /// It must be a single folder name: `Storage` refuses an empty name, `.`, `..`, and anything with + /// a `/` or a control character such as NUL. The storage only ever deletes files named like its + /// objects, directly in this folder, so anything else kept there is left alone. public let name: String /// Expiry date that will be applied by default for every added object /// if it's not overridden in the `setObject(_:forKey:expiry:)` method diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index 6e428a4..e5ecab2 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -24,13 +24,22 @@ final class DiskStorage: Sendable { } // path - self.path = url.appendingPathComponent(config.name, isDirectory: true).path + let path = url.appendingPathComponent(config.name, isDirectory: true).path + // File system calls stop reading a path at a NUL, so they would act on a different folder. + // The URL keeps a NUL as %00, which its path may or may not decode, so both are checked. + guard url.isFileURL, !path.unicodeScalars.contains("\u{0}"), + url.absoluteString.range(of: "%00", options: .caseInsensitive) == nil, + URL(fileURLWithPath: path, isDirectory: true).lastPathComponent == config.name + else { + throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: path]) + } + self.path = path try createDirectory() } // MARK: Internal - /// Files in the current format end in this. Anything else was left by an older version, whose + /// Files in the current format end in this. A file named with just the hash was left by 4.x, whose /// format can't be read any more, so it's never looked up and `removeExpiredObjects()` removes it. static let fileExtension = "cache" @@ -101,10 +110,20 @@ extension DiskStorage: StorageAware { } } + /// Removes this storage's files one by one rather than the whole folder, so that a wrong path + /// can't take anything else with it. func removeAll() throws { try self.lock.withLockUnchecked { - try removeItemIfPresent(atPath: self.path) + var firstError: Swift.Error? + + for file in try listOwnFiles(keys: [], firstError: &firstError) { + removeFile(at: file.url, firstError: &firstError) + } try createDirectory() + + if let firstError { + throw firstError + } } } @@ -112,7 +131,7 @@ extension DiskStorage: StorageAware { try self.lock.withLockUnchecked { var firstError: Swift.Error? - for file in try listFiles(keys: [.contentModificationDateKey], firstError: &firstError) { + for file in try listOwnFiles(keys: [.contentModificationDateKey], firstError: &firstError) { let isExpired = file.resourceValues.contentModificationDate?.inThePast ?? false if isExpired || file.url.pathExtension != Self.fileExtension { removeFile(at: file.url, firstError: &firstError) @@ -174,13 +193,36 @@ extension DiskStorage { private extension DiskStorage { /// Whether the name is one folder inside the directory, rather than the directory itself or a path out of it. + /// Control characters are refused too: file system calls stop reading a path at a NUL. static func isSingleFolderName(_ name: String) -> Bool { !name.isEmpty && name != "." && name != ".." && !name.contains("/") + && !name.unicodeScalars.contains { $0.properties.generalCategory == .control } + } + + /// Whether the file is named like one of this storage's objects: the key's hash, with the extension + /// or without it like in 4.x. Nothing else is ever deleted, even if the folder holds other files. + static func isOwnFileName(_ name: String) -> Bool { + let suffix = ".\(Self.fileExtension)" + let hash = name.hasSuffix(suffix) ? name.dropLast(suffix.count) : Substring(name) + return hash.count == 32 && hash.allSatisfy { $0.isASCII && $0.isHexDigit } + } + + /// Lists this storage's own files: directly in the cache folder, and named like its objects. + /// Must be called while holding the lock. + func listOwnFiles(keys: Set, + firstError: inout Swift.Error?) throws -> [(url: URL, resourceValues: URLResourceValues)] + { + let folder = URL(fileURLWithPath: self.path, isDirectory: true).resolvingSymlinksInPath().path + return try listFiles(keys: keys, firstError: &firstError).filter { file in + Self.isOwnFileName(file.url.lastPathComponent) + && file.url.deletingLastPathComponent().resolvingSymlinksInPath().path == folder + } } /** - Lists the files in the cache directory, hidden ones included, keeping the first failure instead - of stopping at it. A file that vanished during the scan is skipped. Must be called while holding the lock. + Lists the files directly in the cache directory, hidden ones included, without looking inside folders. + Keeps the first failure instead of stopping at it. A file that vanished during the scan is skipped. + Must be called while holding the lock. - Parameter keys: The resource values that the caller needs - Parameter firstError: Keeps the first failure */ @@ -192,7 +234,7 @@ private extension DiskStorage { let fileEnumerator = self.fileManager.enumerator( at: URL(fileURLWithPath: self.path), includingPropertiesForKeys: Array(resourceKeys), - options: [], + options: [.skipsSubdirectoryDescendants], errorHandler: { _, error in let code = (error as? CocoaError)?.code if code != .fileReadNoSuchFile, code != .fileNoSuchFile { diff --git a/Sources/Cache/Storage/Storage.swift b/Sources/Cache/Storage/Storage.swift index e3389d6..fd9b1a3 100644 --- a/Sources/Cache/Storage/Storage.swift +++ b/Sources/Cache/Storage/Storage.swift @@ -88,16 +88,17 @@ extension Storage: StorageAware { } /** - Removes all objects from the cache storage. + Removes all objects from the cache storage. On disk, it deletes the storage's own files, + including ones from an older version of this package, and leaves anything else in the folder. + A file that can't be removed doesn't stop the others. The first failure is thrown at the end. */ public func removeAll() throws { try self.internalStorage.removeAll() } /** - Clears all expired objects, and deletes every other file in the storage's folder that isn't one - of its objects, whatever its age and hidden files included. That covers files left behind by an - older version of this package, so the folder must be used only by this storage. + Clears all expired objects, and files left behind by an older version of this package, whatever + their age. Only files named like the storage's objects, directly in its folder, are ever deleted. A file that can't be removed doesn't stop the others. The first failure is thrown at the end. */ public func removeExpiredObjects() throws { diff --git a/Tests/CacheTests/ParityTests.swift b/Tests/CacheTests/ParityTests.swift index bcaba77..7c16e92 100644 --- a/Tests/CacheTests/ParityTests.swift +++ b/Tests/CacheTests/ParityTests.swift @@ -239,7 +239,8 @@ struct HybridExpiryTests { @Suite("Folder names") struct FolderNameTests { @Test("A name that isn't a single folder is refused, with nothing touched", - arguments: ["", ".", "..", "../escaped", "a/b", "/absolute", "a/"]) + arguments: ["", ".", "..", "../escaped", "a/b", "/absolute", "a/", + "\u{0}", "\u{0}x", "a\u{0}b", "a\nb", "\t", "\u{7F}"]) func refused(name: String) throws { let sandbox = try Sandbox() let bystander = sandbox.root.appendingPathComponent("bystander.txt") @@ -253,6 +254,21 @@ struct FolderNameTests { #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) } + @Test("A directory with a NUL in it is refused, with nothing touched") + func refusedDirectory() throws { + let sandbox = try Sandbox() + let bystander = sandbox.root.appendingPathComponent("bystander.txt") + try Data([1]).write(to: bystander) + let directory = sandbox.root.appendingPathComponent("a\u{0}b", isDirectory: true) + + let error = try #require(throws: CocoaError.self) { + try Storage(diskConfig: DiskConfig(name: "cache", directory: directory)) + } + + #expect(error.code == .fileWriteInvalidFileName) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) + } + @Test("Other names work", arguments: ["Floppy", "with space", "a.b", ".hidden", "..dots", "…", "日本語"]) func accepted(name: String) throws { let sandbox = try Sandbox() diff --git a/Tests/CacheTests/StorageTests.swift b/Tests/CacheTests/StorageTests.swift index 8fbced1..9a615ab 100644 --- a/Tests/CacheTests/StorageTests.swift +++ b/Tests/CacheTests/StorageTests.swift @@ -331,21 +331,43 @@ struct StorageTests { #expect(try storage.diskSize() == 0) } - @Test("Hidden files count toward diskSize, and purging removes them") + @Test("Hidden files count toward diskSize") func hiddenFiles() throws { let sandbox = try Sandbox() let storage = try sandbox.storage(.disk) try Data(repeating: 1, count: 5000).write(to: sandbox.folder().appendingPathComponent(".hidden")) #expect(try storage.diskSize() >= 5000) + } + + @Test("Purging and removeAll leave files that aren't the storage's", arguments: [Sandbox.Mode.disk, .hybrid]) + func othersFilesAreKept(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + try storage.setObject("old", forKey: "old", expiry: .seconds(-10)) + try storage.setObject("new", forKey: "new") + let others = [".hidden", "notes.txt", "README", "ABC.cache", "\(MD5.hash("key")).txt"] + for name in others { + try Data([1]).write(to: sandbox.folder().appendingPathComponent(name)) + } + // A folder named like an object, with a file inside named like one too + let subfolder = sandbox.folder().appendingPathComponent(MD5.hash("folder"), isDirectory: true) + try FileManager.default.createDirectory(at: subfolder, withIntermediateDirectories: true) + try Data([1]).write(to: subfolder.appendingPathComponent(fileName(for: "inside"))) + try FileManager.default.setAttributes([.modificationDate: Date.distantPast], + ofItemAtPath: subfolder.appendingPathComponent(fileName(for: "inside")).path) + let kept = Set(others + [MD5.hash("folder")]) try storage.removeExpiredObjects() + #expect(try Set(sandbox.files()) == kept.union([fileName(for: "new")])) - #expect(try sandbox.files().isEmpty) + try storage.removeAll() + #expect(try Set(sandbox.files()) == kept) + #expect(try FileManager.default.contentsOfDirectory(atPath: subfolder.path) == [fileName(for: "inside")]) } - @Test("A folder that can't be read makes diskSize and purging throw, after doing what they can") - func unreadableFolder() throws { + @Test("Purging and diskSize don't look inside folders, even ones that can't be read") + func unreadableSubfolder() throws { let sandbox = try Sandbox() let storage = try sandbox.storage(.disk) try storage.setObject(1, forKey: "old", expiry: .seconds(-10)) @@ -357,12 +379,8 @@ struct StorageTests { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } - #expect(throws: (any Error).self) { - try storage.diskSize() - } - #expect(throws: (any Error).self) { - try storage.removeExpiredObjects() - } + _ = try storage.diskSize() + try storage.removeExpiredObjects() #expect(try sandbox.files() == ["locked"]) } From 0d4aa339d491b038dba2b5d50b7992c134b981dd Mon Sep 17 00:00:00 2001 From: Gabor Shaio Date: Sat, 7 Nov 2026 15:53:51 -0600 Subject: [PATCH 4/7] Work out expiry once the disk lock is held Hybrid storage worked out a relative expiry before taking the disk's lock, which disk reads and diskSize() hold without the hybrid lock. Waiting for them could use up the expiry, saving an object that had already expired. The disk now works out the date itself and hybrid storage gives the copy in memory the same one. --- CHANGELOG.md | 1 + Sources/Cache/Storage/DiskStorage.swift | 11 ++-- Sources/Cache/Storage/HybridStorage.swift | 9 ++-- Tests/CacheTests/ConcurrencyTests.swift | 61 +++++++++++++++++------ Tests/CacheTests/TestSupport.swift | 6 +++ 5 files changed, 66 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e45da5..06f8a9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Bug fixes - A `DiskConfig` name with a control character such as NUL is refused too, and so is a `directory` with a NUL in it. File system calls stop reading a path at a NUL, so purging could act on files far outside the cache. - `removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Purging used to delete every other file in the folder and in its subfolders, and `removeAll()` deleted the whole folder, so a wrong path could cost files that had nothing to do with the cache. - An object in memory no longer waits for disk access or encoding of another object. +- An object's relative expiry, like `.seconds(10)`, starts once it's being saved. Waiting for another write or a disk read used to use it up, so a short-lived object could be saved already expired. - Encoding and decoding no longer hold any lock, so a slow `Codable` type doesn't hold up other objects, and its code can use the storage it's being saved in. Behaviour changes diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index e5ecab2..56dca1e 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -181,12 +181,17 @@ extension DiskStorage { } } - func write(_ data: Data, forKey key: String, expiry: Expiry?) throws { + /// Works out the expiry date while holding the lock, so that waiting for it doesn't use up the + /// object's lifetime. + /// - Returns: The expiry date the file got + @discardableResult + func write(_ data: Data, forKey key: String, expiry: Expiry?) throws -> Date { try self.lock.withLockUnchecked { - let expiry = expiry ?? self.config.expiry let filePath = makeFilePath(for: key) try writeFile(data, atPath: filePath) - try self.fileManager.setAttributes([.modificationDate: expiry.date], ofItemAtPath: filePath) + let date = (expiry ?? self.config.expiry).date + try self.fileManager.setAttributes([.modificationDate: date], ofItemAtPath: filePath) + return date } } } diff --git a/Sources/Cache/Storage/HybridStorage.swift b/Sources/Cache/Storage/HybridStorage.swift index c734e17..bc8e4c9 100644 --- a/Sources/Cache/Storage/HybridStorage.swift +++ b/Sources/Cache/Storage/HybridStorage.swift @@ -58,12 +58,11 @@ extension HybridStorage: StorageAware { try self.lock.withLockUnchecked { changeCount in changeCount += 1 - // An object has one expiry, worked out once, so the copy in memory can't outlive the file. - // Worked out here, so that waiting for the lock doesn't use up the object's lifetime. - let expiry = Expiry.date((expiry ?? self.diskStorage.config.expiry).date) // Disk first, because it's the one that can fail. Memory then never holds what wasn't saved. - try self.diskStorage.write(data, forKey: key, expiry: expiry) - self.memoryStorage.setObject(object, forKey: key, expiry: expiry) + // An object has one expiry: the disk works it out once it has its own lock, and the copy + // in memory gets the same date, so it can't outlive the file. + let date = try self.diskStorage.write(data, forKey: key, expiry: expiry) + self.memoryStorage.setObject(object, forKey: key, expiry: .date(date)) } } diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift index e7dfa05..933d9a6 100644 --- a/Tests/CacheTests/ConcurrencyTests.swift +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -99,23 +99,15 @@ struct ConcurrencyTests { } } - @Test("Waiting for another write doesn't use up an object's expiry") - func expiryStartsAfterWaiting() throws { - let sandbox = try Sandbox() - let fileManager = HookedFileManager() - let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) - let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) - let gate = Gate() - let slowFile = fileName(for: "slow") - fileManager.beforeSettingAttributes = { path in - if path.hasSuffix(slowFile) { - gate.enter() - } - } + /// Saves an object with a short expiry while `holdUp` is stuck at the gate, and waits longer than + /// that expiry before letting it go. The object's expiry should only start once it got through. + private func expectExpiryStartsAfterWaiting(storage: HybridStorage, sandbox: Sandbox, gate: Gate, + holdUp: @escaping @Sendable () -> Void) throws + { let finished = DispatchSemaphore(value: 0) var endOfWait = Date.distantFuture - try whileHeldUp(at: gate, write: { try? storage.setObject(1, forKey: "slow", expiry: nil) }) { + try whileHeldUp(at: gate, write: holdUp) { DispatchQueue.global().async { try? storage.setObject(2, forKey: "short", expiry: .seconds(0.1)) finished.signal() @@ -132,6 +124,47 @@ struct ConcurrencyTests { #expect(try #require(expiry) > endOfWait) } + @Test("Waiting for another write doesn't use up an object's expiry") + func expiryStartsAfterWaiting() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + let gate = Gate() + let slowFile = fileName(for: "slow") + fileManager.beforeSettingAttributes = { path in + if path.hasSuffix(slowFile) { + gate.enter() + } + } + + try expectExpiryStartsAfterWaiting(storage: storage, sandbox: sandbox, gate: gate) { + try? storage.setObject(1, forKey: "slow", expiry: nil) + } + } + + /// Disk reads don't take hybrid storage's own lock, only the disk's. + @Test("Waiting for a disk read doesn't use up an object's expiry") + func expiryStartsAfterWaitingForRead() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + // On disk only, so that reading it goes to the disk + try disk.setObject(1, forKey: "slow") + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + let gate = Gate() + let slowFile = fileName(for: "slow") + fileManager.beforeReadingAttributes = { path in + if path.hasSuffix(slowFile) { + gate.enter() + } + } + + try expectExpiryStartsAfterWaiting(storage: storage, sandbox: sandbox, gate: gate) { + _ = try? storage.entry(ofType: Int.self, forKey: "slow") + } + } + // MARK: Using the storage from Codable code @Test("A type's Codable code can use the storage it's being saved in", arguments: [Sandbox.Mode.disk, .hybrid]) diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index cdeb6ec..7e686ac 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -78,6 +78,12 @@ struct UnencodableWithStorageError: Codable, Sendable { final class HookedFileManager: FileManager, @unchecked Sendable { var beforeRemoving: (String) throws -> Void = { _ in } var beforeSettingAttributes: (String) -> Void = { _ in } + var beforeReadingAttributes: (String) -> Void = { _ in } + + override func attributesOfItem(atPath path: String) throws -> [FileAttributeKey: Any] { + self.beforeReadingAttributes(path) + return try super.attributesOfItem(atPath: path) + } override func removeItem(atPath path: String) throws { try self.beforeRemoving(path) From 3640f83ea0b9198adc2de25e94e10536781f3f8e Mon Sep 17 00:00:00 2001 From: Gabor Shaio Date: Sat, 7 Nov 2026 16:02:21 -0600 Subject: [PATCH 5/7] Stop a test waiting forever for a write that failed The gate waited without a limit for the other thread to get there, so a write that failed before reaching it hung the test. --- Tests/CacheTests/ConcurrencyTests.swift | 3 ++- Tests/CacheTests/TestSupport.swift | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift index 933d9a6..2d16d1c 100644 --- a/Tests/CacheTests/ConcurrencyTests.swift +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -57,12 +57,13 @@ struct ConcurrencyTests { write() finished.signal() } - gate.waitUntilEntered() + let entered = gate.waitUntilEntered() defer { gate.release() finished.wait() #expect(!gate.timedOut, "The code had to wait for the write to finish") } + try #require(entered, "The write never got to the gate") try code() } diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index 7e686ac..f420737 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -118,8 +118,10 @@ final class Gate: Sendable { } } - func waitUntilEntered() { - self.entered.wait() + /// Gives up after a while too, because a thread that failed before getting to the gate never will. + /// - Returns: Whether the other thread got to the gate in time + func waitUntilEntered() -> Bool { + self.entered.wait(timeout: .now() + 5) == .success } func release() { From 6bf22557de3d793d5cf839dbbd121d7c71537a57 Mon Sep 17 00:00:00 2001 From: Gabor Shaio Date: Sat, 7 Nov 2026 16:28:28 -0600 Subject: [PATCH 6/7] Run the tests' background work on threads of their own Tests that blocked waiting for work on DispatchQueue.global() took every cooperative thread on CI's three-core runners, which left that queue no thread to run the work on, so the test run hung until it timed out. --- Tests/CacheTests/ConcurrencyTests.swift | 4 ++-- Tests/CacheTests/TestSupport.swift | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift index 2d16d1c..7500913 100644 --- a/Tests/CacheTests/ConcurrencyTests.swift +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -53,7 +53,7 @@ struct ConcurrencyTests { /// Runs the code on another thread while `write` is stuck at the gate. private func whileHeldUp(at gate: Gate, write: @escaping @Sendable () -> Void, _ code: () throws -> Void) throws { let finished = DispatchSemaphore(value: 0) - DispatchQueue.global().async { + onNewThread { write() finished.signal() } @@ -109,7 +109,7 @@ struct ConcurrencyTests { var endOfWait = Date.distantFuture try whileHeldUp(at: gate, write: holdUp) { - DispatchQueue.global().async { + onNewThread { try? storage.setObject(2, forKey: "short", expiry: .seconds(0.1)) finished.signal() } diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index f420737..381ded0 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -101,6 +101,12 @@ final class HookedFileManager: FileManager, @unchecked Sendable { } } +/// Runs the code on a new thread. Not on a dispatch queue: tests run on Swift's cooperative threads, +/// and while they block waiting for this, they can take every thread such a queue would get. +func onNewThread(_ code: @escaping @Sendable () -> Void) { + Thread(block: code).start() +} + /// Holds one thread up until another has done something. Gives up after a while and remembers /// that it did, so that a test fails if the other thread was stuck behind it, rather than hanging. final class Gate: Sendable { From 7ac695f23494f7baf0a0c25f092714a74d4bd379 Mon Sep 17 00:00:00 2001 From: Gabor Shaio Date: Sat, 7 Nov 2026 16:28:28 -0600 Subject: [PATCH 7/7] Refuse the root folder as a cache directory On macOS 26, adding a NUL to a folder's URL gives file:///, so a URL that was meant to be refused for its NUL arrived as the root folder instead. The name is now joined to the directory as a string and checked, and the root folder is refused. --- CHANGELOG.md | 2 +- README.md | 2 +- Sources/Cache/Configuration/DiskConfig.swift | 3 ++- Sources/Cache/Storage/DiskStorage.swift | 14 +++++++++----- Tests/CacheTests/ParityTests.swift | 10 ++++++++++ 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06f8a9c..50a1658 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Bug fixes - With both disk and memory, an object could stay readable after its file expired, because the copy in memory used `MemoryConfig.expiry`. An object now has one expiry, and `entry(ofType:forKey:)` reports the same one from memory and from disk. - A `DiskConfig` name that isn't a single folder is refused, because purging or `removeAll()` could delete files outside the cache. With an empty name, they emptied `directory` itself. `Storage` now throws `CocoaError(.fileWriteInvalidFileName)`. -- A `DiskConfig` name with a control character such as NUL is refused too, and so is a `directory` with a NUL in it. File system calls stop reading a path at a NUL, so purging could act on files far outside the cache. +- A `DiskConfig` name with a control character such as NUL is refused too, and so is a `directory` with a NUL in it, or the root folder. File system calls stop reading a path at a NUL, and on macOS 26 a folder's URL with a NUL added comes out as the root folder, so purging could act on files far outside the cache. - `removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Purging used to delete every other file in the folder and in its subfolders, and `removeAll()` deleted the whole folder, so a wrong path could cost files that had nothing to do with the cache. - An object in memory no longer waits for disk access or encoding of another object. - An object's relative expiry, like `.seconds(10)`, starts once it's being saved. Waiting for another write or a disk read used to use it up, so a short-lived object could be saved already expired. diff --git a/README.md b/README.md index 2bfd719..1dcaca7 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ MemoryConfig( ) ``` -The name must be a single folder name. An empty name, `.`, `..`, and anything with a `/` or a control character such as NUL make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. So does a `directory` with a NUL in it. +The name must be a single folder name. An empty name, `.`, `..`, and anything with a `/` or a control character such as NUL make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. So does a `directory` with a NUL in it, or the root folder, which is what a URL with a NUL can turn into. `removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Anything else in the folder, including subfolders, is left alone. diff --git a/Sources/Cache/Configuration/DiskConfig.swift b/Sources/Cache/Configuration/DiskConfig.swift index 0f1782f..bd1981a 100644 --- a/Sources/Cache/Configuration/DiskConfig.swift +++ b/Sources/Cache/Configuration/DiskConfig.swift @@ -9,7 +9,8 @@ public struct DiskConfig: Sendable { /// Expiry date that will be applied by default for every added object /// if it's not overridden in the `setObject(_:forKey:expiry:)` method public let expiry: Expiry - /// A folder to store the disk cache contents. Defaults to the Caches directory if nil + /// A folder to store the disk cache contents. Defaults to the Caches directory if nil. + /// `Storage` refuses the root folder, and a URL with a NUL in it. public let directory: URL? #if os(iOS) || os(tvOS) /// Data protection is used to store files in an encrypted format on disk and to decrypt them on demand. diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index 56dca1e..8de600e 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -24,12 +24,16 @@ final class DiskStorage: Sendable { } // path - let path = url.appendingPathComponent(config.name, isDirectory: true).path - // File system calls stop reading a path at a NUL, so they would act on a different folder. - // The URL keeps a NUL as %00, which its path may or may not decode, so both are checked. - guard url.isFileURL, !path.unicodeScalars.contains("\u{0}"), + // A NUL in a URL can make it come out as the root folder, depending on the OS version: on + // macOS 26, appending "a\u{0}b" to a folder's URL gives file:///. So the root folder is refused, + // and the name is joined as a string rather than with URL methods, then checked. + let directoryPath = url.standardizedFileURL.path + let path = (directoryPath as NSString).appendingPathComponent(config.name) + guard url.isFileURL, !directoryPath.isEmpty, directoryPath != "/", + !path.unicodeScalars.contains("\u{0}"), url.absoluteString.range(of: "%00", options: .caseInsensitive) == nil, - URL(fileURLWithPath: path, isDirectory: true).lastPathComponent == config.name + (path as NSString).deletingLastPathComponent == directoryPath, + (path as NSString).lastPathComponent == config.name else { throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: path]) } diff --git a/Tests/CacheTests/ParityTests.swift b/Tests/CacheTests/ParityTests.swift index 7c16e92..5ac30b3 100644 --- a/Tests/CacheTests/ParityTests.swift +++ b/Tests/CacheTests/ParityTests.swift @@ -269,6 +269,16 @@ struct FolderNameTests { #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) } + /// What a directory with a NUL in it can come out as, depending on the OS version. + @Test("The root folder is refused as the directory") + func refusedRoot() throws { + let error = try #require(throws: CocoaError.self) { + try Storage(diskConfig: DiskConfig(name: "cache", directory: URL(fileURLWithPath: "/", isDirectory: true))) + } + + #expect(error.code == .fileWriteInvalidFileName) + } + @Test("Other names work", arguments: ["Floppy", "with space", "a.b", ".hidden", "..dots", "…", "日本語"]) func accepted(name: String) throws { let sandbox = try Sandbox()