| 1 | package appconfig |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | // TestRenderHeldBeforeAnswersTheHashBeforeTheWrite (moves Plan 5 Task 9a, |
| 12 | // fix round 1, I1): the caller learns the sha256 of the exact bytes the |
| 13 | // render is about to place, before anything is written, so it can journal |
| 14 | // its ownership first; the write that follows places those bytes; a refusal |
| 15 | // from the callback writes nothing and sends no ack. |
| 16 | func TestRenderHeldBeforeAnswersTheHashBeforeTheWrite(t *testing.T) { |
| 17 | ctx, s, reg, dd, privB64, _ := execKit(t) |
| 18 | priv, err := ParsePrivateKey(privB64, "test") |
| 19 | if err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | heldFixture(t, ctx, s) |
| 23 | rt := landingRow() |
| 24 | if err := reg.Upsert(rt); err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | path := ConfigEnvPath(dd, rt) |
| 28 | |
| 29 | refused := errors.New("the journal refused") |
| 30 | if _, err := RenderHeldBefore(ctx, s, priv, dd, rt, heldOp, heldBox, func(string) error { return refused }); !errors.Is(err, refused) { |
| 31 | t.Fatalf("a refusing callback: %v", err) |
| 32 | } |
| 33 | if _, err := os.Stat(path); !os.IsNotExist(err) { |
| 34 | t.Fatalf("a refused render wrote the file: %v", err) |
| 35 | } |
| 36 | if _, _, err := s.Get(ctx, ConfigAckKey(heldBox, heldHost)); err == nil { |
| 37 | t.Fatal("a refused render wrote the ack") |
| 38 | } |
| 39 | |
| 40 | var told string |
| 41 | got, err := RenderHeldBefore(ctx, s, priv, dd, rt, heldOp, heldBox, func(sha string) error { |
| 42 | if _, err := os.Stat(path); !os.IsNotExist(err) { |
| 43 | t.Errorf("the file was there before the callback: %v", err) |
| 44 | } |
| 45 | told = sha |
| 46 | return nil |
| 47 | }) |
| 48 | if err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | body, err := os.ReadFile(path) |
| 52 | if err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | sum := sha256.Sum256(body) |
| 56 | if want := hex.EncodeToString(sum[:]); told != want || got.SHA256 != want { |
| 57 | t.Fatalf("callback %q, render %q, file %q", told, got.SHA256, want) |
| 58 | } |
| 59 | if a := readAck(t, ctx, s); a.FileSHA256 != told { |
| 60 | t.Fatalf("ack %q, callback %q", a.FileSHA256, told) |
| 61 | } |
| 62 | } |
| 63 | |