internal/agenthub/testdata/trust/check-keys.rb

# frozen_string_literal: true
# Independent verifier: no generator or Go implementation is loaded.
require 'digest'
require 'json'

class UniqueObject < Hash
  def []=(key, value)
    raise "duplicate JSON member #{key}" if key?(key)
    super
  end
end

def assert(value, label)
  raise "identity corpus: #{label}" unless value
end

def fields(object, names)
  assert(object.is_a?(Hash) && object.keys.sort == names.sort, "fields #{names.join(',')}")
end

def unhex(value, size = nil)
  assert(value.is_a?(String) && value.match?(/\A(?:[0-9a-f]{2})+\z/), 'lowercase hex')
  bytes = [value].pack('H*')
  assert(!size || bytes.bytesize == size, 'hex length')
  bytes
end

def integer_json(value)
  case value
  when Hash then value.each_value { |v| integer_json(v) }
  when Array then value.each { |v| integer_json(v) }
  when Float then raise 'identity corpus: floating-point number'
  end
end

# Read each candidate in order, stopping at the first acceptance. Deliberately
# use byte arithmetic here, rather than the generator's unpack-based extractor.
def trace(block)
  result = []
  (0...32).step(2) do |offset|
    value = block.getbyte(offset) * 256 + block.getbyte(offset + 1)
    entry = { 'offset' => offset, 'value' => value, 'accepted' => value < 62208 }
    entry['index'] = value % 7776 if value < 62208
    result << entry
    break if value < 62208
  end
  result
end

def word_input(role, position, fingerprint, counter)
  "AgentHub/identity/key-check/word/v1\0".b + [role, position].pack('C*') + fingerprint + [counter].pack('N')
end

def check_input(role, fingerprint)
  "AgentHub/identity/key-check/check-byte/v1\0".b + [role].pack('C') + fingerprint
end

def verify_block(block, input)
  assert(unhex(block.fetch('input_hex')) == input, 'word input')
  digest = Digest::SHA256.digest(input)
  assert(unhex(block.fetch('sha256_hex'), 32) == digest, 'word digest')
  assert(block.fetch('candidates') == trace(digest), 'candidate trace')
  trace(digest).last
end

