From b09f85139701518c314ab619bea593ddc43a89a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Thu, 6 Aug 2026 13:49:57 +0200 Subject: [PATCH 1/7] chore(deps): Require ios-core 19.1.3 # Conflicts: # Tuist/Package.resolved --- Tuist/Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tuist/Package.swift b/Tuist/Package.swift index a18adfac3..6d0fb3e68 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -61,7 +61,7 @@ let package = Package( .package(url: "https://github.com/flowbe/SwiftRegex", .upToNextMajor(from: "1.0.0")), .package(url: "https://github.com/getsentry/sentry-cocoa", .upToNextMajor(from: "9.8.0")), .package(url: "https://github.com/Infomaniak/ios-bug-tracker", .upToNextMajor(from: "19.0.0")), - .package(url: "https://github.com/Infomaniak/ios-core", .upToNextMajor(from: "19.0.0")), + .package(url: "https://github.com/Infomaniak/ios-core", .upToNextMajor(from: "19.1.3")), .package(url: "https://github.com/Infomaniak/ios-core-ui", .upToNextMajor(from: "26.0.0")), .package(url: "https://github.com/Infomaniak/ios-core-uikit", .upToNextMajor(from: "2.0.1")), .package(url: "https://github.com/Infomaniak/ios-dependency-injection", .upToNextMajor(from: "2.0.5")), From a9ea2b95c5e9558c99ad2453dbb53fc4d90e5ba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Thu, 6 Aug 2026 13:50:01 +0200 Subject: [PATCH 2/7] feat(security): Harden shared file imports --- kDriveCore/DI/CoreTargetAssembly.swift | 3 + kDriveCore/Utils/DeeplinkParser.swift | 35 +- .../Utils/Files/FileSharingImporter.swift | 364 ++++++++++++++++++ 3 files changed, 385 insertions(+), 17 deletions(-) create mode 100644 kDriveCore/Utils/Files/FileSharingImporter.swift diff --git a/kDriveCore/DI/CoreTargetAssembly.swift b/kDriveCore/DI/CoreTargetAssembly.swift index e43d69149..d5aae8676 100644 --- a/kDriveCore/DI/CoreTargetAssembly.swift +++ b/kDriveCore/DI/CoreTargetAssembly.swift @@ -110,6 +110,9 @@ open class CoreTargetAssembly: TargetAssembly { Factory(type: DeeplinkParsable.self) { _, _ in DeeplinkParser() }, + Factory(type: FileSharingImportable.self) { _, _ in + FileSharingImporter() + }, Factory(type: PublicShareApiFetcher.self) { _, _ in PublicShareApiFetcher() } diff --git a/kDriveCore/Utils/DeeplinkParser.swift b/kDriveCore/Utils/DeeplinkParser.swift index 311985c50..0b9308815 100644 --- a/kDriveCore/Utils/DeeplinkParser.swift +++ b/kDriveCore/Utils/DeeplinkParser.swift @@ -38,6 +38,7 @@ public struct DeeplinkParser: DeeplinkParsable { @LazyInjectService private var matomo: MatomoUtils @LazyInjectService var accountManager: AccountManageable @LazyInjectService var router: AppNavigable + @LazyInjectService private var fileSharingImporter: FileSharingImportable public init() { // META: keep SonarCloud happy @@ -93,8 +94,23 @@ public struct DeeplinkParser: DeeplinkParsable { } public func parse(url: URL) async -> Bool { - guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true), - let params = components.queryItems else { + guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { + return await handleDeeplink(url: url) + } + + if components.scheme == FileSharingImporter.scheme || components.host == DeeplinkPath.file.rawValue { + do { + let files = try await fileSharingImporter.importFiles(from: url) + await router.navigate(to: .saveFiles(files: files)) + matomo.track(eventWithCategory: .deeplink, name: DeeplinkPath.file.rawValue) + return true + } catch { + Log.sceneDelegate("Failed to import files: Invalid request", level: .error) + return false + } + } + + guard let params = components.queryItems else { return await handleDeeplink(url: url) } @@ -110,21 +126,6 @@ public struct DeeplinkParser: DeeplinkParsable { await router.navigate(to: .store(driveId: driveIdInt, userId: userIdInt)) matomo.track(eventWithCategory: .deeplink, name: DeeplinkPath.store.rawValue) return true - - } else if components.host == DeeplinkPath.file.rawValue { - let files: [ImportedFile] = params.compactMap { param in - guard param.name == "url", let filePath = param.value else { return nil } - let fileUrl = URL(fileURLWithPath: filePath) - - return ImportedFile(name: fileUrl.lastPathComponent, path: fileUrl, uti: fileUrl.uti ?? .data) - } - guard !files.isEmpty else { - Log.sceneDelegate("Failed to import files: No files found", level: .error) - return false - } - await router.navigate(to: .saveFiles(files: files)) - matomo.track(eventWithCategory: .deeplink, name: DeeplinkPath.file.rawValue) - return true } Log.sceneDelegate("unable to parse deeplink URL: \(url)", level: .error) diff --git a/kDriveCore/Utils/Files/FileSharingImporter.swift b/kDriveCore/Utils/Files/FileSharingImporter.swift new file mode 100644 index 000000000..9ae2d40a4 --- /dev/null +++ b/kDriveCore/Utils/Files/FileSharingImporter.swift @@ -0,0 +1,364 @@ +/* + Infomaniak kDrive - iOS App + Copyright (C) 2026 Infomaniak Network SA + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +import Darwin +import Foundation +import InfomaniakCore + +protocol FileSharingImportable { + func importFiles(from url: URL) async throws -> [ImportedFile] +} + +enum FileSharingImportError: Error, Equatable { + case invalidRoute + case invalidQuery + case tooManyFiles + case invalidPath + case duplicateFile + case sourceOutsideHandoffRoot + case invalidHandoffLayout + case invalidFileName + case unsupportedFile + case fileTooLarge + case aggregateSizeExceeded + case insufficientSpace + case unavailableStorage + case stagingFailed +} + +final class FileSharingImporter: FileSharingImportable { + struct Limits { + static let `default` = Limits( + maximumFileCount: 100, + maximumFileSize: Constants.rangeProviderConfig.fileMaxSizeClient - 1, + maximumAggregateSize: Constants.rangeProviderConfig.fileMaxSizeClient - 1, + freeSpaceReserve: 50 * 1024 * 1024 + ) + + let maximumFileCount: Int + let maximumFileSize: UInt64 + let maximumAggregateSize: UInt64 + let freeSpaceReserve: UInt64 + } + + private struct ValidatedFile { + let source: OpenedFile + let name: String + let uti: UTI + let fileExtension: String? + let size: UInt64 + } + + private final class OpenedFile { + let descriptor: Int32 + + init(descriptor: Int32) { + self.descriptor = descriptor + } + + deinit { + Darwin.close(descriptor) + } + } + + static let scheme = "kdrive-file-sharing" + static let host = "file" + + private static let sharedAppGroup = "group.com.infomaniak" + private static let handoffPathComponents = ["Library", "Caches", "file-sharing"] + + private let fileManager: FileManager + private let sharedContainerURL: URL? + private let stagingRootURL: URL + private let limits: Limits + private let makeIdentifier: () -> String + private let availableCapacity: (URL) throws -> UInt64 + + convenience init() { + let fileManager = FileManager.default + self.init( + fileManager: fileManager, + sharedContainerURL: fileManager.containerURL(forSecurityApplicationGroupIdentifier: Self.sharedAppGroup), + stagingRootURL: DriveFileManager.constants.importDirectoryURL + ) + } + + init( + fileManager: FileManager, + sharedContainerURL: URL?, + stagingRootURL: URL, + limits: Limits = .default, + makeIdentifier: @escaping () -> String = { UUID().uuidString }, + availableCapacity: ((URL) throws -> UInt64)? = nil + ) { + self.fileManager = fileManager + self.sharedContainerURL = sharedContainerURL + self.stagingRootURL = stagingRootURL + self.limits = limits + self.makeIdentifier = makeIdentifier + self.availableCapacity = availableCapacity ?? { url in + let attributes = try fileManager.attributesOfFileSystem(forPath: url.path) + guard let capacity = (attributes[.systemFreeSize] as? NSNumber)?.uint64Value else { + throw FileSharingImportError.unavailableStorage + } + return capacity + } + } + + func importFiles(from url: URL) async throws -> [ImportedFile] { + return try await Task.detached(priority: .userInitiated) { [self] in + let validatedFiles = try validate(url: url) + try checkAvailableSpace(for: validatedFiles) + return try stage(validatedFiles) + }.value + } + + private func validate(url: URL) throws -> [ValidatedFile] { + guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), + components.scheme == Self.scheme, + components.host == Self.host, + components.path.isEmpty, + components.user == nil, + components.password == nil, + components.port == nil, + components.fragment == nil else { + throw FileSharingImportError.invalidRoute + } + + guard let queryItems = components.queryItems, + !queryItems.isEmpty, + queryItems.allSatisfy({ $0.name == "url" && !($0.value?.isEmpty ?? true) }) else { + throw FileSharingImportError.invalidQuery + } + guard queryItems.count <= limits.maximumFileCount else { + throw FileSharingImportError.tooManyFiles + } + guard let sharedContainerURL else { + throw FileSharingImportError.unavailableStorage + } + + let handoffRootURL = Self.handoffPathComponents.reduce(sharedContainerURL) { rootURL, component in + rootURL.appendingPathComponent(component, isDirectory: true) + }.standardizedFileURL + let handoffRoot = try openDirectoryTree( + rootURL: sharedContainerURL.standardizedFileURL, + components: Self.handoffPathComponents + ) + var canonicalPaths = Set() + var aggregateSize: UInt64 = 0 + + return try queryItems.map { queryItem in + guard let path = queryItem.value, + path.utf8.count < Int(PATH_MAX), + NSString(string: path).isAbsolutePath else { + throw FileSharingImportError.invalidPath + } + + let candidateURL = URL(fileURLWithPath: path).standardizedFileURL + guard candidateURL.isContained(in: handoffRootURL) else { + throw FileSharingImportError.sourceOutsideHandoffRoot + } + + let relativeComponents = Array(candidateURL.pathComponents.dropFirst(handoffRootURL.pathComponents.count)) + guard relativeComponents.count == 2, + UUID(uuidString: relativeComponents[0]) != nil else { + throw FileSharingImportError.invalidHandoffLayout + } + guard canonicalPaths.insert(candidateURL.path).inserted else { + throw FileSharingImportError.duplicateFile + } + let safeName = relativeComponents[1] + guard isValidFileName(safeName) else { + throw FileSharingImportError.invalidFileName + } + + let handoffDirectory = try openDirectory(at: handoffRoot.descriptor, component: relativeComponents[0]) + let source = try openFile(at: handoffDirectory.descriptor, component: safeName) + var sourceInfo = stat() + guard Darwin.fstat(source.descriptor, &sourceInfo) == 0, + sourceInfo.st_mode & S_IFMT == S_IFREG, + sourceInfo.st_nlink == 1, + sourceInfo.st_size >= 0 else { + throw FileSharingImportError.unsupportedFile + } + let fileSize = UInt64(sourceInfo.st_size) + guard fileSize <= limits.maximumFileSize else { + throw FileSharingImportError.fileTooLarge + } + guard fileSize <= limits.maximumAggregateSize - aggregateSize else { + throw FileSharingImportError.aggregateSizeExceeded + } + aggregateSize += fileSize + + let fileExtension = safeExtension(for: safeName) + let uti = fileExtension.flatMap { UTI(filenameExtension: $0) } ?? .data + return ValidatedFile( + source: source, + name: safeName, + uti: uti, + fileExtension: fileExtension, + size: fileSize + ) + } + } + + private func checkAvailableSpace(for files: [ValidatedFile]) throws { + let aggregateSize = files.reduce(UInt64(0)) { $0 + $1.size } + guard aggregateSize <= UInt64.max - limits.freeSpaceReserve else { + throw FileSharingImportError.aggregateSizeExceeded + } + + let freeSize: UInt64 + do { + freeSize = try availableCapacity(stagingRootURL) + } catch { + throw FileSharingImportError.unavailableStorage + } + guard freeSize >= aggregateSize + limits.freeSpaceReserve else { + throw FileSharingImportError.insufficientSpace + } + } + + private func stage(_ files: [ValidatedFile]) throws -> [ImportedFile] { + let stagingRoot: OpenedFile + do { + stagingRoot = try openDirectory(atPath: stagingRootURL.path) + } catch { + throw FileSharingImportError.unavailableStorage + } + + var stagedNames = [String]() + do { + return try files.map { file in + var destinationName = makeIdentifier() + if let fileExtension = file.fileExtension { + destinationName += ".\(fileExtension)" + } + guard isValidFileName(destinationName) else { + throw FileSharingImportError.stagingFailed + } + + let destination = try createFile(at: stagingRoot.descriptor, component: destinationName) + stagedNames.append(destinationName) + guard fcopyfile(file.source.descriptor, destination.descriptor, nil, copyfile_flags_t(COPYFILE_DATA)) == 0 else { + throw FileSharingImportError.stagingFailed + } + var sourceInfo = stat() + guard Darwin.fstat(file.source.descriptor, &sourceInfo) == 0 else { + throw FileSharingImportError.stagingFailed + } + var timestamps = [sourceInfo.st_atimespec, sourceInfo.st_mtimespec] + guard futimens(destination.descriptor, ×tamps) == 0 else { + throw FileSharingImportError.stagingFailed + } + + var destinationInfo = stat() + guard Darwin.fstat(destination.descriptor, &destinationInfo) == 0, + destinationInfo.st_mode & S_IFMT == S_IFREG, + destinationInfo.st_size >= 0, + UInt64(destinationInfo.st_size) == file.size else { + throw FileSharingImportError.stagingFailed + } + + let destinationURL = stagingRootURL.appendingPathComponent(destinationName, isDirectory: false) + return ImportedFile(name: file.name, path: destinationURL, uti: file.uti) + } + } catch { + for name in stagedNames { + name.withCString { unlinkat(stagingRoot.descriptor, $0, 0) } + } + throw FileSharingImportError.stagingFailed + } + } + + private func isValidFileName(_ fileName: String) -> Bool { + let invalidCharacters = CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/\\")) + return !fileName.isEmpty + && fileName != "." + && fileName != ".." + && fileName.utf8.count <= Int(NAME_MAX) + && fileName.rangeOfCharacter(from: invalidCharacters) == nil + } + + private func safeExtension(for fileName: String) -> String? { + let fileExtension = URL(fileURLWithPath: fileName).pathExtension + guard !fileExtension.isEmpty, + fileExtension.utf8.count <= 16, + fileExtension.unicodeScalars.allSatisfy({ CharacterSet.alphanumerics.contains($0) }) else { + return nil + } + return fileExtension + } + + private func openDirectoryTree(rootURL: URL, components: [String]) throws -> OpenedFile { + var directory = try openDirectory(atPath: rootURL.path) + for component in components { + directory = try openDirectory(at: directory.descriptor, component: component) + } + return directory + } + + private func openDirectory(atPath path: String) throws -> OpenedFile { + let descriptor = path.withCString { Darwin.open($0, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) } + guard descriptor >= 0 else { + throw FileSharingImportError.unavailableStorage + } + return OpenedFile(descriptor: descriptor) + } + + private func openDirectory(at parentDescriptor: Int32, component: String) throws -> OpenedFile { + let descriptor = component.withCString { + openat(parentDescriptor, $0, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + } + guard descriptor >= 0 else { + throw FileSharingImportError.unsupportedFile + } + return OpenedFile(descriptor: descriptor) + } + + private func openFile(at parentDescriptor: Int32, component: String) throws -> OpenedFile { + let descriptor = component.withCString { + openat(parentDescriptor, $0, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) + } + guard descriptor >= 0 else { + throw FileSharingImportError.unsupportedFile + } + return OpenedFile(descriptor: descriptor) + } + + private func createFile(at parentDescriptor: Int32, component: String) throws -> OpenedFile { + let descriptor = component.withCString { + openat(parentDescriptor, $0, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) + } + guard descriptor >= 0 else { + throw FileSharingImportError.stagingFailed + } + return OpenedFile(descriptor: descriptor) + } +} + +private extension URL { + func isContained(in rootURL: URL) -> Bool { + let rootComponents = rootURL.pathComponents + let candidateComponents = pathComponents + guard candidateComponents.count > rootComponents.count else { + return false + } + return Array(candidateComponents.prefix(rootComponents.count)) == rootComponents + } +} From d9d976a9a018357de752341a5a1f4a30c064d1f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Thu, 6 Aug 2026 13:50:06 +0200 Subject: [PATCH 3/7] test(security): Cover shared file import boundaries --- kDriveTestShared/MCKRouter.swift | 5 +- .../DeepLinks/UTFileSharingDeeplink.swift | 106 ++++++ .../Files/UTFileSharingImporter.swift | 322 ++++++++++++++++++ 3 files changed, 431 insertions(+), 2 deletions(-) create mode 100644 kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift create mode 100644 kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift diff --git a/kDriveTestShared/MCKRouter.swift b/kDriveTestShared/MCKRouter.swift index d508aead8..0bdc4c886 100644 --- a/kDriveTestShared/MCKRouter.swift +++ b/kDriveTestShared/MCKRouter.swift @@ -26,6 +26,7 @@ import UIKit /// A NOOP implementation of AppNavigable public final class MCKRouter: AppNavigable { public var rootViewController: UIViewController? + public private(set) var navigatedRoutes = [NavigationRoutes]() public init(topMostViewController: UIViewController? = nil) { self.topMostViewController = topMostViewController @@ -39,8 +40,8 @@ public final class MCKRouter: AppNavigable { logNoop() } - public func navigate(to route: NavigationRoutes) { - logNoop() + @MainActor public func navigate(to route: NavigationRoutes) { + navigatedRoutes.append(route) } public func askForReview() async { diff --git a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift new file mode 100644 index 000000000..c7f435da3 --- /dev/null +++ b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift @@ -0,0 +1,106 @@ +/* + Infomaniak kDrive - iOS App + Copyright (C) 2026 Infomaniak Network SA + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +import Foundation +@testable import InfomaniakDI +@testable import kDriveCore +import XCTest + +final class UTFileSharingDeeplink: XCTestCase { + private let fileManager = FileManager.default + private var testRootURL: URL! + private var handoffRootURL: URL! + private var stagingRootURL: URL! + private var router: MCKRouter! + + override func setUpWithError() throws { + try super.setUpWithError() + TestTargetAssemblyHelper.clearRegisteredTypes() + _ = TestTargetAssemblyHelper(configuration: .minimal) + + testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + handoffRootURL = testRootURL.appendingPathComponent("shared/Library/Caches/file-sharing", isDirectory: true) + stagingRootURL = testRootURL.appendingPathComponent("drive/import", isDirectory: true) + try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) + try fileManager.createDirectory(at: stagingRootURL, withIntermediateDirectories: true) + + let importer = FileSharingImporter( + fileManager: fileManager, + sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), + stagingRootURL: stagingRootURL, + limits: FileSharingImporter.Limits( + maximumFileCount: 3, + maximumFileSize: 1024, + maximumAggregateSize: 2048, + freeSpaceReserve: 0 + ) + ) + SimpleResolver.sharedResolver.store(factory: Factory(type: FileSharingImportable.self) { _, _ in importer }) + + router = MCKRouter() + SimpleResolver.sharedResolver.store(factory: Factory(type: AppNavigable.self) { [router] _, _ in router! }) + } + + override func tearDownWithError() throws { + TestTargetAssemblyHelper.clearRegisteredTypes() + try? fileManager.removeItem(at: testRootURL) + try super.tearDownWithError() + } + + @MainActor func testExactFileSharingRouteStagesAndNavigates() async throws { + let sourceURL = try createSourceFile() + let parser = DeeplinkParser() + + let success = try await parser.parse(url: makeURL(scheme: FileSharingImporter.scheme, sourceURL: sourceURL)) + + XCTAssertTrue(success) + guard case .saveFiles(let files) = router.navigatedRoutes.first else { + return XCTFail("Expected the save files route") + } + XCTAssertEqual(files.count, 1) + XCTAssertEqual(files[0].path.deletingLastPathComponent(), stagingRootURL) + XCTAssertNotEqual(files[0].path, sourceURL) + } + + @MainActor func testOtherSchemeCannotReachFileImport() async throws { + let sourceURL = try createSourceFile() + let parser = DeeplinkParser() + + let success = try await parser.parse(url: makeURL(scheme: "kdrive", sourceURL: sourceURL)) + + XCTAssertFalse(success) + XCTAssertTrue(router.navigatedRoutes.isEmpty) + XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) + } + + private func createSourceFile() throws -> URL { + let handoffDirectoryURL = handoffRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) + try fileManager.createDirectory(at: handoffDirectoryURL, withIntermediateDirectories: true) + let sourceURL = handoffDirectoryURL.appendingPathComponent("file.txt") + try Data("content".utf8).write(to: sourceURL) + return sourceURL + } + + private func makeURL(scheme: String, sourceURL: URL) throws -> URL { + var components = URLComponents() + components.scheme = scheme + components.host = FileSharingImporter.host + components.queryItems = [URLQueryItem(name: "url", value: sourceURL.path)] + return try XCTUnwrap(components.url) + } +} diff --git a/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift b/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift new file mode 100644 index 000000000..64c9b7aaf --- /dev/null +++ b/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift @@ -0,0 +1,322 @@ +/* + Infomaniak kDrive - iOS App + Copyright (C) 2026 Infomaniak Network SA + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +import Foundation +@testable import kDriveCore +import XCTest + +final class UTFileSharingImporter: XCTestCase { + private let fileManager = FileManager.default + private var testRootURL: URL! + private var handoffRootURL: URL! + private var stagingRootURL: URL! + + override func setUpWithError() throws { + try super.setUpWithError() + testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + handoffRootURL = testRootURL.appendingPathComponent("shared/Library/Caches/file-sharing", isDirectory: true) + stagingRootURL = testRootURL.appendingPathComponent("drive/import", isDirectory: true) + try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) + try fileManager.createDirectory(at: stagingRootURL, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try? fileManager.removeItem(at: testRootURL) + try super.tearDownWithError() + } + + func testImportsRegularFileIntoKDriveOwnedStaging() async throws { + let sourceURL = try createSourceFile(name: "facture été.txt", data: Data("content".utf8)) + let importer = makeImporter { "staged" } + + let files = try await importer.importFiles(from: makeURL(paths: [sourceURL.path])) + + let file = try XCTUnwrap(files.first) + XCTAssertEqual(files.count, 1) + XCTAssertEqual(file.name, "facture été.txt") + XCTAssertEqual(file.path.deletingLastPathComponent(), stagingRootURL) + XCTAssertNotEqual(file.path, sourceURL) + XCTAssertEqual(try Data(contentsOf: file.path), Data("content".utf8)) + XCTAssertTrue(fileManager.fileExists(atPath: sourceURL.path)) + } + + func testPreservesLiteralPercentAndFragmentCharactersInFileName() async throws { + let sourceURL = try createSourceFile(name: "100%#final.txt") + + let files = try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) + + XCTAssertEqual(files.first?.name, "100%#final.txt") + } + + func testRejectsWrongRoutes() async throws { + let sourceURL = try createSourceFile(name: "file.txt") + let routes = try [ + makeURL(paths: [sourceURL.path], scheme: "kdrive"), + makeURL(paths: [sourceURL.path], host: "other"), + makeURL(paths: [sourceURL.path], path: "/unexpected"), + makeURL(paths: [sourceURL.path], fragment: "fragment") + ] + + for route in routes { + await assertImportError(.invalidRoute) { + try await makeImporter().importFiles(from: route) + } + } + } + + func testRejectsUnexpectedAndMissingQueryValues() async throws { + var unknownQuery = URLComponents() + unknownQuery.scheme = FileSharingImporter.scheme + unknownQuery.host = FileSharingImporter.host + unknownQuery.queryItems = [URLQueryItem(name: "path", value: "/tmp/file")] + + var missingValue = URLComponents() + missingValue.scheme = FileSharingImporter.scheme + missingValue.host = FileSharingImporter.host + missingValue.queryItems = [URLQueryItem(name: "url", value: nil)] + + await assertImportError(.invalidQuery) { + try await makeImporter().importFiles(from: XCTUnwrap(unknownQuery.url)) + } + await assertImportError(.invalidQuery) { + try await makeImporter().importFiles(from: XCTUnwrap(missingValue.url)) + } + } + + func testDecodesQueryExactlyOnce() async throws { + let url = try XCTUnwrap(URL(string: "kdrive-file-sharing://file?url=%252Ftmp%252Fsecret.txt")) + + await assertImportError(.invalidPath) { + try await makeImporter().importFiles(from: url) + } + } + + func testRejectsPathsOutsideRootIncludingCommonPrefixSibling() async throws { + let outsideURL = testRootURL.appendingPathComponent("outside.txt") + try Data().write(to: outsideURL) + + let siblingRootURL = URL(fileURLWithPath: handoffRootURL.path + "-other", isDirectory: true) + try fileManager.createDirectory(at: siblingRootURL, withIntermediateDirectories: true) + let siblingURL = siblingRootURL.appendingPathComponent("file.txt") + try Data().write(to: siblingURL) + + for sourceURL in [outsideURL, siblingURL] { + await assertImportError(.sourceOutsideHandoffRoot) { + try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) + } + } + } + + func testRejectsInvalidHandoffLayout() async throws { + let invalidDirectoryURL = handoffRootURL.appendingPathComponent("not-a-uuid", isDirectory: true) + try fileManager.createDirectory(at: invalidDirectoryURL, withIntermediateDirectories: true) + let sourceURL = invalidDirectoryURL.appendingPathComponent("file.txt") + try Data().write(to: sourceURL) + + await assertImportError(.invalidHandoffLayout) { + try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) + } + } + + func testRejectsDirectoryAndSymlink() async throws { + let handoffDirectoryURL = try createHandoffDirectory() + let directoryURL = handoffDirectoryURL.appendingPathComponent("folder", isDirectory: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) + + let targetURL = testRootURL.appendingPathComponent("target.txt") + try Data().write(to: targetURL) + let symlinkURL = handoffDirectoryURL.appendingPathComponent("link.txt") + try fileManager.createSymbolicLink(at: symlinkURL, withDestinationURL: targetURL) + + for sourceURL in [directoryURL, symlinkURL] { + await assertImportError(.unsupportedFile) { + try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) + } + } + } + + func testRejectsSymlinkedHandoffRoot() async throws { + let actualRootURL = testRootURL.appendingPathComponent("actual-file-sharing", isDirectory: true) + try fileManager.createDirectory(at: actualRootURL, withIntermediateDirectories: true) + try fileManager.removeItem(at: handoffRootURL) + try fileManager.createSymbolicLink(at: handoffRootURL, withDestinationURL: actualRootURL) + + let handoffDirectoryURL = actualRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) + try fileManager.createDirectory(at: handoffDirectoryURL, withIntermediateDirectories: true) + let actualSourceURL = handoffDirectoryURL.appendingPathComponent("file.txt") + try Data().write(to: actualSourceURL) + let suppliedSourceURL = handoffRootURL + .appendingPathComponent(handoffDirectoryURL.lastPathComponent, isDirectory: true) + .appendingPathComponent(actualSourceURL.lastPathComponent) + + await assertImportError(.unsupportedFile) { + try await makeImporter().importFiles(from: makeURL(paths: [suppliedSourceURL.path])) + } + } + + func testRejectsDuplicateCanonicalPaths() async throws { + let sourceURL = try createSourceFile(name: "file.txt") + + await assertImportError(.duplicateFile) { + try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path, sourceURL.path])) + } + } + + func testEnforcesFileCountAndSizeLimits() async throws { + let firstURL = try createSourceFile(name: "first.txt", data: Data(repeating: 0, count: 3)) + let secondURL = try createSourceFile(name: "second.txt", data: Data(repeating: 0, count: 3)) + + await assertImportError(.tooManyFiles) { + let limits = FileSharingImporter.Limits( + maximumFileCount: 1, + maximumFileSize: 10, + maximumAggregateSize: 10, + freeSpaceReserve: 0 + ) + _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) + } + + await assertImportError(.fileTooLarge) { + let limits = FileSharingImporter.Limits( + maximumFileCount: 2, + maximumFileSize: 2, + maximumAggregateSize: 10, + freeSpaceReserve: 0 + ) + _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path])) + } + + await assertImportError(.aggregateSizeExceeded) { + let limits = FileSharingImporter.Limits( + maximumFileCount: 2, + maximumFileSize: 3, + maximumAggregateSize: 5, + freeSpaceReserve: 0 + ) + _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) + } + } + + func testRejectsImportWhenStagingCapacityIsInsufficient() async throws { + let sourceURL = try createSourceFile(name: "file.txt", data: Data(repeating: 0, count: 3)) + let importer = makeImporter { _ in 2 } + + await assertImportError(.insufficientSpace) { + try await importer.importFiles(from: makeURL(paths: [sourceURL.path])) + } + } + + func testValidatesWholeRequestBeforeStaging() async throws { + let validURL = try createSourceFile(name: "valid.txt") + let invalidURL = testRootURL.appendingPathComponent("outside.txt") + try Data().write(to: invalidURL) + + await assertImportError(.sourceOutsideHandoffRoot) { + try await makeImporter().importFiles(from: makeURL(paths: [validURL.path, invalidURL.path])) + } + XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) + } + + func testRollsBackStagingIfACopyFails() async throws { + let firstURL = try createSourceFile(name: "first.txt") + let secondURL = try createSourceFile(name: "second.txt") + let importer = makeImporter { "same-identifier" } + + await assertImportError(.stagingFailed) { + try await importer.importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) + } + XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) + XCTAssertTrue(fileManager.fileExists(atPath: firstURL.path)) + XCTAssertTrue(fileManager.fileExists(atPath: secondURL.path)) + } + + private func makeImporter( + limits: FileSharingImporter.Limits = FileSharingImporter.Limits( + maximumFileCount: 3, + maximumFileSize: 1024, + maximumAggregateSize: 2048, + freeSpaceReserve: 0 + ), + makeIdentifier: @escaping () -> String = { UUID().uuidString } + ) -> FileSharingImporter { + return FileSharingImporter( + fileManager: fileManager, + sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), + stagingRootURL: stagingRootURL, + limits: limits, + makeIdentifier: makeIdentifier + ) + } + + private func makeImporter( + availableCapacity: @escaping (URL) throws -> UInt64 + ) -> FileSharingImporter { + return FileSharingImporter( + fileManager: fileManager, + sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), + stagingRootURL: stagingRootURL, + limits: FileSharingImporter.Limits( + maximumFileCount: 3, + maximumFileSize: 1024, + maximumAggregateSize: 2048, + freeSpaceReserve: 0 + ), + availableCapacity: availableCapacity + ) + } + + private func createHandoffDirectory() throws -> URL { + let directoryURL = handoffRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) + return directoryURL + } + + private func createSourceFile(name: String, data: Data = Data()) throws -> URL { + let sourceURL = try createHandoffDirectory().appendingPathComponent(name) + try data.write(to: sourceURL) + return sourceURL + } + + private func makeURL( + paths: [String], + scheme: String = FileSharingImporter.scheme, + host: String = FileSharingImporter.host, + path: String = "", + fragment: String? = nil + ) throws -> URL { + var components = URLComponents() + components.scheme = scheme + components.host = host + components.path = path + components.fragment = fragment + components.queryItems = paths.map { URLQueryItem(name: "url", value: $0) } + return try XCTUnwrap(components.url) + } + + private func assertImportError( + _ expectedError: FileSharingImportError, + operation: () async throws -> T + ) async { + do { + _ = try await operation() + XCTFail("Expected \(expectedError)") + } catch { + XCTAssertEqual(error as? FileSharingImportError, expectedError) + } + } +} From 5f5aeaef3b475703f98647a4cf684055873f6604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Mon, 10 Aug 2026 10:00:09 +0200 Subject: [PATCH 4/7] refactor(security): Simplify shared file hardening --- kDriveCore/DI/CoreTargetAssembly.swift | 3 - kDriveCore/Utils/DeeplinkParser.swift | 101 ++++- .../Utils/Files/FileSharingImporter.swift | 364 ------------------ kDriveTestShared/MCKRouter.swift | 5 +- .../DeepLinks/UTFileSharingDeeplink.swift | 103 ++--- .../Files/UTFileSharingImporter.swift | 322 ---------------- 6 files changed, 150 insertions(+), 748 deletions(-) delete mode 100644 kDriveCore/Utils/Files/FileSharingImporter.swift delete mode 100644 kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift diff --git a/kDriveCore/DI/CoreTargetAssembly.swift b/kDriveCore/DI/CoreTargetAssembly.swift index d5aae8676..e43d69149 100644 --- a/kDriveCore/DI/CoreTargetAssembly.swift +++ b/kDriveCore/DI/CoreTargetAssembly.swift @@ -110,9 +110,6 @@ open class CoreTargetAssembly: TargetAssembly { Factory(type: DeeplinkParsable.self) { _, _ in DeeplinkParser() }, - Factory(type: FileSharingImportable.self) { _, _ in - FileSharingImporter() - }, Factory(type: PublicShareApiFetcher.self) { _, _ in PublicShareApiFetcher() } diff --git a/kDriveCore/Utils/DeeplinkParser.swift b/kDriveCore/Utils/DeeplinkParser.swift index 0b9308815..68d41008b 100644 --- a/kDriveCore/Utils/DeeplinkParser.swift +++ b/kDriveCore/Utils/DeeplinkParser.swift @@ -16,6 +16,7 @@ along with this program. If not, see . */ +import InfomaniakCore import InfomaniakCoreCommonUI import InfomaniakDI import MatomoTracker @@ -28,6 +29,11 @@ public protocol DeeplinkParsable { } public struct DeeplinkParser: DeeplinkParsable { + private static let fileSharingScheme = "kdrive-file-sharing" + private static let fileSharingHost = "file" + private static let fileSharingPath = "Library/Caches/file-sharing" + private static let maximumSharedFileCount = 100 + private enum DeeplinkPath: String { case store case file @@ -38,10 +44,15 @@ public struct DeeplinkParser: DeeplinkParsable { @LazyInjectService private var matomo: MatomoUtils @LazyInjectService var accountManager: AccountManageable @LazyInjectService var router: AppNavigable - @LazyInjectService private var fileSharingImporter: FileSharingImportable + + private let sharedContainerURL: URL? public init() { - // META: keep SonarCloud happy + sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.infomaniak") + } + + init(sharedContainerURL: URL?) { + self.sharedContainerURL = sharedContainerURL } private func handleDeeplink(url: URL) async -> Bool { @@ -98,16 +109,14 @@ public struct DeeplinkParser: DeeplinkParsable { return await handleDeeplink(url: url) } - if components.scheme == FileSharingImporter.scheme || components.host == DeeplinkPath.file.rawValue { - do { - let files = try await fileSharingImporter.importFiles(from: url) - await router.navigate(to: .saveFiles(files: files)) - matomo.track(eventWithCategory: .deeplink, name: DeeplinkPath.file.rawValue) - return true - } catch { + if components.scheme == Self.fileSharingScheme, components.host == Self.fileSharingHost { + guard let files = filesForSharingDeeplink(url) else { Log.sceneDelegate("Failed to import files: Invalid request", level: .error) return false } + await router.navigate(to: .saveFiles(files: files)) + matomo.track(eventWithCategory: .deeplink, name: DeeplinkPath.file.rawValue) + return true } guard let params = components.queryItems else { @@ -131,4 +140,78 @@ public struct DeeplinkParser: DeeplinkParsable { Log.sceneDelegate("unable to parse deeplink URL: \(url)", level: .error) return false } + + func filesForSharingDeeplink(_ url: URL) -> [ImportedFile]? { + guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), + components.scheme == Self.fileSharingScheme, + components.host == Self.fileSharingHost, + components.path.isEmpty, + components.user == nil, + components.password == nil, + components.port == nil, + components.fragment == nil, + let queryItems = components.queryItems, + !queryItems.isEmpty, + queryItems.count <= Self.maximumSharedFileCount, + queryItems.allSatisfy({ $0.name == "url" && !($0.value?.isEmpty ?? true) }), + let sharedContainerURL else { + return nil + } + + let handoffRootURL = sharedContainerURL + .appendingPathComponent(Self.fileSharingPath, isDirectory: true) + .standardizedFileURL + let resolvedSharedContainerURL = sharedContainerURL.resolvingSymlinksInPath().standardizedFileURL + let resolvedHandoffRootURL = handoffRootURL.resolvingSymlinksInPath().standardizedFileURL + let expectedHandoffRootURL = resolvedSharedContainerURL + .appendingPathComponent(Self.fileSharingPath, isDirectory: true) + .standardizedFileURL + guard resolvedHandoffRootURL == expectedHandoffRootURL else { + return nil + } + + var files = [ImportedFile]() + for queryItem in queryItems { + guard let path = queryItem.value, + NSString(string: path).isAbsolutePath, + let fileName = path.safeLastPathComponent else { + return nil + } + + let sourceURL = URL(fileURLWithPath: path).standardizedFileURL + guard sourceURL.isSharedFile(in: handoffRootURL) else { + return nil + } + + let resolvedSourceURL = sourceURL.resolvingSymlinksInPath().standardizedFileURL + let expectedSourceURL = sourceURL.pathComponents + .suffix(2) + .reduce(resolvedHandoffRootURL) { $0.appendingPathComponent($1) } + .standardizedFileURL + guard resolvedSourceURL == expectedSourceURL, + let values = try? resolvedSourceURL.resourceValues(forKeys: [.isRegularFileKey]), + values.isRegularFile == true else { + return nil + } + + files.append(ImportedFile( + name: fileName, + path: resolvedSourceURL, + uti: resolvedSourceURL.uti ?? .data + )) + } + return files + } +} + +private extension URL { + func isSharedFile(in rootURL: URL) -> Bool { + let rootComponents = rootURL.pathComponents + let sourceComponents = pathComponents + guard sourceComponents.count == rootComponents.count + 2, + Array(sourceComponents.prefix(rootComponents.count)) == rootComponents else { + return false + } + return UUID(uuidString: sourceComponents[rootComponents.count]) != nil + } } diff --git a/kDriveCore/Utils/Files/FileSharingImporter.swift b/kDriveCore/Utils/Files/FileSharingImporter.swift deleted file mode 100644 index 9ae2d40a4..000000000 --- a/kDriveCore/Utils/Files/FileSharingImporter.swift +++ /dev/null @@ -1,364 +0,0 @@ -/* - Infomaniak kDrive - iOS App - Copyright (C) 2026 Infomaniak Network SA - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ - -import Darwin -import Foundation -import InfomaniakCore - -protocol FileSharingImportable { - func importFiles(from url: URL) async throws -> [ImportedFile] -} - -enum FileSharingImportError: Error, Equatable { - case invalidRoute - case invalidQuery - case tooManyFiles - case invalidPath - case duplicateFile - case sourceOutsideHandoffRoot - case invalidHandoffLayout - case invalidFileName - case unsupportedFile - case fileTooLarge - case aggregateSizeExceeded - case insufficientSpace - case unavailableStorage - case stagingFailed -} - -final class FileSharingImporter: FileSharingImportable { - struct Limits { - static let `default` = Limits( - maximumFileCount: 100, - maximumFileSize: Constants.rangeProviderConfig.fileMaxSizeClient - 1, - maximumAggregateSize: Constants.rangeProviderConfig.fileMaxSizeClient - 1, - freeSpaceReserve: 50 * 1024 * 1024 - ) - - let maximumFileCount: Int - let maximumFileSize: UInt64 - let maximumAggregateSize: UInt64 - let freeSpaceReserve: UInt64 - } - - private struct ValidatedFile { - let source: OpenedFile - let name: String - let uti: UTI - let fileExtension: String? - let size: UInt64 - } - - private final class OpenedFile { - let descriptor: Int32 - - init(descriptor: Int32) { - self.descriptor = descriptor - } - - deinit { - Darwin.close(descriptor) - } - } - - static let scheme = "kdrive-file-sharing" - static let host = "file" - - private static let sharedAppGroup = "group.com.infomaniak" - private static let handoffPathComponents = ["Library", "Caches", "file-sharing"] - - private let fileManager: FileManager - private let sharedContainerURL: URL? - private let stagingRootURL: URL - private let limits: Limits - private let makeIdentifier: () -> String - private let availableCapacity: (URL) throws -> UInt64 - - convenience init() { - let fileManager = FileManager.default - self.init( - fileManager: fileManager, - sharedContainerURL: fileManager.containerURL(forSecurityApplicationGroupIdentifier: Self.sharedAppGroup), - stagingRootURL: DriveFileManager.constants.importDirectoryURL - ) - } - - init( - fileManager: FileManager, - sharedContainerURL: URL?, - stagingRootURL: URL, - limits: Limits = .default, - makeIdentifier: @escaping () -> String = { UUID().uuidString }, - availableCapacity: ((URL) throws -> UInt64)? = nil - ) { - self.fileManager = fileManager - self.sharedContainerURL = sharedContainerURL - self.stagingRootURL = stagingRootURL - self.limits = limits - self.makeIdentifier = makeIdentifier - self.availableCapacity = availableCapacity ?? { url in - let attributes = try fileManager.attributesOfFileSystem(forPath: url.path) - guard let capacity = (attributes[.systemFreeSize] as? NSNumber)?.uint64Value else { - throw FileSharingImportError.unavailableStorage - } - return capacity - } - } - - func importFiles(from url: URL) async throws -> [ImportedFile] { - return try await Task.detached(priority: .userInitiated) { [self] in - let validatedFiles = try validate(url: url) - try checkAvailableSpace(for: validatedFiles) - return try stage(validatedFiles) - }.value - } - - private func validate(url: URL) throws -> [ValidatedFile] { - guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), - components.scheme == Self.scheme, - components.host == Self.host, - components.path.isEmpty, - components.user == nil, - components.password == nil, - components.port == nil, - components.fragment == nil else { - throw FileSharingImportError.invalidRoute - } - - guard let queryItems = components.queryItems, - !queryItems.isEmpty, - queryItems.allSatisfy({ $0.name == "url" && !($0.value?.isEmpty ?? true) }) else { - throw FileSharingImportError.invalidQuery - } - guard queryItems.count <= limits.maximumFileCount else { - throw FileSharingImportError.tooManyFiles - } - guard let sharedContainerURL else { - throw FileSharingImportError.unavailableStorage - } - - let handoffRootURL = Self.handoffPathComponents.reduce(sharedContainerURL) { rootURL, component in - rootURL.appendingPathComponent(component, isDirectory: true) - }.standardizedFileURL - let handoffRoot = try openDirectoryTree( - rootURL: sharedContainerURL.standardizedFileURL, - components: Self.handoffPathComponents - ) - var canonicalPaths = Set() - var aggregateSize: UInt64 = 0 - - return try queryItems.map { queryItem in - guard let path = queryItem.value, - path.utf8.count < Int(PATH_MAX), - NSString(string: path).isAbsolutePath else { - throw FileSharingImportError.invalidPath - } - - let candidateURL = URL(fileURLWithPath: path).standardizedFileURL - guard candidateURL.isContained(in: handoffRootURL) else { - throw FileSharingImportError.sourceOutsideHandoffRoot - } - - let relativeComponents = Array(candidateURL.pathComponents.dropFirst(handoffRootURL.pathComponents.count)) - guard relativeComponents.count == 2, - UUID(uuidString: relativeComponents[0]) != nil else { - throw FileSharingImportError.invalidHandoffLayout - } - guard canonicalPaths.insert(candidateURL.path).inserted else { - throw FileSharingImportError.duplicateFile - } - let safeName = relativeComponents[1] - guard isValidFileName(safeName) else { - throw FileSharingImportError.invalidFileName - } - - let handoffDirectory = try openDirectory(at: handoffRoot.descriptor, component: relativeComponents[0]) - let source = try openFile(at: handoffDirectory.descriptor, component: safeName) - var sourceInfo = stat() - guard Darwin.fstat(source.descriptor, &sourceInfo) == 0, - sourceInfo.st_mode & S_IFMT == S_IFREG, - sourceInfo.st_nlink == 1, - sourceInfo.st_size >= 0 else { - throw FileSharingImportError.unsupportedFile - } - let fileSize = UInt64(sourceInfo.st_size) - guard fileSize <= limits.maximumFileSize else { - throw FileSharingImportError.fileTooLarge - } - guard fileSize <= limits.maximumAggregateSize - aggregateSize else { - throw FileSharingImportError.aggregateSizeExceeded - } - aggregateSize += fileSize - - let fileExtension = safeExtension(for: safeName) - let uti = fileExtension.flatMap { UTI(filenameExtension: $0) } ?? .data - return ValidatedFile( - source: source, - name: safeName, - uti: uti, - fileExtension: fileExtension, - size: fileSize - ) - } - } - - private func checkAvailableSpace(for files: [ValidatedFile]) throws { - let aggregateSize = files.reduce(UInt64(0)) { $0 + $1.size } - guard aggregateSize <= UInt64.max - limits.freeSpaceReserve else { - throw FileSharingImportError.aggregateSizeExceeded - } - - let freeSize: UInt64 - do { - freeSize = try availableCapacity(stagingRootURL) - } catch { - throw FileSharingImportError.unavailableStorage - } - guard freeSize >= aggregateSize + limits.freeSpaceReserve else { - throw FileSharingImportError.insufficientSpace - } - } - - private func stage(_ files: [ValidatedFile]) throws -> [ImportedFile] { - let stagingRoot: OpenedFile - do { - stagingRoot = try openDirectory(atPath: stagingRootURL.path) - } catch { - throw FileSharingImportError.unavailableStorage - } - - var stagedNames = [String]() - do { - return try files.map { file in - var destinationName = makeIdentifier() - if let fileExtension = file.fileExtension { - destinationName += ".\(fileExtension)" - } - guard isValidFileName(destinationName) else { - throw FileSharingImportError.stagingFailed - } - - let destination = try createFile(at: stagingRoot.descriptor, component: destinationName) - stagedNames.append(destinationName) - guard fcopyfile(file.source.descriptor, destination.descriptor, nil, copyfile_flags_t(COPYFILE_DATA)) == 0 else { - throw FileSharingImportError.stagingFailed - } - var sourceInfo = stat() - guard Darwin.fstat(file.source.descriptor, &sourceInfo) == 0 else { - throw FileSharingImportError.stagingFailed - } - var timestamps = [sourceInfo.st_atimespec, sourceInfo.st_mtimespec] - guard futimens(destination.descriptor, ×tamps) == 0 else { - throw FileSharingImportError.stagingFailed - } - - var destinationInfo = stat() - guard Darwin.fstat(destination.descriptor, &destinationInfo) == 0, - destinationInfo.st_mode & S_IFMT == S_IFREG, - destinationInfo.st_size >= 0, - UInt64(destinationInfo.st_size) == file.size else { - throw FileSharingImportError.stagingFailed - } - - let destinationURL = stagingRootURL.appendingPathComponent(destinationName, isDirectory: false) - return ImportedFile(name: file.name, path: destinationURL, uti: file.uti) - } - } catch { - for name in stagedNames { - name.withCString { unlinkat(stagingRoot.descriptor, $0, 0) } - } - throw FileSharingImportError.stagingFailed - } - } - - private func isValidFileName(_ fileName: String) -> Bool { - let invalidCharacters = CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/\\")) - return !fileName.isEmpty - && fileName != "." - && fileName != ".." - && fileName.utf8.count <= Int(NAME_MAX) - && fileName.rangeOfCharacter(from: invalidCharacters) == nil - } - - private func safeExtension(for fileName: String) -> String? { - let fileExtension = URL(fileURLWithPath: fileName).pathExtension - guard !fileExtension.isEmpty, - fileExtension.utf8.count <= 16, - fileExtension.unicodeScalars.allSatisfy({ CharacterSet.alphanumerics.contains($0) }) else { - return nil - } - return fileExtension - } - - private func openDirectoryTree(rootURL: URL, components: [String]) throws -> OpenedFile { - var directory = try openDirectory(atPath: rootURL.path) - for component in components { - directory = try openDirectory(at: directory.descriptor, component: component) - } - return directory - } - - private func openDirectory(atPath path: String) throws -> OpenedFile { - let descriptor = path.withCString { Darwin.open($0, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) } - guard descriptor >= 0 else { - throw FileSharingImportError.unavailableStorage - } - return OpenedFile(descriptor: descriptor) - } - - private func openDirectory(at parentDescriptor: Int32, component: String) throws -> OpenedFile { - let descriptor = component.withCString { - openat(parentDescriptor, $0, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) - } - guard descriptor >= 0 else { - throw FileSharingImportError.unsupportedFile - } - return OpenedFile(descriptor: descriptor) - } - - private func openFile(at parentDescriptor: Int32, component: String) throws -> OpenedFile { - let descriptor = component.withCString { - openat(parentDescriptor, $0, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC) - } - guard descriptor >= 0 else { - throw FileSharingImportError.unsupportedFile - } - return OpenedFile(descriptor: descriptor) - } - - private func createFile(at parentDescriptor: Int32, component: String) throws -> OpenedFile { - let descriptor = component.withCString { - openat(parentDescriptor, $0, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR) - } - guard descriptor >= 0 else { - throw FileSharingImportError.stagingFailed - } - return OpenedFile(descriptor: descriptor) - } -} - -private extension URL { - func isContained(in rootURL: URL) -> Bool { - let rootComponents = rootURL.pathComponents - let candidateComponents = pathComponents - guard candidateComponents.count > rootComponents.count else { - return false - } - return Array(candidateComponents.prefix(rootComponents.count)) == rootComponents - } -} diff --git a/kDriveTestShared/MCKRouter.swift b/kDriveTestShared/MCKRouter.swift index 0bdc4c886..d508aead8 100644 --- a/kDriveTestShared/MCKRouter.swift +++ b/kDriveTestShared/MCKRouter.swift @@ -26,7 +26,6 @@ import UIKit /// A NOOP implementation of AppNavigable public final class MCKRouter: AppNavigable { public var rootViewController: UIViewController? - public private(set) var navigatedRoutes = [NavigationRoutes]() public init(topMostViewController: UIViewController? = nil) { self.topMostViewController = topMostViewController @@ -40,8 +39,8 @@ public final class MCKRouter: AppNavigable { logNoop() } - @MainActor public func navigate(to route: NavigationRoutes) { - navigatedRoutes.append(route) + public func navigate(to route: NavigationRoutes) { + logNoop() } public func askForReview() async { diff --git a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift index c7f435da3..fb98a624f 100644 --- a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift +++ b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift @@ -17,89 +17,98 @@ */ import Foundation -@testable import InfomaniakDI @testable import kDriveCore import XCTest final class UTFileSharingDeeplink: XCTestCase { private let fileManager = FileManager.default private var testRootURL: URL! + private var sharedContainerURL: URL! private var handoffRootURL: URL! - private var stagingRootURL: URL! - private var router: MCKRouter! override func setUpWithError() throws { try super.setUpWithError() - TestTargetAssemblyHelper.clearRegisteredTypes() - _ = TestTargetAssemblyHelper(configuration: .minimal) - testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) - handoffRootURL = testRootURL.appendingPathComponent("shared/Library/Caches/file-sharing", isDirectory: true) - stagingRootURL = testRootURL.appendingPathComponent("drive/import", isDirectory: true) + sharedContainerURL = testRootURL.appendingPathComponent("shared", isDirectory: true) + handoffRootURL = sharedContainerURL.appendingPathComponent("Library/Caches/file-sharing", isDirectory: true) try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) - try fileManager.createDirectory(at: stagingRootURL, withIntermediateDirectories: true) - - let importer = FileSharingImporter( - fileManager: fileManager, - sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), - stagingRootURL: stagingRootURL, - limits: FileSharingImporter.Limits( - maximumFileCount: 3, - maximumFileSize: 1024, - maximumAggregateSize: 2048, - freeSpaceReserve: 0 - ) - ) - SimpleResolver.sharedResolver.store(factory: Factory(type: FileSharingImportable.self) { _, _ in importer }) - - router = MCKRouter() - SimpleResolver.sharedResolver.store(factory: Factory(type: AppNavigable.self) { [router] _, _ in router! }) } override func tearDownWithError() throws { - TestTargetAssemblyHelper.clearRegisteredTypes() try? fileManager.removeItem(at: testRootURL) try super.tearDownWithError() } - @MainActor func testExactFileSharingRouteStagesAndNavigates() async throws { + func testAcceptsRegularFileFromHandoffDirectory() throws { let sourceURL = try createSourceFile() - let parser = DeeplinkParser() - let success = try await parser.parse(url: makeURL(scheme: FileSharingImporter.scheme, sourceURL: sourceURL)) + let deeplinkURL = try makeURL(for: sourceURL) + let files = DeeplinkParser(sharedContainerURL: sharedContainerURL).filesForSharingDeeplink(deeplinkURL) - XCTAssertTrue(success) - guard case .saveFiles(let files) = router.navigatedRoutes.first else { - return XCTFail("Expected the save files route") - } - XCTAssertEqual(files.count, 1) - XCTAssertEqual(files[0].path.deletingLastPathComponent(), stagingRootURL) - XCTAssertNotEqual(files[0].path, sourceURL) + XCTAssertEqual(files?.count, 1) + XCTAssertEqual(files?.first?.name, sourceURL.lastPathComponent) + XCTAssertEqual(files?.first?.path, sourceURL) } - @MainActor func testOtherSchemeCannotReachFileImport() async throws { + func testRejectsWrongRoute() throws { let sourceURL = try createSourceFile() - let parser = DeeplinkParser() + let parser = DeeplinkParser(sharedContainerURL: sharedContainerURL) + + let wrongSchemeURL = try makeURL(for: sourceURL, scheme: "kdrive") + let wrongHostURL = try makeURL(for: sourceURL, host: "other") + + XCTAssertNil(parser.filesForSharingDeeplink(wrongSchemeURL)) + XCTAssertNil(parser.filesForSharingDeeplink(wrongHostURL)) + } + + func testRejectsFileOutsideHandoffDirectory() throws { + let outsideURL = testRootURL.appendingPathComponent("outside.txt") + try Data().write(to: outsideURL) + + let deeplinkURL = try makeURL(for: outsideURL) + let files = DeeplinkParser(sharedContainerURL: sharedContainerURL).filesForSharingDeeplink(deeplinkURL) + + XCTAssertNil(files) + } - let success = try await parser.parse(url: makeURL(scheme: "kdrive", sourceURL: sourceURL)) + func testRejectsSymlinkEscapingHandoffDirectory() throws { + let outsideURL = testRootURL.appendingPathComponent("outside.txt") + try Data().write(to: outsideURL) + let symlinkURL = try createHandoffDirectory().appendingPathComponent("link.txt") + try fileManager.createSymbolicLink(at: symlinkURL, withDestinationURL: outsideURL) + + let deeplinkURL = try makeURL(for: symlinkURL) + let files = DeeplinkParser(sharedContainerURL: sharedContainerURL).filesForSharingDeeplink(deeplinkURL) + + XCTAssertNil(files) + } + + func testRejectsDirectory() throws { + let directoryURL = try createHandoffDirectory().appendingPathComponent("folder", isDirectory: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: false) + + let deeplinkURL = try makeURL(for: directoryURL) + let files = DeeplinkParser(sharedContainerURL: sharedContainerURL).filesForSharingDeeplink(deeplinkURL) + + XCTAssertNil(files) + } - XCTAssertFalse(success) - XCTAssertTrue(router.navigatedRoutes.isEmpty) - XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) + private func createHandoffDirectory() throws -> URL { + let directoryURL = handoffRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: false) + return directoryURL } private func createSourceFile() throws -> URL { - let handoffDirectoryURL = handoffRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) - try fileManager.createDirectory(at: handoffDirectoryURL, withIntermediateDirectories: true) - let sourceURL = handoffDirectoryURL.appendingPathComponent("file.txt") + let sourceURL = try createHandoffDirectory().appendingPathComponent("file.txt") try Data("content".utf8).write(to: sourceURL) return sourceURL } - private func makeURL(scheme: String, sourceURL: URL) throws -> URL { + private func makeURL(for sourceURL: URL, scheme: String = "kdrive-file-sharing", host: String = "file") throws -> URL { var components = URLComponents() components.scheme = scheme - components.host = FileSharingImporter.host + components.host = host components.queryItems = [URLQueryItem(name: "url", value: sourceURL.path)] return try XCTUnwrap(components.url) } diff --git a/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift b/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift deleted file mode 100644 index 64c9b7aaf..000000000 --- a/kDriveTests/kDriveCore/Files/UTFileSharingImporter.swift +++ /dev/null @@ -1,322 +0,0 @@ -/* - Infomaniak kDrive - iOS App - Copyright (C) 2026 Infomaniak Network SA - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ - -import Foundation -@testable import kDriveCore -import XCTest - -final class UTFileSharingImporter: XCTestCase { - private let fileManager = FileManager.default - private var testRootURL: URL! - private var handoffRootURL: URL! - private var stagingRootURL: URL! - - override func setUpWithError() throws { - try super.setUpWithError() - testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) - handoffRootURL = testRootURL.appendingPathComponent("shared/Library/Caches/file-sharing", isDirectory: true) - stagingRootURL = testRootURL.appendingPathComponent("drive/import", isDirectory: true) - try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) - try fileManager.createDirectory(at: stagingRootURL, withIntermediateDirectories: true) - } - - override func tearDownWithError() throws { - try? fileManager.removeItem(at: testRootURL) - try super.tearDownWithError() - } - - func testImportsRegularFileIntoKDriveOwnedStaging() async throws { - let sourceURL = try createSourceFile(name: "facture été.txt", data: Data("content".utf8)) - let importer = makeImporter { "staged" } - - let files = try await importer.importFiles(from: makeURL(paths: [sourceURL.path])) - - let file = try XCTUnwrap(files.first) - XCTAssertEqual(files.count, 1) - XCTAssertEqual(file.name, "facture été.txt") - XCTAssertEqual(file.path.deletingLastPathComponent(), stagingRootURL) - XCTAssertNotEqual(file.path, sourceURL) - XCTAssertEqual(try Data(contentsOf: file.path), Data("content".utf8)) - XCTAssertTrue(fileManager.fileExists(atPath: sourceURL.path)) - } - - func testPreservesLiteralPercentAndFragmentCharactersInFileName() async throws { - let sourceURL = try createSourceFile(name: "100%#final.txt") - - let files = try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) - - XCTAssertEqual(files.first?.name, "100%#final.txt") - } - - func testRejectsWrongRoutes() async throws { - let sourceURL = try createSourceFile(name: "file.txt") - let routes = try [ - makeURL(paths: [sourceURL.path], scheme: "kdrive"), - makeURL(paths: [sourceURL.path], host: "other"), - makeURL(paths: [sourceURL.path], path: "/unexpected"), - makeURL(paths: [sourceURL.path], fragment: "fragment") - ] - - for route in routes { - await assertImportError(.invalidRoute) { - try await makeImporter().importFiles(from: route) - } - } - } - - func testRejectsUnexpectedAndMissingQueryValues() async throws { - var unknownQuery = URLComponents() - unknownQuery.scheme = FileSharingImporter.scheme - unknownQuery.host = FileSharingImporter.host - unknownQuery.queryItems = [URLQueryItem(name: "path", value: "/tmp/file")] - - var missingValue = URLComponents() - missingValue.scheme = FileSharingImporter.scheme - missingValue.host = FileSharingImporter.host - missingValue.queryItems = [URLQueryItem(name: "url", value: nil)] - - await assertImportError(.invalidQuery) { - try await makeImporter().importFiles(from: XCTUnwrap(unknownQuery.url)) - } - await assertImportError(.invalidQuery) { - try await makeImporter().importFiles(from: XCTUnwrap(missingValue.url)) - } - } - - func testDecodesQueryExactlyOnce() async throws { - let url = try XCTUnwrap(URL(string: "kdrive-file-sharing://file?url=%252Ftmp%252Fsecret.txt")) - - await assertImportError(.invalidPath) { - try await makeImporter().importFiles(from: url) - } - } - - func testRejectsPathsOutsideRootIncludingCommonPrefixSibling() async throws { - let outsideURL = testRootURL.appendingPathComponent("outside.txt") - try Data().write(to: outsideURL) - - let siblingRootURL = URL(fileURLWithPath: handoffRootURL.path + "-other", isDirectory: true) - try fileManager.createDirectory(at: siblingRootURL, withIntermediateDirectories: true) - let siblingURL = siblingRootURL.appendingPathComponent("file.txt") - try Data().write(to: siblingURL) - - for sourceURL in [outsideURL, siblingURL] { - await assertImportError(.sourceOutsideHandoffRoot) { - try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) - } - } - } - - func testRejectsInvalidHandoffLayout() async throws { - let invalidDirectoryURL = handoffRootURL.appendingPathComponent("not-a-uuid", isDirectory: true) - try fileManager.createDirectory(at: invalidDirectoryURL, withIntermediateDirectories: true) - let sourceURL = invalidDirectoryURL.appendingPathComponent("file.txt") - try Data().write(to: sourceURL) - - await assertImportError(.invalidHandoffLayout) { - try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) - } - } - - func testRejectsDirectoryAndSymlink() async throws { - let handoffDirectoryURL = try createHandoffDirectory() - let directoryURL = handoffDirectoryURL.appendingPathComponent("folder", isDirectory: true) - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - - let targetURL = testRootURL.appendingPathComponent("target.txt") - try Data().write(to: targetURL) - let symlinkURL = handoffDirectoryURL.appendingPathComponent("link.txt") - try fileManager.createSymbolicLink(at: symlinkURL, withDestinationURL: targetURL) - - for sourceURL in [directoryURL, symlinkURL] { - await assertImportError(.unsupportedFile) { - try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path])) - } - } - } - - func testRejectsSymlinkedHandoffRoot() async throws { - let actualRootURL = testRootURL.appendingPathComponent("actual-file-sharing", isDirectory: true) - try fileManager.createDirectory(at: actualRootURL, withIntermediateDirectories: true) - try fileManager.removeItem(at: handoffRootURL) - try fileManager.createSymbolicLink(at: handoffRootURL, withDestinationURL: actualRootURL) - - let handoffDirectoryURL = actualRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) - try fileManager.createDirectory(at: handoffDirectoryURL, withIntermediateDirectories: true) - let actualSourceURL = handoffDirectoryURL.appendingPathComponent("file.txt") - try Data().write(to: actualSourceURL) - let suppliedSourceURL = handoffRootURL - .appendingPathComponent(handoffDirectoryURL.lastPathComponent, isDirectory: true) - .appendingPathComponent(actualSourceURL.lastPathComponent) - - await assertImportError(.unsupportedFile) { - try await makeImporter().importFiles(from: makeURL(paths: [suppliedSourceURL.path])) - } - } - - func testRejectsDuplicateCanonicalPaths() async throws { - let sourceURL = try createSourceFile(name: "file.txt") - - await assertImportError(.duplicateFile) { - try await makeImporter().importFiles(from: makeURL(paths: [sourceURL.path, sourceURL.path])) - } - } - - func testEnforcesFileCountAndSizeLimits() async throws { - let firstURL = try createSourceFile(name: "first.txt", data: Data(repeating: 0, count: 3)) - let secondURL = try createSourceFile(name: "second.txt", data: Data(repeating: 0, count: 3)) - - await assertImportError(.tooManyFiles) { - let limits = FileSharingImporter.Limits( - maximumFileCount: 1, - maximumFileSize: 10, - maximumAggregateSize: 10, - freeSpaceReserve: 0 - ) - _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) - } - - await assertImportError(.fileTooLarge) { - let limits = FileSharingImporter.Limits( - maximumFileCount: 2, - maximumFileSize: 2, - maximumAggregateSize: 10, - freeSpaceReserve: 0 - ) - _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path])) - } - - await assertImportError(.aggregateSizeExceeded) { - let limits = FileSharingImporter.Limits( - maximumFileCount: 2, - maximumFileSize: 3, - maximumAggregateSize: 5, - freeSpaceReserve: 0 - ) - _ = try await makeImporter(limits: limits).importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) - } - } - - func testRejectsImportWhenStagingCapacityIsInsufficient() async throws { - let sourceURL = try createSourceFile(name: "file.txt", data: Data(repeating: 0, count: 3)) - let importer = makeImporter { _ in 2 } - - await assertImportError(.insufficientSpace) { - try await importer.importFiles(from: makeURL(paths: [sourceURL.path])) - } - } - - func testValidatesWholeRequestBeforeStaging() async throws { - let validURL = try createSourceFile(name: "valid.txt") - let invalidURL = testRootURL.appendingPathComponent("outside.txt") - try Data().write(to: invalidURL) - - await assertImportError(.sourceOutsideHandoffRoot) { - try await makeImporter().importFiles(from: makeURL(paths: [validURL.path, invalidURL.path])) - } - XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) - } - - func testRollsBackStagingIfACopyFails() async throws { - let firstURL = try createSourceFile(name: "first.txt") - let secondURL = try createSourceFile(name: "second.txt") - let importer = makeImporter { "same-identifier" } - - await assertImportError(.stagingFailed) { - try await importer.importFiles(from: makeURL(paths: [firstURL.path, secondURL.path])) - } - XCTAssertTrue(try fileManager.contentsOfDirectory(atPath: stagingRootURL.path).isEmpty) - XCTAssertTrue(fileManager.fileExists(atPath: firstURL.path)) - XCTAssertTrue(fileManager.fileExists(atPath: secondURL.path)) - } - - private func makeImporter( - limits: FileSharingImporter.Limits = FileSharingImporter.Limits( - maximumFileCount: 3, - maximumFileSize: 1024, - maximumAggregateSize: 2048, - freeSpaceReserve: 0 - ), - makeIdentifier: @escaping () -> String = { UUID().uuidString } - ) -> FileSharingImporter { - return FileSharingImporter( - fileManager: fileManager, - sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), - stagingRootURL: stagingRootURL, - limits: limits, - makeIdentifier: makeIdentifier - ) - } - - private func makeImporter( - availableCapacity: @escaping (URL) throws -> UInt64 - ) -> FileSharingImporter { - return FileSharingImporter( - fileManager: fileManager, - sharedContainerURL: testRootURL.appendingPathComponent("shared", isDirectory: true), - stagingRootURL: stagingRootURL, - limits: FileSharingImporter.Limits( - maximumFileCount: 3, - maximumFileSize: 1024, - maximumAggregateSize: 2048, - freeSpaceReserve: 0 - ), - availableCapacity: availableCapacity - ) - } - - private func createHandoffDirectory() throws -> URL { - let directoryURL = handoffRootURL.appendingPathComponent(UUID().uuidString, isDirectory: true) - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - return directoryURL - } - - private func createSourceFile(name: String, data: Data = Data()) throws -> URL { - let sourceURL = try createHandoffDirectory().appendingPathComponent(name) - try data.write(to: sourceURL) - return sourceURL - } - - private func makeURL( - paths: [String], - scheme: String = FileSharingImporter.scheme, - host: String = FileSharingImporter.host, - path: String = "", - fragment: String? = nil - ) throws -> URL { - var components = URLComponents() - components.scheme = scheme - components.host = host - components.path = path - components.fragment = fragment - components.queryItems = paths.map { URLQueryItem(name: "url", value: $0) } - return try XCTUnwrap(components.url) - } - - private func assertImportError( - _ expectedError: FileSharingImportError, - operation: () async throws -> T - ) async { - do { - _ = try await operation() - XCTFail("Expected \(expectedError)") - } catch { - XCTAssertEqual(error as? FileSharingImportError, expectedError) - } - } -} From d0072fe1a01d750c67f852aab3fb43dcab7de7b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Thu, 13 Aug 2026 10:42:12 +0200 Subject: [PATCH 5/7] refactor(security): Share file handoff contract --- Tuist/Package.resolved | 6 ++-- Tuist/Package.swift | 2 +- kDriveCore/Utils/DeeplinkParser.swift | 29 +++++++++---------- .../DeepLinks/UTFileSharingDeeplink.swift | 11 +++++-- 4 files changed, 25 insertions(+), 23 deletions(-) diff --git a/Tuist/Package.resolved b/Tuist/Package.resolved index 4e71d8fb2..bdff87ede 100644 --- a/Tuist/Package.resolved +++ b/Tuist/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "be2917d078b211555241082ce1e100ca53701c019733595f440fc3b514cf4a92", + "originHash" : "3e2210947538647688beeb1541a86665d43e6ad647625f514bbee9ba9ef3ca64", "pins" : [ { "identity" : "alamofire", @@ -69,8 +69,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/Infomaniak/ios-core", "state" : { - "revision" : "0430ec9ee85e55b6d5db63b7f2cbcb66a9d2b2ca", - "version" : "19.1.3" + "branch" : "feat/shared-writing-hardenning", + "revision" : "9a1c55575a605eba2773efe333d4e8597455cf8b" } }, { diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 6d0fb3e68..387d2ec01 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -61,7 +61,7 @@ let package = Package( .package(url: "https://github.com/flowbe/SwiftRegex", .upToNextMajor(from: "1.0.0")), .package(url: "https://github.com/getsentry/sentry-cocoa", .upToNextMajor(from: "9.8.0")), .package(url: "https://github.com/Infomaniak/ios-bug-tracker", .upToNextMajor(from: "19.0.0")), - .package(url: "https://github.com/Infomaniak/ios-core", .upToNextMajor(from: "19.1.3")), + .package(url: "https://github.com/Infomaniak/ios-core", branch: "feat/shared-writing-hardenning"), .package(url: "https://github.com/Infomaniak/ios-core-ui", .upToNextMajor(from: "26.0.0")), .package(url: "https://github.com/Infomaniak/ios-core-uikit", .upToNextMajor(from: "2.0.1")), .package(url: "https://github.com/Infomaniak/ios-dependency-injection", .upToNextMajor(from: "2.0.5")), diff --git a/kDriveCore/Utils/DeeplinkParser.swift b/kDriveCore/Utils/DeeplinkParser.swift index 68d41008b..51c31d1a0 100644 --- a/kDriveCore/Utils/DeeplinkParser.swift +++ b/kDriveCore/Utils/DeeplinkParser.swift @@ -29,11 +29,6 @@ public protocol DeeplinkParsable { } public struct DeeplinkParser: DeeplinkParsable { - private static let fileSharingScheme = "kdrive-file-sharing" - private static let fileSharingHost = "file" - private static let fileSharingPath = "Library/Caches/file-sharing" - private static let maximumSharedFileCount = 100 - private enum DeeplinkPath: String { case store case file @@ -48,7 +43,9 @@ public struct DeeplinkParser: DeeplinkParsable { private let sharedContainerURL: URL? public init() { - sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.infomaniak") + sharedContainerURL = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: KDriveFileSharing.appGroupIdentifier + ) } init(sharedContainerURL: URL?) { @@ -109,7 +106,7 @@ public struct DeeplinkParser: DeeplinkParsable { return await handleDeeplink(url: url) } - if components.scheme == Self.fileSharingScheme, components.host == Self.fileSharingHost { + if components.scheme == KDriveFileSharing.scheme, components.host == KDriveFileSharing.host { guard let files = filesForSharingDeeplink(url) else { Log.sceneDelegate("Failed to import files: Invalid request", level: .error) return false @@ -143,8 +140,8 @@ public struct DeeplinkParser: DeeplinkParsable { func filesForSharingDeeplink(_ url: URL) -> [ImportedFile]? { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), - components.scheme == Self.fileSharingScheme, - components.host == Self.fileSharingHost, + components.scheme == KDriveFileSharing.scheme, + components.host == KDriveFileSharing.host, components.path.isEmpty, components.user == nil, components.password == nil, @@ -152,19 +149,19 @@ public struct DeeplinkParser: DeeplinkParsable { components.fragment == nil, let queryItems = components.queryItems, !queryItems.isEmpty, - queryItems.count <= Self.maximumSharedFileCount, - queryItems.allSatisfy({ $0.name == "url" && !($0.value?.isEmpty ?? true) }), + queryItems.count <= KDriveFileSharing.maximumFileCount, + queryItems.allSatisfy({ + $0.name == KDriveFileSharing.urlQueryItemName && !($0.value?.isEmpty ?? true) + }), let sharedContainerURL else { return nil } - let handoffRootURL = sharedContainerURL - .appendingPathComponent(Self.fileSharingPath, isDirectory: true) - .standardizedFileURL + let handoffRootURL = KDriveFileSharing.handoffDirectoryURL(in: sharedContainerURL).standardizedFileURL let resolvedSharedContainerURL = sharedContainerURL.resolvingSymlinksInPath().standardizedFileURL let resolvedHandoffRootURL = handoffRootURL.resolvingSymlinksInPath().standardizedFileURL - let expectedHandoffRootURL = resolvedSharedContainerURL - .appendingPathComponent(Self.fileSharingPath, isDirectory: true) + let expectedHandoffRootURL = KDriveFileSharing + .handoffDirectoryURL(in: resolvedSharedContainerURL) .standardizedFileURL guard resolvedHandoffRootURL == expectedHandoffRootURL else { return nil diff --git a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift index fb98a624f..31e283098 100644 --- a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift +++ b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift @@ -17,6 +17,7 @@ */ import Foundation +import InfomaniakCore @testable import kDriveCore import XCTest @@ -30,7 +31,7 @@ final class UTFileSharingDeeplink: XCTestCase { try super.setUpWithError() testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) sharedContainerURL = testRootURL.appendingPathComponent("shared", isDirectory: true) - handoffRootURL = sharedContainerURL.appendingPathComponent("Library/Caches/file-sharing", isDirectory: true) + handoffRootURL = KDriveFileSharing.handoffDirectoryURL(in: sharedContainerURL) try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) } @@ -105,11 +106,15 @@ final class UTFileSharingDeeplink: XCTestCase { return sourceURL } - private func makeURL(for sourceURL: URL, scheme: String = "kdrive-file-sharing", host: String = "file") throws -> URL { + private func makeURL( + for sourceURL: URL, + scheme: String = KDriveFileSharing.scheme, + host: String = KDriveFileSharing.host + ) throws -> URL { var components = URLComponents() components.scheme = scheme components.host = host - components.queryItems = [URLQueryItem(name: "url", value: sourceURL.path)] + components.queryItems = [URLQueryItem(name: KDriveFileSharing.urlQueryItemName, value: sourceURL.path)] return try XCTUnwrap(components.url) } } From 351a6b22eb480b52ea52b651457b471da9eb6421 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Thu, 13 Aug 2026 11:36:45 +0200 Subject: [PATCH 6/7] refactor: Inject shared container URL --- kDriveCore/DI/CoreTargetAssembly.swift | 6 +++++- kDriveCore/Utils/DeeplinkParser.swift | 6 ------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/kDriveCore/DI/CoreTargetAssembly.swift b/kDriveCore/DI/CoreTargetAssembly.swift index e43d69149..884f0e791 100644 --- a/kDriveCore/DI/CoreTargetAssembly.swift +++ b/kDriveCore/DI/CoreTargetAssembly.swift @@ -108,7 +108,11 @@ open class CoreTargetAssembly: TargetAssembly { DeeplinkService() }, Factory(type: DeeplinkParsable.self) { _, _ in - DeeplinkParser() + DeeplinkParser( + sharedContainerURL: FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: KDriveFileSharing.appGroupIdentifier + ) + ) }, Factory(type: PublicShareApiFetcher.self) { _, _ in PublicShareApiFetcher() diff --git a/kDriveCore/Utils/DeeplinkParser.swift b/kDriveCore/Utils/DeeplinkParser.swift index 51c31d1a0..a9b09c40c 100644 --- a/kDriveCore/Utils/DeeplinkParser.swift +++ b/kDriveCore/Utils/DeeplinkParser.swift @@ -42,12 +42,6 @@ public struct DeeplinkParser: DeeplinkParsable { private let sharedContainerURL: URL? - public init() { - sharedContainerURL = FileManager.default.containerURL( - forSecurityApplicationGroupIdentifier: KDriveFileSharing.appGroupIdentifier - ) - } - init(sharedContainerURL: URL?) { self.sharedContainerURL = sharedContainerURL } From 88f57b9d86e3a7736bd94ebeb29441051e625726 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Coye=20de=20Brune=CC=81lis?= Date: Fri, 14 Aug 2026 11:37:34 +0200 Subject: [PATCH 7/7] fix: Update shared file handoff symbols --- Tuist/Package.resolved | 6 +++--- Tuist/Package.swift | 2 +- kDriveCore/DI/CoreTargetAssembly.swift | 2 +- kDriveCore/Utils/DeeplinkParser.swift | 14 +++++++------- .../DeepLinks/UTFileSharingDeeplink.swift | 8 ++++---- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Tuist/Package.resolved b/Tuist/Package.resolved index bdff87ede..ce1f83d64 100644 --- a/Tuist/Package.resolved +++ b/Tuist/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "3e2210947538647688beeb1541a86665d43e6ad647625f514bbee9ba9ef3ca64", + "originHash" : "7048349745621ad4c418040ff7c14724e324bfc04f8177c50576b2b87d9b9b54", "pins" : [ { "identity" : "alamofire", @@ -69,8 +69,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/Infomaniak/ios-core", "state" : { - "branch" : "feat/shared-writing-hardenning", - "revision" : "9a1c55575a605eba2773efe333d4e8597455cf8b" + "revision" : "e667ed34941d4e06f0107d9633e2cc9438685fef", + "version" : "19.1.4" } }, { diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 387d2ec01..5e7eae297 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -61,7 +61,7 @@ let package = Package( .package(url: "https://github.com/flowbe/SwiftRegex", .upToNextMajor(from: "1.0.0")), .package(url: "https://github.com/getsentry/sentry-cocoa", .upToNextMajor(from: "9.8.0")), .package(url: "https://github.com/Infomaniak/ios-bug-tracker", .upToNextMajor(from: "19.0.0")), - .package(url: "https://github.com/Infomaniak/ios-core", branch: "feat/shared-writing-hardenning"), + .package(url: "https://github.com/Infomaniak/ios-core", .upToNextMajor(from: "19.1.4")), .package(url: "https://github.com/Infomaniak/ios-core-ui", .upToNextMajor(from: "26.0.0")), .package(url: "https://github.com/Infomaniak/ios-core-uikit", .upToNextMajor(from: "2.0.1")), .package(url: "https://github.com/Infomaniak/ios-dependency-injection", .upToNextMajor(from: "2.0.5")), diff --git a/kDriveCore/DI/CoreTargetAssembly.swift b/kDriveCore/DI/CoreTargetAssembly.swift index 884f0e791..f6a30f0c5 100644 --- a/kDriveCore/DI/CoreTargetAssembly.swift +++ b/kDriveCore/DI/CoreTargetAssembly.swift @@ -110,7 +110,7 @@ open class CoreTargetAssembly: TargetAssembly { Factory(type: DeeplinkParsable.self) { _, _ in DeeplinkParser( sharedContainerURL: FileManager.default.containerURL( - forSecurityApplicationGroupIdentifier: KDriveFileSharing.appGroupIdentifier + forSecurityApplicationGroupIdentifier: KDriveFileSharingConstants.appGroupIdentifier ) ) }, diff --git a/kDriveCore/Utils/DeeplinkParser.swift b/kDriveCore/Utils/DeeplinkParser.swift index a9b09c40c..132879b56 100644 --- a/kDriveCore/Utils/DeeplinkParser.swift +++ b/kDriveCore/Utils/DeeplinkParser.swift @@ -100,7 +100,7 @@ public struct DeeplinkParser: DeeplinkParsable { return await handleDeeplink(url: url) } - if components.scheme == KDriveFileSharing.scheme, components.host == KDriveFileSharing.host { + if components.scheme == KDriveFileSharingConstants.scheme, components.host == KDriveFileSharingConstants.host { guard let files = filesForSharingDeeplink(url) else { Log.sceneDelegate("Failed to import files: Invalid request", level: .error) return false @@ -134,8 +134,8 @@ public struct DeeplinkParser: DeeplinkParsable { func filesForSharingDeeplink(_ url: URL) -> [ImportedFile]? { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), - components.scheme == KDriveFileSharing.scheme, - components.host == KDriveFileSharing.host, + components.scheme == KDriveFileSharingConstants.scheme, + components.host == KDriveFileSharingConstants.host, components.path.isEmpty, components.user == nil, components.password == nil, @@ -143,18 +143,18 @@ public struct DeeplinkParser: DeeplinkParsable { components.fragment == nil, let queryItems = components.queryItems, !queryItems.isEmpty, - queryItems.count <= KDriveFileSharing.maximumFileCount, + queryItems.count <= KDriveFileSharingConstants.maximumFileCount, queryItems.allSatisfy({ - $0.name == KDriveFileSharing.urlQueryItemName && !($0.value?.isEmpty ?? true) + $0.name == KDriveFileSharingConstants.urlQueryItemName && !($0.value?.isEmpty ?? true) }), let sharedContainerURL else { return nil } - let handoffRootURL = KDriveFileSharing.handoffDirectoryURL(in: sharedContainerURL).standardizedFileURL + let handoffRootURL = KDriveFileSharingConstants.handoffDirectoryURL(in: sharedContainerURL).standardizedFileURL let resolvedSharedContainerURL = sharedContainerURL.resolvingSymlinksInPath().standardizedFileURL let resolvedHandoffRootURL = handoffRootURL.resolvingSymlinksInPath().standardizedFileURL - let expectedHandoffRootURL = KDriveFileSharing + let expectedHandoffRootURL = KDriveFileSharingConstants .handoffDirectoryURL(in: resolvedSharedContainerURL) .standardizedFileURL guard resolvedHandoffRootURL == expectedHandoffRootURL else { diff --git a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift index 31e283098..4eec1803a 100644 --- a/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift +++ b/kDriveTests/kDriveCore/DeepLinks/UTFileSharingDeeplink.swift @@ -31,7 +31,7 @@ final class UTFileSharingDeeplink: XCTestCase { try super.setUpWithError() testRootURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) sharedContainerURL = testRootURL.appendingPathComponent("shared", isDirectory: true) - handoffRootURL = KDriveFileSharing.handoffDirectoryURL(in: sharedContainerURL) + handoffRootURL = KDriveFileSharingConstants.handoffDirectoryURL(in: sharedContainerURL) try fileManager.createDirectory(at: handoffRootURL, withIntermediateDirectories: true) } @@ -108,13 +108,13 @@ final class UTFileSharingDeeplink: XCTestCase { private func makeURL( for sourceURL: URL, - scheme: String = KDriveFileSharing.scheme, - host: String = KDriveFileSharing.host + scheme: String = KDriveFileSharingConstants.scheme, + host: String = KDriveFileSharingConstants.host ) throws -> URL { var components = URLComponents() components.scheme = scheme components.host = host - components.queryItems = [URLQueryItem(name: KDriveFileSharing.urlQueryItemName, value: sourceURL.path)] + components.queryItems = [URLQueryItem(name: KDriveFileSharingConstants.urlQueryItemName, value: sourceURL.path)] return try XCTUnwrap(components.url) } }