Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(lume): verify pulled layers against their sha256 digest (#1855)

Dallin Romneye4a81ed86cb1
diff --git a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
index dc2be746c5..2b0729d898 100644
--- a/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
+++ b/libs/lume/src/ContainerRegistry/ImageContainerRegistry.swift
@@ -18,6 +18,28 @@ extension Data {
}
}
+// Streaming SHA256 of a file; disk layers can be multi-GB so we hash in chunks.
+func sha256OfFile(at url: URL) throws -> String {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+
+ var context = CC_SHA256_CTX()
+ CC_SHA256_Init(&context)
+
+ let chunkSize = 4 * 1024 * 1024 // 4 MiB
+ while true {
+ let data = handle.readData(ofLength: chunkSize)
+ if data.isEmpty { break }
+ data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in
+ _ = CC_SHA256_Update(&context, ptr.baseAddress, CC_LONG(data.count))
+ }
+ }
+
+ var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
+ CC_SHA256_Final(&hash, &context)
+ return hash.map { String(format: "%02x", $0) }.joined()
+}
+
// Push-related errors
enum PushError: Error {
case uploadInitiationFailed
@@ -2236,10 +2258,9 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
request.addValue(mediaType, forHTTPHeaderField: "Accept")
request.timeoutInterval = 60
- // Add Accept-Encoding for compressed transfer if content isn't already compressed
- if !mediaType.contains("gzip") && !mediaType.contains("compressed") {
- request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
- }
+ // Request identity encoding: blobs are content-addressed, so transparent
+ // gzip/deflate decompression by URLSession would corrupt the stored bytes.
+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
let (tempURL, response) = try await session.download(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -2262,6 +2283,19 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
_ = try FileManager.default.replaceItemAt(
url, withItemAt: tempURL, backupItemName: nil, options: [])
}
+
+ // Verify the layer against its digest before caching it; a mismatch means
+ // a corrupt blob, so drop it and let the retry loop re-download (issue #296).
+ if digest.hasPrefix("sha256:") {
+ let expected = String(digest.dropFirst("sha256:".count)).lowercased()
+ let actual = try sha256OfFile(at: url)
+ if actual != expected {
+ try? FileManager.default.removeItem(at: url)
+ throw PullError.layerVerificationFailed(
+ expected: digest, actual: "sha256:\(actual)")
+ }
+ }
+
progress.addProgress(Int64(httpResponse.expectedContentLength))
// Always save a copy to the cache directory for use by copyFromCache,
@@ -2286,6 +2320,11 @@ class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
} catch {
lastError = error
+ if case PullError.layerVerificationFailed(let expected, let actual) = error {
+ Logger.info(
+ "Layer checksum mismatch (expected \(expected), got \(actual)); will re-download."
+ )
+ }
if attempt < maxRetries {
// Exponential backoff with jitter for retries
let baseDelay = Double(attempt) * 2
diff --git a/libs/lume/src/Errors/Errors.swift b/libs/lume/src/Errors/Errors.swift
index 10ee6c4e8a..e3968c19fa 100644
--- a/libs/lume/src/Errors/Errors.swift
+++ b/libs/lume/src/Errors/Errors.swift
@@ -52,6 +52,7 @@ enum PullError: Error, LocalizedError {
case tokenFetchFailed
case manifestFetchFailed
case layerDownloadFailed(String)
+ case layerVerificationFailed(expected: String, actual: String)
case missingPart(Int)
case decompressionFailed(String)
case reassemblyFailed(String)
@@ -70,6 +71,11 @@ enum PullError: Error, LocalizedError {
return "Failed to fetch image manifest from registry."
case .layerDownloadFailed(let digest):
return "Failed to download layer: \(digest)"
+ case .layerVerificationFailed(let expected, let actual):
+ return
+ "Downloaded layer failed checksum verification (expected \(expected), got \(actual)). "
+ + "The blob was likely corrupted in transit. Retrying may help; if it persists, "
+ + "clear the lume cache and pull again."
case .missingPart(let partNum):
return "Missing required part number \(partNum) for reassembly."
case .decompressionFailed(let file):
diff --git a/libs/lume/tests/SHA256FileTests.swift b/libs/lume/tests/SHA256FileTests.swift
new file mode 100644
index 0000000000..2d84636185
--- /dev/null
+++ b/libs/lume/tests/SHA256FileTests.swift
@@ -0,0 +1,59 @@
+import Foundation
+import Testing
+
+@testable import lume
+
+// Tests for the streaming file checksum helper backing layer verification (issue #296).
+struct SHA256FileTests {
+ private func makeTempFile(_ data: Data) throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lume-sha256-test-\(UUID().uuidString)")
+ try data.write(to: url)
+ return url
+ }
+
+ @Test func emptyFileMatchesKnownDigest() throws {
+ let url = try makeTempFile(Data())
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ // Well-known SHA256 of the empty input.
+ #expect(
+ try sha256OfFile(at: url)
+ == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
+ }
+
+ @Test func smallContentMatchesKnownDigest() throws {
+ let url = try makeTempFile(Data("abc".utf8))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ // Well-known SHA256 of "abc".
+ #expect(
+ try sha256OfFile(at: url)
+ == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
+ }
+
+ @Test func streamingMatchesInMemoryHashAcrossChunkBoundary() throws {
+ // Larger than the 4 MiB streaming chunk so we exercise multiple
+ // CC_SHA256_Update calls and confirm the streamed result equals the
+ // one-shot Data hash.
+ var bytes = Data(count: 5 * 1024 * 1024 + 17)
+ for i in stride(from: 0, to: bytes.count, by: 7) {
+ bytes[i] = UInt8(i % 251)
+ }
+ let url = try makeTempFile(bytes)
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ #expect(try sha256OfFile(at: url) == bytes.sha256String())
+ }
+
+ @Test func differentContentProducesDifferentDigest() throws {
+ let a = try makeTempFile(Data("hello".utf8))
+ let b = try makeTempFile(Data("world".utf8))
+ defer {
+ try? FileManager.default.removeItem(at: a)
+ try? FileManager.default.removeItem(at: b)
+ }
+
+ #expect(try sha256OfFile(at: a) != sha256OfFile(at: b))
+ }
+}