package domain import ( "errors" "fmt" "strings" "testing" "time" ) // maxRejectionTime is a generous bound for refusing a hostile template. The // refusal reads at most a few kilobytes and never runs the template, so it // takes microseconds; a template that was executed would not finish. const maxRejectionTime = time.Second func TestStatementTemplateAllowsOnlyPlaceholders(t *testing.T) { algorithm := assessmentAlgorithms["lru_hits.v1"] const complete = "{{.capacity}} {{.sequence}}" tests := map[string]string{ "define": complete + `{{define "x"}}y{{end}}`, "template call": complete + `{{template "x"}}`, "block": complete + `{{block "x" .}}y{{end}}`, "range": complete + `{{range .}}x{{end}}`, "with": complete + `{{with .capacity}}x{{end}}`, "if": complete + `{{if .capacity}}x{{end}}`, "variable": complete + `{{$x := .capacity}}`, "printf call": complete + `{{printf "%d" 1}}`, "pipeline": complete + `{{.capacity | len}}`, "nested field": complete + `{{.capacity.x}}`, "dot": complete + `{{.}}`, "string literal": complete + `{{"x"}}`, "unknown placeholder": complete + `{{.nothing}}`, "placeholder of another": complete + `{{.timestamps}}`, "unclosed action": complete + `{{.keys`, "template above size cap": complete + strings.Repeat("x", maxStatementTemplateBytes), } for name, text := range tests { t.Run(name, func(t *testing.T) { if _, err := compileStatementTemplate("test", text, algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err) } }) } if _, err := compileStatementTemplate("test", "Capacity {{.capacity}}; reads {{.sequence}}; keys 1..{{.keys}}.", algorithm); err != nil { t.Fatalf("compileStatementTemplate(plain placeholders) error = %v", err) } } func TestStatementTemplateBombsAreRefusedFast(t *testing.T) { algorithm := assessmentAlgorithms["lru_hits.v1"] // Each template calls the one below it twice: executed, the last of 20 // levels would run about a million bodies. var nested strings.Builder nested.WriteString(`{{define "t0"}}x{{end}}`) for level := 1; level < 20; level++ { fmt.Fprintf(&nested, `{{define "t%d"}}{{template "t%d"}}{{template "t%d"}}{{end}}`, level, level-1, level-1) } nested.WriteString(`{{template "t19"}}`) // A width of a hundred million spaces from a few bytes of template. widthBomb := `{{.capacity}} {{.sequence}}{{printf "%99999999d" 1}}` for name, text := range map[string]string{ "nested define bomb": nested.String(), "printf width bomb": widthBomb, "small nested define": `{{.capacity}} {{.sequence}}{{define "a"}}{{template "a"}}{{end}}{{template "a"}}`, "range over a number": `{{.capacity}} {{.sequence}}{{range 100000000}}x{{end}}`, "recursive block call": `{{.capacity}} {{.sequence}}{{block "b" .}}{{template "b" .}}{{end}}`, } { t.Run(name, func(t *testing.T) { started := time.Now() _, err := compileStatementTemplate("test", text, algorithm) if !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("compileStatementTemplate() error = %v, want ErrInvalidAssessmentFamily", err) } if elapsed := time.Since(started); elapsed > maxRejectionTime { t.Fatalf("compileStatementTemplate() took %s, want a refusal within %s", elapsed, maxRejectionTime) } }) } } func TestStatementTemplateMustShowTheInput(t *testing.T) { for name, algorithm := range assessmentAlgorithms { t.Run(name, func(t *testing.T) { var all strings.Builder for _, required := range algorithm.requiredNames { all.WriteString("{{." + required + "}} ") } if _, err := compileStatementTemplate("test", strings.TrimSpace(all.String()), algorithm); err != nil { t.Fatalf("compileStatementTemplate(all required names) error = %v", err) } for index, missing := range algorithm.requiredNames { var partial strings.Builder for other, required := range algorithm.requiredNames { if other != index { partial.WriteString("{{." + required + "}} ") } } partial.WriteString("Compute the answer.") if _, err := compileStatementTemplate("test", partial.String(), algorithm); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("compileStatementTemplate(without %s) error = %v, want ErrInvalidAssessmentFamily", missing, err) } } }) } } func TestStatementRenderIsBounded(t *testing.T) { statement := statementTemplate{{literal: strings.Repeat("x", maxStatementBytes)}, {field: "name"}} if _, err := statement.render(map[string]string{"name": "y"}); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("render(above the bound) error = %v, want ErrInvalidAssessmentFamily", err) } if got, err := (statementTemplate{{literal: "a"}, {field: "name"}}).render(map[string]string{"name": "b"}); err != nil || got != "ab" { t.Fatalf("render() = %q, %v, want %q", got, err, "ab") } } func TestInvisibleFormatCharactersAreRefused(t *testing.T) { for name, mutate := range map[string]func(*NewAssessmentFamilyDraftInput){ "bidi override in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache \u202Etest" }, "zero width space in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u200Btest" }, "bidi override in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u202E" }, "format character in the rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Principle = "Compare\u2066 it." }, "line separator in the title": func(input *NewAssessmentFamilyDraftInput) { input.Title = "Cache\u2028test" }, "paragraph separator in the rubric": func(input *NewAssessmentFamilyDraftInput) { input.Rubric.Criteria[0].Description = "Matches\u2029the answer." }, "line separator in the template": func(input *NewAssessmentFamilyDraftInput) { input.Generator.StatementTemplate += "\u2028" }, } { t.Run(name, func(t *testing.T) { input := testAssessmentInput() mutate(&input) if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("NewAssessmentFamilyDraft() error = %v, want ErrInvalidAssessmentFamily", err) } }) } } // goldenVariant is one fixed seed of one algorithm with its exact output. // The statements and answers are the contract that stored families depend // on: a change of an algorithm that moves any of them must be a new // versioned algorithm, not an edit. type goldenVariant struct { algorithm string parameters map[string]AssessmentParameterRange template string seed VariantSeed statement string answer string } func TestGoldenVariantsOfEveryAlgorithm(t *testing.T) { golden := []goldenVariant{ { algorithm: "rate_limit_window.v1", parameters: map[string]AssessmentParameterRange{"requests": {Min: 8, Max: 8}, "window": {Min: 4, Max: 4}, "limit": {Min: 2, Max: 2}, "max_gap": {Min: 0, Max: 3}}, template: "n={{.requests}} w={{.window}} l={{.limit}} t={{.timestamps}}", seed: 12345, statement: "n=8 w=4 l=2 t=0 0 1 2 2 3 4 6", answer: "4", }, { algorithm: "dedup_window.v1", parameters: map[string]AssessmentParameterRange{"events": {Min: 8, Max: 8}, "keys": {Min: 3, Max: 3}, "ttl": {Min: 5, Max: 5}, "max_gap": {Min: 1, Max: 3}}, template: "n={{.events}} k={{.keys}} ttl={{.ttl}} s={{.stream}}", seed: 12345, statement: "n=8 k=3 ttl=5 s=C@2 A@4 A@6 C@6 C@8 C@9 A@12 A@12", answer: "4", }, { algorithm: "lru_hits.v1", parameters: map[string]AssessmentParameterRange{"accesses": {Min: 10, Max: 10}, "keys": {Min: 4, Max: 4}, "capacity": {Min: 2, Max: 2}}, template: "n={{.accesses}} k={{.keys}} c={{.capacity}} s={{.sequence}}", seed: 12345, statement: "n=10 k=4 c=2 s=4 1 1 1 4 3 4 2 4 2", answer: "6", }, { algorithm: "dependency_order.v1", parameters: map[string]AssessmentParameterRange{"tasks": {Min: 6, Max: 6}, "links": {Min: 5, Max: 5}}, template: "n={{.tasks}} l={{.links}} d={{.dependencies}}", seed: 12345, statement: "n=6 l=5 d=3->4 1->3 2->5 2->3", answer: "1 2 3 4 5 6", }, } for _, want := range golden { t.Run(want.algorithm, func(t *testing.T) { input := testAssessmentInput() input.Generator = AssessmentSeedGenerator{Algorithm: want.algorithm, Parameters: want.parameters, StatementTemplate: want.template} input.AnswerKey.AnswerFormat = assessmentAlgorithms[want.algorithm].answerFormat variant, err := restoreAssessment(t, input).NewVariant(want.seed) if err != nil { t.Fatalf("NewVariant() error = %v", err) } if variant.Statement != want.statement || variant.ReferenceAnswer != want.answer { t.Fatalf("seed %d of %s:\nstatement %q\nanswer %q\nwant\nstatement %q\nanswer %q", want.seed, want.algorithm, variant.Statement, variant.ReferenceAnswer, want.statement, want.answer) } }) } } func TestContentHashOfSchemeOneIsPinned(t *testing.T) { draft, err := NewAssessmentFamilyDraft(testAssessmentInput()) if err != nil { t.Fatalf("NewAssessmentFamilyDraft() error = %v", err) } const want = "398d109255623c6bdadfa10974b523ca2f661913061746f0862ffaf1bca5a9d3" hash := draft.ContentHash() if got := fmt.Sprintf("%x", hash[:]); got != want { t.Fatalf("content hash = %s, want %s: a changed canonical layout of scheme 1 needs a new scheme, not an edit", got, want) } } // A template close to the size bound must be judged on the largest inputs // and on several seeds: here the highest parameter values render within the // bound for the shortest seed and beyond it for another, and the importer // refuses the template. func TestImportProbesSeveralSeedsAtTheLargestInputs(t *testing.T) { const algorithmName = "dedup_window.v1" algorithm := assessmentAlgorithms[algorithmName] parameters := map[string]AssessmentParameterRange{} highest := map[string]int32{} for _, spec := range algorithm.parameters { parameters[spec.name] = AssessmentParameterRange{Min: spec.lowest, Max: spec.highest} highest[spec.name] = spec.highest } generator := AssessmentSeedGenerator{Algorithm: algorithmName, Parameters: parameters} // The stream placeholder twice, the ttl placeholder once, and a literal // that is sized below so that the shortest probe seed renders exactly at // the bound. body := "{{.stream}} {{.stream}} {{.ttl}}" statement, err := compileStatementTemplate("test", body, algorithm) if err != nil { t.Fatalf("compileStatementTemplate() error = %v", err) } shortest, longest := maxStatementBytes*2, 0 for seed := range VariantSeed(probeSeedCount) { rendered, err := generator.instantiate(algorithm, statement, highest, seed) if err != nil { t.Fatalf("instantiate(seed %d) error = %v", seed, err) } shortest, longest = min(shortest, len(rendered.statement)), max(longest, len(rendered.statement)) } if shortest == longest { t.Skip("every probe seed renders the same size, so the boundary cannot be placed between them") } padding := maxStatementBytes - shortest if padding < 0 || padding+len(body) > maxStatementTemplateBytes { t.Fatalf("padding %d does not fit the template bound: the test needs another shape", padding) } generator.StatementTemplate = strings.Repeat("x", padding) + body input := testAssessmentInput() input.Generator = generator input.AnswerKey.AnswerFormat = algorithm.answerFormat if _, err := NewAssessmentFamilyDraft(input); !errors.Is(err, ErrInvalidAssessmentFamily) { t.Fatalf("NewAssessmentFamilyDraft(template at the bound for one seed only) error = %v, want ErrInvalidAssessmentFamily", err) } // Rendered with the shortest probe seed alone it would have passed. for seed := range VariantSeed(probeSeedCount) { compiled, err := compileStatementTemplate("test", generator.StatementTemplate, algorithm) if err != nil { t.Fatalf("compileStatementTemplate(padded) error = %v", err) } if rendered, err := generator.instantiate(algorithm, compiled, highest, seed); err == nil && len(rendered.statement) == maxStatementBytes { return } } t.Fatal("no probe seed renders the padded template exactly at the bound: the boundary test is not exercising the edge") }