// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tdx

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/x509"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"testing"
	"time"
)

// ============================================================================
// Test Helper Functions
// ============================================================================

// loadTestQuote loads a real quote from testdata/quote
func loadTestQuote(t *testing.T, filename string) ([]byte, *TdxEcdsaQuote) {
	t.Helper()
	path := filepath.Join("testdata", "quote", filename)
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("Failed to load quote %s: %v", filename, err)
	}
	parsed, err := ParseQuote(data)
	if err != nil {
		t.Fatalf("Failed to parse quote %s: %v", filename, err)
	}
	return data, parsed
}

// loadTestCollateral loads collateral from testdata/collateral for a specific quote
// Parameters:
//   - quote: The parsed TDX quote
//   - extractFromPCK: Controls how FMSPC is determined:
//   - true:  Extract actual FMSPC from quote's PCK certificate (accurate, recommended)
//   - false: Infer FMSPC from quote version (v4->50806F000000, v5->90C06F000000)
//
// Returns the collateral with FMSPC-specific TCB Info loaded from testdata
func loadTestCollateral(t *testing.T, quote *TdxEcdsaQuote, extractFromPCK bool) *Collateral {
	t.Helper()

	// Determine FMSPC
	var fmspc string
	if quote != nil {
		if extractFromPCK {
			// Extract FMSPC from quote's PCK certificate
			qeCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData)
			if !ok {
				t.Fatalf("Quote certification data is not QeReportCertificationData")
			}

			certChainBytes, ok := qeCertData.QeCertificationData.CertificationData.([]byte)
			if !ok {
				t.Fatalf("Cert chain data is not byte array")
			}

			certChain, err := ParseCertChain(certChainBytes)
			if err != nil {
				t.Fatalf("Failed to parse cert chain: %v", err)
			}

			if certChain.PCKCert == nil {
				t.Fatalf("No PCK cert in chain")
			}

			// Extract FMSPC from PCK cert
			fmspcBytes, _, err := ExtractSgxExtensions(certChain.PCKCert)
			if err != nil {
				t.Fatalf("Failed to extract FMSPC from PCK cert: %v", err)
			}

			fmspc = hex.EncodeToString(fmspcBytes)
		} else {
			// Infer FMSPC from quote version (simple heuristic)
			if quote.Header.Version == 4 {
				fmspc = "50806F000000"
			} else {
				fmspc = "90C06F000000"
			}
		}
	} else {
		// Default fallback
		fmspc = "90C06F000000"
	}

	tcbInfoFile := fmt.Sprintf("testdata/collateral/tdx_tcb_%s.json", fmspc)
	tcbInfo, err := os.ReadFile(tcbInfoFile)
	if err != nil {
		t.Fatalf("Failed to load TCB Info %s: %v", tcbInfoFile, err)
	}
	qeIdentity, err := os.ReadFile("testdata/collateral/tdx_qe_identity.json")
	if err != nil {
		t.Fatalf("Failed to load QE Identity: %v", err)
	}
	pckCrl, err := os.ReadFile("testdata/collateral/pck_crl_processor.pem")
	if err != nil {
		t.Fatalf("Failed to load PCK CRL: %v", err)
	}
	rootCaCrl, err := os.ReadFile("testdata/collateral/root_ca_crl.pem")
	if err != nil {
		t.Fatalf("Failed to load Root CA CRL: %v", err)
	}
	tcbInfoIssuerChain, err := os.ReadFile("testdata/collateral/tcb_info_issuer_chain.pem")
	if err != nil {
		t.Fatalf("Failed to load TCB Info Issuer Chain: %v", err)
	}
	qeIdentityIssuerChain, err := os.ReadFile("testdata/collateral/qe_identity_issuer_chain.pem")
	if err != nil {
		t.Fatalf("Failed to load QE Identity Issuer Chain: %v", err)
	}
	pckCrlIssuerChain, err := os.ReadFile("testdata/collateral/pck_crl_issuer_chain.pem")
	if err != nil {
		t.Fatalf("Failed to load PCK CRL Issuer Chain: %v", err)
	}

	return &Collateral{
		Version:               QVE_COLLATERAL_VERSION3,
		TcbInfo:               tcbInfo,
		QeIdentity:            qeIdentity,
		PckCrl:                pckCrl,
		RootCaCrl:             rootCaCrl,
		TcbInfoIssuerChain:    tcbInfoIssuerChain,
		QeIdentityIssuerChain: qeIdentityIssuerChain,
		PckCrlIssuerChain:     pckCrlIssuerChain,
	}
}

// mockCollateralProvider is a mock implementation of CollateralProvider for testing
type mockCollateralProvider struct {
	collateral *Collateral
	err        error
}

func (m *mockCollateralProvider) GetCollateral(quote *TdxEcdsaQuote) (*Collateral, error) {
	return m.collateral, m.err
}

func (m *mockCollateralProvider) RefreshCollateral(fmspc []byte) error {
	return nil
}

// newMockQuoteVerifier creates a QuoteVerifier with mock collateral from testdata
func newMockQuoteVerifier(t *testing.T, quote *TdxEcdsaQuote) *QuoteVerifier {
	t.Helper()
	collateral := loadTestCollateral(t, quote, true) // Extract FMSPC from PCK cert for accuracy

	// Create verifier with mock collateral provider
	// Now that collateralProvider is an interface, we can inject our mock directly
	return &QuoteVerifier{
		collateralProvider: &mockCollateralProvider{
			collateral: collateral,
			err:        nil,
		},
	}
}

// ============================================================================
// partA. end-to-end quote verify testing
// ============================================================================

