Skip to content

feat: validate the sha256 after pulling the blob #168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2025

Conversation

chlins
Copy link
Contributor

@chlins chlins commented May 6, 2025

This pull request enhances the integrity verification process in the pkg/backend/pull.go file by introducing digest validation for downloaded blobs. It also includes minor import reorganization for better readability. Below are the key changes grouped by theme:

Integrity Verification Enhancements:

  • Added a SHA-256 hash computation using io.TeeReader in both pullIfNotExist and pullAndExtractFromRemote functions to calculate the hash of the downloaded content while reading. [1] [2]
  • Introduced a new validateDigest function to ensure the computed hash matches the expected digest, improving data integrity checks. This validation is applied after content processing in both functions. [1] [2]
  • Added error handling to abort the progress bar and return an error if the digest validation fails. [1] [2]

Code Organization:

  • Reorganized imports by grouping related packages together and sorting them for better readability.

Summary by CodeRabbit

  • New Features
    • Added SHA-256 digest validation for blobs and manifests pulled from remote repositories to ensure data integrity.
  • Bug Fixes
    • Improved error handling to abort operations if a digest mismatch is detected during artifact pulls.
  • Tests
    • Enhanced fetch tests with realistic file contents and corresponding digests to better simulate content retrieval.
  • Chores
    • Increased initial and maximum retry delays to improve retry timing behavior.

@chlins chlins added the enhancement New feature or request label May 6, 2025
Copy link

coderabbitai bot commented May 6, 2025

