gunk-dev/the-valley

manifest_test.go

sourcef5c9a830d01emain's published tip history
11.5 KiB
1package export_test
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "strings"
7 "testing"
8 "time"
9
10 "the-valley/note"
11 "the-valley/webui/export"
12 "the-valley/webui/export/exporttest"
13)
14
15// A manifest's text reads back as the manifest it was written from.
16func TestManifestRoundTrip(t *testing.T) {
17 f := exporttest.New(t)
18 m, err := export.ParseManifest(f.Manifest.Text())
19 if err != nil {
20 t.Fatal(err)
21 }
22 if !bytes.Equal(m.Text(), f.Manifest.Text()) {
23 t.Errorf("read back as\n%s\nfrom\n%s", m.Text(), f.Manifest.Text())
24 }
25 if got := strings.SplitN(string(f.Manifest.Text()), "\n", 2)[0]; got != export.ManifestType {
26 t.Errorf("the first line is %q", got)
27 }
28}
29
30// signText signs text as the fixture's publisher would, so a test can
31// sign a manifest a writer would never produce.
32func signText(t *testing.T, text string) []byte {
33 t.Helper()
34 signed, err := note.Sign([]byte(text), exporttest.SignerName, exporttest.Key())
35 if err != nil {
36 t.Fatal(err)
37 }
38 return signed
39}
40
41// variant is the fixture's manifest with one change, signed.
42func variant(t *testing.T, f *exporttest.Fixture, change func(m *export.Manifest)) []byte {
43 t.Helper()
44 m := *f.Manifest
45 m.Projects = append([]export.ManifestProject{}, f.Manifest.Projects...)
46 change(&m)
47 return f.Sign(t, &m)
48}
49
50func wantCode(t *testing.T, err error, code export.Code) {
51 t.Helper()
52 if got := export.CodeOf(err); got != code {
53 t.Fatalf("refused with %q (%v), want %q", got, err, code)
54 }
55}
56
57// Step 1: a manifest is read up to 64 KiB, and one longer is refused
58// without being opened.
59func TestVerifyManifestReadsAtMost64KiB(t *testing.T) {
60 f := exporttest.New(t)
61 long := append(bytes.Repeat([]byte("x"), export.MaxManifest+1-len(f.Signed)), f.Signed...)
62 _, err := export.VerifyManifest(bytes.NewReader(long), f.Admission())
63 wantCode(t, err, export.CodeTooLarge)
64 // The cap is on bytes read: a reader that never ends is refused too.
65 _, err = export.VerifyManifest(endless{}, f.Admission())
66 wantCode(t, err, export.CodeTooLarge)
67}
68
69type endless struct{}
70
71func (endless) Read(p []byte) (int, error) {
72 for i := range p {
73 p[i] = 'x'
74 }
75 return len(p), nil
76}
77
78// Step 2: the note opens under the pinned key alone.
79func TestVerifyManifestOpensUnderThePinnedKey(t *testing.T) {
80 f := exporttest.New(t)
81 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, 32))
82 byOther, err := f.Manifest.Sign(exporttest.SignerName, other)
83 if err != nil {
84 t.Fatal(err)
85 }
86 tampered := bytes.Replace(f.Signed, []byte("instance valley-host"), []byte("instance valley-hosT"), 1)
87 for name, signed := range map[string][]byte{
88 "signed by another key": byOther,
89 "text changed": tampered,
90 "no signature": f.Manifest.Text(),
91 } {
92 t.Run(name, func(t *testing.T) {
93 _, err := export.VerifyManifest(bytes.NewReader(signed), f.Admission())
94 wantCode(t, err, export.CodeBadSignature)
95 })
96 }
97}
98
99// Step 3: the first line is exactly the manifest type; a validly signed
100// note of any other type is refused.
101func TestVerifyManifestRequiresTheTypeLine(t *testing.T) {
102 f := exporttest.New(t)
103 rest := strings.SplitN(string(f.Manifest.Text()), "\n", 2)[1]
104 for _, first := range []string{"the-valley/attestation/v1", "the-valley/web-export/v2", "the-valley/web-export/v1 ", ""} {
105 _, err := export.VerifyManifest(bytes.NewReader(signText(t, first+"\n"+rest)), f.Admission())
106 wantCode(t, err, export.CodeBadManifest)
107 }
108}
109
110// Step 4: the instance and the destination are the configured ones.
111func TestVerifyManifestRequiresInstanceAndDestination(t *testing.T) {
112 f := exporttest.New(t)
113 other := variant(t, f, func(m *export.Manifest) { m.Instance = "other-host" })
114 _, err := export.VerifyManifest(bytes.NewReader(other), f.Admission())
115 wantCode(t, err, export.CodeWrongInstance)
116 elsewhere := variant(t, f, func(m *export.Manifest) { m.Destination = "other.example.org" })
117 _, err = export.VerifyManifest(bytes.NewReader(elsewhere), f.Admission())
118 wantCode(t, err, export.CodeWrongDestination)
119}
120
121// Step 5: the sequence is greater than the high-water mark. A replay and
122// an older manifest are both refused as replayed, with the mark.
123func TestVerifyManifestRefusesReplays(t *testing.T) {
124 f := exporttest.New(t)
125 for name, hw := range map[string]int64{"a replay": f.Manifest.Sequence, "an older manifest": f.Manifest.Sequence + 1} {
126 t.Run(name, func(t *testing.T) {
127 a := f.Admission()
128 a.HighWater = hw
129 _, err := export.VerifyManifest(bytes.NewReader(f.Signed), a)
130 wantCode(t, err, export.CodeReplayed)
131 if e := err.(*export.Error); e.HighWater != hw || e.Reply().HighWater != hw {
132 t.Errorf("the refusal gives high water %d, want %d", e.HighWater, hw)
133 }
134 })
135 }
136 a := f.Admission()
137 a.HighWater = f.Manifest.Sequence - 1
138 if _, err := export.VerifyManifest(bytes.NewReader(f.Signed), a); err != nil {
139 t.Errorf("a manifest one past the mark was refused: %v", err)
140 }
141}
142
143// Step 6: the signing time is no more than three days old and no more
144// than a minute ahead, both bounds inclusive.
145func TestVerifyManifestBoundsTheSigningTime(t *testing.T) {
146 f := exporttest.New(t)
147 for _, c := range []struct {
148 now time.Time
149 ok bool
150 }{
151 {exporttest.SignedAt.Add(export.MaxAge), true},
152 {exporttest.SignedAt.Add(export.MaxAge + time.Nanosecond), false},
153 {exporttest.SignedAt.Add(-export.MaxAhead), true},
154 {exporttest.SignedAt.Add(-export.MaxAhead - time.Nanosecond), false},
155 } {
156 a := f.Admission()
157 a.Now = c.now
158 _, err := export.VerifyManifest(bytes.NewReader(f.Signed), a)
159 if c.ok && err != nil {
160 t.Errorf("at %s: %v", c.now, err)
161 }
162 if !c.ok {
163 wantCode(t, err, export.CodeOutOfWindow)
164 }
165 }
166}
167
168// The steps run in their order: a manifest wrong in several ways is
169// refused by the earliest step that applies.
170func TestVerifyManifestRunsItsStepsInOrder(t *testing.T) {
171 f := exporttest.New(t)
172 late := f.Admission()
173 late.Now = exporttest.SignedAt.Add(30 * 24 * time.Hour)
174 late.HighWater = f.Manifest.Sequence
175 late.Instance = "other-host"
176 steps := []export.Code{export.CodeWrongInstance, export.CodeReplayed, export.CodeOutOfWindow}
177 for _, want := range steps {
178 _, err := export.VerifyManifest(bytes.NewReader(f.Signed), late)
179 wantCode(t, err, want)
180 switch want {
181 case export.CodeWrongInstance:
182 late.Instance = exporttest.Instance
183 case export.CodeReplayed:
184 late.HighWater = 0
185 }
186 }
187 other := late
188 other.Verifiers = []note.VerifierKey{note.NewVerifierKey("someone-else", ed25519.NewKeyFromSeed(bytes.Repeat([]byte{9}, 32)).Public().(ed25519.PublicKey))}
189 _, err := export.VerifyManifest(bytes.NewReader(f.Signed), other)
190 wantCode(t, err, export.CodeBadSignature)
191}
192
193// The manifest's grammar: every record once where it must be, no unsafe
194// name, and each field in its shape.
195func TestParseManifestRefuses(t *testing.T) {
196 f := exporttest.New(t)
197 text := string(f.Manifest.Text())
198 line := func(prefix string) string {
199 for _, l := range strings.Split(text, "\n") {
200 if strings.HasPrefix(l, prefix) {
201 return l
202 }
203 }
204 t.Fatalf("no line opens with %q", prefix)
205 return ""
206 }
207 project, bundle := line("project app "), line("bundle app ")
208 sha := strings.Fields(bundle)[2]
209 replace := func(old, new string) string { return strings.Replace(text, old, new, 1) }
210 cases := map[string]string{
211 "a second instance": text + "instance valley-host\n",
212 "a second destination": text + "destination example.org\n",
213 "a second sequence": text + "sequence 1\n",
214 "a second file": text + line("file ") + "\n",
215 "a second project record": text + project + "\n",
216 "a second bundle record": text + bundle + "\n",
217 "a bundle with no project": text + "bundle other " + sha + " 10\n",
218 "a project with no bundle": replace(bundle+"\n", ""),
219 "no instance": replace("instance valley-host\n", ""),
220 "no file": replace(line("file ")+"\n", ""),
221 "a dot-dot project": strings.ReplaceAll(text, " app ", " .. "),
222 "a dot project": strings.ReplaceAll(text, " app ", " . "),
223 "a project with a slash": strings.ReplaceAll(text, " app ", " a/b "),
224 "a project climbing out": strings.ReplaceAll(text, " app ", " ../app "),
225 "a hidden file's name": strings.ReplaceAll(text, " app ", " .git "),
226 "an instance with a slash": replace("instance valley-host", "instance valley/host"),
227 "another file": replace("file export.json", "file other.json"),
228 "a file climbing out": replace("file export.json", "file ../export.json"),
229 "an unknown record": text + "comment hello\n",
230 "a blank line": replace("\nfile ", "\n\nfile "),
231 "a field too many": replace(project, project+" extra"),
232 "two spaces": replace("instance valley-host", "instance valley-host"),
233 "a sequence of zero": replace(line("sequence "), "sequence 0"),
234 "a sequence with a sign": replace(line("sequence "), "sequence +1"),
235 "a sequence past int64": replace(line("sequence "), "sequence 99999999999999999999"),
236 "a size with a leading zero": replace(bundle, strings.Join(append(strings.Fields(bundle)[:3], "0"+strings.Fields(bundle)[3]), " ")),
237 "a hash in uppercase": replace(sha, strings.ToUpper(sha)),
238 "a short hash": replace(sha, sha[:63]),
239 "a private project": replace(" public ", " private "),
240 "a short source tip": replace(project, project[:len(project)-1]),
241 "no closing newline": strings.TrimSuffix(text, "\n"),
242 "one hash with two sizes": text + "project other public - " + f.Export.Projects[0].SourceTip + "\nbundle other " + sha + " 1\n",
243 }
244 for name, text := range cases {
245 t.Run(name, func(t *testing.T) {
246 _, err := export.ParseManifest([]byte(text))
247 wantCode(t, err, export.CodeBadManifest)
248 })
249 }
250 // Records may come in any order, and a project with no graph has -.
251 lines := strings.Split(strings.TrimSuffix(text, "\n"), "\n")
252 reordered := append([]string{lines[0]}, append(lines[4:], lines[1:4]...)...)
253 if _, err := export.ParseManifest([]byte(strings.Join(reordered, "\n") + "\n")); err != nil {
254 t.Errorf("records in another order: %v", err)
255 }
256 if m, err := export.ParseManifest([]byte(strings.Replace(text, f.Export.Projects[0].GraphTip, "-", 1))); err != nil || m.Projects[0].GraphTip != "" {
257 t.Errorf("a project with no graph: %v", err)
258 }
259}
260
261// export.json agrees with the manifest: its hash and size, and every
262// project with its visibility and both tips.
263func TestCheckExport(t *testing.T) {
264 f := exporttest.New(t)
265 if _, err := f.Manifest.CheckExport(f.ExportJSON); err != nil {
266 t.Fatal(err)
267 }
268 disagree := map[string]func(m *export.Manifest){
269 "a source tip": func(m *export.Manifest) { m.Projects[0].SourceTip = strings.Repeat("0", 40) },
270 "a graph tip": func(m *export.Manifest) { m.Projects[0].GraphTip = "" },
271 "the project": func(m *export.Manifest) { m.Projects[0].Name = "other" },
272 "a project more": func(m *export.Manifest) { m.Projects = append(m.Projects, export.ManifestProject{Name: "zzz"}) },
273 }
274 for name, change := range disagree {
275 t.Run(name, func(t *testing.T) {
276 m := *f.Manifest
277 m.Projects = append([]export.ManifestProject{}, f.Manifest.Projects...)
278 change(&m)
279 _, err := m.CheckExport(f.ExportJSON)
280 wantCode(t, err, export.CodeBadExport)
281 })
282 }
283 _, err := f.Manifest.CheckExport(append(append([]byte{}, f.ExportJSON...), ' '))
284 wantCode(t, err, export.CodeHashMismatch)
285
286 // A valid export.json that names the right hash but not the manifest's
287 // projects is caught by the agreement, not the hash.
288 other := *f.Export
289 other.Projects = nil
290 data, err := other.Encode()
291 if err != nil {
292 t.Fatal(err)
293 }
294 m := *f.Manifest
295 m.File = export.BodyOf(export.ExportFile, data)
296 _, err = m.CheckExport(data)
297 wantCode(t, err, export.CodeBadExport)
298}