package demo import ( "bytes" "errors" "strings" "testing" ) func TestSealedBundleRoundTripsWithTheCodeAsTyped(t *testing.T) { code, err := NewCode() if err != nil { t.Fatal(err) } if len(NormalizeCode(code)) != 24 { t.Fatalf("code should be 24 base32 chars, got %q", code) } secret := []byte(`[{"id":"cam1","password":"the-camera-admin-password"}]`) sealed, err := Seal(code, secret) if err != nil { t.Fatal(err) } // People type codes in lower case, with the dashes dropped, with a space // where a dash was. All of those are the same code. for _, typed := range []string{ code, strings.ToLower(code), strings.ReplaceAll(code, "-", ""), strings.ReplaceAll(code, "-", " "), " " + code + "\n", } { got, err := Open(typed, sealed) if err != nil { t.Fatalf("open with %q: %v", typed, err) } if !bytes.Equal(got, secret) { t.Fatalf("round trip changed the contents") } } } // The whole point of the file: the password is not in it. func TestTheSealedFileDoesNotContainTheSecret(t *testing.T) { code, _ := NewCode() sealed, _ := Seal(code, []byte(`{"password":"the-camera-admin-password","host":"192.168.1.121"}`)) for _, leak := range []string{"the-camera-admin-password", "192.168.1.121", "password"} { if bytes.Contains(sealed, []byte(leak)) { t.Fatalf("sealed bundle contains %q in the clear", leak) } } } func TestAWrongCodeIsRefusedNotMisread(t *testing.T) { code, _ := NewCode() other, _ := NewCode() sealed, _ := Seal(code, []byte("secret")) if _, err := Open(other, sealed); !errors.Is(err, ErrWrongCode) { t.Fatalf("a different code should be ErrWrongCode, got %v", err) } // One flipped byte in the ciphertext is the same answer: GCM refuses // rather than returning garbage that then gets written into cameras.json. tampered := append([]byte{}, sealed...) tampered[len(tampered)-1] ^= 0x01 if _, err := Open(code, tampered); !errors.Is(err, ErrWrongCode) { t.Fatalf("a tampered bundle should be refused, got %v", err) } } func TestSomethingThatIsNotABundleSaysSo(t *testing.T) { if _, err := Open("ABCDEF-GHIJKL-MNOPQR-STUVWX", []byte("hello")); err == nil || errors.Is(err, ErrWrongCode) { t.Fatalf("a non-bundle should be named as such, not blamed on the code: %v", err) } } // Two seals of the same plaintext under the same code must differ: a fixed // nonce would let two releases' bundles be compared byte for byte. func TestEverySealIsDifferent(t *testing.T) { code, _ := NewCode() a, _ := Seal(code, []byte("same")) b, _ := Seal(code, []byte("same")) if bytes.Equal(a, b) { t.Fatal("nonce is not random") } }