| 1 | package github |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "crypto/aes" |
| 6 | "crypto/cipher" |
| 7 | "encoding/base64" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | func TestAppKeySealing(t *testing.T) { |
| 13 | secret := "generated key material for this test" |
| 14 | sealed, err := sealKey("instance-key", "https://equipo.example", "connection-one", 101, secret) |
| 15 | if err != nil { |
| 16 | t.Fatal(err) |
| 17 | } |
| 18 | if strings.Contains(sealed, secret) { |
| 19 | t.Fatal("key persisted in plaintext") |
| 20 | } |
| 21 | raw, _ := base64.RawURLEncoding.DecodeString(sealed) |
| 22 | if strings.Contains(string(raw), secret) { |
| 23 | t.Fatal("key merely encoded") |
| 24 | } |
| 25 | opened, err := openKey("instance-key", "https://equipo.example", "connection-one", 101, sealed) |
| 26 | if err != nil || opened != secret { |
| 27 | t.Fatal("sealed key cannot be opened") |
| 28 | } |
| 29 | for _, tc := range []struct { |
| 30 | name, root, origin, id string |
| 31 | app int64 |
| 32 | }{ |
| 33 | {"root", "other-key", "https://equipo.example", "connection-one", 101}, |
| 34 | {"origin", "instance-key", "https://other.example", "connection-one", 101}, |
| 35 | {"connection", "instance-key", "https://equipo.example", "connection-two", 101}, |
| 36 | {"app", "instance-key", "https://equipo.example", "connection-one", 102}, |
| 37 | } { |
| 38 | t.Run(tc.name, func(t *testing.T) { |
| 39 | got, err := openKey(tc.root, tc.origin, tc.id, tc.app, sealed) |
| 40 | if err == nil || got != "" { |
| 41 | t.Fatal("key opened with the wrong binding") |
| 42 | } |
| 43 | }) |
| 44 | } |
| 45 | for _, purpose := range []string{"person-device-results", "person-api-cursor"} { |
| 46 | block, _ := aes.NewCipher(kernel.PurposeKey("instance-key", purpose)) |
| 47 | box, _ := cipher.NewGCM(block) |
| 48 | if _, err := box.Open(nil, raw[:box.NonceSize()], raw[box.NonceSize():], appBinding("https://equipo.example", "connection-one", 101)); err == nil { |
| 49 | t.Fatal("App key shares a credential purpose") |
| 50 | } |
| 51 | } |
| 52 | raw[len(raw)-1] ^= 1 |
| 53 | if got, err := openKey("instance-key", "https://equipo.example", "connection-one", 101, base64.RawURLEncoding.EncodeToString(raw)); err == nil || got != "" { |
| 54 | t.Fatal("corrupt ciphertext accepted") |
| 55 | } |
| 56 | second, err := sealKey("instance-key", "https://equipo.example", "connection-one", 101, secret) |
| 57 | if err != nil || sealed == second { |
| 58 | t.Fatal("nonce was reused") |
| 59 | } |
| 60 | } |
| 61 | |