Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Sources/XcodesKit/Services/ArchiveDownloadService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions Sources/XcodesKit/Services/Aria2DownloadService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 92 additions & 0 deletions Tests/XcodesKitTests/XcodesKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<html></html>' > "$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)
Expand Down