def verify(fixture, dictionary)
  integer_json(fixture)
  fields(fixture, %w[fixture_version contract word_domain check_byte_domain word_count wordlist_sha256_hex wordlist_bytes cutoff counter_encoding keys counter_vectors synthetic_blocks extraction_cases negative_substitutions negative_extractions])
  assert(fixture.fetch('fixture_version') == 1 && fixture.fetch('contract') == 'AgentHub identity KEY CHECK v1', 'contract')
  assert(fixture.fetch('word_count') == 7776 && fixture.fetch('cutoff') == 62208, 'extractor constants')
  assert(fixture.fetch('counter_encoding') == 'U32BE, 0 through 255', 'counter encoding')
  assert(unhex(fixture.fetch('word_domain')) == "AgentHub/identity/key-check/word/v1\0", 'word domain')
  assert(unhex(fixture.fetch('check_byte_domain')) == "AgentHub/identity/key-check/check-byte/v1\0", 'check domain')
  expected_digest = 'addd35536511597a02fa0a9ff1e5284677b8883b83e986e43f15a3db996b903e'
  assert(fixture.fetch('wordlist_sha256_hex') == expected_digest && Digest::SHA256.hexdigest(dictionary) == expected_digest, 'EFF digest')
  assert(fixture.fetch('wordlist_bytes') == 108800 && dictionary.bytesize == 108800 && dictionary.end_with?("\n"), 'EFF bytes')
  lines = dictionary.lines(chomp: true)
  assert(lines.size == 7776, 'EFF count')
  words = lines.each_with_index.map do |line, i|
    code, word = line.split("\t", -1)
    # Five base-six digits, translated to dice faces 1..6.
    assert(code == i.to_s(6).rjust(5, '0').tr('012345', '123456') && word.match?(/\A[a-z]+(?:-[a-z]+)*\z/), 'EFF layout')
    word
  end
  assert(words.uniq.size == 7776, 'EFF duplicates')

  keys = fixture.fetch('keys')
  assert(keys.map { |k| k.fetch('name') } == %w[rfc8032-ed25519-test-1 client-fixture p384-generator], 'required keys')
  # Anchor public keys and private test material. SPKI hashing below is independent;
  # Go additionally derives both public-key algorithms from these seeds/scalar.
  anchors = [
    ['Ed25519', '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60', '302a300506032b6570032100d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a'],
    ['Ed25519', '03' * 32, '302a300506032b6570032100ed4928c628d1c2c6eae90338905995612959273a5c63f93636c14614ac8737d1'],
    ['P-384', '00' * 47 + '01', '3076301006072a8648ce3d020106052b8104002203620004aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab73617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f']
  ]
  keys.each_with_index do |key, i|
    fields(key, %w[name algorithm private_input spki_der_hex id_sha256_hex key_checks])
    algorithm, private_value, spki = anchors.fetch(i)
    assert(key.fetch('algorithm') == algorithm && key.fetch('spki_der_hex') == spki, 'canonical key anchor')
    encoding = algorithm == 'Ed25519' ? '32-byte seed, hex' : '48-byte unsigned big-endian scalar, hex'
    assert(key.fetch('private_input') == { 'encoding' => encoding, 'value' => private_value }, 'private test material')
    fingerprint = Digest::SHA256.digest(unhex(spki))
    assert(unhex(key.fetch('id_sha256_hex'), 32) == fingerprint, 'SPKI fingerprint')
    checks = key.fetch('key_checks')
    assert(checks.map { |c| c.fetch('role') } == [1, 2, 3], 'all roles once')
    checks.each do |check|
      fields(check, %w[role role_name indices words display streams check_input_hex check_sha256_hex check_byte_hex])
      role = check.fetch('role')
      assert(check.fetch('role_name') == %w[hub-authority client-device endpoint].fetch(role - 1), 'role name')
      assert(check.fetch('streams').map { |s| s.fetch('position') } == [0, 1, 2, 3], 'independent positions')
      indices = check.fetch('streams').map do |stream|
        fields(stream, %w[position blocks])
        blocks = stream.fetch('blocks')
        assert(blocks.size.between?(1, 256), 'stream length')
        accepted = nil
        blocks.each_with_index do |block, counter|
          fields(block, %w[counter input_hex sha256_hex candidates])
          assert(block.fetch('counter') == counter && accepted.nil?, 'counter sequence or block after acceptance')
          last = verify_block(block, word_input(role, stream.fetch('position'), fingerprint, counter))
          accepted = last.fetch('index') if last.fetch('accepted')
        end
        assert(!accepted.nil?, 'missing acceptance')
        accepted
      end
      assert(check.fetch('indices') == indices, 'indices')
      names = indices.map { |index| words.fetch(index) }
      assert(check.fetch('words') == names && check.fetch('display') == names.join('_'), 'words and display')
      input = check_input(role, fingerprint)
      digest = Digest::SHA256.digest(input)
      assert(unhex(check.fetch('check_input_hex')) == input && unhex(check.fetch('check_sha256_hex'), 32) == digest, 'check-byte input and digest')
      assert(unhex(check.fetch('check_byte_hex'), 1) == digest.byteslice(0, 1), 'check byte')
    end
  end
  fixed_key = keys.first
  fingerprint = unhex(fixed_key.fetch('id_sha256_hex'), 32)
  counters = fixture.fetch('counter_vectors')
  assert(counters.map { |b| b.fetch('counter') } == [1, 255], 'counter boundaries')
  counters.each do |block|
    fields(block, %w[key role position counter input_hex sha256_hex candidates])
    assert(block.fetch('key') == fixed_key.fetch('name') && block.fetch('role') == 1 && block.fetch('position') == 0, 'counter vector identity')
    verify_block(block, word_input(1, 0, fingerprint, block.fetch('counter')))
  end

  definitions = fixture.fetch('synthetic_blocks')
  values = [[0] + [65535] * 15, [62207] + [65535] * 15, [62208, 65535, 7775] + [65535] * 13, [62208] * 15 + [0], [62208, 65535] * 8]
  names = %w[index-zero cutoff-minus-one reject-then-accept accept-last-offset all-rejected]
  assert(definitions.map { |b| b.fetch('name') } == names, 'synthetic block coverage')
  definitions.each_with_index do |block, i|
    fields(block, %w[name block_hex candidates])
    bytes = unhex(block.fetch('block_hex'), 32)
    assert(bytes.bytes.each_slice(2).map { |a, b| a * 256 + b } == values.fetch(i), 'synthetic boundary values')
    assert(block.fetch('candidates') == trace(bytes), 'synthetic trace')
  end
  cases = fixture.fetch('extraction_cases')
  assert(cases.map { |c| c.fetch('name') } == names.first(4) + %w[counter-transition counter-255 exhaustion], 'extraction coverage')
  sequences = names.first(4).map { |n| [n] } + [['all-rejected', 'index-zero'], ['all-rejected'] * 255 + ['cutoff-minus-one'], ['all-rejected'] * 256]
  cases.each_with_index do |entry, i|
    sequence = sequences.fetch(i)
    assert(entry.fetch('blocks') == sequence.each_with_index.map { |b, c| { 'counter' => c, 'block' => b } }, 'literal counter schedule')
    accepted = nil
    entry.fetch('blocks').each do |reference|
      assert(accepted.nil?, 'block after acceptance')
      block = definitions.fetch(names.index(reference.fetch('block')))
      last = trace(unhex(block.fetch('block_hex'), 32)).last
      accepted = [reference.fetch('counter'), last.fetch('offset'), last.fetch('index')] if last.fetch('accepted')
    end
    if accepted
      fields(entry, %w[name blocks outcome index word accepted_counter accepted_offset])
      counter, offset, index = accepted
      assert(entry.fetch('outcome') == 'accept' && entry.fetch('index') == index && entry.fetch('word') == words.fetch(index) && entry.fetch('accepted_counter') == counter && entry.fetch('accepted_offset') == offset, 'extraction result')
    else
      fields(entry, %w[name blocks outcome])
      assert(entry.fetch('outcome') == 'exhausted' && entry.fetch('blocks').size == 256, 'exhaustion')
    end
  end

  negatives = fixture.fetch('negative_substitutions')
  specifications = []
  %w[word check-byte].each do |kind|
    (1..3).each do |role|
      (1..3).each { |other| specifications << ["#{kind}-role-#{role}-to-#{other}", kind, 'role', role, 0, other] unless role == other }
    end
    if kind == 'word'
      (0..3).each do |position|
        (0..3).each { |other| specifications << ["word-position-#{position}-to-#{other}", kind, 'position', 1, position, other] unless position == other }
      end
    end
    %w[domain other-domain nul doubled-nul hex-f sliced-f sliced-f-tail].each { |m| specifications << ["#{kind}-#{m}", kind, m, 1, 0, 0] }
    specifications << ['word-endian', kind, 'endian', 1, 0, 0] if kind == 'word'
  end
  expected_names = specifications.map(&:first)
  assert(negatives.map { |n| n.fetch('name') } == expected_names, 'negative coverage')
  negatives.each_with_index do |entry, i|
    fields(entry, %w[name kind mutation key role position counter replacement canonical_input_hex input_hex sha256_hex expected])
    name, kind, mutation, role, position, replacement = specifications.fetch(i)
    assert([entry.fetch('name'), entry.fetch('kind'), entry.fetch('mutation'), entry.fetch('role'), entry.fetch('position'), entry.fetch('replacement')] == [name, kind, mutation, role, position, replacement], 'negative parameters')
    word = entry.fetch('kind') == 'word'
    assert(entry.fetch('key') == fixed_key.fetch('name') && entry.fetch('counter') == (word ? 1 : 0), 'negative identity and counter')
    canonical = word ? word_input(role, position, fingerprint, 1) : check_input(role, fingerprint)
    altered = canonical.dup
    domain_size = (word ? 'AgentHub/identity/key-check/word/v1' : 'AgentHub/identity/key-check/check-byte/v1').bytesize
    f_offset = domain_size + (word ? 3 : 2)
    case entry.fetch('mutation')
    when 'role' then altered.setbyte(domain_size + 1, replacement)
    when 'position' then assert(word, 'position kind'); altered.setbyte(domain_size + 2, replacement)
    when 'domain' then altered.setbyte(domain_size - 1, '2'.ord)
    when 'other-domain' then altered[0, domain_size] = word ? 'AgentHub/identity/key-check/check-byte/v1' : 'AgentHub/identity/key-check/word/v1'
    when 'nul' then altered.slice!(domain_size, 1)
    when 'doubled-nul' then altered.insert(domain_size, "\0")
    when 'endian' then assert(word, 'endian kind'); altered[-4, 4] = "\x01\0\0\0".b
    when 'hex-f' then altered[f_offset, 32] = fingerprint.unpack1('H*')
    when 'sliced-f' then altered.slice!(f_offset + 16, 16)
    when 'sliced-f-tail' then altered.slice!(f_offset, 16)
    else raise 'unknown mutation'
    end
    assert(unhex(entry.fetch('canonical_input_hex')) == canonical && unhex(entry.fetch('input_hex')) == altered, 'negative substitution bytes')
    digest = Digest::SHA256.digest(altered)
    assert(unhex(entry.fetch('sha256_hex'), 32) == digest && altered != canonical && digest != Digest::SHA256.digest(canonical) && entry.fetch('expected') == 'reject', 'negative rejection')
  end
  endian = fixture.fetch('negative_extractions')
  assert(endian.size == 1, 'negative extractor coverage')
  entry = endian.first
  fields(entry, %w[name block_hex candidate_endian candidates index canonical_index expected])
  assert(entry.fetch('name') == 'little-endian-candidates' && entry.fetch('candidate_endian') == 'little', 'negative extractor label')
  bytes = unhex(entry.fetch('block_hex'), 32)
  assert(entry.fetch('block_hex') == definitions.fetch(2).fetch('block_hex'), 'negative extractor block')
  incorrect = []
  (0...32).step(2) do |offset|
    value = bytes.getbyte(offset) + bytes.getbyte(offset + 1) * 256
    candidate = { 'offset' => offset, 'value' => value, 'accepted' => value < 62208 }
    candidate['index'] = value % 7776 if value < 62208
    incorrect << candidate
    break if value < 62208
  end
  assert(entry.fetch('candidates') == incorrect && entry.fetch('index') == incorrect.last.fetch('index'), 'little-endian trace')
  assert(entry.fetch('canonical_index') == trace(bytes).last.fetch('index') && entry.fetch('index') != entry.fetch('canonical_index') && entry.fetch('expected') == 'reject', 'little-endian rejection')
  true
