candidate-xml.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import { SaxesParser } from 'saxes';
  2. const MAX_DOCUMENT_LENGTH = 1_000_000;
  3. const MAX_NODE_COUNT = 1_000;
  4. const MAX_DEPTH = 32;
  5. interface XmlNode {
  6. name: string;
  7. attributes: Record<string, string>;
  8. children: XmlNode[];
  9. text: string;
  10. }
  11. const FINDING_PARSE_ERROR_FIELD = '__reviewCandidateFindingParseError';
  12. export function getReviewCandidateFindingParseError(value: unknown): string | undefined {
  13. if (!value || typeof value !== 'object') return undefined;
  14. const message = (value as Record<string, unknown>)[FINDING_PARSE_ERROR_FIELD];
  15. return typeof message === 'string' ? message : undefined;
  16. }
  17. export function parseReviewCandidateXml(text: string): unknown {
  18. const root = parseXmlDocument(text);
  19. if (root.name === 'review-candidates') return parseCandidateDocument(root);
  20. if (root.name === 'annotation-result') return parseUntrustedAnnotationResult(root);
  21. throw new Error(`Unexpected review candidate XML root: ${root.name}`);
  22. }
  23. export function parseReviewCandidateCorrectionsXml(text: string): unknown {
  24. const root = parseXmlDocument(text);
  25. assertElement(root, 'review-candidate-corrections');
  26. assertAttributes(root, ['version']);
  27. if (requiredAttribute(root, 'version') !== '1') {
  28. throw new Error('review-candidate-corrections version must be 1');
  29. }
  30. assertWhitespaceOnly(root);
  31. return {
  32. type: 'code_review_candidate_corrections',
  33. version: 1,
  34. corrections: root.children.map((node) => {
  35. assertElement(node, 'correction');
  36. assertAttributes(node, ['candidate-key', 'action']);
  37. assertWhitespaceOnly(node);
  38. const candidateKey = requiredAttribute(node, 'candidate-key');
  39. const action = requiredAttribute(node, 'action');
  40. if (action === 'drop') {
  41. if (node.children.length !== 0) {
  42. throw new Error('drop correction must not contain a finding');
  43. }
  44. return { candidateKey, action };
  45. }
  46. if (action !== 'replace') {
  47. throw new Error(`Unsupported review correction action: ${action}`);
  48. }
  49. return {
  50. candidateKey,
  51. action,
  52. finding: parseCandidateFinding(onlyChild(node, 'finding')),
  53. };
  54. }),
  55. };
  56. }
  57. function parseCandidateDocument(root: XmlNode): unknown {
  58. assertAttributes(root, ['version', 'verdict']);
  59. if (requiredAttribute(root, 'version') !== '2') {
  60. throw new Error('review-candidates version must be 2');
  61. }
  62. assertWhitespaceOnly(root);
  63. assertChildNames(root, ['summary', 'findings']);
  64. const verdict = requiredAttribute(root, 'verdict');
  65. if (verdict !== 'pass' && verdict !== 'needs-changes') {
  66. throw new Error(`Unsupported review verdict: ${verdict}`);
  67. }
  68. const findings = onlyChild(root, 'findings');
  69. assertAttributes(findings, []);
  70. assertWhitespaceOnly(findings);
  71. return {
  72. type: 'code_review_candidates',
  73. version: 2,
  74. summary: readTextElement(onlyChild(root, 'summary')),
  75. verdict,
  76. findings: findings.children.map(parseCandidateFindingIsolated),
  77. };
  78. }
  79. function parseCandidateFindingIsolated(node: XmlNode): unknown {
  80. try {
  81. return parseCandidateFinding(node);
  82. } catch (error) {
  83. return {
  84. [FINDING_PARSE_ERROR_FIELD]: error instanceof Error ? error.message : String(error),
  85. rawNode: snapshotXmlNode(node),
  86. };
  87. }
  88. }
  89. function snapshotXmlNode(node: XmlNode): unknown {
  90. return {
  91. element: node.name,
  92. attributes: { ...node.attributes },
  93. ...(node.text.trim() ? { text: node.text.trim() } : {}),
  94. ...(node.children.length > 0
  95. ? { children: node.children.map((child) => snapshotXmlNode(child)) }
  96. : {}),
  97. };
  98. }
  99. function parseCandidateFinding(node: XmlNode): unknown {
  100. assertElement(node, 'finding');
  101. assertAttributes(node, ['priority']);
  102. assertWhitespaceOnly(node);
  103. assertChildNames(node, ['target', 'related-change', 'title', 'content']);
  104. const target = optionalChild(node, 'target');
  105. const relatedChange = optionalChild(node, 'related-change');
  106. return {
  107. priority: requiredAttribute(node, 'priority'),
  108. ...(target ? { target: parseCandidateTarget(target) } : {}),
  109. ...(relatedChange ? { relatedChange: parseRelatedChange(relatedChange, false) } : {}),
  110. title: readTextElement(onlyChild(node, 'title')),
  111. content: readTextElement(onlyChild(node, 'content')),
  112. };
  113. }
  114. function parseCandidateTarget(node: XmlNode): unknown {
  115. assertElement(node, 'target');
  116. assertWhitespaceOnly(node);
  117. if (node.children.length !== 0) throw new Error('candidate target must be self-contained');
  118. const type = requiredAttribute(node, 'type');
  119. if (type === 'file') {
  120. assertAttributes(node, ['type', 'path', 'state']);
  121. return {
  122. type,
  123. path: requiredAttribute(node, 'path'),
  124. state: requiredAttribute(node, 'state'),
  125. };
  126. }
  127. if (type !== 'line-range') throw new Error(`Unsupported review target type: ${type}`);
  128. assertAttributes(node, ['type', 'path', 'side', 'start-line', 'end-line']);
  129. return {
  130. type,
  131. path: requiredAttribute(node, 'path'),
  132. side: requiredAttribute(node, 'side'),
  133. startLine: positiveIntegerAttribute(node, 'start-line'),
  134. endLine: positiveIntegerAttribute(node, 'end-line'),
  135. };
  136. }
  137. /**
  138. * Historical annotation-result blocks are accepted only as untrusted model
  139. * drafts. Runtime-owned identity, anchor, context and revision attributes are
  140. * intentionally discarded before the ordinary ReviewCandidate validation and
  141. * projection pipeline runs.
  142. */
  143. function parseUntrustedAnnotationResult(root: XmlNode): unknown {
  144. assertAttributes(root, ['version', 'source', 'review-run-id', 'trigger', 'mode', 'verdict']);
  145. if (requiredAttribute(root, 'version') !== '2') {
  146. throw new Error('annotation-result version must be 2');
  147. }
  148. assertWhitespaceOnly(root);
  149. assertChildNames(root, ['summary', 'annotations']);
  150. const annotations = onlyChild(root, 'annotations');
  151. assertAttributes(annotations, []);
  152. assertWhitespaceOnly(annotations);
  153. const findings = annotations.children.map(parseUntrustedAnnotation);
  154. return {
  155. type: 'code_review_candidates',
  156. version: 2,
  157. summary: readTextElement(onlyChild(root, 'summary')),
  158. verdict: findings.length === 0 ? 'pass' : 'needs-changes',
  159. findings,
  160. };
  161. }
  162. function parseUntrustedAnnotation(node: XmlNode): unknown {
  163. assertElement(node, 'annotation');
  164. assertAttributes(node, ['id', 'kind', 'priority']);
  165. assertWhitespaceOnly(node);
  166. assertChildNames(node, ['target', 'title', 'content']);
  167. const parsedTarget = parseUntrustedTarget(onlyChild(node, 'target'));
  168. return {
  169. priority: requiredAttribute(node, 'priority'),
  170. target: parsedTarget.target,
  171. ...(parsedTarget.relatedChange ? { relatedChange: parsedTarget.relatedChange } : {}),
  172. title: readTextElement(onlyChild(node, 'title')),
  173. content: readTextElement(onlyChild(node, 'content')),
  174. };
  175. }
  176. function parseUntrustedTarget(node: XmlNode): { target: unknown; relatedChange?: unknown } {
  177. assertElement(node, 'target');
  178. assertWhitespaceOnly(node);
  179. const type = requiredAttribute(node, 'type');
  180. if (type !== 'file') throw new Error(`Unsupported annotation target type: ${type}`);
  181. assertAttributes(node, ['type', 'uri', 'state', 'blob-revision']);
  182. const path = requiredAttribute(node, 'uri');
  183. if (node.attributes.state !== undefined) {
  184. if (node.children.length !== 0)
  185. throw new Error('deleted file target must not contain selectors');
  186. return { target: { type: 'file', path, state: node.attributes.state } };
  187. }
  188. assertChildNames(node, ['selector', 'related-change']);
  189. const selector = onlyChild(node, 'selector');
  190. assertAttributes(selector, [
  191. 'type',
  192. 'side',
  193. 'start-line',
  194. 'end-line',
  195. 'anchor-revision',
  196. 'context-before',
  197. 'context-after',
  198. ]);
  199. assertWhitespaceOnly(selector);
  200. if (selector.children.length !== 0) throw new Error('annotation selector must be empty');
  201. if (requiredAttribute(selector, 'type') !== 'line-range') {
  202. throw new Error('annotation selector type must be line-range');
  203. }
  204. const relatedChange = optionalChild(node, 'related-change');
  205. return {
  206. target: {
  207. type: 'line-range',
  208. path,
  209. side: requiredAttribute(selector, 'side'),
  210. startLine: positiveIntegerAttribute(selector, 'start-line'),
  211. endLine: positiveIntegerAttribute(selector, 'end-line'),
  212. },
  213. ...(relatedChange ? { relatedChange: parseRelatedChange(relatedChange, true) } : {}),
  214. };
  215. }
  216. function parseRelatedChange(node: XmlNode, allowRevision: boolean): unknown {
  217. assertElement(node, 'related-change');
  218. assertAttributes(node, [
  219. 'path',
  220. 'side',
  221. 'start-line',
  222. 'end-line',
  223. ...(allowRevision ? ['revision'] : []),
  224. ]);
  225. assertWhitespaceOnly(node);
  226. if (node.children.length !== 0) throw new Error('related-change must be empty');
  227. return {
  228. path: requiredAttribute(node, 'path'),
  229. side: requiredAttribute(node, 'side'),
  230. startLine: positiveIntegerAttribute(node, 'start-line'),
  231. endLine: positiveIntegerAttribute(node, 'end-line'),
  232. };
  233. }
  234. function parseXmlDocument(text: string): XmlNode {
  235. const source = text.trim();
  236. if (source.length === 0) throw new Error('Review candidate XML is empty');
  237. if (source.length > MAX_DOCUMENT_LENGTH) throw new Error('Review candidate XML is too large');
  238. let root: XmlNode | undefined;
  239. let parseError: Error | undefined;
  240. let outsideText = '';
  241. let nodeCount = 0;
  242. const stack: XmlNode[] = [];
  243. const parser = new SaxesParser({ xmlns: false });
  244. parser.on('opentag', (tag) => {
  245. nodeCount += 1;
  246. if (nodeCount > MAX_NODE_COUNT) throw new Error('Review candidate XML has too many nodes');
  247. if (stack.length >= MAX_DEPTH) throw new Error('Review candidate XML is too deeply nested');
  248. const node: XmlNode = {
  249. name: tag.name,
  250. attributes: { ...tag.attributes },
  251. children: [],
  252. text: '',
  253. };
  254. const parent = stack.at(-1);
  255. if (parent) parent.children.push(node);
  256. else if (root) throw new Error('Review candidate XML must contain exactly one root');
  257. else root = node;
  258. stack.push(node);
  259. });
  260. const appendText = (value: string): void => {
  261. const current = stack.at(-1);
  262. if (current) current.text += value;
  263. else outsideText += value;
  264. };
  265. parser.on('text', appendText);
  266. parser.on('cdata', appendText);
  267. parser.on('closetag', () => {
  268. stack.pop();
  269. });
  270. parser.on('doctype', () => {
  271. parseError ??= new Error('DOCTYPE is not allowed in Review candidate XML');
  272. });
  273. parser.on('processinginstruction', () => {
  274. parseError ??= new Error('Processing instructions are not allowed in Review candidate XML');
  275. });
  276. parser.on('comment', () => {
  277. parseError ??= new Error('Comments are not allowed in Review candidate XML');
  278. });
  279. parser.on('error', (error) => {
  280. parseError ??= error;
  281. });
  282. parser.write(source).close();
  283. if (parseError) throw parseError;
  284. if (!root) throw new Error('Review candidate XML root is missing');
  285. if (stack.length !== 0) throw new Error('Review candidate XML is not closed');
  286. if (outsideText.trim()) throw new Error('Text outside Review candidate XML root is not allowed');
  287. return root;
  288. }
  289. function assertElement(node: XmlNode, expected: string): void {
  290. if (node.name !== expected) throw new Error(`Expected <${expected}> but found <${node.name}>`);
  291. }
  292. function assertAttributes(node: XmlNode, allowed: readonly string[]): void {
  293. const allowedSet = new Set(allowed);
  294. const unexpected = Object.keys(node.attributes).find((name) => !allowedSet.has(name));
  295. if (unexpected) throw new Error(`Unexpected ${node.name} attribute: ${unexpected}`);
  296. }
  297. function requiredAttribute(node: XmlNode, name: string): string {
  298. const value = node.attributes[name];
  299. if (value === undefined || value === '') {
  300. throw new Error(`Missing ${node.name} attribute: ${name}`);
  301. }
  302. return value;
  303. }
  304. function positiveIntegerAttribute(node: XmlNode, name: string): number {
  305. const raw = requiredAttribute(node, name);
  306. if (!/^[1-9]\d*$/u.test(raw)) throw new Error(`${node.name}.${name} must be a positive integer`);
  307. return Number(raw);
  308. }
  309. function assertWhitespaceOnly(node: XmlNode): void {
  310. if (node.text.trim()) throw new Error(`Unexpected text inside <${node.name}>`);
  311. }
  312. function assertChildNames(node: XmlNode, allowed: readonly string[]): void {
  313. const allowedSet = new Set(allowed);
  314. const unexpected = node.children.find((child) => !allowedSet.has(child.name));
  315. if (unexpected) throw new Error(`Unexpected <${unexpected.name}> inside <${node.name}>`);
  316. }
  317. function onlyChild(node: XmlNode, name: string): XmlNode {
  318. const matches = node.children.filter((child) => child.name === name);
  319. const match = matches[0];
  320. if (matches.length !== 1 || !match) {
  321. throw new Error(`<${node.name}> must contain exactly one <${name}>`);
  322. }
  323. return match;
  324. }
  325. function optionalChild(node: XmlNode, name: string): XmlNode | undefined {
  326. const matches = node.children.filter((child) => child.name === name);
  327. if (matches.length > 1) throw new Error(`<${node.name}> must not repeat <${name}>`);
  328. return matches[0];
  329. }
  330. function readTextElement(node: XmlNode): string {
  331. assertAttributes(node, []);
  332. if (node.children.length !== 0) throw new Error(`<${node.name}> must contain plain text only`);
  333. return node.text.trim();
  334. }