diff --git a/Sources/XcodesKit/Services/ArchiveDownloadService.swift b/Sources/XcodesKit/Services/ArchiveDownloadService.swift index 62be18b..b127803 100644 --- a/Sources/XcodesKit/Services/ArchiveDownloadService.swift +++ b/Sources/XcodesKit/Services/ArchiveDownloadService.swift @@ -69,7 +69,14 @@ public struct ArchiveDownloadService: Sendable { progressChanged(progress) let result = try await task.value - try validateResponse(result.response) + do { + try validateResponse(result.response) + } catch { + // The rejected response is already saved at the archive's path. Remove it so a later run + // doesn't find it and use it as the archive. + try? removeItem(result.saveLocation) + throw error + } return result.saveLocation } try? removeItem(resumeDataPath.url) diff --git a/Sources/XcodesKit/Services/Aria2DownloadService.swift b/Sources/XcodesKit/Services/Aria2DownloadService.swift index 11ea699..a274d68 100644 --- a/Sources/XcodesKit/Services/Aria2DownloadService.swift +++ b/Sources/XcodesKit/Services/Aria2DownloadService.swift @@ -52,6 +52,9 @@ public struct Aria2DownloadService: Sendable { }, successHandler: { guard !state.isUnauthorized else { + // aria2 saved the page Apple redirected to at the archive's path. Remove it so a later run + // doesn't find it and use it as the archive. + try? FileManager.default.removeItem(at: destination.url) return unauthorizedError?() ?? XcodesKitError("Received 403: Unauthorized.") } return nil diff --git a/Tests/XcodesKitTests/XcodesKitTests.swift b/Tests/XcodesKitTests/XcodesKitTests.swift index f66818e..0fb2260 100644 --- a/Tests/XcodesKitTests/XcodesKitTests.swift +++ b/Tests/XcodesKitTests/XcodesKitTests.swift @@ -975,6 +975,98 @@ final class XcodesKitTests: XCTestCase { } } + func testArchiveDownloadServiceURLSessionRemovesRejectedDownload() async throws { + enum UnauthorizedTestError: Error, Equatable { + case notAuthorized + } + + let recorder = DownloadRecorder() + let destination = try XCTUnwrap(Path("/tmp/Xcode-15.xip")) + let unauthorizedURL = try XCTUnwrap(URL(string: "https://developer.apple.com/unauthorized/")) + let service = ArchiveDownloadService( + aria2Download: { _, _, _, _ in + XCTFail("Aria2 should not be used") + return AsyncThrowingStream { $0.finish() } + }, + urlSessionDownload: { _, destination, _ in + ( + Progress(totalUnitCount: 10), + Task { + ( + saveLocation: destination, + response: try XCTUnwrap(URLResponse(url: unauthorizedURL, mimeType: "text/html", expectedContentLength: 0, textEncodingName: nil)) + ) + } + ) + }, + contentsAtPath: { _ in nil }, + createFile: { _, _ in XCTFail("Resume data should not be persisted") }, + removeItem: { url in recorder.recordRemovedURL(url) }, + shouldRetry: { _ in false }, + validateResponse: { response in + try ArchiveDownloadService.validateDeveloperDownloadResponse( + response, + unauthorizedError: { UnauthorizedTestError.notAuthorized } + ) + } + ) + + do { + _ = try await service.downloadWithURLSession( + url: try XCTUnwrap(URL(string: "https://example.com/Xcode.xip")), + destination: destination, + resumeDataPath: try XCTUnwrap(Path("/tmp/Xcode-15.resumedata")), + progressChanged: { _ in } + ) + XCTFail("Expected unauthorized download to throw") + } catch let error as UnauthorizedTestError { + XCTAssertEqual(error, .notAuthorized) + XCTAssertEqual(recorder.removedURLs.map(\.path), [destination.string]) + } + } + + func testAria2DownloadServiceRemovesRejectedDownload() async throws { + enum UnauthorizedTestError: Error, Equatable { + case notAuthorized + } + + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + // Stands in for aria2c: saves a page at --dir/--out and logs Apple's unauthorized redirect. + let aria2 = directory.appendingPathComponent("aria2c") + try """ + #!/bin/sh + for argument in "$@"; do + case "$argument" in + --dir=*) dir="${argument#--dir=}" ;; + --out=*) out="${argument#--out=}" ;; + esac + done + printf '' > "$dir/$out" + echo 'Redirecting to https://developer.apple.com/unauthorized/' + """.write(to: aria2, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: aria2.path) + + let destination = try XCTUnwrap(Path(directory.appendingPathComponent("Xcode-15.xip").path)) + let stream = Aria2DownloadService().download( + aria2Path: try XCTUnwrap(Path(aria2.path)), + url: try XCTUnwrap(URL(string: "https://example.com/Xcode.xip")), + destination: destination, + cookies: [], + unauthorizedError: { UnauthorizedTestError.notAuthorized } + ) + + do { + for try await _ in stream {} + XCTFail("Expected unauthorized download to throw") + } catch let error as UnauthorizedTestError { + XCTAssertEqual(error, .notAuthorized) + XCTAssertFalse(FileManager.default.fileExists(atPath: destination.string)) + } + } + func testArchiveDownloadServiceAria2YieldsProgressAndReturnsDestination() async throws { let recorder = DownloadRecorder() let progress = Progress(totalUnitCount: 100)