TestServerURLInjection checks that attacker-controlled spec text (server description, URL, and variable default), which flows into generated Go line comments and string literals, cannot break out into an executable top-level declaration.
(t *testing.T)
| 88 | // comments and string literals, cannot break out into an executable top-level |
| 89 | // declaration. |
| 90 | func TestServerURLInjection(t *testing.T) { |
| 91 | // commentBreakout escapes a `//` comment, declares the sentinel, then |
| 92 | // re-opens a comment so the surrounding template text stays valid. |
| 93 | commentBreakout := "benign\nvar " + injectSentinel + " = 1\n//" |
| 94 | // literalBreakout escapes a `"…"` string literal, declares the |
| 95 | // sentinel, then re-opens a literal to swallow the template's closing |
| 96 | // quote. |
| 97 | literalBreakout := `https://api.example.com"; var ` + injectSentinel + ` = 1; var _ = "` |
| 98 | |
| 99 | t.Run("newline in description cannot escape the doc comment", func(t *testing.T) { |
| 100 | out := renderServerURLs(t, &openapi3.T{Servers: openapi3.Servers{ |
| 101 | {URL: "https://api.example.com", Description: commentBreakout}, |
| 102 | }}) |
| 103 | assertSentinelNotDeclared(t, out) |
| 104 | }) |
| 105 | |
| 106 | t.Run("description in the function (variable-bearing) form cannot escape", func(t *testing.T) { |
| 107 | out := renderServerURLs(t, &openapi3.T{Servers: openapi3.Servers{ |
| 108 | {URL: "https://api.example.com/{tenant}", Description: commentBreakout}, |
| 109 | }}) |
| 110 | assertSentinelNotDeclared(t, out) |
| 111 | }) |
| 112 | |
| 113 | t.Run("quote in URL cannot escape the const string literal", func(t *testing.T) { |
| 114 | out := renderServerURLs(t, &openapi3.T{Servers: openapi3.Servers{ |
| 115 | {URL: literalBreakout}, |
| 116 | }}) |
| 117 | assertSentinelNotDeclared(t, out) |
| 118 | }) |
| 119 | |
| 120 | t.Run("quote in a variable default cannot escape the const string literal", func(t *testing.T) { |
| 121 | out := renderServerURLs(t, &openapi3.T{Servers: openapi3.Servers{ |
| 122 | { |
| 123 | URL: "https://api.example.com/{base}", |
| 124 | Variables: map[string]*openapi3.ServerVariable{ |
| 125 | // non-enum, used → emits `const …BaseVariableDefault = "<default>"` |
| 126 | "base": {Default: `v2"; var ` + injectSentinel + ` = 1; var _ = "`}, |
| 127 | }, |
| 128 | }, |
| 129 | }}) |
| 130 | assertSentinelNotDeclared(t, out) |
| 131 | }) |
| 132 | } |
| 133 | |
| 134 | // assertSentinelNotDeclared parses the generated output as a package body |
| 135 | // and fails if it is not valid Go or if injectSentinel appears as a |
nothing calls this directly
no test coverage detected