| 1 | // Copyright 2019 The age Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package age_test |
| 6 | |
| 7 | import ( |
| 8 | "archive/zip" |
| 9 | "bytes" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "io/fs" |
| 14 | "log" |
| 15 | "os" |
| 16 | "slices" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "testing" |
| 20 | |
| 21 | "filippo.io/age" |
| 22 | "filippo.io/age/internal/bech32" |
| 23 | "filippo.io/age/plugin" |
| 24 | ) |
| 25 | |
| 26 | func ExampleEncrypt() { |
| 27 | publicKey := "age1cy0su9fwf3gf9mw868g5yut09p6nytfmmnktexz2ya5uqg9vl9sss4euqm" |
| 28 | recipient, err := age.ParseX25519Recipient(publicKey) |
| 29 | if err != nil { |
| 30 | log.Fatalf("Failed to parse public key %q: %v", publicKey, err) |
| 31 | } |
| 32 | |
| 33 | out := &bytes.Buffer{} |
| 34 | |
| 35 | w, err := age.Encrypt(out, recipient) |
| 36 | if err != nil { |
| 37 | log.Fatalf("Failed to create encrypted file: %v", err) |
| 38 | } |
| 39 | if _, err := io.WriteString(w, "Black lives matter."); err != nil { |
| 40 | log.Fatalf("Failed to write to encrypted file: %v", err) |
| 41 | } |
| 42 | if err := w.Close(); err != nil { |
| 43 | log.Fatalf("Failed to close encrypted file: %v", err) |
| 44 | } |
| 45 | |
| 46 | fmt.Printf("Encrypted file size: %d\n", out.Len()) |
| 47 | // Output: |
| 48 | // Encrypted file size: 219 |
| 49 | } |
| 50 | |
| 51 | // DO NOT hardcode the private key. Store it in a secret storage solution, |
| 52 | // on disk if the local machine is trusted, or have the user provide it. |
| 53 | var privateKey string |
| 54 | |
| 55 | func init() { |
| 56 | privateKey = "AGE-SECRET-KEY-184JMZMVQH3E6U0PSL869004Y3U2NYV7R30EU99CSEDNPH02YUVFSZW44VU" |
| 57 | } |
| 58 | |
| 59 | func ExampleDecrypt() { |
| 60 | identity, err := age.ParseX25519Identity(privateKey) |
| 61 | if err != nil { |
| 62 | log.Fatalf("Failed to parse private key: %v", err) |
| 63 | } |
| 64 | |
| 65 | f, err := os.Open("testdata/example.age") |
| 66 | if err != nil { |
| 67 | log.Fatalf("Failed to open file: %v", err) |
| 68 | } |
| 69 | |
| 70 | r, err := age.Decrypt(f, identity) |
| 71 | if err != nil { |
| 72 | log.Fatalf("Failed to open encrypted file: %v", err) |
| 73 | } |
| 74 | out := &bytes.Buffer{} |
| 75 | if _, err := io.Copy(out, r); err != nil { |
| 76 | log.Fatalf("Failed to read encrypted file: %v", err) |
| 77 | } |
| 78 | |
| 79 | fmt.Printf("File contents: %q\n", out.Bytes()) |
| 80 | // Output: |
| 81 | // File contents: "Black lives matter." |
| 82 | } |
| 83 | |
| 84 | func ExampleParseIdentities() { |
| 85 | keyFile, err := os.Open("testdata/example_keys.txt") |
| 86 | if err != nil { |
| 87 | log.Fatalf("Failed to open private keys file: %v", err) |
| 88 | } |
| 89 | identities, err := age.ParseIdentities(keyFile) |
| 90 | if err != nil { |
| 91 | log.Fatalf("Failed to parse private key: %v", err) |
| 92 | } |
| 93 | |
| 94 | f, err := os.Open("testdata/example.age") |
| 95 | if err != nil { |
| 96 | log.Fatalf("Failed to open file: %v", err) |
| 97 | } |
| 98 | |
| 99 | r, err := age.Decrypt(f, identities...) |
| 100 | if err != nil { |
| 101 | log.Fatalf("Failed to open encrypted file: %v", err) |
| 102 | } |
| 103 | out := &bytes.Buffer{} |
| 104 | if _, err := io.Copy(out, r); err != nil { |
| 105 | log.Fatalf("Failed to read encrypted file: %v", err) |
| 106 | } |
| 107 | |
| 108 | fmt.Printf("File contents: %q\n", out.Bytes()) |
| 109 | // Output: |
| 110 | // File contents: "Black lives matter." |
| 111 | } |
| 112 | |
| 113 | func ExampleGenerateX25519Identity() { |
| 114 | identity, err := age.GenerateX25519Identity() |
| 115 | if err != nil { |
| 116 | log.Fatalf("Failed to generate key pair: %v", err) |
| 117 | } |
| 118 | |
| 119 | fmt.Printf("Public key: %s...\n", identity.Recipient().String()[:4]) |
| 120 | fmt.Printf("Private key: %s...\n", identity.String()[:16]) |
| 121 | // Output: |
| 122 | // Public key: age1... |
| 123 | // Private key: AGE-SECRET-KEY-1... |
| 124 | } |
| 125 | |
| 126 | const helloWorld = "Hello, Twitch!" |
| 127 | |
| 128 | func TestEncryptDecryptX25519(t *testing.T) { |
| 129 | a, err := age.GenerateX25519Identity() |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | b, err := age.GenerateX25519Identity() |
| 134 | if err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | buf := &bytes.Buffer{} |
| 138 | w, err := age.Encrypt(buf, a.Recipient(), b.Recipient()) |
| 139 | if err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | if _, err := io.WriteString(w, helloWorld); err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | if err := w.Close(); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | |
| 149 | out, err := age.Decrypt(buf, b) |
| 150 | if err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | outBytes, err := io.ReadAll(out) |
| 154 | if err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | if string(outBytes) != helloWorld { |
| 158 | t.Errorf("wrong data: %q, excepted %q", outBytes, helloWorld) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | func TestEncryptDecryptScrypt(t *testing.T) { |
| 163 | password := "twitch.tv/filosottile" |
| 164 | |
| 165 | r, err := age.NewScryptRecipient(password) |
| 166 | if err != nil { |
| 167 | t.Fatal(err) |
| 168 | } |
| 169 | r.SetWorkFactor(15) |
| 170 | buf := &bytes.Buffer{} |
| 171 | w, err := age.Encrypt(buf, r) |
| 172 | if err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | if _, err := io.WriteString(w, helloWorld); err != nil { |
| 176 | t.Fatal(err) |
| 177 | } |
| 178 | if err := w.Close(); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | |
| 182 | i, err := age.NewScryptIdentity(password) |
| 183 | if err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | out, err := age.Decrypt(buf, i) |
| 187 | if err != nil { |
| 188 | t.Fatal(err) |
| 189 | } |
| 190 | outBytes, err := io.ReadAll(out) |
| 191 | if err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | if string(outBytes) != helloWorld { |
| 195 | t.Errorf("wrong data: %q, excepted %q", outBytes, helloWorld) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | func ExampleDecryptReaderAt() { |
| 200 | identity, err := age.ParseX25519Identity(privateKey) |
| 201 | if err != nil { |
| 202 | log.Fatalf("Failed to parse private key: %v", err) |
| 203 | } |
| 204 | |
| 205 | f, err := os.Open("testdata/example.zip.age") |
| 206 | if err != nil { |
| 207 | log.Fatalf("Failed to open file: %v", err) |
| 208 | } |
| 209 | stat, err := f.Stat() |
| 210 | if err != nil { |
| 211 | log.Fatalf("Failed to stat file: %v", err) |
| 212 | } |
| 213 | |
| 214 | r, size, err := age.DecryptReaderAt(f, stat.Size(), identity) |
| 215 | if err != nil { |
| 216 | log.Fatalf("Failed to open encrypted file: %v", err) |
| 217 | } |
| 218 | |
| 219 | z, err := zip.NewReader(r, size) |
| 220 | if err != nil { |
| 221 | log.Fatalf("Failed to open zip: %v", err) |
| 222 | } |
| 223 | contents, err := fs.ReadFile(z, "example.txt") |
| 224 | if err != nil { |
| 225 | log.Fatalf("Failed to read file from zip: %v", err) |
| 226 | } |
| 227 | |
| 228 | fmt.Printf("File contents: %q\n", contents) |
| 229 | // Output: |
| 230 | // File contents: "Black lives matter." |
| 231 | } |
| 232 | |
| 233 | func TestParseIdentities(t *testing.T) { |
| 234 | tests := []struct { |
| 235 | name string |
| 236 | wantCount int |
| 237 | wantErr bool |
| 238 | file string |
| 239 | }{ |
| 240 | {"valid", 2, false, ` |
| 241 | # this is a comment |
| 242 | # AGE-SECRET-KEY-1705XN76M8EYQ8M9PY4E2G3KA8DN7NSCGT3V4HMN20H3GCX4AS6HSSTG8D3 |
| 243 | # |
| 244 | |
| 245 | AGE-SECRET-KEY-1D6K0SGAX3NU66R4GYFZY0UQWCLM3UUSF3CXLW4KXZM342WQSJ82QKU59QJ |
| 246 | AGE-SECRET-KEY-19WUMFE89H3928FRJ5U3JYRNHM6CERQGKSQ584AQ8QY7T7R09D32SWE4DYH`}, |
| 247 | {"invalid", 0, true, ` |
| 248 | AGE-SECRET-KEY-1705XN76M8EYQ8M9PY4E2G3KA8DN7NSCGT3V4HMN20H3GCX4AS6HSSTG8D3 |
| 249 | AGE-SECRET-KEY--1D6K0SGAX3NU66R4GYFZY0UQWCLM3UUSF3CXLW4KXZM342WQSJ82QKU59Q`}, |
| 250 | } |
| 251 | for _, tt := range tests { |
| 252 | t.Run(tt.name, func(t *testing.T) { |
| 253 | got, err := age.ParseIdentities(strings.NewReader(tt.file)) |
| 254 | if (err != nil) != tt.wantErr { |
| 255 | t.Errorf("ParseIdentities() error = %v, wantErr %v", err, tt.wantErr) |
| 256 | return |
| 257 | } |
| 258 | if len(got) != tt.wantCount { |
| 259 | t.Errorf("ParseIdentities() returned %d identities, want %d", len(got), tt.wantCount) |
| 260 | } |
| 261 | }) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | func TestParseErrorsDoNotIncludeLine(t *testing.T) { |
| 266 | x25519, err := age.GenerateX25519Identity() |
| 267 | if err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | hybrid, err := age.GenerateHybridIdentity() |
| 271 | if err != nil { |
| 272 | t.Fatal(err) |
| 273 | } |
| 274 | // Re-encode the hybrid identity as a plugin identity. |
| 275 | _, seed, err := bech32.Decode(hybrid.String()) |
| 276 | if err != nil { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | pluginIdentity, err := bech32.Encode("AGE-PLUGIN-PQ-", seed) |
| 280 | if err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | |
| 284 | tests := []struct { |
| 285 | name string |
| 286 | line string |
| 287 | parse func(io.Reader) error |
| 288 | }{ |
| 289 | {"identities/plugin", pluginIdentity, func(r io.Reader) error { |
| 290 | _, err := age.ParseIdentities(r) |
| 291 | return err |
| 292 | }}, |
| 293 | {"recipients/x25519", x25519.String(), func(r io.Reader) error { |
| 294 | _, err := age.ParseRecipients(r) |
| 295 | return err |
| 296 | }}, |
| 297 | {"recipients/hybrid", hybrid.String(), func(r io.Reader) error { |
| 298 | _, err := age.ParseRecipients(r) |
| 299 | return err |
| 300 | }}, |
| 301 | } |
| 302 | for _, tt := range tests { |
| 303 | t.Run(tt.name, func(t *testing.T) { |
| 304 | err := tt.parse(strings.NewReader("# a comment\n" + tt.line + "\n")) |
| 305 | if err == nil { |
| 306 | t.Fatal("expected an error for an unrecognized line, got nil") |
| 307 | } |
| 308 | if strings.Contains(err.Error(), tt.line) { |
| 309 | t.Errorf("error includes the private key from the file: %v", err) |
| 310 | } |
| 311 | if !strings.Contains(err.Error(), "line 2") { |
| 312 | t.Errorf("error doesn't say which line failed: %v", err) |
| 313 | } |
| 314 | }) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | func paddedFile(pad int, lines string) io.Reader { |
| 319 | const chunkSize = 1 << 16 |
| 320 | chunk := strings.Repeat("#\n", chunkSize/2) |
| 321 | var readers []io.Reader |
| 322 | if pad%2 != 0 { |
| 323 | readers = append(readers, strings.NewReader("\n")) |
| 324 | pad-- |
| 325 | } |
| 326 | for ; pad > chunkSize; pad -= chunkSize { |
| 327 | readers = append(readers, strings.NewReader(chunk)) |
| 328 | } |
| 329 | return io.MultiReader(append(readers, |
| 330 | strings.NewReader(chunk[:pad]), strings.NewReader(lines))...) |
| 331 | } |
| 332 | |
| 333 | func TestParseFileSizeLimit(t *testing.T) { |
| 334 | const sizeLimit = 1 << 24 |
| 335 | const identity = "AGE-SECRET-KEY-1D6K0SGAX3NU66R4GYFZY0UQWCLM3UUSF3CXLW4KXZM342WQSJ82QKU59QJ\n" |
| 336 | const recipient = "age1cy0su9fwf3gf9mw868g5yut09p6nytfmmnktexz2ya5uqg9vl9sss4euqm\n" |
| 337 | tests := []struct { |
| 338 | name string |
| 339 | entry string |
| 340 | parse func(io.Reader) (int, error) |
| 341 | }{ |
| 342 | {"identities", identity, func(r io.Reader) (int, error) { |
| 343 | ids, err := age.ParseIdentities(r) |
| 344 | return len(ids), err |
| 345 | }}, |
| 346 | {"recipients", recipient, func(r io.Reader) (int, error) { |
| 347 | recipients, err := age.ParseRecipients(r) |
| 348 | return len(recipients), err |
| 349 | }}, |
| 350 | } |
| 351 | for _, tt := range tests { |
| 352 | t.Run(tt.name+"/at limit", func(t *testing.T) { |
| 353 | r := paddedFile(sizeLimit-4*len(tt.entry), strings.Repeat(tt.entry, 4)) |
| 354 | n, err := tt.parse(r) |
| 355 | if err != nil { |
| 356 | t.Fatal(err) |
| 357 | } |
| 358 | if n != 4 { |
| 359 | t.Errorf("got %d entries, want 4", n) |
| 360 | } |
| 361 | }) |
| 362 | t.Run(tt.name+"/over limit", func(t *testing.T) { |
| 363 | r := paddedFile(sizeLimit-4*len(tt.entry), strings.Repeat(tt.entry, 8)) |
| 364 | if _, err := tt.parse(r); err == nil { |
| 365 | t.Error("expected an error") |
| 366 | } |
| 367 | }) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | type testRecipient struct { |
| 372 | labels []string |
| 373 | } |
| 374 | |
| 375 | func (testRecipient) Wrap(fileKey []byte) ([]*age.Stanza, error) { |
| 376 | panic("expected WrapWithLabels instead") |
| 377 | } |
| 378 | |
| 379 | func (t testRecipient) WrapWithLabels(fileKey []byte) (s []*age.Stanza, labels []string, err error) { |
| 380 | return []*age.Stanza{{Type: "test"}}, t.labels, nil |
| 381 | } |
| 382 | |
| 383 | type emptyRecipient struct{} |
| 384 | |
| 385 | func (emptyRecipient) Wrap(fileKey []byte) ([]*age.Stanza, error) { |
| 386 | return nil, nil |
| 387 | } |
| 388 | |
| 389 | func TestEmptyRecipient(t *testing.T) { |
| 390 | buf := &bytes.Buffer{} |
| 391 | if _, err := age.Encrypt(buf, emptyRecipient{}); err == nil { |
| 392 | t.Fatal("Encrypt accepted a recipient with no stanzas") |
| 393 | } |
| 394 | if buf.Len() != 0 { |
| 395 | t.Errorf("Encrypt wrote %d bytes", buf.Len()) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | func TestLabels(t *testing.T) { |
| 400 | scrypt, err := age.NewScryptRecipient("xxx") |
| 401 | if err != nil { |
| 402 | t.Fatal(err) |
| 403 | } |
| 404 | i, err := age.GenerateX25519Identity() |
| 405 | if err != nil { |
| 406 | t.Fatal(err) |
| 407 | } |
| 408 | x25519 := i.Recipient() |
| 409 | pqc := testRecipient{[]string{"postquantum"}} |
| 410 | pqcAndFoo := testRecipient{[]string{"postquantum", "foo"}} |
| 411 | fooAndPQC := testRecipient{[]string{"foo", "postquantum"}} |
| 412 | |
| 413 | if _, err := age.Encrypt(io.Discard, scrypt, scrypt); err == nil { |
| 414 | t.Error("expected two scrypt recipients to fail") |
| 415 | } |
| 416 | if _, err := age.Encrypt(io.Discard, scrypt, x25519); err == nil { |
| 417 | t.Error("expected x25519 mixed with scrypt to fail") |
| 418 | } |
| 419 | if _, err := age.Encrypt(io.Discard, x25519, scrypt); err == nil { |
| 420 | t.Error("expected x25519 mixed with scrypt to fail") |
| 421 | } |
| 422 | if _, err := age.Encrypt(io.Discard, pqc, x25519); err == nil { |
| 423 | t.Error("expected x25519 mixed with pqc to fail") |
| 424 | } |
| 425 | if _, err := age.Encrypt(io.Discard, x25519, pqc); err == nil { |
| 426 | t.Error("expected x25519 mixed with pqc to fail") |
| 427 | } |
| 428 | if _, err := age.Encrypt(io.Discard, pqc, pqc); err != nil { |
| 429 | t.Errorf("expected two pqc to work, got %v", err) |
| 430 | } |
| 431 | if _, err := age.Encrypt(io.Discard, pqc); err != nil { |
| 432 | t.Errorf("expected one pqc to work, got %v", err) |
| 433 | } |
| 434 | if _, err := age.Encrypt(io.Discard, pqcAndFoo, pqc); err == nil { |
| 435 | t.Error("expected pqc+foo mixed with pqc to fail") |
| 436 | } |
| 437 | if _, err := age.Encrypt(io.Discard, pqc, pqcAndFoo); err == nil { |
| 438 | t.Error("expected pqc+foo mixed with pqc to fail") |
| 439 | } |
| 440 | if _, err := age.Encrypt(io.Discard, pqc, pqc, pqcAndFoo); err == nil { |
| 441 | t.Error("expected pqc+foo mixed with pqc to fail") |
| 442 | } |
| 443 | if _, err := age.Encrypt(io.Discard, pqcAndFoo, pqcAndFoo); err != nil { |
| 444 | t.Errorf("expected two pqc+foo to work, got %v", err) |
| 445 | } |
| 446 | if _, err := age.Encrypt(io.Discard, pqcAndFoo, fooAndPQC); err != nil { |
| 447 | t.Errorf("expected pqc+foo mixed with foo+pqc to work, got %v", err) |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | // testIdentity is a non-native identity that records if Unwrap is called. |
| 452 | type testIdentity struct { |
| 453 | called bool |
| 454 | } |
| 455 | |
| 456 | func (ti *testIdentity) Unwrap(stanzas []*age.Stanza) ([]byte, error) { |
| 457 | ti.called = true |
| 458 | return nil, age.ErrIncorrectIdentity |
| 459 | } |
| 460 | |
| 461 | type noMatchIdentity int |
| 462 | |
| 463 | func (noMatchIdentity) Unwrap(stanzas []*age.Stanza) ([]byte, error) { |
| 464 | return nil, age.ErrIncorrectIdentity |
| 465 | } |
| 466 | |
| 467 | func TestDecryptDoesNotReorderIdentities(t *testing.T) { |
| 468 | identity, err := age.GenerateX25519Identity() |
| 469 | if err != nil { |
| 470 | t.Fatal(err) |
| 471 | } |
| 472 | buf := &bytes.Buffer{} |
| 473 | w, err := age.Encrypt(buf, identity.Recipient()) |
| 474 | if err != nil { |
| 475 | t.Fatal(err) |
| 476 | } |
| 477 | if err := w.Close(); err != nil { |
| 478 | t.Fatal(err) |
| 479 | } |
| 480 | encrypted := buf.Bytes() |
| 481 | header, err := age.ExtractHeader(bytes.NewReader(encrypted)) |
| 482 | if err != nil { |
| 483 | t.Fatal(err) |
| 484 | } |
| 485 | |
| 486 | tests := []struct { |
| 487 | name string |
| 488 | decrypt func([]age.Identity) error |
| 489 | }{ |
| 490 | {"Decrypt", func(identities []age.Identity) error { |
| 491 | _, err := age.Decrypt(bytes.NewReader(encrypted), identities...) |
| 492 | return err |
| 493 | }}, |
| 494 | {"DecryptReaderAt", func(identities []age.Identity) error { |
| 495 | _, _, err := age.DecryptReaderAt(bytes.NewReader(encrypted), int64(len(encrypted)), identities...) |
| 496 | return err |
| 497 | }}, |
| 498 | {"DecryptHeader", func(identities []age.Identity) error { |
| 499 | _, err := age.DecryptHeader(header, identities...) |
| 500 | return err |
| 501 | }}, |
| 502 | } |
| 503 | for _, tt := range tests { |
| 504 | t.Run(tt.name, func(t *testing.T) { |
| 505 | identities := []age.Identity{noMatchIdentity(1), identity, noMatchIdentity(2)} |
| 506 | want := slices.Clone(identities) |
| 507 | if err := tt.decrypt(identities); err != nil { |
| 508 | t.Fatal(err) |
| 509 | } |
| 510 | if !slices.Equal(identities, want) { |
| 511 | t.Error("identities were reordered") |
| 512 | } |
| 513 | }) |
| 514 | } |
| 515 | |
| 516 | t.Run("concurrent", func(t *testing.T) { |
| 517 | identities := []age.Identity{noMatchIdentity(1), identity, noMatchIdentity(2)} |
| 518 | want := slices.Clone(identities) |
| 519 | var wg sync.WaitGroup |
| 520 | for range 4 { |
| 521 | wg.Add(1) |
| 522 | go func() { |
| 523 | defer wg.Done() |
| 524 | for range 20 { |
| 525 | if _, err := age.Decrypt(bytes.NewReader(encrypted), identities...); err != nil { |
| 526 | t.Error(err) |
| 527 | } |
| 528 | } |
| 529 | }() |
| 530 | } |
| 531 | wg.Wait() |
| 532 | if !slices.Equal(identities, want) { |
| 533 | t.Error("identities were reordered") |
| 534 | } |
| 535 | }) |
| 536 | } |
| 537 | |
| 538 | func TestDecryptNativeIdentitiesFirst(t *testing.T) { |
| 539 | correct, err := age.GenerateX25519Identity() |
| 540 | if err != nil { |
| 541 | t.Fatal(err) |
| 542 | } |
| 543 | unrelated, err := age.GenerateX25519Identity() |
| 544 | if err != nil { |
| 545 | t.Fatal(err) |
| 546 | } |
| 547 | |
| 548 | buf := &bytes.Buffer{} |
| 549 | w, err := age.Encrypt(buf, correct.Recipient()) |
| 550 | if err != nil { |
| 551 | t.Fatal(err) |
| 552 | } |
| 553 | if err := w.Close(); err != nil { |
| 554 | t.Fatal(err) |
| 555 | } |
| 556 | |
| 557 | nonNative := &testIdentity{} |
| 558 | |
| 559 | // Pass identities: unrelated native, non-native, correct native. |
| 560 | // Native identities should be tried first, so correct should match |
| 561 | // before nonNative is ever called. |
| 562 | _, err = age.Decrypt(bytes.NewReader(buf.Bytes()), unrelated, nonNative, correct) |
| 563 | if err != nil { |
| 564 | t.Fatal(err) |
| 565 | } |
| 566 | |
| 567 | if nonNative.called { |
| 568 | t.Error("non-native identity was called, but native identities should be tried first") |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | type stanzaTypeRecipient string |
| 573 | |
| 574 | func (s stanzaTypeRecipient) Wrap(fileKey []byte) ([]*age.Stanza, error) { |
| 575 | return []*age.Stanza{{Type: string(s)}}, nil |
| 576 | } |
| 577 | |
| 578 | func TestNoIdentityMatchErrorStanzaTypes(t *testing.T) { |
| 579 | a, err := age.GenerateX25519Identity() |
| 580 | if err != nil { |
| 581 | t.Fatal(err) |
| 582 | } |
| 583 | b, err := age.GenerateX25519Identity() |
| 584 | if err != nil { |
| 585 | t.Fatal(err) |
| 586 | } |
| 587 | wrong, err := age.GenerateX25519Identity() |
| 588 | if err != nil { |
| 589 | t.Fatal(err) |
| 590 | } |
| 591 | |
| 592 | buf := &bytes.Buffer{} |
| 593 | w, err := age.Encrypt(buf, a.Recipient(), stanzaTypeRecipient("other"), b.Recipient()) |
| 594 | if err != nil { |
| 595 | t.Fatal(err) |
| 596 | } |
| 597 | if _, err := io.WriteString(w, helloWorld); err != nil { |
| 598 | t.Fatal(err) |
| 599 | } |
| 600 | if err := w.Close(); err != nil { |
| 601 | t.Fatal(err) |
| 602 | } |
| 603 | |
| 604 | _, err = age.Decrypt(bytes.NewReader(buf.Bytes()), wrong) |
| 605 | if err == nil { |
| 606 | t.Fatal("expected decryption to fail") |
| 607 | } |
| 608 | |
| 609 | var noMatch *age.NoIdentityMatchError |
| 610 | if !errors.As(err, &noMatch) { |
| 611 | t.Fatalf("expected NoIdentityMatchError, got %T: %v", err, err) |
| 612 | } |
| 613 | |
| 614 | want := []string{"X25519", "other", "X25519"} |
| 615 | if !slices.Equal(noMatch.StanzaTypes, want) { |
| 616 | t.Errorf("StanzaTypes = %v, want %v", noMatch.StanzaTypes, want) |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | func TestScryptIdentityErrors(t *testing.T) { |
| 621 | t.Run("not passphrase-encrypted", func(t *testing.T) { |
| 622 | i, err := age.GenerateX25519Identity() |
| 623 | if err != nil { |
| 624 | t.Fatal(err) |
| 625 | } |
| 626 | |
| 627 | buf := &bytes.Buffer{} |
| 628 | w, err := age.Encrypt(buf, i.Recipient()) |
| 629 | if err != nil { |
| 630 | t.Fatal(err) |
| 631 | } |
| 632 | if err := w.Close(); err != nil { |
| 633 | t.Fatal(err) |
| 634 | } |
| 635 | |
| 636 | scryptID, err := age.NewScryptIdentity("password") |
| 637 | if err != nil { |
| 638 | t.Fatal(err) |
| 639 | } |
| 640 | _, err = age.Decrypt(bytes.NewReader(buf.Bytes()), scryptID) |
| 641 | if err == nil { |
| 642 | t.Fatal("expected decryption to fail") |
| 643 | } |
| 644 | if !errors.Is(err, age.ErrIncorrectIdentity) { |
| 645 | t.Errorf("expected ErrIncorrectIdentity, got %v", err) |
| 646 | } |
| 647 | if !strings.Contains(err.Error(), "not passphrase-encrypted") { |
| 648 | t.Errorf("expected error to mention 'not passphrase-encrypted', got %v", err) |
| 649 | } |
| 650 | }) |
| 651 | |
| 652 | t.Run("incorrect passphrase", func(t *testing.T) { |
| 653 | r, err := age.NewScryptRecipient("correct-password") |
| 654 | if err != nil { |
| 655 | t.Fatal(err) |
| 656 | } |
| 657 | r.SetWorkFactor(10) // Low for fast test |
| 658 | |
| 659 | buf := &bytes.Buffer{} |
| 660 | w, err := age.Encrypt(buf, r) |
| 661 | if err != nil { |
| 662 | t.Fatal(err) |
| 663 | } |
| 664 | if err := w.Close(); err != nil { |
| 665 | t.Fatal(err) |
| 666 | } |
| 667 | |
| 668 | scryptID, err := age.NewScryptIdentity("wrong-password") |
| 669 | if err != nil { |
| 670 | t.Fatal(err) |
| 671 | } |
| 672 | _, err = age.Decrypt(bytes.NewReader(buf.Bytes()), scryptID) |
| 673 | if err == nil { |
| 674 | t.Fatal("expected decryption to fail") |
| 675 | } |
| 676 | if !errors.Is(err, age.ErrIncorrectIdentity) { |
| 677 | t.Errorf("expected ErrIncorrectIdentity, got %v", err) |
| 678 | } |
| 679 | if !strings.Contains(err.Error(), "incorrect passphrase") { |
| 680 | t.Errorf("expected error to mention 'incorrect passphrase', got %v", err) |
| 681 | } |
| 682 | }) |
| 683 | } |
| 684 | |
| 685 | func TestDetachedHeader(t *testing.T) { |
| 686 | i, err := age.GenerateX25519Identity() |
| 687 | if err != nil { |
| 688 | t.Fatal(err) |
| 689 | } |
| 690 | |
| 691 | buf := &bytes.Buffer{} |
| 692 | w, err := age.Encrypt(buf, i.Recipient()) |
| 693 | if err != nil { |
| 694 | t.Fatal(err) |
| 695 | } |
| 696 | if _, err := io.WriteString(w, helloWorld); err != nil { |
| 697 | t.Fatal(err) |
| 698 | } |
| 699 | if err := w.Close(); err != nil { |
| 700 | t.Fatal(err) |
| 701 | } |
| 702 | encrypted := buf.Bytes() |
| 703 | |
| 704 | header, err := age.ExtractHeader(bytes.NewReader(encrypted)) |
| 705 | if err != nil { |
| 706 | t.Fatal(err) |
| 707 | } |
| 708 | |
| 709 | fileKey, err := age.DecryptHeader(header, i) |
| 710 | if err != nil { |
| 711 | t.Fatal(err) |
| 712 | } |
| 713 | |
| 714 | identity := age.NewInjectedFileKeyIdentity(fileKey) |
| 715 | out, err := age.Decrypt(bytes.NewReader(encrypted), identity) |
| 716 | if err != nil { |
| 717 | t.Fatal(err) |
| 718 | } |
| 719 | outBytes, err := io.ReadAll(out) |
| 720 | if err != nil { |
| 721 | t.Fatal(err) |
| 722 | } |
| 723 | if string(outBytes) != helloWorld { |
| 724 | t.Errorf("wrong data: %q, expected %q", outBytes, helloWorld) |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | func TestEncryptReader(t *testing.T) { |
| 729 | a, err := age.GenerateX25519Identity() |
| 730 | if err != nil { |
| 731 | t.Fatal(err) |
| 732 | } |
| 733 | r, err := age.EncryptReader(strings.NewReader(helloWorld), a.Recipient()) |
| 734 | if err != nil { |
| 735 | t.Fatal(err) |
| 736 | } |
| 737 | buf := &bytes.Buffer{} |
| 738 | if _, err := io.Copy(buf, r); err != nil { |
| 739 | t.Fatal(err) |
| 740 | } |
| 741 | |
| 742 | out, err := age.Decrypt(buf, a) |
| 743 | if err != nil { |
| 744 | t.Fatal(err) |
| 745 | } |
| 746 | outBytes, err := io.ReadAll(out) |
| 747 | if err != nil { |
| 748 | t.Fatal(err) |
| 749 | } |
| 750 | if string(outBytes) != helloWorld { |
| 751 | t.Errorf("wrong data: %q, excepted %q", outBytes, helloWorld) |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | func TestParseUnicode(t *testing.T) { |
| 756 | // U+212A folds to "k", shrinking the data part below the checksum. |
| 757 | w := "AA3100AC" + string(rune(0x212A)) |
| 758 | for _, tc := range []struct { |
| 759 | name string |
| 760 | fn func(string) error |
| 761 | }{ |
| 762 | {"age.ParseX25519Recipient", func(s string) error { _, err := age.ParseX25519Recipient(s); return err }}, |
| 763 | {"age.ParseX25519Identity", func(s string) error { _, err := age.ParseX25519Identity(s); return err }}, |
| 764 | {"age.ParseHybridRecipient", func(s string) error { _, err := age.ParseHybridRecipient(s); return err }}, |
| 765 | {"age.ParseHybridIdentity", func(s string) error { _, err := age.ParseHybridIdentity(s); return err }}, |
| 766 | {"plugin.ParseIdentity", func(s string) error { _, _, err := plugin.ParseIdentity(s); return err }}, |
| 767 | {"plugin.ParseRecipient", func(s string) error { _, _, err := plugin.ParseRecipient(s); return err }}, |
| 768 | } { |
| 769 | t.Run(tc.name, func(t *testing.T) { |
| 770 | defer func() { |
| 771 | if r := recover(); r != nil { |
| 772 | t.Errorf("%s panicked on malformed input: %v", tc.name, r) |
| 773 | } |
| 774 | }() |
| 775 | if err := tc.fn(w); err == nil { |
| 776 | t.Errorf("%s returned nil error, want error", tc.name) |
| 777 | } |
| 778 | }) |
| 779 | } |
| 780 | } |