// TestVerifyQuoteValid tests VerifyQuote with valid quotes
// Tests both local collateral (from testdata) and PCCS collateral
// Ref: QVL sgx_qve_verify_quote entry point
func TestVerifyQuoteValid(t *testing.T) {
	quoteFiles := []string{
		"tdx_quote_4.dat",
		"tdx_quote_5.dat",
		"tdx_quote_5_2.dat",
		"tdx_quote_pai.dat",
	}

	for _, quoteFile := range quoteFiles {
		// Load quote once
		quoteData, parsedQuote := loadTestQuote(t, quoteFile)

		// Test 1: With local collateral from testdata
		t.Run(quoteFile+"/LocalCollateral", func(t *testing.T) {
			t.Logf("Testing quote version: %d, TEE type: %d", parsedQuote.Header.Version, parsedQuote.Header.TeeType)

			// Create verifier with mock collateral provider (loads FMSPC-specific TCB Info)
			verifier := newMockQuoteVerifier(t, parsedQuote)

			// Verify quote with local collateral
			result, ret := verifier.VerifyQuote(quoteData)

			// Check return code - local collateral may have expired CRLs/certs
			// NOTE: Even with FMSPC-matched TCB Info, local collateral may fail due to:
			//   - Expired CRLs (saved at fetch time, may be outdated)
			//   - Certificate chain validation issues with static collateral
			// This is expected and acceptable - local collateral tests code logic, not freshness
			if ret != SGX_QL_SUCCESS {
				t.Logf("VerifyQuote returned: %v (0x%08x)", ret, uint32(ret))
			}

			// Check result is not nil
			if result == nil {
				t.Fatal("VerificationResult is nil")
			}

			t.Logf("QV Result: %v", result.QvResult)
			t.Logf("Collateral Expiration Status: %d", result.CollateralExpStatus)

			// Check QV result - local collateral may have issues, so we allow UNSPECIFIED
			// This is expected when CRLs/certs are expired or validation fails with static data
			switch result.QvResult {
			case SGX_QL_QV_RESULT_OK,
				SGX_QL_QV_RESULT_OUT_OF_DATE,
				SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED,
				SGX_QL_QV_RESULT_CONFIG_NEEDED,
				SGX_QL_QV_RESULT_SW_HARDENING_NEEDED,
				SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED,
				TEE_QV_RESULT_TD_RELAUNCH_ADVISED,
				TEE_QV_RESULT_TD_RELAUNCH_ADVISED_CONFIG_NEEDED,
				SGX_QL_QV_RESULT_UNSPECIFIED: // Allow UNSPECIFIED for expired/invalid local collateral
				// Acceptable result
			default:
				t.Errorf("Unexpected QV Result: %v", result.QvResult)
			}

			// Check parsed quote is populated
			if result.ParsedQuote == nil {
				t.Error("ParsedQuote is nil")
			}

			// Note: Supplemental data may not be populated with problematic local collateral
		})

		// Test 2: With real PCCS collateral
		t.Run(quoteFile+"/PCCSCollateral", func(t *testing.T) {
			t.Logf("Testing quote version: %d, TEE type: %d", parsedQuote.Header.Version, parsedQuote.Header.TeeType)

			// Use Aliyun PCCS server
			verifier := NewQuoteVerifier("https://sgx-dcap-server.cn-hangzhou.aliyuncs.com")

			// Verify quote with real PCCS collateral
			result, ret := verifier.VerifyQuote(quoteData)

			// Check return code - should succeed or be non-terminal error
			if ret != SGX_QL_SUCCESS {
				t.Logf("VerifyQuote returned: %v (0x%08x)", ret, uint32(ret))
			}

			// Check result is not nil
			if result == nil {
				t.Fatal("VerificationResult is nil")
			}

			t.Logf("QV Result: %v", result.QvResult)
			t.Logf("Collateral Expiration Status: %d", result.CollateralExpStatus)

			// NOTE: VerifyQuote follows QVL's sgx_qve_verify_quote design:
			// - If collateral verification fails with expiration (e.g., STATUS_SGX_TCB_INFO_EXPIRED),
			//   it sets CollateralExpStatus=1 but continues to verify the quote itself
			// - Final QvResult is determined by sgxAttestationVerifyQuote (quote signature, TCB level match, etc.)
			// - QvResult can be OK even if CollateralExpStatus=1 (expired collateral but valid quote)
			// This explains why this test returns OK while TestVerifyTcbInfo may return EXPIRED.
			switch result.QvResult {
			case SGX_QL_QV_RESULT_OK,
				SGX_QL_QV_RESULT_OUT_OF_DATE,
				SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED,
				SGX_QL_QV_RESULT_CONFIG_NEEDED,
				SGX_QL_QV_RESULT_SW_HARDENING_NEEDED,
				SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED,
				TEE_QV_RESULT_TD_RELAUNCH_ADVISED,
				TEE_QV_RESULT_TD_RELAUNCH_ADVISED_CONFIG_NEEDED:
				// Acceptable result
			default:
				t.Errorf("Unexpected QV Result: %v", result.QvResult)
			}

			// Check parsed quote is populated
			if result.ParsedQuote == nil {
				t.Error("ParsedQuote is nil")
			}

			// Check supplemental data is populated on success
			if ret == SGX_QL_SUCCESS {
				if result.SupplementalData == nil {
					t.Error("SupplementalData is nil on success")
				}
				if len(result.SupplementalDataBuf) == 0 {
					t.Error("SupplementalDataBuf is empty on success")
				}
			}
		})
	}
}

