Powered by AppSignal & Oban Pro

Content assertions

content-assertions.livemd

Content assertions

Use this notebook to bind exact content bytes to a signed context and lineage. Verify the assertion and check how edited bytes or mismatched trust inputs are refused.

Open this file in Livebook and choose Run all. Check Compatibility and allow access to Hex.

Mix.install([{:bounded_authority_report_adapter, "== 2.0.0"}])

"2.0.0" = to_string(Application.spec(:bounded_authority_report_adapter, :vsn))
:installed
:installed

Local key custody

This is an actual OTP process holding freshly generated demonstration keys. Handles carry public metadata and opaque process/key references; private bytes never enter an adapter call. It demonstrates callbacks and conversion, not a remote HSM’s security or availability. Every key is discarded when the process stops.

defmodule Demo.Custody do
  use GenServer

  alias BoundedAuthorityReportAdapter.Custody

  def start_link, do: GenServer.start_link(__MODULE__, %{})
  def new(pid, suite, key_id, purposes), do: GenServer.call(pid, {:new, suite, key_id, purposes})

  def snapshot(%{custody: pid, reference: reference}),
    do: GenServer.call(pid, {:snapshot, reference}, 5_000)

  def sign({pid, reference}, purpose, message),
    do: GenServer.call(pid, {:sign, reference, purpose, message}, 5_000)

  @impl true
  def init(keys), do: {:ok, keys}

  @impl true
  def handle_call({:new, suite, key_id, purposes}, _from, keys) do
    {public, private} =
      case suite do
        :ed25519 -> :crypto.generate_key(:eddsa, :ed25519)
        :p256 -> :crypto.generate_key(:ecdh, :prime256v1)
      end

    reference = make_ref()
    key = %{custody: self(), reference: reference, key_id: key_id, public: public}
    {:reply, key, Map.put(keys, reference, {suite, key_id, public, purposes, private})}
  end

  def handle_call({:snapshot, reference}, _from, keys) do
    result =
      case Map.fetch(keys, reference) do
        {:ok, {_suite, key_id, public, purposes, _private}} ->
          {:ok, {key_id, public, purposes, {self(), reference}}}

        :error ->
          {:error, :unknown_version}
      end

    {:reply, result, keys}
  end

  def handle_call({:sign, reference, purpose, message}, _from, keys) do
    result =
      with {:ok, {suite, _key_id, _public, allowed, private}} <- Map.fetch(keys, reference),
           true <- purpose in allowed,
           {:ok, ^purpose} <- Custody.purpose(message) do
        {:ok, sign_bytes(suite, message, private)}
      else
        _ -> {:error, :purpose_mismatch}
      end

    {:reply, result, keys}
  end

  defp sign_bytes(:ed25519, message, private),
    do: :crypto.sign(:eddsa, :none, message, [private, :ed25519])

  defp sign_bytes(:p256, message, private),
    do: :crypto.sign(:ecdsa, :sha256, message, [private, :prime256v1])
end

defmodule Demo.Ed25519Handle do
  @behaviour BoundedAuthorityReportAdapter

  @impl true
  defdelegate key_snapshot(handle), to: Demo.Custody, as: :snapshot

  @impl true
  def sign(purpose, message, reference), do: Demo.Custody.sign(reference, purpose, message)
end

defmodule Demo.P256Handle do
  @behaviour BoundedAuthorityReportAdapter

  @n 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551

  @impl true
  defdelegate key_snapshot(handle), to: Demo.Custody, as: :snapshot

  @impl true
  def sign(purpose, message, reference) do
    with {:ok, der} <- Demo.Custody.sign(reference, purpose, message),
         {:ok, <<r::unsigned-big-256, s::unsigned-big-256>>} <-
           BoundedAuthorityProtocol.Es256.der_to_raw(der) do
      # Exercise the adapter's normalization with a valid high-S signature.
      high_s = if s > div(@n, 2), do: s, else: @n - s
      {:ok, <<r::unsigned-big-256, high_s::unsigned-big-256>>}
    end
  end
end

{:ok, custody} = Demo.Custody.start_link()
[Demo.Custody, Demo.Ed25519Handle, Demo.P256Handle]
[Demo.Custody, Demo.Ed25519Handle, Demo.P256Handle]
alias BoundedAuthorityProtocol.V1
alias BoundedAuthorityProtocol.V3
alias BoundedAuthorityProtocol.ApplicationProfile.LocalLoopbackHttp.V1, as: LocalLoopback
alias BoundedAuthorityProtocol.ContentAssertion.V1, as: ContentAssertion
alias BoundedAuthorityProtocol.RoleAttestation.V1, as: RoleAttestation
alias BoundedAuthorityReportAdapter, as: Adapter