end

path = File.join(__dir__, 'identity.json')
abort 'usage: check-keys.rb [--self-test | corpus.json]' if ARGV.size > 1
path = ARGV.first if ARGV.first && ARGV.first != '--self-test'
fixture = JSON.parse(File.binread(path), object_class: UniqueObject)
root = File.expand_path('../../../..', __dir__)
dictionary = File.binread(File.join(root, 'internal/agenthub/identity/wordlist/eff_large_wordlist_2016.txt'))
verify(fixture, dictionary)
if ARGV == ['--self-test']
  mutations = [
    ->(f) { f['keys'] = [] },
    ->(f) { f['keys'][0]['key_checks'].pop },
    ->(f) { f['keys'][0]['key_checks'][0]['streams'].pop },
    ->(f) { f['keys'][0]['id_sha256_hex'] = '00' * 32 },
    ->(f) { f['keys'][0]['key_checks'][0]['words'][0] = 'wrong' },
    ->(f) { f['keys'][0]['key_checks'][0]['display'] = 'wrong' },
    ->(f) { f['keys'][0]['key_checks'][0]['streams'][0]['blocks'][0]['candidates'] = [] },
    ->(f) { f['counter_vectors'].pop },
    ->(f) { f['extraction_cases'].pop },
    ->(f) { f['extraction_cases'].last['blocks'].pop },
    ->(f) { f['negative_substitutions'].pop },
    ->(f) { f['negative_substitutions'][0]['expected'] = 'accept' },
    ->(f) { f['negative_substitutions'][0]['input_hex'] = f['negative_substitutions'][0]['canonical_input_hex'] },
    ->(f) { f['negative_extractions'] = [] },
    ->(f) { f['negative_extractions'][0]['index'] = 7775 },
    ->(f) { f['synthetic_blocks'].last['candidates'].pop },
    ->(f) { f['counter_vectors'][0]['sha256_hex'] = '00' * 32 },
    ->(f) { f['counter_vectors'][0]['input_hex'] += '0' },
    ->(f) { f['wordlist_sha256_hex'] = '00' * 32 },
    ->(f) { f['word_count'] = 7776.0 },
    ->(f) { f['unexpected'] = true }
  ]
  # Every required top-level section must also be present.
  mutations += fixture.keys.map { |key| ->(f) { f.delete(key) } }
  mutations.each_with_index do |mutate, i|
    copy = JSON.parse(JSON.generate(fixture))
    mutate.call(copy)
    rejected = false
    begin
      verify(copy, dictionary)
    rescue StandardError
      rejected = true
    end
    assert(rejected, "checker accepted malformed case #{i}")
  end
  duplicate_rejected = false
  begin
    JSON.parse('{"role":1,"role":2}', object_class: UniqueObject)
  rescue StandardError
    duplicate_rejected = true
  end
  assert(duplicate_rejected, 'duplicate JSON member accepted')
  puts "keys: #{mutations.size} malformed or missing corpus cases rejected"
end
puts 'keys: SPKI hashes, EFF binding, role streams, counter boundaries, extraction and negative substitutions passed'