// TestVerifyQuoteInvalid tests VerifyQuote with various invalid quote scenarios
// Uses real quotes from testdata and modifies them to create error conditions
func TestVerifyQuoteInvalid(t *testing.T) {
	verifier := NewQuoteVerifier("")

	// Test 1: Empty quote data
	t.Run("EmptyQuote", func(t *testing.T) {
		result, ret := verifier.VerifyQuote([]byte{})

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result == nil {
			t.Error("Result should not be nil")
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})

	// Test 2: Truncated v4 quote
	t.Run("TruncatedQuoteV4", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_4.dat")
		truncated := quoteData[:10] // Header is 48 bytes, this is too short

		result, ret := verifier.VerifyQuote(truncated)

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})

	// Test 3: Truncated v5 quote
	t.Run("TruncatedQuoteV5", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_5.dat")
		truncated := quoteData[:10]

		result, ret := verifier.VerifyQuote(truncated)

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})

	// Test 4: Corrupted signature in v4 quote
	t.Run("CorruptedSignatureV4", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_4.dat")
		corrupted := make([]byte, len(quoteData))
		copy(corrupted, quoteData)

		// Flip bits in signature area (after header+report+signatureDataLen)
		// Header=48, Report=584, signatureDataLen=4, total offset=636
		if len(corrupted) > 636+64 {
			for i := 636; i < 636+64; i++ {
				corrupted[i] ^= 0xFF
			}
		}

		result, ret := verifier.VerifyQuote(corrupted)

		// Should fail with invalid signature error (terminal error)
		if ret != SGX_QL_RESULT_INVALID_SIGNATURE {
			t.Errorf("Expected SGX_QL_RESULT_INVALID_SIGNATURE, got %v (0x%04X)", ret, int(ret))
		}
		if result == nil {
			t.Fatal("Result should not be nil")
		}
		// For terminal errors, QvResult is UNSPECIFIED
		if result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED for terminal error, got %v", result.QvResult)
		}
	})

	// Test 5: Corrupted signature in v5 quote
	t.Run("CorruptedSignatureV5", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_5.dat")
		corrupted := make([]byte, len(quoteData))
		copy(corrupted, quoteData)

		// Flip bits in signature area
		if len(corrupted) > 636+64 {
			for i := 636; i < 636+64; i++ {
				corrupted[i] ^= 0xFF
			}
		}

		result, ret := verifier.VerifyQuote(corrupted)

		// Should fail with invalid signature error (terminal error)
		if ret != SGX_QL_RESULT_INVALID_SIGNATURE {
			t.Errorf("Expected SGX_QL_RESULT_INVALID_SIGNATURE, got %v (0x%04X)", ret, int(ret))
		}
		if result == nil {
			t.Fatal("Result should not be nil")
		}
		// For terminal errors, QvResult is UNSPECIFIED
		if result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED for terminal error, got %v", result.QvResult)
		}
	})

	// Test 6: Invalid version
	t.Run("InvalidVersion", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_4.dat")
		invalid := make([]byte, len(quoteData))
		copy(invalid, quoteData)

		// Modify version to 2 (unsupported)
		invalid[0] = 0x02
		invalid[1] = 0x00

		result, ret := verifier.VerifyQuote(invalid)

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})

	// Test 7: Invalid TEE type
	t.Run("InvalidTeeType", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_4.dat")
		invalid := make([]byte, len(quoteData))
		copy(invalid, quoteData)

		// Modify TEE type to 0x99 (invalid)
		invalid[4] = 0x99
		invalid[5] = 0x00
		invalid[6] = 0x00
		invalid[7] = 0x00

		result, ret := verifier.VerifyQuote(invalid)

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})

	// Test 8: Invalid attestation key type
	t.Run("InvalidKeyType", func(t *testing.T) {
		quoteData, _ := loadTestQuote(t, "tdx_quote_4.dat")
		invalid := make([]byte, len(quoteData))
		copy(invalid, quoteData)

		// Modify attestation key type to 1 (unsupported)
		invalid[2] = 0x01
		invalid[3] = 0x00

		result, ret := verifier.VerifyQuote(invalid)

		if ret != SGX_QL_ERROR_INVALID_PARAMETER {
			t.Errorf("Expected SGX_QL_ERROR_INVALID_PARAMETER, got %v", ret)
		}
		if result != nil && result.QvResult != SGX_QL_QV_RESULT_UNSPECIFIED {
			t.Errorf("Expected QvResult UNSPECIFIED, got %v", result.QvResult)
		}
	})
}

// ============================================================================
// PartB. Quote parsing and format validation testing
// ============================================================================

// TestValidateQuoteFormat tests quote format validation using real quotes
// Tests the validate() function with various format errors
func TestValidateQuoteFormat(t *testing.T) {
	verifier := NewQuoteVerifier("")

	// Test 1: Valid v4 quote format
	t.Run("ValidQuoteFormatV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		result := verifier.validate(parsedQuote)
		if !result {
			t.Error("Valid v4 quote should pass format validation")
		}
	})

	// Test 2: Valid v5 quote format
	t.Run("ValidQuoteFormatV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		result := verifier.validate(parsedQuote)
		if !result {
			t.Error("Valid v5 quote should pass format validation")
		}
	})

	// Test 3: Invalid certification data type for v4
	t.Run("InvalidCertDataTypeForV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// v4 quotes must have certification data type 6
		parsedQuote.QeCertificationData.CertificationDataType = 5

		result := verifier.validate(parsedQuote)
		if result {
			t.Error("v4 quote with wrong cert data type should fail validation")
		}
	})

	// Test 4: Invalid certification data type for v5
	t.Run("InvalidCertDataTypeForV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// v5 quotes support types 5, 6, 7
		parsedQuote.QeCertificationData.CertificationDataType = 4

		result := verifier.validate(parsedQuote)
		if result {
			t.Error("v5 quote with wrong cert data type should fail validation")
		}
	})

	// Test 5: v5 TDX quote without body descriptor
	t.Run("V5TdxWithoutBodyDescriptor", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// v5 TDX quotes must have body descriptor
		parsedQuote.BodyDescriptor = nil

		result := verifier.validate(parsedQuote)
		if result {
			t.Error("v5 TDX quote without body descriptor should fail validation")
		}
	})
}

// ============================================================================
// PartC. Quote signature verification testing
// ============================================================================

