| 1 | package contract_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "math" |
| 9 | "os" |
| 10 | "reflect" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "github.com/carlosframework/docs/internal/contract" |
| 15 | "github.com/carlosframework/docs/internal/export" |
| 16 | ) |
| 17 | |
| 18 | func field(key string) contract.Node { |
| 19 | return contract.Node{Type: "merge_field", Attrs: contract.Attrs{Key: key}} |
| 20 | } |
| 21 | |
| 22 | func template() contract.Template { |
| 23 | return contract.Template{Version: 1, Title: "Service agreement", Fields: []contract.Field{ |
| 24 | {Key: "customer", Label: "Customer name", Kind: contract.Text}, |
| 25 | {Key: "start", Label: "Start date", Kind: contract.Date}, |
| 26 | {Key: "fee", Label: "Fee", Kind: contract.Money, Currency: "EUR"}, |
| 27 | }, Root: contract.Node{Type: "doc", Content: []contract.Node{ |
| 28 | {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Prepared for "}, field("customer")}}, |
| 29 | {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Effective "}, field("start")}}, |
| 30 | {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Fee: "}, field("fee")}}, |
| 31 | {Type: "paragraph", Content: []contract.Node{{Type: "text", Text: "Accepted by "}, field("customer")}}, |
| 32 | }}} |
| 33 | } |
| 34 | |
| 35 | func values() map[string]contract.Value { |
| 36 | return map[string]contract.Value{ |
| 37 | "customer": {Kind: contract.Text, Text: "Acme Workshops"}, |
| 38 | "start": {Kind: contract.Date, Text: "2028-02-29"}, |
| 39 | "fee": {Kind: contract.Money, MinorUnits: 125050, Currency: "EUR"}, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func code(t *testing.T, err error, want string) { |
| 44 | t.Helper() |
| 45 | var d *contract.Diagnostic |
| 46 | if !errors.As(err, &d) || d.Code != want { |
| 47 | t.Fatalf("error = %v, want code %s", err, want) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func text(n export.Node) string { |
| 52 | s := n.Text |
| 53 | for _, c := range n.Content { |
| 54 | s += text(c) |
| 55 | } |
| 56 | return s |
| 57 | } |
| 58 | |
| 59 | func TestResolveSubstitutesStructuralFieldsWithoutChangingInputs(t *testing.T) { |
| 60 | t.Parallel() |
| 61 | tpl, vals := template(), values() |
| 62 | tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "strong"}} |
| 63 | before, _ := json.Marshal(tpl) |
| 64 | doc, err := contract.Resolve(tpl, vals, contract.ISOFormat) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | got := text(doc.Root) |
| 69 | if strings.Count(got, "Acme Workshops") != 2 || !strings.Contains(got, "2028-02-29") || !strings.Contains(got, "EUR 1250.50") { |
| 70 | t.Fatal(got) |
| 71 | } |
| 72 | if doc.Root.Content[0].Content[1].Marks[0].Type != "strong" { |
| 73 | t.Fatal("lost field formatting") |
| 74 | } |
| 75 | // Mutating the returned slices must not edit the template's slices. |
| 76 | doc.Root.Content[0].Content[1].Marks[0].Type = "em" |
| 77 | doc.Root.Content[0].Content[0].Text = "changed" |
| 78 | after, _ := json.Marshal(tpl) |
| 79 | if !bytes.Equal(before, after) || !reflect.DeepEqual(vals, values()) { |
| 80 | t.Fatal("inputs mutated") |
| 81 | } |
| 82 | tpl.Fields[0].Label = "Renamed label" |
| 83 | again, err := contract.Resolve(tpl, vals, contract.ISOFormat) |
| 84 | if err != nil || text(again.Root) != got { |
| 85 | t.Fatal("label rename changed binding", err) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func TestValuesAreLiteralAndZeroIsPresent(t *testing.T) { |
| 90 | t.Parallel() |
| 91 | v := values() |
| 92 | v["customer"] = contract.Value{Kind: contract.Text, Text: `<script>{{fee}}</script>`} |
| 93 | v["fee"] = contract.Value{Kind: contract.Money, Currency: "EUR"} |
| 94 | doc, err := contract.Resolve(template(), v, contract.ISOFormat) |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | if !strings.Contains(text(doc.Root), `<script>{{fee}}</script>`) || !strings.Contains(text(doc.Root), "EUR 0.00") { |
| 99 | t.Fatal(text(doc.Root)) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | func TestMultilineValuesPreserveLineBreaks(t *testing.T) { |
| 104 | t.Parallel() |
| 105 | v := values() |
| 106 | v["customer"] = contract.Value{Kind: contract.Text, Text: "Acme\nWorkshop\n"} |
| 107 | doc, err := contract.Resolve(template(), v, contract.ISOFormat) |
| 108 | if err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | nodes := doc.Root.Content[0].Content |
| 112 | if len(nodes) != 5 || nodes[1].Text != "Acme" || nodes[2].Type != "hard_break" || nodes[3].Text != "Workshop" || nodes[4].Type != "hard_break" { |
| 113 | t.Fatalf("lost line breaks: %#v", nodes) |
| 114 | } |
| 115 | v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("a\n", 6000)} |
| 116 | _, err = contract.Resolve(template(), v, contract.ISOFormat) |
| 117 | code(t, err, "expanded_node_limit") |
| 118 | } |
| 119 | |
| 120 | func TestMissingEmptyAndWrongValuesRefuseWithoutDocument(t *testing.T) { |
| 121 | t.Parallel() |
| 122 | cases := []struct { |
| 123 | name, key, code string |
| 124 | value contract.Value |
| 125 | remove bool |
| 126 | }{ |
| 127 | {"absent", "customer", "required_value", contract.Value{}, true}, |
| 128 | {"empty", "customer", "required_value", contract.Value{Kind: contract.Text}, false}, |
| 129 | {"space", "customer", "required_value", contract.Value{Kind: contract.Text, Text: " \n "}, false}, |
| 130 | {"kind", "customer", "value_type", contract.Value{Kind: contract.Date, Text: "2026-01-01"}, false}, |
| 131 | {"bad leap", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2027-02-29"}, false}, |
| 132 | {"timestamp", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "2028-02-29T00:00:00Z"}, false}, |
| 133 | {"year zero", "start", "invalid_date", contract.Value{Kind: contract.Date, Text: "0000-01-01"}, false}, |
| 134 | {"currency", "fee", "currency_mismatch", contract.Value{Kind: contract.Money, Currency: "GBP"}, false}, |
| 135 | {"unused money", "customer", "unexpected_money", contract.Value{Kind: contract.Text, Text: "Acme", MinorUnits: 1}, false}, |
| 136 | {"invalid unicode", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "\xff"}, false}, |
| 137 | {"control", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: "secret\x00"}, false}, |
| 138 | {"oversized", "customer", "invalid_value", contract.Value{Kind: contract.Text, Text: strings.Repeat("x", contract.MaxValueBytes+1)}, false}, |
| 139 | } |
| 140 | for _, tc := range cases { |
| 141 | t.Run(tc.name, func(t *testing.T) { |
| 142 | v := values() |
| 143 | if tc.remove { |
| 144 | delete(v, tc.key) |
| 145 | } else { |
| 146 | v[tc.key] = tc.value |
| 147 | } |
| 148 | doc, err := contract.Resolve(template(), v, contract.ISOFormat) |
| 149 | code(t, err, tc.code) |
| 150 | if !reflect.DeepEqual(doc, export.Document{}) { |
| 151 | t.Fatal("partial result returned") |
| 152 | } |
| 153 | if strings.Contains(err.Error(), "secret") { |
| 154 | t.Fatal("error leaked value") |
| 155 | } |
| 156 | }) |
| 157 | } |
| 158 | |
| 159 | tpl, v := template(), values() |
| 160 | tpl.Fields[0].Optional = true |
| 161 | delete(v, "customer") |
| 162 | doc, err := contract.Resolve(tpl, v, contract.ISOFormat) |
| 163 | if err != nil || len(doc.Root.Content[0].Content) != 1 { |
| 164 | t.Fatal("optional missing field", err) |
| 165 | } |
| 166 | v["customer"] = contract.Value{Kind: contract.Text} |
| 167 | if _, err := contract.Resolve(tpl, v, contract.ISOFormat); err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | v["unknown_secret_key"] = contract.Value{Kind: contract.Text} |
| 171 | _, err = contract.Resolve(tpl, v, contract.ISOFormat) |
| 172 | code(t, err, "unexpected_values") |
| 173 | if strings.Contains(err.Error(), "unknown_secret_key") { |
| 174 | t.Fatal("untrusted key leaked") |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func TestMoneyUsesExactMinorUnits(t *testing.T) { |
| 179 | t.Parallel() |
| 180 | for _, tc := range []struct { |
| 181 | currency string |
| 182 | minor int64 |
| 183 | want string |
| 184 | }{ |
| 185 | {"EUR", math.MinInt64, "EUR -92233720368547758.08"}, |
| 186 | {"EUR", math.MaxInt64, "EUR 92233720368547758.07"}, |
| 187 | {"EUR", -1, "EUR -0.01"}, {"JPY", 100, "JPY 100"}, |
| 188 | {"KWD", 1, "KWD 0.001"}, {"KWD", 1234567, "KWD 1234.567"}, |
| 189 | } { |
| 190 | t.Run(tc.want, func(t *testing.T) { |
| 191 | tpl, v := template(), values() |
| 192 | tpl.Fields[2].Currency = tc.currency |
| 193 | v["fee"] = contract.Value{Kind: contract.Money, Currency: tc.currency, MinorUnits: tc.minor} |
| 194 | doc, err := contract.Resolve(tpl, v, contract.ISOFormat) |
| 195 | if err != nil || !strings.Contains(text(doc.Root), tc.want) { |
| 196 | t.Fatal(text(doc.Root), err) |
| 197 | } |
| 198 | }) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | func TestTemplateValidation(t *testing.T) { |
| 203 | t.Parallel() |
| 204 | for _, tc := range []struct { |
| 205 | name, code string |
| 206 | change func(*contract.Template) |
| 207 | }{ |
| 208 | {"version", "unsupported_version", func(t *contract.Template) { t.Version = 2 }}, |
| 209 | {"title", "invalid_title", func(t *contract.Template) { t.Title = "\xff" }}, |
| 210 | {"duplicate", "duplicate_field", func(t *contract.Template) { t.Fields = append(t.Fields, t.Fields[0]) }}, |
| 211 | {"unused", "unused_field", func(t *contract.Template) { |
| 212 | t.Fields = append(t.Fields, contract.Field{Key: "unused", Label: "Unused", Kind: contract.Text}) |
| 213 | }}, |
| 214 | {"currency", "invalid_currency", func(t *contract.Template) { t.Fields[2].Currency = "xxx" }}, |
| 215 | {"unknown", "unknown_field", func(t *contract.Template) { t.Root.Content[0].Content[1].Attrs.Key = "absent" }}, |
| 216 | {"image", "unsupported_structure", func(t *contract.Template) { t.Root.Content[0].Content[0].Type = "image" }}, |
| 217 | {"leaf children", "unexpected_children", func(t *contract.Template) { t.Root.Content[0].Content[0].Content = []contract.Node{field("fee")} }}, |
| 218 | {"no children", "missing_children", func(t *contract.Template) { t.Root.Content = nil }}, |
| 219 | {"bad heading", "invalid_heading", func(t *contract.Template) { t.Root.Content[0].Type = "heading" }}, |
| 220 | {"block marks", "unexpected_marks", func(t *contract.Template) { t.Root.Marks = []export.Mark{{Type: "strong"}} }}, |
| 221 | {"unknown mark", "unsupported_mark", func(t *contract.Template) { t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "link"}} }}, |
| 222 | {"two sizes", "conflicting_marks", func(t *contract.Template) { |
| 223 | t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "size_8"}, {Type: "size_14"}} |
| 224 | }}, |
| 225 | {"two fonts", "conflicting_marks", func(t *contract.Template) { |
| 226 | t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "font_sans"}, {Type: "font_mono"}} |
| 227 | }}, |
| 228 | {"code font", "conflicting_marks", func(t *contract.Template) { |
| 229 | t.Root.Content[0].Content[0].Marks = []export.Mark{{Type: "code"}, {Type: "font_sans"}} |
| 230 | }}, |
| 231 | {"indent", "invalid_indent", func(t *contract.Template) { t.Root.Content[0].Attrs.Indent = 9 }}, |
| 232 | {"alignment", "invalid_alignment", func(t *contract.Template) { t.Root.Content[0].Attrs.Align = "justify" }}, |
| 233 | } { |
| 234 | t.Run(tc.name, func(t *testing.T) { |
| 235 | tpl := template() |
| 236 | tc.change(&tpl) |
| 237 | code(t, tpl.Validate(), tc.code) |
| 238 | }) |
| 239 | } |
| 240 | _, err := contract.Resolve(template(), values(), "en-IE") |
| 241 | code(t, err, "unsupported_format") |
| 242 | } |
| 243 | |
| 244 | func TestStrictJSON(t *testing.T) { |
| 245 | t.Parallel() |
| 246 | b, _ := json.Marshal(template()) |
| 247 | parsed, err := contract.Parse(b) |
| 248 | if err != nil || !reflect.DeepEqual(parsed, template()) { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | for _, input := range [][]byte{ |
| 252 | append(append([]byte(nil), b...), []byte(` {}`)...), |
| 253 | []byte(strings.Replace(string(b), `"version":1`, `"version":1,"version":1`, 1)), |
| 254 | []byte(strings.Replace(string(b), `"version":1`, `"version":1,"unexpected":"secret"`, 1)), |
| 255 | []byte(strings.Replace(string(b), `"Service agreement"`, `"\ud800"`, 1)), |
| 256 | []byte(strings.Replace(string(b), `"paragraph"`, `"paragraph","attrs":{"surprise":true}`, 1)), |
| 257 | } { |
| 258 | _, err := contract.Parse(input) |
| 259 | code(t, err, "invalid_json") |
| 260 | } |
| 261 | _, err = contract.Parse(bytes.Repeat([]byte(" "), contract.MaxTemplateBytes+1)) |
| 262 | code(t, err, "template_too_large") |
| 263 | } |
| 264 | |
| 265 | func TestResourceBounds(t *testing.T) { |
| 266 | t.Parallel() |
| 267 | tpl := template() |
| 268 | for i := 0; i <= contract.MaxDepth; i++ { |
| 269 | tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}} |
| 270 | } |
| 271 | code(t, tpl.Validate(), "tree_limit") |
| 272 | tpl = template() |
| 273 | tpl.Root.Content = append(tpl.Root.Content, make([]contract.Node, contract.MaxNodes)...) |
| 274 | for i := 4; i < len(tpl.Root.Content); i++ { |
| 275 | tpl.Root.Content[i] = contract.Node{Type: "paragraph"} |
| 276 | } |
| 277 | code(t, tpl.Validate(), "tree_limit") |
| 278 | tpl = template() |
| 279 | for i := 0; i < 20; i++ { |
| 280 | tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer")) |
| 281 | } |
| 282 | v := values() |
| 283 | v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)} |
| 284 | _, err := contract.Resolve(tpl, v, contract.ISOFormat) |
| 285 | code(t, err, "expanded_text_limit") |
| 286 | } |
| 287 | |
| 288 | func TestRenderPDF(t *testing.T) { |
| 289 | t.Parallel() |
| 290 | p, err := contract.Render(template(), values(), contract.ISOFormat) |
| 291 | if err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | if !bytes.HasPrefix(p.PDF, []byte("%PDF-")) || !bytes.Contains(p.PDF, []byte("%%EOF")) || p.SHA256 != sha256.Sum256(p.PDF) { |
| 295 | t.Fatal("invalid PDF or digest") |
| 296 | } |
| 297 | if p.TemplateVersion != 1 || p.Renderer == "" { |
| 298 | t.Fatal("missing version") |
| 299 | } |
| 300 | // Optional local QA artifact, always using the fictional fixture above. |
| 301 | // The independent pdftotext check is run against these exact output bytes. |
| 302 | if path := os.Getenv("CONTRACT_PREVIEW_PDF"); path != "" { |
| 303 | if err := os.WriteFile(path, p.PDF, 0600); err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | func TestRenderRefusesLossyPDF(t *testing.T) { |
| 310 | t.Parallel() |
| 311 | t.Run("missing glyph", func(t *testing.T) { |
| 312 | v := values() |
| 313 | v["customer"] = contract.Value{Kind: contract.Text, Text: "\U0010ffff"} |
| 314 | p, err := contract.Render(template(), v, contract.ISOFormat) |
| 315 | code(t, err, "missing_glyphs") |
| 316 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 317 | t.Fatal("partial artifact") |
| 318 | } |
| 319 | }) |
| 320 | t.Run("nested indentation", func(t *testing.T) { |
| 321 | tpl := template() |
| 322 | tpl.Root.Content[0].Attrs.Indent = 8 |
| 323 | for i := 0; i < 20; i++ { |
| 324 | tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}} |
| 325 | } |
| 326 | p, err := contract.Render(tpl, values(), contract.ISOFormat) |
| 327 | code(t, err, "layout_overflow") |
| 328 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 329 | t.Fatal("partial artifact") |
| 330 | } |
| 331 | }) |
| 332 | t.Run("single glyph wider than column", func(t *testing.T) { |
| 333 | tpl, v := template(), values() |
| 334 | tpl.Root.Content[0].Attrs.Indent = 8 |
| 335 | tpl.Root.Content[0].Content[1].Marks = []export.Mark{{Type: "size_72"}} |
| 336 | v["customer"] = contract.Value{Kind: contract.Text, Text: "W"} |
| 337 | for i := 0; i < 14; i++ { |
| 338 | tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}} |
| 339 | } |
| 340 | p, err := contract.Render(tpl, v, contract.ISOFormat) |
| 341 | code(t, err, "layout_overflow") |
| 342 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 343 | t.Fatal("partial artifact") |
| 344 | } |
| 345 | }) |
| 346 | } |
| 347 | |
| 348 | func TestRenderWorkLimits(t *testing.T) { |
| 349 | t.Parallel() |
| 350 | for _, literal := range []bool{false, true} { |
| 351 | tpl, v := template(), values() |
| 352 | long := strings.Repeat("x", contract.MaxWordBytes+1) |
| 353 | if literal { |
| 354 | tpl.Root.Content[0].Content[0].Text = long |
| 355 | } else { |
| 356 | v["customer"] = contract.Value{Kind: contract.Text, Text: long} |
| 357 | } |
| 358 | p, err := contract.Render(tpl, v, contract.ISOFormat) |
| 359 | code(t, err, "word_limit") |
| 360 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 361 | t.Fatal("partial output") |
| 362 | } |
| 363 | } |
| 364 | tpl, v := template(), values() |
| 365 | v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("x ", contract.MaxValueBytes/2)} |
| 366 | tpl.Root.Content[0].Content = append(tpl.Root.Content[0].Content, field("customer")) |
| 367 | p, err := contract.Render(tpl, v, contract.ISOFormat) |
| 368 | code(t, err, "render_text_limit") |
| 369 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 370 | t.Fatal("partial output") |
| 371 | } |
| 372 | |
| 373 | tpl = template() |
| 374 | // Empty paragraphs are real blank lines: byte caps alone cannot bound pages. |
| 375 | for i := 0; i < 5000; i++ { |
| 376 | tpl.Root.Content = append(tpl.Root.Content, contract.Node{Type: "paragraph"}) |
| 377 | } |
| 378 | p, err = contract.Render(tpl, values(), contract.ISOFormat) |
| 379 | code(t, err, "page_limit") |
| 380 | if !reflect.DeepEqual(p, contract.Preview{}) { |
| 381 | t.Fatal("truncated output") |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | func TestLongestWordInNarrowColumn(t *testing.T) { |
| 386 | t.Parallel() |
| 387 | tpl, v := template(), values() |
| 388 | tpl.Root.Content[0].Attrs.Indent = 8 |
| 389 | // 468pt content - 288pt paragraph indent - 14*12pt quote indent = |
| 390 | // 12pt remaining. A regular W fits, but nearly every glyph wraps. |
| 391 | for i := 0; i < 14; i++ { |
| 392 | tpl.Root.Content = []contract.Node{{Type: "blockquote", Content: tpl.Root.Content}} |
| 393 | } |
| 394 | v["customer"] = contract.Value{Kind: contract.Text, Text: strings.Repeat("W", contract.MaxWordBytes)} |
| 395 | p, err := contract.Render(tpl, v, contract.ISOFormat) |
| 396 | if err != nil || len(p.PDF) == 0 { |
| 397 | t.Fatal(err) |
| 398 | } |
| 399 | } |
| 400 | |