[V1, V3, LocalLoopback, ContentAssertion, RoleAttestation, Adapter]
[
  BoundedAuthorityProtocol.V1,
  BoundedAuthorityProtocol.V3,
  BoundedAuthorityProtocol.ApplicationProfile.LocalLoopbackHttp.V1,
  BoundedAuthorityProtocol.ContentAssertion.V1,
  BoundedAuthorityProtocol.RoleAttestation.V1,
  BoundedAuthorityReportAdapter
]
now = System.system_time(:second)

ed25519_key = fn key_id, purposes ->
  Demo.Custody.new(custody, :ed25519, key_id, purposes)
end

p256_key = fn key_id, purposes ->
  Demo.Custody.new(custody, :p256, key_id, purposes)
end

# Ed25519 keys (contract-major 1 and the content-assertion profile).
issuer = ed25519_key.("issuer-key-1", [:grant, :diagnostic_probe])
holder = ed25519_key.("holder-key-1", [:holder_proof, :loopback_proof, :diagnostic_probe])
chain_key = ed25519_key.("chain-key-1", [:chain_anchor, :key_transition])
next_chain_key = ed25519_key.("chain-key-2", [:chain_anchor, :key_transition])
publisher = ed25519_key.("publisher-key-1", [:content_assertion])

# P-256 keys (contract-major 3, ES256).
ec_issuer = p256_key.("issuer-ec-key-1", [:grant, :diagnostic_probe])
ec_holder = p256_key.("holder-ec-key-1", [:holder_proof, :loopback_proof, :diagnostic_probe])
ec_chain_key = p256_key.("chain-ec-key-1", [:chain_anchor, :key_transition])
ec_next_chain_key = p256_key.("chain-ec-key-2", [:chain_anchor, :key_transition])

# What a verifier is told about a key: its id, its public half, and when it is valid.
validity = fn key ->
  %V1.HistoricalPublicKey{
    key_id: key.key_id,
    public_key: key.public,
    valid_from: now - 3_600,
    valid_before: now + 3_600
  }
end

# Selected fields of a result, in a fixed order (a map would print in no fixed order).
facts_of = fn struct, keys -> Enum.map(keys, &{&1, Map.fetch!(struct, &1)}) end

# Flip one bit in the first byte of a compact's signature segment.
flip_one_byte = fn compact ->
  [header, payload, signature] = String.split(compact, ".")
  <<first, rest::binary>> = Base.url_decode64!(signature, padding: false)
  flipped = Base.url_encode64(<<Bitwise.bxor(first, 1), rest::binary>>, padding: false)
  Enum.join([header, payload, flipped], ".")
end

32 = byte_size(holder.public)
65 = byte_size(ec_holder.public)

[
  ed25519_public_key_bytes: byte_size(holder.public),
  p256_public_key_bytes: byte_size(ec_holder.public)
]
[ed25519_public_key_bytes: 32, p256_public_key_bytes: 65]

Content assertions

dataset = ~s({"station":"riverside","pm25":[8.1,7.9,8.4]})
{:ok, content_digest} = ContentAssertion.content_digest(dataset, %{})
profile_digest = :crypto.hash(:sha256, "urn:example:profile:air-quality/1 schema")
publisher_handle = {Demo.Ed25519Handle, publisher}

assertion_input = %{
  jti: "urn:example:assertion:riverside-1",
  iss: "urn:example:publisher",
  aud: "urn:example:archive",
  sub: "urn:example:dataset:riverside-air-quality",
  profile: "urn:example:profile:air-quality/1",
  profile_digest: profile_digest,
  content_digest: content_digest,
  gen: 1,
  prev: <<0::256>>,
  iat: now - 60,
  nbf: now - 60,
  exp: now + 3_600
}

{:ok, %{content_assertion: assertion}} =
  Adapter.sign_content_assertion(assertion_input, publisher_handle)

expected_assertion = %ContentAssertion.ExpectedContentAssertion{
  attestor: validity.(publisher),
  issuer: "urn:example:publisher",
  audience: "urn:example:archive",
  subject: "urn:example:dataset:riverside-air-quality",
  profile: "urn:example:profile:air-quality/1",
  profile_digest: profile_digest,
  content_digest: content_digest,
  now: now,
  bounds: V1.Bounds.maximum()
}

{:ok, assertion_facts} = ContentAssertion.verify_assertion(assertion, expected_assertion)
facts_of.(assertion_facts, [:sub, :gen, :verification, :trust])
[
  sub: "urn:example:dataset:riverside-air-quality",
  gen: 1,
  verification: :signature_and_window,
  trust: :not_evaluated
]
{:ok, edited_digest} = ContentAssertion.content_digest(dataset <> " ", %{})

# Tampered assertion.
{:error, :invalid} =
  ContentAssertion.verify_assertion(flip_one_byte.(assertion), expected_assertion)

# Edited content.
{:error, :invalid} =
  ContentAssertion.verify_assertion(assertion, %{
    expected_assertion
    | content_digest: edited_digest
  })

# Wrong publisher key.
{:error, :invalid} =
  ContentAssertion.verify_assertion(assertion, %{
    expected_assertion
    | attestor: %{validity.(publisher) | public_key: holder.public}
  })

# Wrong audience.
{:error, :invalid} =
  ContentAssertion.verify_assertion(assertion, %{
    expected_assertion
    | audience: "urn:example:other-archive"
  })

# Missing field.
{:error, :invalid_content_assertion} =
  Adapter.sign_content_assertion(Map.delete(assertion_input, :content_digest), publisher_handle)
{:error, :invalid_content_assertion}

ES256 content assertions

Select the ES256 content-assertion profile explicitly. The P-256 backend hashes the exact signing input once and returns a raw signature. The content digest is shared by both suites.

alias BoundedAuthorityProtocol.ContentAssertion.ES256.V1, as: ES256Content

ec_publisher = p256_key.("publisher-ec-key-1", [:content_assertion])
ec_publisher_handle = {Demo.P256Handle, ec_publisher}

{:ok, %{content_assertion: ec_assertion}} =
  Adapter.V3.sign_content_assertion(assertion_input, ec_publisher_handle)

ec_expected =
  expected_assertion
  |> Map.from_struct()
  |> Map.put(:attestor, validity.(ec_publisher))
  |> then(&struct!(ES256Content.ExpectedContentAssertion, &1))

{:ok, %{trust: :not_evaluated}} = ES256Content.verify_assertion(ec_assertion, ec_expected)
{:error, :invalid} = ContentAssertion.verify_assertion(ec_assertion, expected_assertion)
{:error, :invalid} = ES256Content.verify_assertion(assertion, ec_expected)
:suite_separation
:suite_separation

Action approvals

The host prepares an exact request and selects eligible approver roles through its operation policy. The approver uses a plain signing-backend signature. Carry the exact returned record bytes alongside the assertion.

alias BoundedAuthorityProtocol.ActionApproval.V1, as: Approval

prepared = %{
  request_id: "urn:example:request:field-notes-release",
  revision_digest: :crypto.hash(:sha256, "prepared field notes revision"),
  subject: "field notes",
  action: "publish",
  resources: ["observations", "summary"]
}

record = struct!(Approval.Record, Map.put(prepared, :approver_role, "reviewer"))
issuer_id = "urn:example:reviewer"
audience = "urn:example:archive"

approval_input = %{
  record: record,
  jti: "urn:example:approval:field-notes-1",
  iss: issuer_id,
  aud: audience,
  iat: now,
  nbf: now,
  exp: now + 60
}

approver = ed25519_key.("reviewer-key-1", [:action_approval])
ec_approver = p256_key.("reviewer-ec-key-1", [:action_approval])

{:ok, %{record: bytes, content_assertion: approval}} =
  Adapter.sign_action_approval(approval_input, {Demo.Ed25519Handle, approver})

{:ok, %{record: ^bytes, content_assertion: ec_approval}} =
  Adapter.V3.sign_action_approval(approval_input, {Demo.P256Handle, ec_approver})

context = fn suite, enrolled ->
  Map.merge(prepared, %{
    trust_domain: "archive",
    audience: audience,
    roles: ["reviewer"],
    now: now,
    max_staleness: 30,
    max_lifetime: 60,
    bounds: %{},
    record_bounds: %{},
    snapshot: %{
      trust_domain: "archive",
      suite: suite,
      provenance: "configured-enrollment",
      as_of: now,
      entries: [%{issuer: issuer_id, key: validity.(enrolled), roles: ["reviewer"]}]
    }
  })
end

ed_context = context.(:eddsa, approver)
ec_context = context.(:es256, ec_approver)
{:ok, %{trust: :not_evaluated}} = Approval.verify_eddsa(bytes, approval, ed_context)
{:ok, %{trust: :not_evaluated}} = Approval.verify_es256(bytes, ec_approval, ec_context)

{:error, :scope_mismatch} =
  Approval.verify_es256(bytes, ec_approval, %{ec_context | resources: ["summary"]})
{:error, :scope_mismatch}

Clean up

:ok = GenServer.stop(custody)
false = Process.alive?(custody)
:clean
:clean

Continue with Getting started, Framework and runtime integration, and Operations.