// TestVerifyQuoteSignature tests quote signature verification using real quotes
// Tests the verifyQuoteSignature() function
func TestVerifyQuoteSignature(t *testing.T) {
	verifier := NewQuoteVerifier("")

	// Test 1: Valid v4 quote signature
	t.Run("ValidQuoteSignatureV4", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		status := verifier.verifyQuoteSignature(parsedQuote, quoteData)
		if status != STATUS_OK {
			t.Errorf("Expected STATUS_OK for valid v4 quote signature, got %v", status)
		}
	})

	// Test 2: Valid v5 quote signature
	t.Run("ValidQuoteSignatureV5", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		status := verifier.verifyQuoteSignature(parsedQuote, quoteData)
		if status != STATUS_OK {
			t.Errorf("Expected STATUS_OK for valid v5 quote signature, got %v", status)
		}
	})

	// Test 3: Corrupted quote signature
	t.Run("CorruptedQuoteSignature", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Corrupt the signature
		parsedQuote.QuoteSignature[0] ^= 0xFF
		parsedQuote.QuoteSignature[1] ^= 0xFF

		status := verifier.verifyQuoteSignature(parsedQuote, quoteData)
		if status != STATUS_INVALID_QUOTE_SIGNATURE {
			t.Errorf("Expected STATUS_INVALID_QUOTE_SIGNATURE, got %v", status)
		}
	})

	// Test 4: Invalid ECDSA key (all zeros)
	t.Run("InvalidEcdsaKey", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Replace with invalid key (all zeros)
		parsedQuote.EcdsaAttestationKey = [64]byte{}

		status := verifier.verifyQuoteSignature(parsedQuote, quoteData)
		if status != STATUS_INVALID_QUOTE_SIGNATURE {
			t.Errorf("Expected STATUS_INVALID_QUOTE_SIGNATURE for invalid key, got %v", status)
		}
	})

	// Test 5: Truncated raw quote (cannot extract signed data)
	t.Run("TruncatedRawQuote", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Use truncated raw quote
		truncatedQuote := make([]byte, 10)

		status := verifier.verifyQuoteSignature(parsedQuote, truncatedQuote)
		if status != STATUS_INVALID_QUOTE_SIGNATURE {
			t.Errorf("Expected STATUS_INVALID_QUOTE_SIGNATURE for truncated quote, got %v", status)
		}
	})
}

// TestVerifyQeReportSignature tests QE Report signature verification using real quotes
// Tests the verifyQeReportSignature() function
func TestVerifyQeReportSignature(t *testing.T) {
	verifier := NewQuoteVerifier("")

	// Test 1: Valid QE Report signature with real v4 quote
	t.Run("ValidQeReportSignatureV4", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Extract PCK certificate from quote's cert chain
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)

		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		pckCert := certChain.PCKCert
		if pckCert == nil {
			t.Fatal("PCK cert is nil")
		}

		status := verifier.verifyQeReportSignature(pckCert, parsedQuote, quoteData)
		if status != STATUS_OK {
			t.Logf("QE Report signature verification returned: %v (may be expected)", status)
		}
	})

	// Test 2: Valid QE Report signature with real v5 quote
	t.Run("ValidQeReportSignatureV5", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)

		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		pckCert := certChain.PCKCert
		if pckCert == nil {
			t.Fatal("PCK cert is nil")
		}

		status := verifier.verifyQeReportSignature(pckCert, parsedQuote, quoteData)
		if status != STATUS_OK {
			t.Logf("QE Report signature verification returned: %v (may be expected)", status)
		}
	})

	// Test 3: Invalid certification data type (not QE Report)
	t.Run("InvalidCertDataType", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Extract PCK cert first
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, _ := ParseCertChain(certChainBytes)

		// Change cert data type to unsupported type
		parsedQuote.QeCertificationData.CertificationDataType = PCK_ID_PCK_CERT_CHAIN

		status := verifier.verifyQeReportSignature(certChain.PCKCert, parsedQuote, quoteData)
		// Note: Function may return OK if cert type is not QE Report (graceful handling)
		if status == STATUS_OK {
			t.Logf("Function gracefully handled invalid cert data type (returned OK)")
		} else {
			t.Logf("Function returned error for invalid cert data type: %v", status)
		}
	})

	// Test 4: Corrupted QE Report signature
	t.Run("CorruptedQeReportSignature", func(t *testing.T) {
		quoteData, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Extract PCK cert
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, _ := ParseCertChain(certChainBytes)

		// Corrupt the QE Report signature
		qeCertData.QeReportSignature[0] ^= 0xFF
		qeCertData.QeReportSignature[1] ^= 0xFF

		status := verifier.verifyQeReportSignature(certChain.PCKCert, parsedQuote, quoteData)
		if status == STATUS_OK {
			t.Error("Expected failure for corrupted QE Report signature")
		}
	})
}

// ============================================================================
// PartD. Certificate chain and verification testing
// ============================================================================

// TestVerifyPCKCertificateChain tests PCK certificate chain verification
func TestVerifyPCKCertificateChain(t *testing.T) {
	verifier := NewQuoteVerifier("")

	// Test 1: Verify valid PCK certificate chain from v4 quote
	t.Run("ValidPCKCertChainV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")
		collateral := loadTestCollateral(t, parsedQuote, true) // Extract FMSPC from PCK cert

		// Extract cert chain from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Parse CRLs
		pckCrl, err := verifier.parseCrlBytes(collateral.PckCrl)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL: %v", err)
		}
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}
		// Note: crls[0] should be Root CA CRL, crls[1] should be Intermediate CA CRL (PCK CRL)
		crls := []*x509.RevocationList{rootCaCrl, pckCrl}

		// Get root CA cert from PCK CRL issuer chain
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test the PCK cert chain verification (heavy verification)
		status := verifier.sgxAttestationVerifyPCKCertificate(certChain, crls, rootCert, time.Now().Unix())

		t.Logf("PCK Certificate Chain verification result: %v (code: %d)", status, int(status))

		// Should succeed or return specific acceptable status
		// Note: Local collateral may have expired CRLs, so we accept expiration-related statuses
		if status != STATUS_OK &&
			status != STATUS_TCB_OUT_OF_DATE &&
			status != STATUS_TCB_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED &&
			status != STATUS_SGX_CRL_EXPIRED &&
			status != STATUS_SGX_PCK_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED {
			t.Errorf("Expected OK or acceptable TCB status, got %v (code: %d)", status, int(status))
		}
	})

	// Test 2: Verify valid PCK certificate chain from v5 quote
	t.Run("ValidPCKCertChainV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")
		collateral := loadTestCollateral(t, parsedQuote, true) // Extract FMSPC from PCK cert

		// Extract cert chain from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Parse CRLs
		pckCrl, err := verifier.parseCrlBytes(collateral.PckCrl)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL: %v", err)
		}
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}
		// Note: crls[0] should be Root CA CRL, crls[1] should be Intermediate CA CRL (PCK CRL)
		crls := []*x509.RevocationList{rootCaCrl, pckCrl}

		// Get root CA cert from PCK CRL issuer chain
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test the PCK cert chain verification
		status := verifier.sgxAttestationVerifyPCKCertificate(certChain, crls, rootCert, time.Now().Unix())

		t.Logf("PCK Certificate Chain verification result: %v (code: %d)", status, int(status))

		// Note: Local collateral may have expired CRLs, so we accept expiration-related statuses
		if status != STATUS_OK &&
			status != STATUS_TCB_OUT_OF_DATE &&
			status != STATUS_TCB_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED &&
			status != STATUS_SGX_CRL_EXPIRED &&
			status != STATUS_SGX_PCK_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED {
			t.Errorf("Expected OK or acceptable TCB status, got %v (code: %d)", status, int(status))
		}
	})
}

