-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore_test.go
More file actions
305 lines (272 loc) · 7.61 KB
/
Copy pathstore_test.go
File metadata and controls
305 lines (272 loc) · 7.61 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package cryptlite_test
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/berbyte/cryptlite"
"github.com/berbyte/cryptlite/keyring"
)
func newTestStore(t *testing.T) *cryptlite.Store {
t.Helper()
dir := t.TempDir()
cfg := cryptlite.Config{
DBPath: filepath.Join(dir, "test.db"),
Keychain: cryptlite.KeychainConfig{
Service: "cryptlite-test",
Account: "default",
},
}
s, err := cryptlite.OpenWithKeyring(cfg, keyring.NewMemory())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
return s
}
func TestStoreEncryptDecryptRoundtrip(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
payload := []byte(`{"key":"value"}`)
blob, err := s.Encrypt(ctx, payload, []byte("table/col/id"))
if err != nil {
t.Fatal(err)
}
got, err := s.Decrypt(ctx, *blob, []byte("table/col/id"))
if err != nil {
t.Fatal(err)
}
if string(got) != string(payload) {
t.Fatalf("got %q want %q", got, payload)
}
}
func TestStoreEncryptJSONRoundtrip(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
payload := []byte(`{"name":"Alice","age":30}`)
blob, err := s.EncryptJSON(ctx, payload)
if err != nil {
t.Fatal(err)
}
got, err := s.DecryptJSON(ctx, *blob)
if err != nil {
t.Fatal(err)
}
if string(got) != string(payload) {
t.Fatalf("got %q want %q", got, payload)
}
}
func TestStoreDecryptWrongAAD(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
blob, _ := s.Encrypt(ctx, []byte("secret"), []byte("ctx-a"))
if _, err := s.Decrypt(ctx, *blob, []byte("ctx-b")); err == nil {
t.Fatal("expected failure with wrong AAD")
}
}
func TestStoreKeyRotation(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
// Encrypt with key v1.
blob, err := s.Encrypt(ctx, []byte("old"), nil)
if err != nil {
t.Fatal(err)
}
if blob.KeyVersion != 1 {
t.Fatalf("expected key version 1, got %d", blob.KeyVersion)
}
// Rotate to v2.
v, err := s.RotateKey(ctx)
if err != nil {
t.Fatal(err)
}
if v != 2 {
t.Fatalf("expected new version 2, got %d", v)
}
// New blobs use v2.
blob2, err := s.Encrypt(ctx, []byte("new"), nil)
if err != nil {
t.Fatal(err)
}
if blob2.KeyVersion != 2 {
t.Fatalf("expected key version 2, got %d", blob2.KeyVersion)
}
// Old blob (v1) still decryptable.
got, err := s.Decrypt(ctx, *blob, nil)
if err != nil {
t.Fatal("old blob should still decrypt:", err)
}
if string(got) != "old" {
t.Fatalf("got %q", got)
}
}
func TestStoreMigrationIdempotent(t *testing.T) {
dir := t.TempDir()
cfg := cryptlite.Config{
DBPath: filepath.Join(dir, "idem.db"),
Keychain: cryptlite.KeychainConfig{Service: "svc", Account: "acc"},
}
kr := keyring.NewMemory()
s1, err := cryptlite.OpenWithKeyring(cfg, kr)
if err != nil {
t.Fatal(err)
}
s1.Close()
s2, err := cryptlite.OpenWithKeyring(cfg, kr)
if err != nil {
t.Fatal("second open failed:", err)
}
s2.Close()
}
func TestStorePersistKey(t *testing.T) {
dir := t.TempDir()
cfg := cryptlite.Config{
DBPath: filepath.Join(dir, "persist.db"),
Keychain: cryptlite.KeychainConfig{Service: "svc", Account: "acc"},
}
kr := keyring.NewMemory()
s1, _ := cryptlite.OpenWithKeyring(cfg, kr)
ctx := context.Background()
blob, _ := s1.Encrypt(ctx, []byte("hello"), nil)
s1.Close()
// Re-open and decrypt using the persisted keychain entry.
s2, err := cryptlite.OpenWithKeyring(cfg, kr)
if err != nil {
t.Fatal(err)
}
defer s2.Close()
got, err := s2.Decrypt(ctx, *blob, nil)
if err != nil {
t.Fatal(err)
}
if string(got) != "hello" {
t.Fatalf("got %q", got)
}
}
func TestStoreSQLiteIntegration(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
db := s.DB()
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
body_ciphertext BLOB NOT NULL,
body_nonce BLOB NOT NULL,
body_key_version INTEGER NOT NULL
)`)
if err != nil {
t.Fatal(err)
}
payload := []byte(`{"content":"secret note"}`)
blob, err := s.Encrypt(ctx, payload, []byte("notes/body/1"))
if err != nil {
t.Fatal(err)
}
_, err = db.Exec(
`INSERT INTO notes (id, title, body_ciphertext, body_nonce, body_key_version) VALUES (?,?,?,?,?)`,
"1", "My Note", blob.Ciphertext, blob.Nonce, blob.KeyVersion,
)
if err != nil {
t.Fatal(err)
}
var loaded cryptlite.EncryptedBlob
err = db.QueryRow(`SELECT body_ciphertext, body_nonce, body_key_version FROM notes WHERE id = '1'`).
Scan(&loaded.Ciphertext, &loaded.Nonce, &loaded.KeyVersion)
if err != nil {
t.Fatal(err)
}
got, err := s.Decrypt(ctx, loaded, []byte("notes/body/1"))
if err != nil {
t.Fatal(err)
}
if string(got) != string(payload) {
t.Fatalf("got %q", got)
}
}
func TestStoreBatchInsert(t *testing.T) {
s := newTestStore(t)
ctx := context.Background()
db := s.DB()
_, _ = db.Exec(`CREATE TABLE items (id INTEGER PRIMARY KEY, val_ciphertext BLOB, val_nonce BLOB, val_key_version INTEGER)`)
tx, err := db.Begin()
if err != nil {
t.Fatal(err)
}
for i := 0; i < 50; i++ {
blob, err := s.Encrypt(ctx, []byte("item"), nil)
if err != nil {
tx.Rollback()
t.Fatal(err)
}
if _, err = tx.Exec(`INSERT INTO items VALUES (?,?,?,?)`, i, blob.Ciphertext, blob.Nonce, blob.KeyVersion); err != nil {
tx.Rollback()
t.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
var count int
db.QueryRow(`SELECT COUNT(*) FROM items`).Scan(&count)
if count != 50 {
t.Fatalf("expected 50, got %d", count)
}
}
func TestInvalidConfig(t *testing.T) {
_, err := cryptlite.Open(cryptlite.Config{})
if err != cryptlite.ErrInvalidConfig {
t.Fatalf("expected ErrInvalidConfig, got %v", err)
}
}
// TestLoadOrCreateActiveKey_InconsistentState covers the data-loss bug where a
// database with no active-key metadata (e.g. restored from backup, or a
// partially-applied migration) used to silently mint a brand-new key and
// overwrite whatever was already in the keychain for version 1 — orphaning
// every row encrypted under the real key. It must now fail loudly instead.
func TestLoadOrCreateActiveKey_InconsistentState(t *testing.T) {
dir := t.TempDir()
cfg := cryptlite.Config{
DBPath: filepath.Join(dir, "inconsistent.db"),
Keychain: cryptlite.KeychainConfig{Service: "svc", Account: "default"},
}
kr := keyring.NewMemory()
// Simulate a pre-existing real key for v1 with no corresponding db metadata
// (fresh/restored db file, divergent keychain).
if err := kr.Set("svc", "default/v1", "deadbeef"); err != nil {
t.Fatal(err)
}
_, err := cryptlite.OpenWithKeyring(cfg, kr)
if !errors.Is(err, cryptlite.ErrInconsistentKeyState) {
t.Fatalf("expected ErrInconsistentKeyState, got %v", err)
}
}
// TestStoreKeyVersion_RefusesOverwrite covers RotateKey racing (or being
// retried) such that a key already exists in the keychain for the version
// about to be minted — it must refuse rather than silently clobber it.
func TestStoreKeyVersion_RefusesOverwrite(t *testing.T) {
dir := t.TempDir()
cfg := cryptlite.Config{
DBPath: filepath.Join(dir, "rotate.db"),
Keychain: cryptlite.KeychainConfig{Service: "svc", Account: "default"},
}
kr := keyring.NewMemory()
s, err := cryptlite.OpenWithKeyring(cfg, kr)
if err != nil {
t.Fatal(err)
}
defer s.Close()
// Pre-seed the keychain with whatever the *next* version's account would
// be, simulating a key that's already there (e.g. a previous RotateKey
// call whose db write didn't commit).
if err := kr.Set("svc", "default/v2", "deadbeef"); err != nil {
t.Fatal(err)
}
if _, err := s.RotateKey(context.Background()); !errors.Is(err, cryptlite.ErrKeyAlreadyExists) {
t.Fatalf("expected ErrKeyAlreadyExists, got %v", err)
}
}
func init() {
// Ensure temp dir cleanup.
_ = os.MkdirTemp
}