package main import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "testing" ) // A box the agent module's TypeScript sealed opens here: the two implementations are one format. func TestABoxSealedInTypeScriptOpensInGo(t *testing.T) { raw, err := os.ReadFile("testdata/sealed-by-typescript.json") if err != nil { t.Fatal(err) } var f struct { PrivateKey string `json:"privateKey"` Box SealedBox `json:"box"` Plaintext string `json:"plaintext"` } if err := json.Unmarshal(raw, &f); err != nil { t.Fatal(err) } got, err := Open(f.Box, f.PrivateKey) if err != nil || got != f.Plaintext { t.Fatalf("opened %q, %v", got, err) } } // What Go seals opens with its own key and no other. func TestABoxOpensOnlyForItsRecipient(t *testing.T) { a, _ := GenerateKeyPair() b, _ := GenerateKeyPair() box, err := Seal("a token", a.PublicKey) if err != nil { t.Fatal(err) } if got, err := Open(box, a.PrivateKey); err != nil || got != "a token" { t.Fatalf("opened %q, %v", got, err) } if _, err := Open(box, b.PrivateKey); err == nil { t.Fatal("a box opened for another key") } } // design 39 bus-and-switch C2: a key pair the manager finds and cannot read (left by another account, here mode 000) is // replaced in its place by a new one, said in its journal; the new one is read back by the next start. func TestAKeyPairItCannotReadIsMadeAnew(t *testing.T) { if os.Geteuid() == 0 { t.Fatal("run as root, a file of mode 000 is still read: this test needs an ordinary account") } dir := t.TempDir() file := filepath.Join(dir, "manager-key.json") if err := os.WriteFile(file, []byte(`{"publicKey":"old","privateKey":"old"}`), 0o000); err != nil { t.Fatal(err) } var said []string log := func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) } k, err := keypair(dir, log) if err != nil { t.Fatalf("a key pair it cannot read stops the manager: %v", err) } if k.PublicKey == "" || k.PublicKey == "old" || len(said) != 1 || !strings.Contains(said[0], "manager-key.json") { t.Fatalf("not made anew and said: key %q, journal %q", k.PublicKey, said) } again, err := keypair(dir, log) if err != nil || again != k || len(said) != 1 { t.Fatalf("the new pair is not the one read at the next start: %v, %v, %q", again == k, err, said) } }