// TestVerifyTcbInfo tests TCB Info signature and issuer chain verification
// Tests the sgxAttestationVerifyTCBInfo() function with real data
func TestVerifyTcbInfo(t *testing.T) {
	// Use real PCCS to get fresh collateral with valid issuer chain
	verifier := NewQuoteVerifier("https://sgx-dcap-server.cn-hangzhou.aliyuncs.com")

	// Test 1: Verify TCB Info for v4 quote
	t.Run("VerifyTcbInfoV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Get FRESH collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral from PCCS: %v", err)
		}

		// Parse TCB Info with signature - use the ORIGINAL collateral.TcbInfo
		// This is critical because the signature is over the exact JSON bytes
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info with signature: %v", err)
		}

		// Parse the inner TCB Info structure (but use original TcbInfo RawMessage for signature)
		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		// Parse TCB Info issuer chain (from FRESH collateral)
		tcbInfoIssuerChain, err := ParseCertChain(collateral.TcbInfoIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info issuer chain: %v", err)
		}

		// Parse Root CA CRL (from FRESH collateral)
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}

		// Get root CA cert from PCK CRL issuer chain (from FRESH collateral)
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test TCB Info verification with FRESH collateral from PCCS
		// Use the ORIGINAL tcbInfoWithSig that contains the exact JSON bytes that were signed
		status := verifier.sgxAttestationVerifyTCBInfo(&tcbInfoWithSig, &tcbInfo, tcbInfoIssuerChain, rootCaCrl, rootCert, time.Now().Unix())

		t.Logf("TCB Info verification result: %v (code: %d)", status, int(status))

		// NOTE: sgxAttestationVerifyTCBInfo only validates TCB Info collateral (signature/issuer/expiration)
		// Expiration errors (e.g., STATUS_SGX_TCB_INFO_EXPIRED) are acceptable here because:
		// 1. This test directly calls the collateral verification function
		// 2. In QVL's full flow (VerifyQuote), expiration sets CollateralExpStatus=1 but is NON-FATAL
		// 3. The final QvResult is determined by sgxAttestationVerifyQuote, not collateral expiration
		// This is why TestVerifyTcbInfo may return EXPIRED while TestVerifyQuoteValid returns OK.
		if status != STATUS_OK &&
			status != STATUS_SGX_TCB_INFO_EXPIRED && // TCB Info from some PCCS might be expired (e.g., FMSPC 90C06F000000)
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_CRL_EXPIRED {
			t.Errorf("Unexpected status with PCCS collateral: got %v (code: %d), expected OK or expiration-related status", status, int(status))
		}
	})

	// Test 2: Verify TCB Info for v5 quote
	t.Run("VerifyTcbInfoV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Get FRESH collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral from PCCS: %v", err)
		}

		// Parse TCB Info with signature
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info with signature: %v", err)
		}

		// Parse the inner TCB Info
		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		// Parse TCB Info issuer chain (from FRESH collateral)
		tcbInfoIssuerChain, err := ParseCertChain(collateral.TcbInfoIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info issuer chain: %v", err)
		}

		// Parse Root CA CRL (from FRESH collateral)
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}

		// Get root CA cert from PCK CRL issuer chain (from FRESH collateral)
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test TCB Info verification with FRESH collateral from PCCS
		status := verifier.sgxAttestationVerifyTCBInfo(&tcbInfoWithSig, &tcbInfo, tcbInfoIssuerChain, rootCaCrl, rootCert, time.Now().Unix())

		t.Logf("TCB Info verification result: %v (code: %d)", status, int(status))

		// NOTE: Same as VerifyTcbInfoV4 - expiration errors are acceptable and NON-FATAL in QVL design.
		// FMSPC 90C06F000000 from some PCCS may have outdated TCB Info.
		// But VerifyQuote can still return QvResult=OK because it continues after setting CollateralExpStatus=1.
		if status != STATUS_OK &&
			status != STATUS_SGX_TCB_INFO_EXPIRED &&
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_CRL_EXPIRED {
			t.Errorf("Unexpected status with PCCS collateral: got %v (code: %d), expected OK or expiration-related status", status, int(status))
		}
	})
}

