diff --git a/internal/identity/BUILD.bazel b/internal/identity/BUILD.bazel index f9625fc..29b25c5 100644 --- a/internal/identity/BUILD.bazel +++ b/internal/identity/BUILD.bazel @@ -12,3 +12,11 @@ go_library( "@org_golang_google_protobuf//reflect/protoreflect", ], ) + +load("@rules_go//go:def.bzl", "go_test") + +go_test( + name = "identity_test", + srcs = ["identity_test.go"], + embed = [":identity"], +) diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go index 21dee9a..ac751fa 100644 --- a/internal/identity/identity_test.go +++ b/internal/identity/identity_test.go @@ -27,3 +27,62 @@ func TestGenerate(t *testing.T) { t.Error("Generate() returned identity with nil private key") } } + +func TestMarshalUnmarshalCertificate(t *testing.T) { + shortName := "test-agent-cert" + ident, err := Generate(shortName) + if err != nil { + t.Fatalf("Generate() failed: %v", err) + } + + pemData := MarshalCertificate(ident.Certificate) + if len(pemData) == 0 { + t.Fatal("MarshalCertificate() returned empty byte slice") + } + + cert, err := UnmarshalCertificate(pemData) + if err != nil { + t.Fatalf("UnmarshalCertificate() failed: %v", err) + } + + if cert == nil { + t.Fatal("UnmarshalCertificate() returned nil certificate") + } + + if cert.Subject.CommonName != shortName { + t.Errorf("UnmarshalCertificate() returned certificate with CommonName %q, want %q", cert.Subject.CommonName, shortName) + } +} + +func TestUnmarshalCertificate_Errors(t *testing.T) { + tests := []struct { + name string + pemData []byte + }{ + { + name: "empty input", + pemData: []byte(""), + }, + { + name: "invalid PEM data", + pemData: []byte("NOT A PEM"), + }, + { + name: "corrupted certificate bytes", + pemData: []byte("-----BEGIN CERTIFICATE-----\nYXNkZg==\n-----END CERTIFICATE-----"), + }, + { + name: "incorrect PEM block type", + pemData: []byte("-----BEGIN PRIVATE KEY-----\nYXNkZg==\n-----END PRIVATE KEY-----"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := UnmarshalCertificate(tt.pemData) + if err == nil { + t.Error("UnmarshalCertificate() expected error, got nil") + } + }) + } +}