Openapi documentation generator crushed by window.postMessage
<!--IssueSummary start--> <details> <summary> Everyone can contribute. [Help move this issue forward](https://handbook.gitlab.com/handbook/marketing/developer-relations/contributor-success/community-contributors-workflows/#contributor-links) while earning points, leveling up and collecting rewards. </summary> - [Close this issue](https://contributors.gitlab.com/manage-issue?action=close&projectId=278964&issueIid=557254) </details> <!--IssueSummary end--> ## Context OpenApi [preview](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/api/openapi/openapi_v2.yaml) is rendered in an iframe. The code inside of this iframe [listens for a message](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/lib/swagger.js#L39) posted [from the parent page](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/blob/openapi/index.js?ref_type=heads#L50) and takes a message's data as a spec to render. The users reported us an issue about crushes of a preview. The investigation shown the cause: some browser extensions post messages on the iframe's window with their own data, and preview code does not validate received data and tries to [render it](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/lib/swagger.js#L45). ## To reproduce the issue 1. Install one of the browser extensions using messages. For example https://chromewebstore.google.com/detail/semrush-ai-writer-and-edi/dfajcklndiadlfmiabpohgpbcohchhop. No need to register or do anything else with it. 2. Visit a page with swagger documentation. For example, [the one from gitlab's repository](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/api/openapi/openapi_v2.yaml). 3. The preview shows error: ![image.png](/uploads/b16345105d481a5284102c427dc8c64f/image.png) ## Proposed We'd like to propose more strict validation of incoming data inside preview iframe. 1. On the [sending side](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/blob/openapi/index.js?ref_type=heads#L50) use unique key ```diff sandboxEl.addEventListener('load', () => { - if (spec) sandboxEl.contentWindow.postMessage(JSON.stringify(spec), '*'); + if (spec) sandboxEl.contentWindow.postMessage({ openapiSpecString: JSON.stringify(spec) }, '*'); }); ``` 2. On the [listening side](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/lib/swagger.js#L45) check the presence of the unique key in the data. ```diff const addInitHook = () => { window.addEventListener( 'message', (event) => { if (event.origin !== window.location.origin) { return; } - renderSwaggerUI(event.data); + if (isObject(event.data)) { + const { openapiSpecString } = event.data; + + if (typeof openapiSpecString === 'string') { + renderSwaggerUI(openapiSpecString); + } + } }, false, ); }; ```
issue