// TestVerifyQeIdentity tests QE Identity signature and issuer chain verification
// Tests the sgxAttestationVerifyEnclaveIdentity() function with real data
func TestVerifyQeIdentity(t *testing.T) {
	// Use real PCCS to get fresh collateral with valid issuer chain
	verifier := NewQuoteVerifier("https://sgx-dcap-server.cn-hangzhou.aliyuncs.com")

	// Test 1: Verify QE Identity for v4 quote
	t.Run("VerifyQeIdentityV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Get FRESH collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral from PCCS: %v", err)
		}

		// Parse QE Identity with signature - use the ORIGINAL collateral.QeIdentity
		var qeIdentityWithSig QeIdentityWithSignature
		err = json.Unmarshal(collateral.QeIdentity, &qeIdentityWithSig)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity with signature: %v", err)
		}

		// Parse the inner QE Identity structure
		var qeIdentity QeIdentity
		err = json.Unmarshal(qeIdentityWithSig.EnclaveIdentity, &qeIdentity)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity: %v", err)
		}

		// Parse QE Identity issuer chain (from FRESH collateral)
		qeIdentityIssuerChain, err := ParseCertChain(collateral.QeIdentityIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity issuer chain: %v", err)
		}

		// Parse Root CA CRL (from FRESH collateral)
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}

		// Get root CA cert from PCK CRL issuer chain (from FRESH collateral)
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test QE Identity verification with FRESH collateral from PCCS
		status := verifier.sgxAttestationVerifyEnclaveIdentity(&qeIdentityWithSig, &qeIdentity, qeIdentityIssuerChain, rootCaCrl, rootCert, time.Now().Unix())

		t.Logf("QE Identity verification result: %v (code: %d)", status, int(status))

		// With PCCS collateral, signature verification should always succeed (STATUS_OK)
		// or return expiration issues (signing chain/CRL/identity expired)
		if status != STATUS_OK &&
			status != STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED &&
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_CRL_EXPIRED {
			t.Errorf("Unexpected status with PCCS collateral: got %v (code: %d), expected OK or expiration-related status", status, int(status))
		}
	})

	// Test 2: Verify QE Identity for v5 quote
	t.Run("VerifyQeIdentityV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Get FRESH collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral from PCCS: %v", err)
		}

		// Parse QE Identity with signature
		var qeIdentityWithSig QeIdentityWithSignature
		err = json.Unmarshal(collateral.QeIdentity, &qeIdentityWithSig)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity with signature: %v", err)
		}

		// Parse the inner QE Identity
		var qeIdentity QeIdentity
		err = json.Unmarshal(qeIdentityWithSig.EnclaveIdentity, &qeIdentity)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity: %v", err)
		}

		// Parse QE Identity issuer chain (from FRESH collateral)
		qeIdentityIssuerChain, err := ParseCertChain(collateral.QeIdentityIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse QE Identity issuer chain: %v", err)
		}

		// Parse Root CA CRL (from FRESH collateral)
		rootCaCrl, err := verifier.parseCrlBytes(collateral.RootCaCrl)
		if err != nil {
			t.Fatalf("Failed to parse Root CA CRL: %v", err)
		}

		// Get root CA cert from PCK CRL issuer chain (from FRESH collateral)
		pckCrlIssuerChain, err := ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil {
			t.Fatalf("Failed to parse PCK CRL issuer chain: %v", err)
		}
		if pckCrlIssuerChain.RootCA == nil {
			t.Fatalf("No root CA cert in PCK CRL issuer chain")
		}
		rootCert := pckCrlIssuerChain.RootCA

		// Test QE Identity verification with FRESH collateral from PCCS
		status := verifier.sgxAttestationVerifyEnclaveIdentity(&qeIdentityWithSig, &qeIdentity, qeIdentityIssuerChain, rootCaCrl, rootCert, time.Now().Unix())

		t.Logf("QE Identity verification result: %v (code: %d)", status, int(status))

		// With PCCS collateral, signature verification should always succeed (STATUS_OK)
		// or return expiration issues
		if status != STATUS_OK &&
			status != STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED &&
			status != STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED &&
			status != STATUS_SGX_CRL_EXPIRED {
			t.Errorf("Unexpected status with PCCS collateral: got %v (code: %d), expected OK or expiration-related status", status, int(status))
		}
	})
}

// ============================================================================
// PartE. TCB and Identity verification testing
// ============================================================================

// TestCheckTcbLevel tests TCB level matching and status determination using real quotes
func TestCheckTcbLevel(t *testing.T) {
	verifier := NewQuoteVerifier("https://sgx-dcap-server.cn-hangzhou.aliyuncs.com")

	// Test with v4 quote
	t.Run("TcbLevelCheckV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Get collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral: %v", err)
		}

		// Parse TCB Info
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse inner TCB Info: %v", err)
		}

		// Extract PCK cert from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Get TDX Module Identity - use first one from TCB Info
		var tdxModuleIdentity *TdxModuleIdentity
		if len(tcbInfo.TdxModuleIdentities) > 0 {
			tdxModuleIdentity = &tcbInfo.TdxModuleIdentities[0]
		}

		// Test checkTcbLevel with real data
		status := verifier.checkTcbLevel(&tcbInfo, certChain.PCKCert, parsedQuote, STATUS_OK, tdxModuleIdentity)

		t.Logf("TCB Level check result for v4: %v (code: %d)", status, int(status))

		// Should return OK or acceptable TCB status (out of date, config needed, etc.)
		if status != STATUS_OK &&
			status != STATUS_TCB_OUT_OF_DATE &&
			status != STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_SW_HARDENING_NEEDED &&
			status != STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED &&
			status != STATUS_SGX_TCB_INFO_EXPIRED {
			t.Errorf("Unexpected TCB Level status: got %v (code: %d)", status, int(status))
		}
	})

	// Test with v5 quote
	t.Run("TcbLevelCheckV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Get collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral: %v", err)
		}

		// Parse TCB Info
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse inner TCB Info: %v", err)
		}

		// Extract PCK cert from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Get TDX Module Identity
		var tdxModuleIdentity *TdxModuleIdentity
		if len(tcbInfo.TdxModuleIdentities) > 0 {
			tdxModuleIdentity = &tcbInfo.TdxModuleIdentities[0]
		}

		// Test checkTcbLevel with real data
		status := verifier.checkTcbLevel(&tcbInfo, certChain.PCKCert, parsedQuote, STATUS_OK, tdxModuleIdentity)

		t.Logf("TCB Level check result for v5: %v (code: %d)", status, int(status))

		// Should return OK or acceptable TCB status
		if status != STATUS_OK &&
			status != STATUS_TCB_OUT_OF_DATE &&
			status != STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_CONFIGURATION_NEEDED &&
			status != STATUS_TCB_SW_HARDENING_NEEDED &&
			status != STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED &&
			status != STATUS_SGX_TCB_INFO_EXPIRED {
			t.Errorf("Unexpected TCB Level status: got %v (code: %d)", status, int(status))
		}
	})
}

