Debian Codegraph @

actions/recovery_test.go

raw
1 /*
2 * recovery_test.go - tests for recovery passphrases
3 *
4 * Copyright 2019 Google LLC
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7 * use this file except in compliance with the License. You may obtain a copy of
8 * the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 * License for the specific language governing permissions and limitations under
16 * the License.
17 */
18
19 package actions
20
21 import (
22 "os"
23 "path/filepath"
24 "strings"
25 "testing"
26
27 "github.com/google/fscrypt/crypto"
28 )
29
30 func TestRecoveryPassphrase(t *testing.T) {
31 tempDir, err := os.MkdirTemp("", "fscrypt")
32 if err != nil {
33 t.Fatal(err)
34 }
35 defer os.RemoveAll(tempDir)
36 recoveryFile := filepath.Join(tempDir, "recovery.txt")
37
38 firstProtector, policy, err := makeBoth()
39 if err != nil {
40 t.Fatal(err)
41 }
42 defer cleanupPolicy(policy)
43 defer cleanupProtector(firstProtector)
44
45 // Add a recovery passphrase and verify that it worked correctly.
46 passphrase, recoveryProtector, err := AddRecoveryPassphrase(policy, "foo")
47 if err != nil {
48 t.Fatal(err)
49 }
50 defer cleanupProtector(recoveryProtector)
51 if passphrase.Len() != 20 {
52 t.Error("Recovery passphrase has wrong length")
53 }
54 if recoveryProtector.data.Name != "Recovery passphrase for foo" {
55 t.Error("Recovery passphrase protector has wrong name")
56 }
57 if len(policy.ProtectorDescriptors()) != 2 {
58 t.Error("There should be 2 protectors now")
59 }
60 getPassphraseFn := func(info ProtectorInfo, retry bool) (*crypto.Key, error) {
61 return passphrase.Clone()
62 }
63 recoveryProtector.Lock()
64 if err = recoveryProtector.Unlock(getPassphraseFn); err != nil {
65 t.Fatal(err)
66 }
67
68 // Test writing the recovery instructions.
69 if err = WriteRecoveryInstructions(passphrase, recoveryProtector, policy,
70 recoveryFile); err != nil {
71 t.Fatal(err)
72 }
73 contentsBytes, err := os.ReadFile(recoveryFile)
74 if err != nil {
75 t.Fatal(err)
76 }
77 contents := string(contentsBytes)
78 if !strings.Contains(contents, string(passphrase.Data())) {
79 t.Error("Recovery instructions don't actually contain the passphrase!")
80 }
81
82 // Test for protector naming collision.
83 if passphrase, recoveryProtector, err = AddRecoveryPassphrase(policy, "foo"); err != nil {
84 t.Fatal(err)
85 }
86 defer cleanupProtector(recoveryProtector)
87 if recoveryProtector.data.Name != "Recovery passphrase for foo (2)" {
88 t.Error("Recovery passphrase protector has wrong name (after naming collision)")
89 }
90 }