Class: Beni::Vendor::Checksum

Inherits:
Object
  • Object
show all
Defined in:
lib/beni/vendor/checksum.rb,
sig/beni/vendor/checksum.rbs

Overview

SHA256 verification for vendored tarballs. One instance per +(path, expected_sha)+ pair; reuse is not supported and not needed by Beni::Tasks. Operates in two modes:

* Explicit expected hash (a built-in pair entry or a consumer
override) — must match exactly; mismatch raises.
* Trust-on-first-use (TOFU) — when +expected_sha+ is +nil+ or empty,
the actual hash is pinned to a +.sha256+ sidecar next to the
tarball. Subsequent runs compare against the pinned value and
raise on drift.

Public contract is the single #verify_or_pin entry point; the two branches and the digest helper are internal.

Instance Method Summary collapse

Constructor Details

#initialize(path, expected_sha) ⇒ Checksum

Returns a new instance of Checksum.

Parameters:

  • path (String)
  • expected_sha (String, nil)


21
22
23
24
# File 'lib/beni/vendor/checksum.rb', line 21

def initialize(path, expected_sha)
  @path = path
  @expected_sha = expected_sha
end

Instance Method Details

#expected?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/beni/vendor/checksum.rb', line 40

def expected?
  !@expected_sha.to_s.empty?
end

#sha256String

Returns:

  • (String)


44
45
46
# File 'lib/beni/vendor/checksum.rb', line 44

def sha256
  Digest::SHA256.file(@path).hexdigest
end

#verify_against_expected(actual, sidecar) ⇒ void

This method returns an undefined value.

Parameters:

  • actual (String)
  • sidecar (String)


48
49
50
51
52
53
54
# File 'lib/beni/vendor/checksum.rb', line 48

def verify_against_expected(actual, sidecar)
  unless actual == @expected_sha
    raise Error, "[beni] checksum mismatch for #{File.basename(@path)}: " \
                 "expected #{@expected_sha}, got #{actual}"
  end
  File.write(sidecar, "#{actual}\n")
end

#verify_or_pinString

Verify the tarball against expected_sha (if non-empty) or TOFU-pin against the .sha256 sidecar. Returns the computed SHA256 hex digest on success. Raises Beni::Error on mismatch (explicit mode) or drift (TOFU mode); both error messages carry a [beni] prefix for CI log grepping.

Returns:

  • (String)


31
32
33
34
35
36
# File 'lib/beni/vendor/checksum.rb', line 31

def verify_or_pin
  actual = sha256
  sidecar = "#{@path}.sha256"
  expected? ? verify_against_expected(actual, sidecar) : verify_or_pin_sidecar(actual, sidecar)
  actual
end

#verify_or_pin_sidecar(actual, sidecar) ⇒ void

This method returns an undefined value.

Parameters:

  • actual (String)
  • sidecar (String)


56
57
58
59
60
61
62
63
64
65
# File 'lib/beni/vendor/checksum.rb', line 56

def verify_or_pin_sidecar(actual, sidecar)
  if File.exist?(sidecar)
    pinned = File.read(sidecar).strip
    return if actual == pinned

    raise Error, "[beni] checksum drift for #{File.basename(@path)}: " \
                 "pinned #{pinned}, got #{actual}"
  end
  File.write(sidecar, "#{actual}\n")
end