package auth import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "encoding/base64" "errors" "fmt" "sync" "testing" "time" commonCrypto "security-connector/common/crypto" "security-connector/common/proto" "security-connector/common/types" "security-connector/connector/tpm" "security-connector/server/attest" serverCrypto "security-connector/server/crypto" ) // testDevice drives the connector half of the enrollment protocol using the // real software TPM, so these tests exercise the actual wire contract rather // than a convenient fiction. type testDevice struct { tpm tpm.TPM priv *ecdsa.PrivateKey pubB64 string } func newTestDevice(t *testing.T) *testDevice { t.Helper() sw := tpm.NewSoftwareFPGATPM("/dev/null-test") if err := sw.Initialize(); err != nil { t.Fatalf("tpm init: %v", err) } if _, err := sw.GenerateKey("device_key", tpm.KeyTypeSigning); err != nil { t.Fatalf("generate device key: %v", err) } // Minimal boot measurement chain covering the policy's required PCRs. for pcr, value := range map[int]string{ attest.PCRFirmware: "connector-binary", attest.PCRPlatform: "linux/amd64", attest.PCRTPMProvider: "software", attest.PCRTrustAnchor: "root-ca", } { h := sha256.Sum256([]byte(value)) if err := sw.PCR_Extend(pcr, h[:]); err != nil { t.Fatalf("pcr extend: %v", err) } } key, err := sw.GetKeyByID("device_key") if err != nil { t.Fatalf("get device key: %v", err) } pubBytes, err := sw.GetPublicKey("device_key") if err != nil { t.Fatalf("get public key: %v", err) } return &testDevice{ tpm: sw, priv: key.PrivateKey, pubB64: base64.StdEncoding.EncodeToString(pubBytes), } } // attestedRequest builds a registration request bound to a nonce the server // just issued. func (d *testDevice) attestedRequest(t *testing.T, da *DeviceAuthenticator, deviceID string) *proto.RegisterRequest { t.Helper() ch, err := da.IssueEnrollmentNonce(deviceID) if err != nil { t.Fatalf("issue enrollment nonce: %v", err) } nonce, err := base64.StdEncoding.DecodeString(ch.Nonce) if err != nil { t.Fatalf("decode nonce: %v", err) } q, err := d.tpm.Quote("device_key", nonce, ch.PCRMask) if err != nil { t.Fatalf("tpm quote: %v", err) } return &proto.RegisterRequest{ APIRequest: proto.APIRequest{Type: proto.TypeRegisterRequest, DeviceID: deviceID}, DeviceID: deviceID, TPMPublicKey: d.pubB64, TPMQuote: base64.StdEncoding.EncodeToString(q.Quote), QuoteSignature: base64.StdEncoding.EncodeToString(q.Signature), QuotePCRMask: ch.PCRMask, Nonce: ch.Nonce, FirmwareHash: "mock_firmware_hash", } } // registerAttested is the happy path used by tests that care about what // happens *after* enrollment. func registerAttested(t *testing.T, da *DeviceAuthenticator, deviceID string) (*testDevice, *proto.RegisterResponse) { t.Helper() dev := newTestDevice(t) resp, err := da.RegisterDevice(dev.attestedRequest(t, da, deviceID)) if err != nil { t.Fatalf("attested registration of %s failed: %v", deviceID, err) } return dev, resp } func newAuthenticator(t *testing.T) *DeviceAuthenticator { t.Helper() km, err := serverCrypto.NewServerKeyManager(commonCrypto.CipherSuiteInternational) if err != nil { t.Fatalf("key manager: %v", err) } return NewDeviceAuthenticator(km) } func TestNewDeviceAuthenticator(t *testing.T) { da := newAuthenticator(t) if da.keyManager == nil { t.Error("KeyManager should not be nil") } if da.challenges == nil { t.Error("Challenges map should be initialized") } if da.devices == nil { t.Error("Devices map should be initialized") } if da.challengeExpiry != 5*time.Minute { t.Errorf("ChallengeExpiry should be 5 minutes, got %v", da.challengeExpiry) } // Fail-closed default: an authenticator built without explicit // configuration must still enforce attestation. if da.attestor == nil { t.Fatal("Attestor should never be nil") } if got := da.attestor.Mode(); got != attest.ModeStrict { t.Errorf("default attestation mode should be strict, got %s", got) } } func TestRegisterDevice(t *testing.T) { da := newAuthenticator(t) _, resp := registerAttested(t, da, "DEV_test_001") if resp.EncryptedKEK == "" { t.Error("EncryptedKEK should not be empty") } if resp.KEKVersion == 0 { t.Error("KEKVersion should not be zero") } if resp.ServerPublicKey == "" { t.Error("ServerPublicKey should not be empty") } if resp.ValidUntil == 0 { t.Error("ValidUntil should be set") } if resp.AttestationStatus != "tofu-recorded" { t.Errorf("first enrollment should record a golden value, got %q", resp.AttestationStatus) } if resp.PCRDigest == "" { t.Error("PCRDigest should be reported back to the device") } device, err := da.GetDevice("DEV_test_001") if err != nil { t.Fatalf("GetDevice failed: %v", err) } if device.Status != types.StatusActive { t.Errorf("Device status should be StatusActive, got %v", device.Status) } if device.FirmwareHash != "mock_firmware_hash" { t.Error("FirmwareHash mismatch") } if len(device.PCRValues) == 0 { t.Error("quoted PCR values should be recorded on the device") } } // The regression that motivated the attest package: registration used to // accept a request whose quote fields were pure decoration. func TestRegisterDeviceRejectsUnattestedRequest(t *testing.T) { da := newAuthenticator(t) privKey, _ := commonCrypto.GenerateECDSAKey() pubKeyBytes, _ := commonCrypto.EncodePublicKey(&privKey.PublicKey) req := &proto.RegisterRequest{ APIRequest: proto.APIRequest{Type: proto.TypeRegisterRequest, DeviceID: "DEV_rogue"}, DeviceID: "DEV_rogue", TPMPublicKey: base64.StdEncoding.EncodeToString(pubKeyBytes), FirmwareHash: "whatever", QuotePCRMask: 0xFFFFFFFF, Nonce: base64.StdEncoding.EncodeToString(make([]byte, 32)), TPMQuote: base64.StdEncoding.EncodeToString([]byte("not a quote")), } if _, err := da.RegisterDevice(req); err == nil { t.Fatal("a request with no valid attestation must be rejected") } else if !errors.Is(err, attest.ErrNonceUnknown) { t.Fatalf("expected the nonce to be rejected as un-issued, got: %v", err) } if _, err := da.GetDevice("DEV_rogue"); err == nil { t.Fatal("a rejected device must not be recorded") } } func TestRegisterDeviceRejectsReplayedQuote(t *testing.T) { da := newAuthenticator(t) dev := newTestDevice(t) req := dev.attestedRequest(t, da, "DEV_replay_001") if _, err := da.RegisterDevice(req); err != nil { t.Fatalf("first enrollment failed: %v", err) } if _, err := da.RegisterDevice(req); !errors.Is(err, attest.ErrNonceReplay) { t.Fatalf("expected a replay rejection, got %v", err) } } func TestRegisterDeviceInvalidKey(t *testing.T) { da := newAuthenticator(t) req := &proto.RegisterRequest{ APIRequest: proto.APIRequest{Type: proto.TypeRegisterRequest, DeviceID: "DEV_test_002"}, DeviceID: "DEV_test_002", TPMPublicKey: "not_valid_base64!@#$", FirmwareHash: "mock_firmware_hash", } if _, err := da.RegisterDevice(req); err == nil { t.Error("RegisterDevice should fail with invalid key") } } func TestCreateChallenge(t *testing.T) { da := newAuthenticator(t) registerAttested(t, da, "DEV_test_003") challengeReq, err := da.CreateChallenge("DEV_test_003") if err != nil { t.Fatalf("CreateChallenge failed: %v", err) } if challengeReq.Nonce == "" { t.Error("Nonce should not be empty") } if challengeReq.Challenge == "" { t.Error("Challenge should not be empty") } if challengeReq.ExpireAt == 0 { t.Error("ExpireAt should be set") } if challengeReq.Type != proto.TypeChallengeRequest { t.Errorf("Type should be TypeChallengeRequest, got %s", challengeReq.Type) } } func TestCreateChallengeDeviceNotFound(t *testing.T) { da := newAuthenticator(t) if _, err := da.CreateChallenge("nonexistent_device"); err == nil { t.Error("CreateChallenge should fail for nonexistent device") } } func TestVerifyChallengeResponse(t *testing.T) { da := newAuthenticator(t) dev, _ := registerAttested(t, da, "DEV_verify_001") challengeReq, err := da.CreateChallenge("DEV_verify_001") if err != nil { t.Fatalf("CreateChallenge failed: %v", err) } nonce, _ := base64.StdEncoding.DecodeString(challengeReq.Nonce) challenge, _ := base64.StdEncoding.DecodeString(challengeReq.Challenge) signedData := append(challenge, nonce...) signature, err := commonCrypto.Sign(dev.priv, signedData) if err != nil { t.Fatalf("Sign failed: %v", err) } resp := &proto.ChallengeResponse{ APIRequest: proto.APIRequest{Type: proto.TypeChallengeResponse, DeviceID: "DEV_verify_001"}, Nonce: challengeReq.Nonce, Signature: base64.StdEncoding.EncodeToString(signature), } authResp, err := da.VerifyChallengeResponse("DEV_verify_001", resp) if err != nil { t.Fatalf("VerifyChallengeResponse failed: %v", err) } if authResp.SessionKey == "" { t.Error("SessionKey should not be empty") } if authResp.ValidUntil == 0 { t.Error("ValidUntil should be set") } device, _ := da.GetDevice("DEV_verify_001") if device.Status != types.StatusActive { t.Errorf("Device status should be StatusActive, got %v", device.Status) } } func TestVerifyChallengeResponseExpired(t *testing.T) { da := newAuthenticator(t) registerAttested(t, da, "DEV_expired_001") da.challengeExpiry = -1 * time.Second // Already expired challengeReq, err := da.CreateChallenge("DEV_expired_001") if err != nil { t.Fatalf("CreateChallenge failed: %v", err) } resp := &proto.ChallengeResponse{ APIRequest: proto.APIRequest{Type: proto.TypeChallengeResponse, DeviceID: "DEV_expired_001"}, Nonce: challengeReq.Nonce, Signature: "signature", } if _, err := da.VerifyChallengeResponse("DEV_expired_001", resp); err == nil { t.Error("VerifyChallengeResponse should fail for expired challenge") } } func TestVerifyChallengeResponseNonceMismatch(t *testing.T) { da := newAuthenticator(t) dev, _ := registerAttested(t, da, "DEV_nonce_001") if _, err := da.CreateChallenge("DEV_nonce_001"); err != nil { t.Fatalf("CreateChallenge failed: %v", err) } wrongNonce := make([]byte, 32) if _, err := rand.Read(wrongNonce); err != nil { t.Fatal(err) } challenge := make([]byte, 32) if _, err := rand.Read(challenge); err != nil { t.Fatal(err) } signedData := append(challenge, wrongNonce...) signature, _ := commonCrypto.Sign(dev.priv, signedData) resp := &proto.ChallengeResponse{ APIRequest: proto.APIRequest{Type: proto.TypeChallengeResponse, DeviceID: "DEV_nonce_001"}, Nonce: base64.StdEncoding.EncodeToString(wrongNonce), Signature: base64.StdEncoding.EncodeToString(signature), } if _, err := da.VerifyChallengeResponse("DEV_nonce_001", resp); err == nil { t.Error("VerifyChallengeResponse should fail for nonce mismatch") } } func TestVerifyChallengeResponseNoChallenge(t *testing.T) { da := newAuthenticator(t) resp := &proto.ChallengeResponse{ APIRequest: proto.APIRequest{Type: proto.TypeChallengeResponse, DeviceID: "DEV_no_challenge"}, Nonce: "some_nonce", Signature: "signature", } if _, err := da.VerifyChallengeResponse("DEV_no_challenge", resp); err == nil { t.Error("VerifyChallengeResponse should fail when no challenge exists") } } func TestGetDevice(t *testing.T) { da := newAuthenticator(t) registerAttested(t, da, "DEV_get_001") device, err := da.GetDevice("DEV_get_001") if err != nil { t.Fatalf("GetDevice failed: %v", err) } if device.DeviceID != "DEV_get_001" { t.Errorf("DeviceID mismatch: got %s, want DEV_get_001", device.DeviceID) } } func TestGetDeviceNotFound(t *testing.T) { da := newAuthenticator(t) if _, err := da.GetDevice("nonexistent"); err == nil { t.Error("GetDevice should fail for nonexistent device") } } func TestGetDeviceStatus(t *testing.T) { da := newAuthenticator(t) registerAttested(t, da, "DEV_status_001") status, err := da.GetDeviceStatus("DEV_status_001") if err != nil { t.Fatalf("GetDeviceStatus failed: %v", err) } if status.DeviceID != "DEV_status_001" { t.Errorf("DeviceID mismatch") } if status.Status != "active" { t.Errorf("Status should be active after successful attestation, got %s", status.Status) } } func TestListDevices(t *testing.T) { da := newAuthenticator(t) if devices := da.ListDevices(); len(devices) != 0 { t.Errorf("Should have no devices initially, got %d", len(devices)) } for i := 0; i < 3; i++ { registerAttested(t, da, fmt.Sprintf("DEV_list_%03d", i)) } if devices := da.ListDevices(); len(devices) != 3 { t.Errorf("Should have 3 devices, got %d", len(devices)) } } func TestConcurrentAccess(t *testing.T) { da := newAuthenticator(t) // Pre-build the devices: TPM key generation is slow enough that doing it // inside the goroutines would measure the CSPRNG, not the lock discipline. const n = 10 devices := make([]*testDevice, n) for i := range devices { devices[i] = newTestDevice(t) } var wg sync.WaitGroup errCh := make(chan error, n) for i := 0; i < n; i++ { wg.Add(1) go func(id int) { defer wg.Done() deviceID := fmt.Sprintf("DEV_concurrent_%02d", id) ch, err := da.IssueEnrollmentNonce(deviceID) if err != nil { errCh <- err return } nonce, _ := base64.StdEncoding.DecodeString(ch.Nonce) q, err := devices[id].tpm.Quote("device_key", nonce, ch.PCRMask) if err != nil { errCh <- err return } _, err = da.RegisterDevice(&proto.RegisterRequest{ APIRequest: proto.APIRequest{Type: proto.TypeRegisterRequest, DeviceID: deviceID}, DeviceID: deviceID, TPMPublicKey: devices[id].pubB64, TPMQuote: base64.StdEncoding.EncodeToString(q.Quote), QuoteSignature: base64.StdEncoding.EncodeToString(q.Signature), QuotePCRMask: ch.PCRMask, Nonce: ch.Nonce, FirmwareHash: "firmware", }) if err != nil { errCh <- err return } if _, err := da.GetDevice(deviceID); err != nil { errCh <- err } }(i) } wg.Wait() close(errCh) for err := range errCh { t.Errorf("concurrent enrollment error: %v", err) } if got := len(da.ListDevices()); got != n { t.Errorf("expected %d devices, got %d", n, got) } } // TC-Auth-005: re-registration of an already known device. // Each attempt needs its own nonce; the measurement must match the golden value // recorded the first time round. func TestDuplicateRegistration(t *testing.T) { da := newAuthenticator(t) dev := newTestDevice(t) resp1, err := da.RegisterDevice(dev.attestedRequest(t, da, "DEV_dup_001")) if err != nil { t.Fatalf("First registration failed: %v", err) } if resp1.AttestationStatus != "tofu-recorded" { t.Errorf("first registration should record a golden value, got %q", resp1.AttestationStatus) } resp2, err := da.RegisterDevice(dev.attestedRequest(t, da, "DEV_dup_001")) if err != nil { t.Fatalf("Second registration failed: %v", err) } if resp2.AttestationStatus != "verified" { t.Errorf("second registration should match the golden value, got %q", resp2.AttestationStatus) } if resp2.KEKVersion != resp1.KEKVersion { t.Errorf("KEKVersion should remain %d, got %d", resp1.KEKVersion, resp2.KEKVersion) } if resp2.PCRDigest != resp1.PCRDigest { t.Error("an unchanged device must report an unchanged measurement") } device, err := da.GetDevice("DEV_dup_001") if err != nil { t.Fatalf("GetDevice failed: %v", err) } if device.Status != types.StatusActive { t.Errorf("Device status should be StatusActive, got %v", device.Status) } if devices := da.ListDevices(); len(devices) != 1 { t.Errorf("Should have exactly 1 device after duplicate registration, got %d", len(devices)) } } // A device whose boot state drifted after enrollment must not be re-admitted. func TestReRegistrationWithChangedMeasurementIsRejected(t *testing.T) { da := newAuthenticator(t) dev := newTestDevice(t) if _, err := da.RegisterDevice(dev.attestedRequest(t, da, "DEV_drift_001")); err != nil { t.Fatalf("baseline registration failed: %v", err) } h := sha256.Sum256([]byte("unauthorised-module")) if err := dev.tpm.PCR_Extend(attest.PCRFirmware, h[:]); err != nil { t.Fatal(err) } _, err := da.RegisterDevice(dev.attestedRequest(t, da, "DEV_drift_001")) if !errors.Is(err, attest.ErrMeasurementMismatch) { t.Fatalf("expected ErrMeasurementMismatch, got %v", err) } }