summaryrefslogtreecommitdiff
path: root/internal/notify/vapid_test.go
blob: a45047d1aa3111290da62295f044603c4a67bb01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package notify

import (
	"encoding/base64"
	"testing"
)

// TestValidateVAPIDPublicKey verifies that ValidateVAPIDPublicKey accepts valid
// public keys and rejects private keys, empty strings, and invalid base64.
func TestValidateVAPIDPublicKey(t *testing.T) {
	pub, priv, err := GenerateVAPIDKeys()
	if err != nil {
		t.Fatalf("GenerateVAPIDKeys: %v", err)
	}
	if !ValidateVAPIDPublicKey(pub) {
		t.Error("valid public key should pass validation")
	}
	if ValidateVAPIDPublicKey(priv) {
		t.Error("private key (32 bytes) should fail public key validation")
	}
	if ValidateVAPIDPublicKey("") {
		t.Error("empty string should fail validation")
	}
	if ValidateVAPIDPublicKey("notbase64!!!") {
		t.Error("invalid base64 should fail validation")
	}
}

// TestGenerateVAPIDKeys_PublicKeyIs65Bytes verifies that the public key returned
// by GenerateVAPIDKeys is a 65-byte uncompressed P256 EC point (base64url, no padding = 87 chars)
// and the private key is 32 bytes (43 chars). Previously the return values were swapped.
func TestGenerateVAPIDKeys_PublicKeyIs65Bytes(t *testing.T) {
	pub, priv, err := GenerateVAPIDKeys()
	if err != nil {
		t.Fatalf("GenerateVAPIDKeys: %v", err)
	}

	// Public key: 65 bytes → 87 base64url chars (no padding).
	if len(pub) != 87 {
		t.Errorf("public key: want 87 chars (65 bytes), got %d chars (%q)", len(pub), pub)
	}
	pubBytes, err := base64.RawURLEncoding.DecodeString(pub)
	if err != nil {
		t.Fatalf("public key base64url decode: %v", err)
	}
	if len(pubBytes) != 65 {
		t.Errorf("public key bytes: want 65, got %d", len(pubBytes))
	}
	if pubBytes[0] != 0x04 {
		t.Errorf("public key first byte: want 0x04 (uncompressed point), got 0x%02x", pubBytes[0])
	}

	// Private key: 32 bytes → 43 base64url chars (no padding).
	if len(priv) != 43 {
		t.Errorf("private key: want 43 chars (32 bytes), got %d chars (%q)", len(priv), priv)
	}
	privBytes, err := base64.RawURLEncoding.DecodeString(priv)
	if err != nil {
		t.Fatalf("private key base64url decode: %v", err)
	}
	if len(privBytes) != 32 {
		t.Errorf("private key bytes: want 32, got %d", len(privBytes))
	}
}