"""

Walkthrough

The update adds SHA-256 digest validation for blobs and manifests pulled from a remote repository. After downloading content, the code computes its SHA-256 hash and checks it against the expected digest. If the digests do not match, an error is returned. A helper function for digest validation is introduced. The test suite is enhanced to use realistic file contents and corresponding digests for more accurate testing of blob fetching. Additionally, retry delay parameters for backend processes are increased.

Changes

File(s) Change Summary
pkg/backend/pull.go Added SHA-256 digest validation to blob/manifest pull functions; introduced validateDigest helper; updated imports.
pkg/backend/fetch_test.go Enhanced TestFetch to use realistic file contents and correct SHA-256 digests; updated mock server responses to return actual content.
pkg/backend/processor/options.go
pkg/backend/retry.go
Increased initial and maximum retry delays from 1s to 5s and from 5s to 10s respectively; retry count and backoff style unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Backend
    participant RemoteRepo

    Client->>Backend: Request to pull blob/manifest
    Backend->>RemoteRepo: Fetch content
    RemoteRepo-->>Backend: Return content stream
    Backend->>Backend: Read content & compute SHA-256 hash
    Backend->>Backend: Validate computed hash vs expected digest
    alt Digest matches
        Backend-->>Client: Success (content available)
    else Digest mismatch
        Backend-->>Client: Error (digest validation failed)
    end
Loading

Poem

In the warren of code, a new check appears,
SHA-256 now guards what the backend retrieves.
Each blob and manifest, with hashes in tow,
Are checked for their truth before onward they go.
If bytes do not match, the pull hops away—
Integrity’s champion, a rabbit at play!
🐇🔒
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0adf2bf and 36fe73c.

📒 Files selected for processing (4)
  • pkg/backend/fetch_test.go (4 hunks)
  • pkg/backend/processor/options.go (1 hunks)
  • pkg/backend/pull.go (4 hunks)
  • pkg/backend/retry.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/backend/pull.go (1)
pkg/backend/remote/client.go (1)
  • New (42-89)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (11)
pkg/backend/processor/options.go (1)

51-52: LGTM: Increased retry delays for more robust error handling

The retry delays have been increased from 1s to 5s (initial) and from 5s to 10s (maximum), which will give network operations more time to recover during transient failures. This change aligns with the identical update in the backend retry.go file.

pkg/backend/retry.go (1)

28-29: LGTM: Increased retry delays for more robust error handling

The retry delays have been increased from 1s to 5s (initial) and from 5s to 10s (maximum), which will give network operations more time to recover during transient failures. This change aligns with the identical update in processor/options.go.

pkg/backend/fetch_test.go (3)

45-52: LGTM: Added realistic test data with proper digest calculation

Good improvement to the test by adding actual content and calculating real SHA256 digests instead of using empty content. This makes the test more realistic and properly exercises the new digest validation logic.


65-67: LGTM: Updated manifest to include correct digest and size

The manifest now uses the correctly calculated digests and actual content sizes, which better simulates real-world scenarios.

Also applies to: 73-75


83-90: LGTM: Updated mock server to return real content

The mock server now returns the actual file content for blob requests, and includes proper error handling for the Write calls as addressed in a previous review. This ensures the digest validation logic can be properly tested.

pkg/backend/pull.go (6)

25-29: LGTM: Improved import organization and added SHA256 dependency

The imports have been reorganized and grouped logically, with the addition of the high-performance SHA256 implementation from minio, which is appropriate for data integrity validation.


140-142: LGTM: Efficiently calculate SHA256 hash during read

Using io.TeeReader is an efficient approach as it calculates the hash while reading the content, avoiding the need to read the content twice.


191-196: LGTM: Added digest validation for blobs

This adds important integrity verification after downloading blobs, which enhances security by ensuring the content hasn't been corrupted or tampered with during transfer.


212-214: LGTM: Efficiently calculate SHA256 hash during extraction

Similar to the blob pulling, this efficiently calculates the hash during extraction using io.TeeReader.


221-227: LGTM: Added digest validation for extracted content

This adds important integrity verification after extraction, ensuring the content wasn't corrupted during the download or extraction process.


231-246: LGTM: Well-implemented digest validation function

The validation function is thorough with proper error checking:

  1. Ensures the digest isn't empty
  2. Verifies the hash is the correct length for SHA256
  3. Compares the calculated hash with the expected digest

The error messages are clear and descriptive, which helps with debugging if validation fails.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
pkg/backend/pull.go (1)

231-246: Well-structured validation function

The validateDigest function is well-structured with appropriate checks and clear error messages. The validation covers empty digest check, hash length check, and digest comparison.

Two minor suggestions:

  1. Consider extracting "sha256:" as a constant to avoid hardcoding the algorithm name
  2. Consider using encoding/hex package for the hash formatting
+ const digestAlgorithmPrefix = "sha256:"
  
  func validateDigest(digest string, hash []byte) error {
      if digest == "" {
          return fmt.Errorf("digest is empty")
      }
  
      if len(hash) != sha256.Size {
          return fmt.Errorf("invalid hash length")
      }
  
-     if digest != fmt.Sprintf("sha256:%x", hash) {
-         return fmt.Errorf("actual digest %s does not match the expected digest %s", fmt.Sprintf("sha256:%x", hash), digest)
+     computedDigest := digestAlgorithmPrefix + hex.EncodeToString(hash)
+     if digest != computedDigest {
+         return fmt.Errorf("actual digest %s does not match the expected digest %s", computedDigest, digest)
      }
  
      return nil
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7f486c and 2500e59.

📒 Files selected for processing (1)
  • pkg/backend/pull.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
pkg/backend/pull.go (5)

25-29: Good job on organizing imports

The imports are now properly grouped and sorted, making the code more readable and maintainable.


140-141: Well-implemented hash verification approach

Using io.TeeReader to calculate the hash while reading the content is an efficient approach as it avoids having to read the content twice.


191-196: Good integrity check implementation

Adding digest validation after pushing the content ensures data integrity. This is a critical security feature for artifact distribution systems.


212-214: Consistent application of hash verification

The same TeeReader approach used in pullIfNotExist is correctly applied here for consistency.


221-226: Good error handling for digest validation

The error handling is thorough and includes aborting the progress bar, which provides good feedback to the user in case of corruption.

@chlins chlins force-pushed the feat/pull-validate-sha256 branch from 2500e59 to 9793166 Compare May 7, 2025 02:02
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2500e59 and 9793166.

📒 Files selected for processing (2)
  • pkg/backend/fetch_test.go (4 hunks)
  • pkg/backend/pull.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/backend/pull.go
🧰 Additional context used
🪛 GitHub Actions: Lint
pkg/backend/fetch_test.go

[error] 84-84: Error return value of w.Write is not checked (errcheck)


[error] 86-86: Error return value of w.Write is not checked (errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
pkg/backend/fetch_test.go (2)

44-51: Great test setup with realistic content!

Using explicit file contents and computing their corresponding digests with godigest.FromString() makes the tests more realistic and ensures proper validation of the newly added SHA-256 digest validation functionality. This approach is better than using static mock values.


65-67: Good update to use accurate content sizes and digests in the manifest

The test now correctly uses the computed digests and actual file sizes in the manifest, making the test more realistic and aligned with the SHA-256 validation functionality introduced in this PR.

Also applies to: 73-75

@chlins chlins force-pushed the feat/pull-validate-sha256 branch from 9793166 to 0adf2bf Compare May 7, 2025 02:07
Copy link
Contributor

@gaius-qi gaius-qi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Contributor

@gaius-qi gaius-qi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change the retry config.

Signed-off-by: chlins <chlins.zhang@gmail.com>
@chlins chlins force-pushed the feat/pull-validate-sha256 branch from 0adf2bf to 36fe73c Compare May 7, 2025 02:49
Copy link
Contributor

@gaius-qi gaius-qi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link
Contributor

@BraveY BraveY left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@BraveY BraveY merged commit d88624b into main May 7, 2025
6 checks passed
@BraveY BraveY deleted the feat/pull-validate-sha256 branch May 7, 2025 05:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants