// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Package tpm2 provides TPM2.0 related functionality helpers.
package tpm2_test

import (
	"testing"

	"github.com/google/go-tpm/tpm2"
	"github.com/google/go-tpm/tpm2/transport"
	"github.com/stretchr/testify/require"

	tpm2internal "github.com/siderolabs/talos/internal/pkg/secureboot/tpm2"
)

func TestCalculatePolicy(t *testing.T) {
	t.Parallel()

	policy, err := tpm2internal.CalculatePolicy([]byte{1, 3, 5}, tpm2.TPMLPCRSelection{
		PCRSelections: []tpm2.TPMSPCRSelection{
			{
				Hash:      tpm2.TPMAlgSHA256,
				PCRSelect: []byte{10, 11, 12},
			},
		},
	})
	require.NoError(t, err)
	require.Equal(t,
		[]byte{0x84, 0xd6, 0x51, 0x47, 0xb0, 0x53, 0x94, 0xd0, 0xfa, 0xc4, 0x5e, 0x36, 0x0, 0x20, 0x3e, 0x3a, 0x11, 0x1, 0x27, 0xfb, 0xe2, 0x6f, 0xc1, 0xe3, 0x3, 0x3, 0x10, 0x21, 0x33, 0xf9, 0x15, 0xe3},
		policy,
	)
}

func TestCalculateSealingPolicyDigestWithNOPCRs(t *testing.T) {
	t.Parallel()

	calculated, err := tpm2internal.CalculateSealingPolicyDigest(nil, tpm2internal.SealingPolicyDigestInfo{
		PublicKey: "testdata/pcr-signing-crt.pem",
		ReadPCRFunc: func(t transport.TPM, pcr int) ([]byte, error) {
			return nil, nil
		},
	})

	require.NoError(t, err)

	require.Equal(t,
		[]byte{0x86, 0xdc, 0x2b, 0x7f, 0x5a, 0xeb, 0xde, 0x57, 0xd4, 0x72, 0xdd, 0xbc, 0x3d, 0x5b, 0xd5, 0xb5, 0xb, 0x15, 0x6f, 0x4d, 0x6b, 0xa6, 0x62, 0xc2, 0x1a, 0xff, 0xbf, 0xb1, 0xb2, 0xd4, 0xb9, 0x84},
		calculated,
	)
}

func TestCalculateSealingPolicyDigestWithPCRs(t *testing.T) {
	t.Parallel()

	calculated, err := tpm2internal.CalculateSealingPolicyDigest(nil, tpm2internal.SealingPolicyDigestInfo{
		PublicKey: "testdata/pcr-signing-crt.pem",
		PCRs:      []int{0, 11},
		ReadPCRFunc: func(t transport.TPM, pcr int) ([]byte, error) {
			return []byte{0x9c, 0x9c, 0x10, 0x58, 0x77, 0x9d, 0x2b, 0xf6, 0x30, 0x1b, 0x56, 0x8, 0x5b, 0x26, 0xe9, 0xae, 0x98, 0x62, 0x2e, 0x1f, 0xa7, 0x3e, 0xad, 0xd9, 0x8b, 0x9c, 0xa3, 0xa1, 0x8, 0x29, 0xc1, 0x9c}, nil //nolint:lll
		},
	})

	require.NoError(t, err)

	require.Equal(t, []byte{0x14, 0xff, 0x86, 0xf8, 0x6, 0x9c, 0xe4, 0xf2, 0xc9, 0x18, 0x32, 0x5e, 0x2e, 0x1b, 0x78, 0x11, 0xcf, 0xc5, 0xe6, 0x27, 0x8d, 0xd1, 0xb, 0x86, 0xa9, 0x4, 0x16, 0xc2, 0x8f, 0xe6, 0x47, 0x6a}, calculated) //nolint:lll
}