// TestCheckForRelaunch tests TD relaunch advisory logic for TDX v1.5 (quote v5)
func TestCheckForRelaunch(t *testing.T) {
	verifier := NewQuoteVerifier("https://sgx-dcap-server.cn-hangzhou.aliyuncs.com")

	// Test with v5 quote (TDX v1.5 supports relaunch advisory)
	t.Run("CheckForRelaunchV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Get collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral: %v", err)
		}

		// Parse TCB Info
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse inner TCB Info: %v", err)
		}

		// Extract teeTcbSvn2 from v5 quote body
		// Note: v5 quote Report field is interface{}, needs type assertion to TdReport15
		// For simplicity in this test, we use all zeros which triggers no-relaunch path
		var teeTcbSvn2 [16]byte // All zeros for simplified test

		// Test checkForRelaunch with real data
		sgxTcbStatus := STATUS_OK
		tdxTcbStatus := STATUS_OK
		tdxModuleTcbStatus := STATUS_OK
		qeTcbStatus := STATUS_OK

		finalStatus := verifier.checkForRelaunch(teeTcbSvn2, &tcbInfo, sgxTcbStatus, tdxTcbStatus, tdxModuleTcbStatus, qeTcbStatus)

		t.Logf("Check for relaunch result: %v (code: %d)", finalStatus, int(finalStatus))

		// The function should return a valid status
		if finalStatus == STATUS_UNSUPPORTED_QUOTE_FORMAT {
			t.Error("Unexpected STATUS_UNSUPPORTED_QUOTE_FORMAT for valid v5 quote")
		}
	})

	// Test with v4 quote (TDX v1.0 does not support relaunch advisory - teeTcbSvn2 is all zeros)
	t.Run("CheckForRelaunchV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Get collateral from PCCS
		collateral, err := verifier.collateralProvider.GetCollateral(parsedQuote)
		if err != nil {
			t.Fatalf("Failed to get collateral: %v", err)
		}

		// Parse TCB Info
		var tcbInfoWithSig TcbInfoWithSignature
		err = json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSig)
		if err != nil {
			t.Fatalf("Failed to parse TCB Info: %v", err)
		}

		var tcbInfo TcbInfo
		err = json.Unmarshal(tcbInfoWithSig.TcbInfo, &tcbInfo)
		if err != nil {
			t.Fatalf("Failed to parse inner TCB Info: %v", err)
		}

		// V4 quote - teeTcbSvn2 is not present, use all zeros
		var teeTcbSvn2 [16]byte // All zeros

		// Test checkForRelaunch with v4 quote
		sgxTcbStatus := STATUS_OK
		tdxTcbStatus := STATUS_OK
		tdxModuleTcbStatus := STATUS_OK
		qeTcbStatus := STATUS_OK

		finalStatus := verifier.checkForRelaunch(teeTcbSvn2, &tcbInfo, sgxTcbStatus, tdxTcbStatus, tdxModuleTcbStatus, qeTcbStatus)

		t.Logf("V4 - Check for relaunch result: %v (code: %d)", finalStatus, int(finalStatus))

		// With all-zero teeTcbSvn2 (v4/v1.0), should return the input tdxTcbStatus (STATUS_OK)
		if finalStatus != STATUS_OK {
			t.Logf("Note: V4 quote returned %v instead of OK - this is acceptable", finalStatus)
		}
	})
}

// ============================================================================
// PartF. Auxiliary function testing
// ============================================================================

// TestExtractCpuSvn tests CPU SVN extraction from real PCK certificates
func TestExtractCpuSvn(t *testing.T) {
	// Test with v4 quote
	t.Run("ExtractCpuSvnV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Extract cert chain from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Extract CPU SVN from PCK cert
		cpuSvn, err := ExtractCpuSvnFromSgxExtensions(certChain.PCKCert)
		if err != nil {
			t.Fatalf("Failed to extract CPU SVN: %v", err)
		}

		// Validate CPU SVN
		if len(cpuSvn) != 16 {
			t.Errorf("Expected CPU SVN length 16, got %d", len(cpuSvn))
		}

		t.Logf("Successfully extracted CPU SVN from v4 quote: %x", cpuSvn)
	})

	// Test with v5 quote
	t.Run("ExtractCpuSvnV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Extract cert chain from quote
		qeCertData := parsedQuote.QeCertificationData.CertificationData.(*QeReportCertificationData)
		certChainBytes := qeCertData.QeCertificationData.CertificationData.([]byte)
		certChain, err := ParseCertChain(certChainBytes)
		if err != nil {
			t.Fatalf("Failed to parse cert chain: %v", err)
		}

		// Extract CPU SVN from PCK cert
		cpuSvn, err := ExtractCpuSvnFromSgxExtensions(certChain.PCKCert)
		if err != nil {
			t.Fatalf("Failed to extract CPU SVN: %v", err)
		}

		// Validate CPU SVN
		if len(cpuSvn) != 16 {
			t.Errorf("Expected CPU SVN length 16, got %d", len(cpuSvn))
		}

		t.Logf("Successfully extracted CPU SVN from v5 quote: %x", cpuSvn)
	})
}

