Debian Codegraph @

server/tpm/js_ek_tpm_test.go

raw
1 // Copyright 2024 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build windows
15
16 package tpm
17
18 import (
19 "os"
20 "testing"
21 )
22
23 func getTempFile(t *testing.T) string {
24 return t.TempDir() + "/jskeys.json"
25 }
26
27 func TestLoadJetStreamEncryptionKeyFromTPM(t *testing.T) {
28 testFile := getTempFile(t)
29 type args struct {
30 srkPassword string
31 jsKeyFile string
32 jsKeyPassword string
33 pcr int
34 }
35 tests := []struct {
36 name string
37 args args
38 clear bool
39 wantErr bool
40 }{
41 {"TestLoadJetStreamEncryptionKeyFromTPM-Load", args{"", testFile, "password", 22}, true, false},
42 {"TestLoadJetStreamEncryptionKeyFromTPM-Read", args{"", testFile, "password", 22}, false, false},
43 {"TestLoadJetStreamEncryptionKeyFromTPM-BadPass", args{"", testFile, "badpass", 22}, false, true},
44 }
45 for _, tt := range tests {
46 t.Run(tt.name, func(t *testing.T) {
47 if tt.clear {
48 os.Remove(tt.args.jsKeyFile)
49 }
50 _, err := LoadJetStreamEncryptionKeyFromTPM(tt.args.srkPassword, tt.args.jsKeyFile, tt.args.jsKeyPassword, tt.args.pcr)
51 if (err != nil) != tt.wantErr {
52 t.Errorf("LoadJetStreamEncryptionKeyFromTPM() error = %v, wantErr %v", err, tt.wantErr)
53 return
54 }
55 })
56 }
57 }
58
59 // TestLoadJetStreamEncryptionKeyFromTPMBasic tests the basic functionality.
60 // The first pass will create the keys and generate the js encryption key.
61 // the second pass will read the keys from disk, decrypt with the TPM (unseal),
62 // and return the same key.
63 func TestLoadJetStreamEncryptionKeyFromTPMBasic(t *testing.T) {
64 testFile := getTempFile(t)
65
66 // Create the key file.
67 key1, err := LoadJetStreamEncryptionKeyFromTPM("", testFile, "password", 22)
68 if err != nil {
69 t.Errorf("LoadJetStreamEncryptionKeyFromTPM() failed: %v", err)
70 }
71
72 // Now obtain the newly generated key from the file.
73 key2, err := LoadJetStreamEncryptionKeyFromTPM("", testFile, "password", 22)
74 if err != nil {
75 t.Errorf("LoadJetStreamEncryptionKeyFromTPM() failed: %v", err)
76 }
77 if key1 != key2 {
78 t.Errorf("Keys should match")
79 }
80 }