|
| 1 | +// @ts-check |
| 2 | +/** |
| 3 | + * Fuzz harness for the skip-if search query parser in skip_if_query.cjs. |
| 4 | + * |
| 5 | + * Checks parser and backend-selection invariants for arbitrary queries: |
| 6 | + * - parsing never throws and is deterministic |
| 7 | + * - accepted queries are fully structured (single repo, valid enums, no OR label lists) |
| 8 | + * - unsupported queries route only to search; supported ones always keep search as fallback |
| 9 | + * - GraphQL is offered only when it is exact (<= 1 label, user filters only on issues) |
| 10 | + * - acceptance is invariant to token order, extra whitespace, and sort: qualifiers |
| 11 | + * - appending free text or a negated qualifier always forces the search API |
| 12 | + * - pressure ordering is always a permutation of the capable backends |
| 13 | + * |
| 14 | + * Used by vitest and by Go's fuzzing framework when run as main module via stdin. |
| 15 | + */ |
| 16 | + |
| 17 | +const { tokenizeSearchQuery, parseSearchQuery, getCapableBackends, orderBackendsByPressure } = require("./skip_if_query.cjs"); |
| 18 | +const { getErrorMessage } = require("./error_helpers.cjs"); |
| 19 | + |
| 20 | +const TYPES = [null, "issue", "pr"]; |
| 21 | +const STATES = [null, "open", "closed", "merged"]; |
| 22 | +const LOGIN_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/; |
| 23 | + |
| 24 | +/** |
| 25 | + * Rate-limit scenarios exercised for every query. |
| 26 | + * @type {(Record<string, { limit: number, remaining: number }> | null)[]} |
| 27 | + */ |
| 28 | +const RESOURCE_SCENARIOS = [ |
| 29 | + null, |
| 30 | + {}, |
| 31 | + { graphql: { limit: 5000, remaining: 5000 }, core: { limit: 5000, remaining: 5000 }, search: { limit: 30, remaining: 30 } }, |
| 32 | + { graphql: { limit: 5000, remaining: 10 }, core: { limit: 5000, remaining: 4000 }, search: { limit: 30, remaining: 30 } }, |
| 33 | + { graphql: { limit: 5000, remaining: 0 }, core: { limit: 5000, remaining: 0 }, search: { limit: 30, remaining: 1 } }, |
| 34 | + { graphql: { limit: 0, remaining: 0 }, core: { limit: 5000, remaining: 499 }, search: { limit: 30, remaining: 0 } }, |
| 35 | +]; |
| 36 | + |
| 37 | +/** |
| 38 | + * Normalizes a parse result for comparisons that must ignore token order and casing. |
| 39 | + * @param {ReturnType<typeof parseSearchQuery>} result |
| 40 | + * @returns {string} |
| 41 | + */ |
| 42 | +function normalize(result) { |
| 43 | + if (!result.ok) return "unsupported"; |
| 44 | + const q = result.query; |
| 45 | + const lower = (/** @type {string | null} */ v) => (v === null ? null : v.toLowerCase()); |
| 46 | + return JSON.stringify({ |
| 47 | + type: q.type, |
| 48 | + state: q.state, |
| 49 | + labels: [...q.labels].sort(), |
| 50 | + repo: q.repo && `${q.repo.owner}/${q.repo.repo}`.toLowerCase(), |
| 51 | + author: lower(q.author), |
| 52 | + assignee: lower(q.assignee), |
| 53 | + mentions: lower(q.mentions), |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Returns all invariant violations for a query. Never throws. |
| 59 | + * @param {string} query |
| 60 | + * @returns {string[]} |
| 61 | + */ |
| 62 | +function checkSkipIfQueryInvariants(query) { |
| 63 | + /** @type {string[]} */ |
| 64 | + const violations = []; |
| 65 | + try { |
| 66 | + const result = parseSearchQuery(query); |
| 67 | + if (JSON.stringify(parseSearchQuery(query)) !== JSON.stringify(result)) violations.push("parse is not deterministic"); |
| 68 | + |
| 69 | + const backends = getCapableBackends(result); |
| 70 | + if (!result.ok) { |
| 71 | + if (typeof result.reason !== "string" || !result.reason) violations.push("rejection has no reason"); |
| 72 | + if (JSON.stringify(backends) !== '["search"]') violations.push(`unsupported query offered ${backends.join(",")}`); |
| 73 | + } else { |
| 74 | + const q = result.query; |
| 75 | + if (!q.repo || !q.repo.owner || !q.repo.repo) violations.push("accepted query without repository"); |
| 76 | + if (!TYPES.includes(q.type)) violations.push(`invalid type ${q.type}`); |
| 77 | + if (!STATES.includes(q.state)) violations.push(`invalid state ${q.state}`); |
| 78 | + if (q.state === "merged" && q.type !== "pr") violations.push("merged state without pr type"); |
| 79 | + if (q.labels.some(l => !l || l.includes(","))) violations.push("empty or OR label accepted"); |
| 80 | + if ([...q.labels, q.author, q.assignee, q.mentions, q.repo?.owner, q.repo?.repo].some(v => v?.includes('"'))) violations.push("value with stray quote accepted"); |
| 81 | + if (new Set(q.labels).size !== q.labels.length) violations.push("duplicate labels"); |
| 82 | + for (const login of [q.author, q.assignee, q.mentions]) { |
| 83 | + if (login !== null && !LOGIN_PATTERN.test(login)) violations.push(`invalid login ${login}`); |
| 84 | + } |
| 85 | + |
| 86 | + if (backends[backends.length - 1] !== "search") violations.push("search is not the final fallback"); |
| 87 | + if (!backends.includes("rest")) violations.push("REST not offered for supported query"); |
| 88 | + const graphqlExact = q.labels.length <= 1 && (q.type === "issue" || !(q.author || q.assignee || q.mentions)); |
| 89 | + if (backends.includes("graphql") !== graphqlExact) violations.push(`graphql offered=${backends.includes("graphql")} exact=${graphqlExact}`); |
| 90 | + |
| 91 | + for (const suffix of [" zzfreetext", " -label:x", ' "quoted text"', " in:title"]) { |
| 92 | + if (parseSearchQuery(query + suffix).ok) violations.push(`suffix ${JSON.stringify(suffix)} did not force search`); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + for (const resources of RESOURCE_SCENARIOS) { |
| 97 | + const ordered = orderBackendsByPressure(backends, resources); |
| 98 | + if (ordered.length !== backends.length || [...ordered].sort().join() !== [...backends].sort().join()) { |
| 99 | + violations.push(`pressure ordering ${ordered.join(",")} is not a permutation of ${backends.join(",")}`); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + const tokens = tokenizeSearchQuery(query); |
| 104 | + if (tokens === null) { |
| 105 | + if (result.ok) violations.push("accepted query with unbalanced quotes"); |
| 106 | + } else { |
| 107 | + const expected = normalize(result); |
| 108 | + const variants = { |
| 109 | + reordered: [...tokens].reverse().join(" "), |
| 110 | + "extra whitespace": ` \t${tokens.join(" \n\t ")} `, |
| 111 | + "sort qualifier": [...tokens, "sort:updated-desc"].join(" "), |
| 112 | + }; |
| 113 | + for (const [name, variant] of Object.entries(variants)) { |
| 114 | + if (normalize(parseSearchQuery(variant)) !== expected) violations.push(`${name} variant changed result`); |
| 115 | + } |
| 116 | + } |
| 117 | + } catch (err) { |
| 118 | + violations.push(`threw: ${getErrorMessage(err)}`); |
| 119 | + } |
| 120 | + return violations; |
| 121 | +} |
| 122 | + |
| 123 | +const FRAGMENTS = [ |
| 124 | + "is:issue", |
| 125 | + "is:pr", |
| 126 | + "is:pull-request", |
| 127 | + "IS:Open", |
| 128 | + "is:open", |
| 129 | + "is:closed", |
| 130 | + "is:merged", |
| 131 | + "is:draft", |
| 132 | + "type:issue", |
| 133 | + "type:pr", |
| 134 | + "state:open", |
| 135 | + "state:closed", |
| 136 | + "state:merged", |
| 137 | + "label:bug", |
| 138 | + "label:Bug", |
| 139 | + 'label:"needs triage"', |
| 140 | + "label:a,b", |
| 141 | + 'label:""', |
| 142 | + "label:", |
| 143 | + "-label:bug", |
| 144 | + "repo:octo/demo", |
| 145 | + "repo:Octo/Demo", |
| 146 | + "repo:octo/other", |
| 147 | + "repo:bad", |
| 148 | + "author:octocat", |
| 149 | + "author:app/bot", |
| 150 | + "assignee:@me", |
| 151 | + "assignee:octocat", |
| 152 | + "mentions:hubot", |
| 153 | + "sort:created-desc", |
| 154 | + "org:octo", |
| 155 | + "in:title", |
| 156 | + "no:assignee", |
| 157 | + '"[daily-report]"', |
| 158 | + "free", |
| 159 | + '"unterminated', |
| 160 | + ":", |
| 161 | + "-", |
| 162 | +]; |
| 163 | + |
| 164 | +/** |
| 165 | + * Builds a query from a byte choice stream and a free-form payload. |
| 166 | + * @param {number[]} bytes |
| 167 | + * @param {string} payload |
| 168 | + * @returns {string} |
| 169 | + */ |
| 170 | +function buildModelQuery(bytes, payload) { |
| 171 | + const parts = []; |
| 172 | + for (const b of bytes.slice(0, 64)) { |
| 173 | + const pick = b % (FRAGMENTS.length + 4); |
| 174 | + if (pick < FRAGMENTS.length) parts.push(FRAGMENTS[pick]); |
| 175 | + else if (pick === FRAGMENTS.length) parts.push(`label:${payload}`); |
| 176 | + else if (pick === FRAGMENTS.length + 1) parts.push(`author:${payload}`); |
| 177 | + else if (pick === FRAGMENTS.length + 2) parts.push(`repo:${payload}`); |
| 178 | + else parts.push(payload); |
| 179 | + } |
| 180 | + return parts.join((bytes[0] ?? 0) % 3 === 0 ? " \t " : " "); |
| 181 | +} |
| 182 | + |
| 183 | +// Read input from stdin for Go-driven fuzzing |
| 184 | +if (require.main === module) { |
| 185 | + let input = ""; |
| 186 | + process.stdin.on("data", chunk => { |
| 187 | + input += chunk; |
| 188 | + }); |
| 189 | + process.stdin.on("end", () => { |
| 190 | + try { |
| 191 | + // Expected JSON: { query?: string, bytes?: number[], payload?: string } |
| 192 | + const { query, bytes, payload } = JSON.parse(input); |
| 193 | + const text = Array.isArray(bytes) ? buildModelQuery(bytes, payload ?? "") : (query ?? ""); |
| 194 | + const violations = checkSkipIfQueryInvariants(text); |
| 195 | + process.stdout.write(JSON.stringify({ ok: violations.length === 0, query: text, violations })); |
| 196 | + process.exit(0); |
| 197 | + } catch (err) { |
| 198 | + process.stdout.write(JSON.stringify({ ok: false, violations: [getErrorMessage(err)] })); |
| 199 | + process.exit(1); |
| 200 | + } |
| 201 | + }); |
| 202 | +} |
| 203 | + |
| 204 | +module.exports = { checkSkipIfQueryInvariants, buildModelQuery, FRAGMENTS }; |
0 commit comments