| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/aes" |
| 6 | "crypto/cipher" |
| 7 | "crypto/hkdf" |
| 8 | "crypto/hmac" |
| 9 | "crypto/sha256" |
| 10 | "encoding/base64" |
| 11 | "encoding/hex" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 15 | ) |
| 16 | |
| 17 | func TestPersonAPIDevicePurposeKeys(t *testing.T) { |
| 18 | root := "fixture-instance-key" |
| 19 | derive := func(purpose string) []byte { |
| 20 | key, err := hkdf.Key(sha256.New, []byte(root), nil, "equipo.v1/"+purpose, 32) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | return key |
| 25 | } |
| 26 | macKey := derive("person-device-hmac") |
| 27 | resultKey := derive("person-device-results") |
| 28 | cursorKey := derive("person-api-cursor") |
| 29 | if bytes.Equal(macKey, resultKey) || bytes.Equal(macKey, cursorKey) || bytes.Equal(resultKey, cursorKey) { |
| 30 | t.Fatal("purpose keys overlap") |
| 31 | } |
| 32 | s := DeviceStore{Key: root} |
| 33 | h := hmac.New(sha256.New, macKey) |
| 34 | h.Write([]byte("fixture\x00value")) |
| 35 | if s.mac("fixture", "value") != hex.EncodeToString(h.Sum(nil)) { |
| 36 | t.Fatal("device HMAC does not use purpose key") |
| 37 | } |
| 38 | sealed, err := s.seal("row", "value") |
| 39 | if err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | decrypt := func(key []byte, raw, scope string) error { |
| 43 | block, e := aes.NewCipher(key) |
| 44 | if e != nil { |
| 45 | return e |
| 46 | } |
| 47 | g, e := cipher.NewGCM(block) |
| 48 | if e != nil { |
| 49 | return e |
| 50 | } |
| 51 | b, e := base64.RawURLEncoding.DecodeString(raw) |
| 52 | if e != nil { |
| 53 | return e |
| 54 | } |
| 55 | _, e = g.Open(nil, b[:g.NonceSize()], b[g.NonceSize():], []byte(scope)) |
| 56 | return e |
| 57 | } |
| 58 | if err = decrypt(resultKey, sealed, "row"); err != nil { |
| 59 | t.Fatal("result does not use purpose key", err) |
| 60 | } |
| 61 | if decrypt(macKey, sealed, "row") == nil { |
| 62 | t.Fatal("HMAC key decrypted result") |
| 63 | } |
| 64 | token, err := (kernel.CursorCodec{Key: root}).Seal("scope", "position") |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | if err = decrypt(cursorKey, token, "scope"); err != nil { |
| 69 | t.Fatal("cursor does not use purpose key", err) |
| 70 | } |
| 71 | if decrypt(resultKey, token, "scope") == nil { |
| 72 | t.Fatal("result key decrypted cursor") |
| 73 | } |
| 74 | } |
| 75 | |