// TestCompareRootPublicKey tests root CA public key comparison with Intel's hardcoded key
func TestCompareRootPublicKey(t *testing.T) {
	// Test with v4 quote
	t.Run("CompareRootPubKeyV4", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_4.dat")

		// Extract certificate chain from quote
		certChain, extractRet := extractChainFromQuote(parsedQuote)
		if extractRet != SGX_QL_SUCCESS || certChain == nil {
			t.Fatalf("Failed to extract certificate chain from quote: %v", extractRet)
		}

		// Get the root CA certificate
		if certChain.RootCA == nil {
			t.Fatal("Root CA certificate is nil")
		}

		// Extract public key from root CA certificate
		ecdsaPubKey, ok := certChain.RootCA.PublicKey.(*ecdsa.PublicKey)
		if !ok {
			t.Fatalf("Expected ECDSA public key, got %T", certChain.RootCA.PublicKey)
		}

		// Serialize the public key in uncompressed format
		pubKeyBytes := append([]byte{0x04}, append(ecdsaPubKey.X.Bytes(), ecdsaPubKey.Y.Bytes()...)...)

		// Compare with hardcoded Intel root public key
		if !bytes.Equal(pubKeyBytes, INTEL_ROOT_PUB_KEY) {
			t.Errorf("Root CA public key does not match Intel root public key")
			t.Errorf("Extracted: %x", pubKeyBytes)
			t.Errorf("Expected:  %x", INTEL_ROOT_PUB_KEY)
		} else {
			t.Logf("Root CA public key matches Intel root public key")
		}
	})

	// Test with v5 quote
	t.Run("CompareRootPubKeyV5", func(t *testing.T) {
		_, parsedQuote := loadTestQuote(t, "tdx_quote_5.dat")

		// Extract certificate chain from quote
		certChain, extractRet := extractChainFromQuote(parsedQuote)
		if extractRet != SGX_QL_SUCCESS || certChain == nil {
			t.Fatalf("Failed to extract certificate chain from quote: %v", extractRet)
		}

		// Get the root CA certificate
		if certChain.RootCA == nil {
			t.Fatal("Root CA certificate is nil")
		}

		// Extract public key from root CA certificate
		ecdsaPubKey, ok := certChain.RootCA.PublicKey.(*ecdsa.PublicKey)
		if !ok {
			t.Fatalf("Expected ECDSA public key, got %T", certChain.RootCA.PublicKey)
		}

		// Serialize the public key in uncompressed format
		pubKeyBytes := append([]byte{0x04}, append(ecdsaPubKey.X.Bytes(), ecdsaPubKey.Y.Bytes()...)...)

		// Compare with hardcoded Intel root public key
		if !bytes.Equal(pubKeyBytes, INTEL_ROOT_PUB_KEY) {
			t.Errorf("Root CA public key does not match Intel root public key")
		} else {
			t.Logf("Root CA public key matches Intel root public key")
		}
	})
}

// TestStatusToQvResult tests the Status to QvResult mapping function
func TestStatusToQvResult(t *testing.T) {
	testCases := []struct {
		name     string
		status   Status
		expected QvResultType
	}{
		// OK status
		{"STATUS_OK", STATUS_OK, SGX_QL_QV_RESULT_OK},

		// Invalid signature bucket
		{"STATUS_INVALID_QUOTE_SIGNATURE", STATUS_INVALID_QUOTE_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},
		{"STATUS_INVALID_QE_REPORT_SIGNATURE", STATUS_INVALID_QE_REPORT_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},
		{"STATUS_SGX_ENCLAVE_IDENTITY_INVALID_SIGNATURE", STATUS_SGX_ENCLAVE_IDENTITY_INVALID_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},
		{"STATUS_SGX_QE_IDENTITY_INVALID_SIGNATURE", STATUS_SGX_QE_IDENTITY_INVALID_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},
		{"STATUS_SGX_CRL_INVALID_SIGNATURE", STATUS_SGX_CRL_INVALID_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},
		{"STATUS_TCB_INFO_INVALID_SIGNATURE", STATUS_TCB_INFO_INVALID_SIGNATURE, SGX_QL_QV_RESULT_INVALID_SIGNATURE},

		// Revoked bucket
		{"STATUS_PCK_REVOKED", STATUS_PCK_REVOKED, SGX_QL_QV_RESULT_REVOKED},
		{"STATUS_TCB_REVOKED", STATUS_TCB_REVOKED, SGX_QL_QV_RESULT_REVOKED},
		{"STATUS_SGX_TCB_SIGNING_CERT_REVOKED", STATUS_SGX_TCB_SIGNING_CERT_REVOKED, SGX_QL_QV_RESULT_REVOKED},
		{"STATUS_SGX_PCK_REVOKED", STATUS_SGX_PCK_REVOKED, SGX_QL_QV_RESULT_REVOKED},
		{"STATUS_SGX_INTERMEDIATE_CA_REVOKED", STATUS_SGX_INTERMEDIATE_CA_REVOKED, SGX_QL_QV_RESULT_REVOKED},

		// Configuration needed
		{"STATUS_TCB_CONFIGURATION_NEEDED", STATUS_TCB_CONFIGURATION_NEEDED, SGX_QL_QV_RESULT_CONFIG_NEEDED},

		// Out of date + config needed
		{"STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED", STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED, SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED},

		// Out of date bucket
		{"STATUS_TCB_OUT_OF_DATE", STATUS_TCB_OUT_OF_DATE, SGX_QL_QV_RESULT_OUT_OF_DATE},
		{"STATUS_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE", STATUS_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE, SGX_QL_QV_RESULT_OUT_OF_DATE},
		{"STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE", STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE, SGX_QL_QV_RESULT_OUT_OF_DATE},
		{"STATUS_QE_IDENTITY_OUT_OF_DATE", STATUS_QE_IDENTITY_OUT_OF_DATE, SGX_QL_QV_RESULT_OUT_OF_DATE},

		// SW hardening needed
		{"STATUS_TCB_SW_HARDENING_NEEDED", STATUS_TCB_SW_HARDENING_NEEDED, SGX_QL_QV_RESULT_SW_HARDENING_NEEDED},

		// Config + SW hardening needed
		{"STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED", STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED, SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED},

		// TD relaunch advisories
		{"STATUS_TCB_TD_RELAUNCH_ADVISED", STATUS_TCB_TD_RELAUNCH_ADVISED, TEE_QV_RESULT_TD_RELAUNCH_ADVISED},
		{"STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED", STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED, TEE_QV_RESULT_TD_RELAUNCH_ADVISED_CONFIG_NEEDED},

		// Default/Unspecified
		{"STATUS_UNSUPPORTED_QUOTE_FORMAT", STATUS_UNSUPPORTED_QUOTE_FORMAT, SGX_QL_QV_RESULT_UNSPECIFIED},
		{"STATUS_INVALID_PCK_CERT", STATUS_INVALID_PCK_CERT, SGX_QL_QV_RESULT_UNSPECIFIED},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			result := statusToQvResult(tc.status)
			if result != tc.expected {
				t.Errorf("statusToQvResult(%v) = %v, expected %v", tc.status, result, tc.expected)
			} else {
				t.Logf("statusToQvResult(%v) = %v as expected", tc.status, result)
			}
		})
	}
}
