69 seconds
Two browser windows, side by side.
On the left: OpenCloud, signed in. A folder called postmessage validation. Inside it, a few harmless test files and an empty folder named picker-poc-target.
On the right: a page that has nothing to do with OpenCloud. It runs on http://127.0.0.1:8765. Its title is "Picker postMessage validation". It has four buttons and a text box.
I right-click private-copy.txt and choose Copy to. The familiar folder picker opens and waits for me to pick a destination.
I don't pick one.
Instead, on the right side, I click Send forged Copy/Move destination.
The picker closes. The copy runs. I open picker-poc-target, and there it is: private-copy.txt, sitting in a folder that the other page chose.
No exploit kit. No browser bug. No backend authorization bypass.
Just a missing if.
This is the story of that if: why it was missing, what a stranger's tab could do because of it, and how 11 lines of code (plus a pile of tests) closed the hole.
Every source snippet below is quoted verbatim from the repository: from the parent of the fix (
71c5c57), from the fix commit itself (c4ef961), or from neighbouring files at that commit that the PR did not touch. The PoC payloads are transcribed from my recording with instance-specific identifiers redacted. The private instance address, resource IDs and private evidence are deliberately left out.
Act 1: The lie we tell ourselves about postMessage
Browsers are paranoid by design. The same-origin policy keeps evil.example from reading your bank's tab, your mail tab, or your cloud storage tab.
window.postMessage() is the deliberate hole in that wall.
If a window on origin A gets hold of a reference to a window on origin B (the return value of window.open(), an iframe.contentWindow, window.parent, window.opener), it can call postMessage on it. The browser delivers the message even though the two pages are cross-origin. That's the whole point of the API.
On the receiving end you get a MessageEvent. Four of its fields matter: data, origin, source and ports. Here is the part that everything else in this story hangs on:
| Field | Who writes it | Can the sender fake it? |
|---|---|---|
data |
the sending script | Yes. It's whatever they want. |
origin |
the browser | No |
source |
the browser | No |
The sender only ever writes data. The browser stamps origin (the sender's origin) and source (the sender's WindowProxy). The WHATWG HTML Standard and MDN are explicit about this split, and MessageEvent.source is documented as a WindowProxy you can compare by identity.
The misconception that keeps this bug class alive
Look at the second argument:
otherWindow.postMessage(message, targetOrigin)
targetOrigin is a delivery condition on the sender's side. The browser only dispatches the message if the recipient is on that origin. Otherwise it's dropped.
So for an attacker, setting targetOrigin to the right OpenCloud origin isn't a defence they have to get past. It's a requirement for the attack to arrive at all. It says nothing about who is allowed to send.
From the receiver's point of view, a correctly addressed message from an attacker page arrives with:
event.origin === 'http://127.0.0.1:8765'-
event.sourcepointing at the attacker's window
Those two fields are the only trustworthy provenance in the event.
targetOriginprotects the recipient from a sender that's confused about where it's posting. It does not authenticate the sender to the recipient. That check has to happen in the receiver.
A message handler that never reads origin or source has quietly turned itself into a public API endpoint.
Now let's look at OpenCloud's.
Act 2: A bouncer who only checks name tags
OpenCloud Web builds its file pickers in a neat way: it embeds its own files UI in an iframe with ?embed=true. The modal and the embedded UI then talk over postMessage. The embed mode documentation describes the wire format as { name: string, data: any }, with the events opencloud-embed:select, opencloud-embed:file-pick and opencloud-embed:cancel.
Here is the entire inbound validation in LocationPickerModal.vue before the fix:
// packages/web-pkg/src/components/Modals/LocationPickerModal.vue (before #4289)
const onLocationPick = ({ data }: MessageEvent) => {
if (data.name !== 'opencloud-embed:select') {
return
}
let resources = (data.data as embedModeLocationPickMessageData)?.resources
let fileName = (data.data as embedModeLocationPickMessageData)?.fileName
if (Array.isArray(data.data)) {
resources = data.data as embedModeLocationPickMessageData['resources']
fileName = undefined
}
if (!resources?.length) {
return
}
callbackFn(resources, { fileName })
removeModal(modal.id)
}
onMounted(() => {
window.addEventListener('message', onLocationPick)
window.addEventListener('message', onCancel)
})
Read the first line of the handler again:
if (data.name !== 'opencloud-embed:select') {
That's the bouncer. And the bouncer's only question is: "Does your name tag say opencloud-embed:select?"
But data is written by whoever calls postMessage. A name is a routing key, not an identity. Anyone can print that name tag.
FilePickerModal.vue had exactly the same shape for opencloud-embed:file-pick.
And the matching cancel handler in Show: FilePickerModal.vue before the fix
// packages/web-pkg/src/components/Modals/FilePickerModal.vue (before #4289)
const onFilePick = ({ data }: MessageEvent) => {
if (data.name !== 'opencloud-embed:file-pick') {
return
}
const { resource, locationQuery }: embedModeFilePickMessageData = data.data
callbackFn({ resource, locationQuery })
removeModal(modal.id)
}
const onCancel = ({ data }: MessageEvent) => {
if (data.name !== 'opencloud-embed:cancel') {
return
}
removeModal(modal.id)
}
LocationPickerModal.vue:
const onCancel = ({ data }: MessageEvent) => {
if (data.name !== 'opencloud-embed:cancel') {
return
}
removeModal(modal.id)
}
onBeforeUnmount(() => {
window.removeEventListener('message', onLocationPick)
window.removeEventListener('message', onCancel)
})
Two shapes, one forgery
The legitimate sender lives inside the iframe. EmbedActions.vue sends opencloud-embed:select in two different shapes: an object when a file name is being chosen, and a plain array otherwise.
// packages/web-app-files/src/components/EmbedActions/EmbedActions.vue
const emitSelect = (): void => {
if (unref(chooseFileName)) {
postMessage<embedModeLocationPickMessageData>('opencloud-embed:select', {
resources: JSON.parse(JSON.stringify(selectedFiles.value)),
fileName: unref(fullFileName),
locationQuery: JSON.parse(JSON.stringify(routeToContextQuery(unref(router.currentRoute))))
})
return
}
// TODO: adjust type to embedModeLocationPickMessageData later (breaking)
postMessage<Resource[]>('opencloud-embed:select', JSON.parse(JSON.stringify(selectedFiles.value)))
}
That dual shape is exactly why the forged messages could hit two different workflows with almost the same payload. Nothing in the receiver could tell "the embedded UI sent this after the user clicked Copy here" apart from "some other window built the same object".
Show: the payload types and the outgoing helper in useEmbedMode.ts
// packages/web-pkg/src/composables/embedMode/useEmbedMode.ts
export interface embedModeFilePickMessageData {
resource: Resource
locationQuery: LocationQuery
}
export interface embedModeLocationPickMessageData {
resources: Resource[]
fileName?: string
locationQuery?: LocationQuery
}
// packages/web-pkg/src/composables/embedMode/useEmbedMode.ts
const postMessage = <Payload>(name: string, data?: Payload): void => {
const options: WindowPostMessageOptions = {}
if (unref(messagesTargetOrigin)) {
options.targetOrigin = unref(messagesTargetOrigin)
}
window.parent.postMessage({ name, data }, options)
}
messagesTargetOrigin is computed(() => configStore.options.embed?.messagesOrigin), so the sender only sets targetOrigin when that option is configured. That's the outbound delivery condition from Act 1. It has no bearing on who may send to the parent.
// packages/web-app-files/src/components/EmbedActions/EmbedActions.vue
const emitCancel = (): void => {
postMessage<null>('opencloud-embed:cancel', null)
}
Act 3: Why a fake message is not "just a UI event"
Here's where it stops being a curiosity.
The picker modal doesn't copy anything itself. It calls callbackFn, which the Copy to action handed it when it opened the modal:
// packages/web-app-files/src/composables/actions/files/useFileActionsCopy.ts
const handler = ({ resources }: FileActionOptions) => {
resourcesStore.setSelection(resources.map(({ id }) => id))
const parentFolderLink = getParentFolderLink(resources[0])
dispatchModal({
elementClass: 'location-picker-modal',
title: $gettext('Copy to'),
customComponent: markRaw(LocationPickerModal),
hideActions: true,
customComponentAttrs: () => ({
submitButtonTitle: $gettext('Copy here'),
parentFolderLink,
callbackFn: (targetResources: Resource[]) =>
onLocationPicked({ sourceResources: resources, targetResources })
}),
focusTrapInitial: false
})
}
onLocationPicked takes targetResources[0] as the destination, resolves the target space, builds a ResourceTransfer and hands it to startWorker, which performs a WebDAV copy using the signed-in user's session. Move to is the same structure with TransferType.MOVE.
Show: the Move to handler
// packages/web-app-files/src/composables/actions/files/useFileActionsMove.ts
const handler = ({ resources }: FileActionOptions) => {
if (!resources.length) {
return
}
resourcesStore.setSelection(resources.map(({ id }) => id))
const parentFolderLink = getParentFolderLink(resources[0])
dispatchModal({
elementClass: 'location-picker-modal',
title: $gettext('Move to'),
customComponent: markRaw(LocationPickerModal),
hideActions: true,
customComponentAttrs: () => ({
submitButtonTitle: $gettext('Move here'),
parentFolderLink,
callbackFn: (targetResources: Resource[]) =>
onLocationPicked({ sourceResources: resources, targetResources })
}),
focusTrapInitial: false
})
}
So the chain looks like this:
foreign window ──postMessage──▶ LocationPickerModal ──callbackFn──▶ onLocationPicked ──▶ WebDAV COPY / MOVE
(untrusted) (checks only the name) (user's session)
The forged message is the input to a state-changing server operation. The frontend is a textbook confused deputy: it holds the user's authenticated WebDAV client and acts on a destination supplied by a window it never vetted.
Save as: the stranger even picks the file name
SaveAsModal.vue goes one step further. It pulls the destination, the file name and the location query straight out of data.data:
// packages/web-pkg/src/components/Modals/SaveAsModal.vue (before #4289)
const onLocationPick = async ({ data }: MessageEvent) => {
if (data.name !== 'opencloud-embed:select') {
return
}
const { resources, fileName, locationQuery }: embedModeLocationPickMessageData = data.data
const destinationFolder: Resource = resources[0]
const space = getMatchingSpace(destinationFolder)
try {
const resource = await saveFile({ destinationFolder, fileName, space })
if (resource) {
showMessage({
title: $gettext('»%{fileName}« was saved successfully', { fileName: resource.name })
})
openFile({ resource, space, locationQuery })
}
} catch (e) {
console.error(e)
showErrorMessage({
title: $gettext('Unable to save »%{fileName}«', { fileName }),
errors: [e]
})
console.error(e)
}
removeModal(modal.id)
}
And the write uses those values verbatim:
// packages/web-pkg/src/components/Modals/SaveAsModal.vue (before #4289)
return clientService.webdav.putFileContents(space, {
fileName,
parentFolderId: destinationFolder.id,
content: content,
path: urlJoin(destinationFolder.path, fileName)
})
Folder: attacker-supplied. Name: attacker-supplied. Content: the document the victim had open.
openFile then calls window.open(buildUrl(router, routeOpts), '_blank'), which is why my recording ends with a brand-new editor tab showing the saved file.
The same hole, in the office apps
The PR also covers the external app iframes (Collabora and Microsoft Office). Same pattern, no provenance check at all. The Microsoft handler would switch the document into write mode for anyone who asked nicely:
// packages/web-app-external/src/App.vue (before #4289)
// switch to write mode when edit is clicked
const catchClickMicrosoftEdit = (event: MessageEvent) => {
try {
if (JSON.parse(event.data)?.MessageId === 'UI_Edit') {
loadAppUrl.perform('write')
}
} catch {}
}
The Collabora handler dispatched on MessageId the same way, and its branches open FilePickerModal and FileNameModal, trigger router.push on Action_Save_Resp, and notify mentioned users. Before the fix, the GET-based iframe didn't even have a ref.
In the PR's own words: "A malicious page or frame could send fake `opencloud-embed:` or Collabora/WOPI messages to trigger picks, cancels or edit-mode switches."*
⚠️ My recording does not exercise the external-app path. For that part I'm quoting the upstream description and the code, not claiming a demonstrated exploit.
Show: App.vue iframes and the Collabora handler before the fix
<!-- packages/web-app-external/src/App.vue (before #4289) -->
<iframe
v-else-if="appUrl && method === 'GET'"
:src="appUrl"
class="size-full"
:title="iFrameTitle"
allowfullscreen
allow="clipboard-read *; clipboard-write *"
/>
<!-- packages/web-app-external/src/App.vue (before #4289) -->
<iframe
ref="appIframe"
name="app-iframe"
class="size-full"
:title="iFrameTitle"
allowfullscreen
allow="clipboard-read *; clipboard-write *"
/>
// packages/web-app-external/src/composables/useCollaboraPostMessages.ts (before #4289)
async function handlePostMessagesCollabora(event: MessageEvent): Promise<void> {
try {
const message: CollaboraMessage = JSON.parse(event.data || '{}')
switch (message.MessageId) {
case 'App_LoadingStatus':
handleAppLoadingStatus(message)
break
case 'Doc_ModifiedStatus':
handleDocModifiedStatus(message)
break
case 'UI_Close':
handleUiClose()
break
case 'UI_SaveAs':
handleUiSaveAs(message)
break
case 'Action_Save_Resp':
await handleActionSaveResp(message)
break
case 'UI_InsertGraphic':
handleUiInsertGraphic()
break
case 'UI_InsertFile':
handleUiInsertFile(message)
break
case 'UI_Mention':
await handleUiMention(message)
break
case 'UI_PickLink':
handleUiPickLink()
break
}
} catch (e) {
console.debug('Error parsing Collabora PostMessage', e)
}
}
One detail that limits the damage: all these listeners are registered in onMounted and removed in onBeforeUnmount. They only exist while a picker or an external app view is open. That narrows the attack window a lot. But a narrow window is still a window. It doesn't authenticate anything.
Act 4: Building the trap
The proof of concept is a single HTML file, attacker.html, served locally on http://127.0.0.1:8765. OpenCloud runs on a different HTTPS origin; I'll call it https://cloud.example.
The page calls itself a "Local, harmless PoC for OpenCloud instance" and has four buttons:
- Open signed-in OpenCloud
- Send forged Copy/Move destination
- Send forged Save As destination
- Send forged Cancel
plus a text box labelled "Destination resource".
Step 1: get a handle
The first button calls window.open() and keeps the returned WindowProxy. Opening a window normally needs a user gesture, and the button click provides it.
That handle is all you need. The browser does not require the two pages to be same-origin. It does not require OpenCloud to opt in. You hold a reference to the window, so you can post to it.
Step 2: describe a folder
The text box holds a JSON description of an existing folder in the test account (identifiers redacted). The receiver will later treat this as resources[0]:
{
"id": "<folder-id>",
"fileId": "<folder-file-id>",
"storageId": "<storage-id>",
"name": "picker-poc-target",
"path": "/postmessage validation/picker-poc-target",
"type": "folder",
"mimeType": "httpd/unix-directory"
}
Step 3: forge the name tag
For Copy to and Move to, the array form that LocationPickerModal accepts:
{
"name": "opencloud-embed:select",
"data": [
{
"id": "<folder-id>",
"fileId": "<folder-file-id>",
"storageId": "<storage-id>",
"name": "picker-poc-target",
"path": "/postmessage validation/picker-poc-target",
"type": "folder",
"mimeType": "httpd/unix-directory"
}
]
}
For Save as, the object form, now with a file name of the attacker's choosing:
{
"name": "opencloud-embed:select",
"data": {
"resources": [
{
"id": "<folder-id>",
"fileId": "<folder-file-id>",
"storageId": "<storage-id>",
"name": "picker-poc-target",
"path": "/postmessage validation/picker-poc-target",
"type": "folder",
"mimeType": "httpd/unix-directory"
}
],
"fileName": "save-as-forged.md",
"locationQuery": {}
}
}
A cancel payload, { "name": "opencloud-embed:cancel", "data": null }, is prepared too. The recording doesn't show it being used, so I'm not claiming a demonstrated cancel effect.
In every case the sender sets targetOrigin correctly to the OpenCloud origin. It has to, or the browser wouldn't deliver the message. On arrival, event.origin is http://127.0.0.1:8765 and event.source is the attacker's window.
Before the fix, neither field was ever read.
That's the entire vulnerability.
Act 5: Three heists in 69 seconds
The recording runs about 69 seconds. Signed-in OpenCloud on the left, the PoC page on the right. Every step needs the same three things: a signed-in user, an OpenCloud window the test page holds a reference to, and an open picker, so that the listeners are mounted.
🟢 Heist #1: Copy to (≈ 0:15–0:24)
The folder postmessage validation contains private-copy.txt, the folder picker-poc-target, a screen recording and save-as-source.md.
private-copy.txt is selected. Copy to opens from the context menu. The normal location picker appears.
The test page fires the array-form opencloud-embed:select.
The dialog closes without anyone clicking a destination in the picker. The copy runs. Inside picker-poc-target: private-copy.txt.
The destination came from the foreign page, not from the user.
🟡 Heist #2: Move to (≈ 0:35–0:45)
The original private-copy.txt is selected again. Move to opens. The same forged selection is sent.
This time OpenCloud pushes back with its normal conflict dialog, because the earlier copy already put a file with that name in the target:
File already exists
File with name »private-copy.txt« already exists.
Skip · Replace · Keep both
In the recording I choose Keep both. The target now holds private-copy.txt and private-copy (1).txt, and the original is gone from the parent folder.
This detail matters, so I want to be loud about it: the existing file was not silently overwritten. The ordinary conflict handling still ran and still required a human decision. The forged message controlled the destination, not the conflict policy.
🔴 Heist #3: Save as (≈ 0:52–1:08)
save-as-source.md is open in the built-in text editor. It's a harmless dummy document headed "Picker PoC".
Save as opens the normal picker. The test page sends the object-form message with fileName: "save-as-forged.md".
OpenCloud shows a cheerful toast:
»save-as-forged.md« was saved successfully
and a new editor tab opens the saved file in picker-poc-target, with the same content as the source document.
Both the folder and the file name were chosen by a page OpenCloud had never met.
The scene at the end
When the recording stops, picker-poc-target holds three files:
save-as-forged.md
private-copy (1).txt
private-copy.txt
That's the entire observable result. Which brings us to the most important section of this post.
What this bug is, and what it is not
Security write-ups have a habit of growing in the telling. I'd rather not do that, so here is the claim split into three honest buckets.
✅ Observed in the recording
- A foreign-origin page forged the destination for Copy to and Move to.
- It forged both destination and file name for Save as.
- The resulting files appeared in the chosen folder.
- The normal "File already exists" dialog still appeared and still required a user choice.
- The Save-as toast appeared and a new editor tab opened the saved document.
🤔 Technically plausible, but not demonstrated
- If the chosen destination is readable by someone else (a shared folder, say), a redirected copy or save could expose a document's contents to that person, and a redirected move could hurt the availability or integrity of the original.
- Per the PR description, the external-app handlers could be triggered to switch to edit mode or open extra dialogs.
- All of this stays bounded by the victim's own permissions and the server's authorization checks.
❌ Not demonstrated, and not claimed
Remote code execution. Account takeover. Direct exfiltration of file contents to the attacker's server. Arbitrary file reads that bypass backend permissions. Silent overwrite of existing documents. Any backend authorization bypass.
The backend did its job. copySelectedFiles, moveSelectedFiles and putFileContents still went to the server with the victim's token, and the server still applied its ACLs. The PoC used a folder inside the victim's own account that the victim could write to. Nothing in the recording suggests a destination outside their permissions would have worked.
A forged picker selection is a serious integrity problem in an authenticated client. It is not the same as reading arbitrary files or stealing a session. The recording shows file operations being steered inside the victim's own account. It does not show data leaving OpenCloud.
The root cause: a trust boundary nobody drew
The same-origin policy can't protect a window that registers a global message listener, because postMessage is the browser's official way across that wall.
The moment you write:
window.addEventListener('message', ...)
you've published an endpoint. The browser will hand you events from any window that can get a WindowProxy for yours. Deciding which of those events to trust is your job.
OpenCloud decided based on event.data.name, a routing key. The boundary between "some untrusted window" and "the iframe I created and loaded with my own embed URL" simply didn't exist on the receiving side.
Act 6: The fix fits on a sticky note
PR #4289 adds one small helper and wires it into every affected handler. This is the complete new file:
// packages/web-pkg/src/helpers/postMessage.ts (added by #4289)
export function isMessageFromIframe(
event: MessageEvent,
iframe: HTMLIFrameElement | null | undefined,
expectedOrigin?: string
): boolean {
if (!iframe?.contentWindow || event.source !== iframe.contentWindow) {
return false
}
return !expectedOrigin || event.origin === expectedOrigin
}
It's re-exported from the helpers barrel so both packages can use it:
// packages/web-pkg/src/helpers/index.ts (added by #4289)
export * from './postMessage'
Eleven lines. Three things make them the right eleven lines.
1. It fails closed. !iframe?.contentWindow means: no ref, iframe not loaded, element gone → reject. A missing contentWindow never gets reinterpreted as "unknown, so allow".
2. It compares identity, not strings. event.source !== iframe.contentWindow compares two WindowProxy references. iframe.contentWindow is a stable proxy for the iframe the component itself rendered. The browser sets event.source to whoever actually called postMessage. An attacker can stuff anything into event.data, but they can't make event.source point at a window they don't control, and certainly not at the victim's picker iframe. In the PoC, event.source is the attacker's own window, so the very first condition kills it.
3. It binds the origin when it can. contentWindow stays the same object across navigations of that frame. If the picker iframe were ever navigated to another origin, a source-only check would still pass. The origin check wouldn't.
For the pickers, the expected origin is free: the iframe loads OpenCloud's own embed URL. The modals build iframeUrl with new URL(buildUrl(router, parentFolderLink)) and append the embed parameters, so iframeUrl.origin is the OpenCloud origin, and that's what gets passed as the third argument.
External apps are different. Collabora and WOPI-style integrations are served from the app provider's origin, not OpenCloud's, so those call sites pass only the iframe ref and rely on the source identity check. Both choices are visible in the diff, and both are deliberate.
Show: buildUrl.ts, where the expected origin comes from
// packages/web-pkg/src/helpers/router/buildUrl.ts
export const buildUrl = (router: Router, to: RouteLocationRaw) => {
const base = document.querySelector('base')
const isHistoryMode = !!base
const baseUrl = new URL(window.location.href.split('#')[0])
baseUrl.search = ''
if (isHistoryMode) {
// in history mode we can't determine the base path, it must be provided by the document
baseUrl.pathname = new URL(base.href).pathname
} else {
// in hash mode, auto-determine the base path by removing `/index.html`
if (baseUrl.pathname.endsWith('/index.html')) {
baseUrl.pathname = baseUrl.pathname.split('/').slice(0, -1).filter(Boolean).join('/')
}
}
/**
* build full url by either
* - concatenating baseUrl and path (for unknown/non-router urls, e.g. `oidc-callback.html`) or
* - resolving via router (for known routes, given as path or route location)
*/
if (typeof to === 'string' && /\.(html?)$/i.test(to)) {
baseUrl.pathname = [...baseUrl.pathname.split('/'), ...to.split('/')].filter(Boolean).join('/')
return baseUrl.href
}
const { href } = router.resolve(to)
if (isHistoryMode) {
return new URL(href, baseUrl).href
}
baseUrl.hash = href
return baseUrl.href
}
The bouncer gets a new first question
Here's LocationPickerModal.vue after the fix:
// packages/web-pkg/src/components/Modals/LocationPickerModal.vue (after #4289)
const onLocationPick = (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:select'
) {
return
}
let resources = (data.data as embedModeLocationPickMessageData)?.resources
let fileName = (data.data as embedModeLocationPickMessageData)?.fileName
if (Array.isArray(data.data)) {
resources = data.data as embedModeLocationPickMessageData['resources']
fileName = undefined
}
if (!resources?.length) {
return
}
callbackFn(resources, { fileName })
removeModal(modal.id)
}
The bouncer no longer starts with "what does your name tag say?" The first question is now "did you come out of my iframe?" Only then does the name tag matter.
Two smaller hardening details came along for the ride:
- Handlers now take the whole
eventand destructuredata, instead of only ever seeingdata. -
data?.nameinstead ofdata.name, so a message whosedatais a string ornullno longer throws before the guard runs.
The same guard lands in FilePickerModal.vue and in both handlers of SaveAsModal.vue.
Show: FilePickerModal.vue and SaveAsModal.vue after the fix
// packages/web-pkg/src/components/Modals/LocationPickerModal.vue (after #4289)
const onCancel = (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:cancel'
) {
return
}
removeModal(modal.id)
}
// packages/web-pkg/src/components/Modals/FilePickerModal.vue (after #4289)
const onFilePick = (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:file-pick'
) {
return
}
const { resource, locationQuery }: embedModeFilePickMessageData = data.data
callbackFn({ resource, locationQuery })
removeModal(modal.id)
}
const onCancel = (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:cancel'
) {
return
}
removeModal(modal.id)
}
// packages/web-pkg/src/components/Modals/SaveAsModal.vue (after #4289)
const onLocationPick = async (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:select'
) {
return
}
const { resources, fileName, locationQuery }: embedModeLocationPickMessageData = data.data
const destinationFolder: Resource = resources[0]
const space = getMatchingSpace(destinationFolder)
try {
const resource = await saveFile({ destinationFolder, fileName, space })
if (resource) {
showMessage({
title: $gettext('»%{fileName}« was saved successfully', { fileName: resource.name })
})
openFile({ resource, space, locationQuery })
}
} catch (e) {
console.error(e)
showErrorMessage({
title: $gettext('Unable to save »%{fileName}«', { fileName }),
errors: [e]
})
console.error(e)
}
removeModal(modal.id)
}
// packages/web-pkg/src/components/Modals/SaveAsModal.vue (after #4289)
const onCancel = (event: MessageEvent) => {
const { data } = event
if (
!isMessageFromIframe(event, unref(iframeRef), iframeUrl.origin) ||
data?.name !== 'opencloud-embed:cancel'
) {
return
}
removeModal(modal.id)
}
The easy-to-miss line in the external apps
In App.vue, the fix guards the Microsoft edit handler:
// packages/web-app-external/src/App.vue (after #4289)
const appIframeRef = useTemplateRef<HTMLIFrameElement>('appIframe')
// switch to write mode when edit is clicked
const catchClickMicrosoftEdit = (event: MessageEvent) => {
if (!isMessageFromIframe(event, unref(appIframeRef))) {
return
}
try {
if (JSON.parse(event.data)?.MessageId === 'UI_Edit') {
loadAppUrl.perform('write')
}
} catch {}
}
But the line I find most interesting is a tiny one in the template:
<!-- packages/web-app-external/src/App.vue (after #4289) -->
<iframe
v-else-if="appUrl && method === 'GET'"
ref="appIframe"
:src="appUrl"
class="size-full"
:title="iFrameTitle"
allowfullscreen
allow="clipboard-read *; clipboard-write *"
/>
ref="appIframe" on the GET iframe. Before, only the POST iframe (the Collabora form-target case) had it. Without this line, useTemplateRef('appIframe') would be null for GET-based apps and the new check could never succeed, quietly breaking them. The PR also moves appIframeRef above its first use.
Show: the Collabora handler after the fix
// packages/web-app-external/src/composables/useCollaboraPostMessages.ts (after #4289)
async function handlePostMessagesCollabora(event: MessageEvent): Promise<void> {
if (!isMessageFromIframe(event, unref(appIframeRef))) {
return
}
try {
const message: CollaboraMessage = JSON.parse(event.data || '{}')
switch (message.MessageId) {
case 'App_LoadingStatus':
handleAppLoadingStatus(message)
break
case 'Doc_ModifiedStatus':
handleDocModifiedStatus(message)
break
case 'UI_Close':
handleUiClose()
break
case 'UI_SaveAs':
handleUiSaveAs(message)
break
case 'Action_Save_Resp':
await handleActionSaveResp(message)
break
case 'UI_InsertGraphic':
handleUiInsertGraphic()
break
case 'UI_InsertFile':
handleUiInsertFile(message)
break
case 'UI_Mention':
await handleUiMention(message)
break
case 'UI_PickLink':
handleUiPickLink()
break
}
} catch (e) {
console.debug('Error parsing Collabora PostMessage', e)
}
}
The whole PR: one commit, 12 files, +452 / −134. Three picker modals, the external app component and composable, the helpers barrel, the new helper, and six test files (five modified, one added).
Act 7: The tests that keep it fixed
Here's a slightly controversial opinion: the most valuable lines in #4289 aren't the helper. They're the tests.
A sender check without a regression test tends to vanish in the next refactor. These tests make sure it can't.
The helper, branch by branch
// packages/web-pkg/tests/unit/helpers/postMessage.spec.ts (added by #4289)
import { isMessageFromIframe } from '../../../src/helpers/postMessage'
function createMessageEvent({ source, origin }: { source: unknown; origin: string }) {
const event = new MessageEvent('message', { origin })
Object.defineProperty(event, 'source', { value: source })
return event
}
describe('isMessageFromIframe', () => {
const contentWindow = {}
const iframe = { contentWindow } as unknown as HTMLIFrameElement
it('returns true if source and origin match', () => {
const event = createMessageEvent({ source: contentWindow, origin: 'https://cloud.example' })
expect(isMessageFromIframe(event, iframe, 'https://cloud.example')).toBe(true)
})
it('returns true if source matches and no origin is expected', () => {
const event = createMessageEvent({ source: contentWindow, origin: 'https://other.example' })
expect(isMessageFromIframe(event, iframe)).toBe(true)
})
it('returns false if the source is a different window', () => {
const event = createMessageEvent({ source: {}, origin: 'https://cloud.example' })
expect(isMessageFromIframe(event, iframe, 'https://cloud.example')).toBe(false)
})
it('returns false if the origin does not match', () => {
const event = createMessageEvent({ source: contentWindow, origin: 'https://attacker.example' })
expect(isMessageFromIframe(event, iframe, 'https://cloud.example')).toBe(false)
})
it.each([null, undefined, { contentWindow: null } as unknown as HTMLIFrameElement])(
'returns false if the iframe is not available',
(unavailableIframe) => {
const event = createMessageEvent({ source: null, origin: 'https://cloud.example' })
expect(isMessageFromIframe(event, unavailableIframe)).toBe(false)
}
)
})
Matching source and origin. Matching source with no expected origin. Wrong window. Wrong origin. No iframe at all. Every branch that matters, and nothing else.
Faking what can't be faked
MessageEvent.source is read-only, so the component specs build real events and redefine the property:
// packages/web-pkg/tests/unit/components/Modals/FilePickerModal.spec.ts (added by #4289)
function createMessageEvent(
wrapper: ReturnType<typeof getWrapper>['wrapper'],
{ data }: { data: unknown },
{ source, origin = 'http://localhost:3000' }: { source?: unknown; origin?: string } = {}
) {
const event = new MessageEvent('message', { data, origin })
Object.defineProperty(event, 'source', {
value: source === undefined ? wrapper.find('iframe').element.contentWindow : source
})
return event
}
jsdom doesn't give an iframe a usable contentWindow, so the setup stubs one with Object.defineProperty(wrapper.find('iframe').element, 'contentWindow', { value: {} }). That stub is what the identity comparison runs against.
Each modal spec then gets a message sender verification block with two negative cases per message name:
| Case | Means |
|---|---|
{ source: {}, origin: 'http://localhost:3000' } |
wrong window, right origin |
{ source: undefined, origin: 'http://attacker.example' } |
right window, wrong origin |
That source: undefined case is worth reading twice. Because of the default in createMessageEvent, undefined means "use the real iframe". So it's the right window with the wrong origin. Together, the two cases exercise both halves of isMessageFromIframe independently.
Show: the full verification block from LocationPickerModal.spec.ts
// packages/web-pkg/tests/unit/components/Modals/LocationPickerModal.spec.ts (added by #4289)
describe('message sender verification', () => {
it.each([
{ source: {}, origin: 'http://localhost:3000' },
{ source: undefined, origin: 'http://attacker.example' }
])(
'ignores "opencloud-embed:select" messages not sent by the picker iframe (%o)',
async ({ source, origin }) => {
const { wrapper } = getWrapper()
const modalStore = useModals()
await (wrapper.vm as any).onLocationPick(
createMessageEvent(
wrapper,
{
data: {
name: 'opencloud-embed:select',
data: { resources: [mock<Resource>({ storageId: '1' })] }
}
},
{ source, origin }
)
)
expect((wrapper.vm as any).callbackFn).not.toHaveBeenCalled()
expect(modalStore.removeModal).not.toHaveBeenCalled()
}
)
it.each([
{ source: {}, origin: 'http://localhost:3000' },
{ source: undefined, origin: 'http://attacker.example' }
])(
'ignores "opencloud-embed:cancel" messages not sent by the picker iframe (%o)',
({ source, origin }) => {
const { wrapper } = getWrapper()
const modalStore = useModals()
;(wrapper.vm as any).onCancel(
createMessageEvent(
wrapper,
{ data: { name: 'opencloud-embed:cancel' } },
{ source, origin }
)
)
expect(modalStore.removeModal).not.toHaveBeenCalled()
}
)
it('closes the modal on "opencloud-embed:cancel" sent by the picker iframe', () => {
const { wrapper } = getWrapper()
const modalStore = useModals()
;(wrapper.vm as any).onCancel(
createMessageEvent(wrapper, { data: { name: 'opencloud-embed:cancel' } })
)
expect(modalStore.removeModal).toHaveBeenCalled()
})
})
The Save-as spec asserts the strongest consequence of all:
expect(mocks.$clientService.webdav.putFileContents).not.toHaveBeenCalled()
because that's exactly where a forged message used to turn into a write. And every block ends with a positive control: a legitimate cancel from the real picker iframe still closes the modal. The fix doesn't break the feature.
Probing Collabora with UI_Close
// packages/web-app-external/tests/unit/composables/useCollaboraPostMessages.spec.ts (added by #4289)
describe('message sender verification', () => {
it.each([
{ description: 'another window', source: {} },
{ description: 'no window', source: null }
])('ignores messages sent by $description', async ({ source }) => {
const { instance, onClose } = getWrapper()
await instance.handlePostMessagesCollabora(
createMessageEvent({ MessageId: 'UI_Close' }, source)
)
expect(onClose).not.toHaveBeenCalled()
expect(mockMentionUsers.notifyMentionedUsers).not.toHaveBeenCalled()
})
it('ignores messages when the iframe is not available', async () => {
const { instance, onClose } = getWrapper({
appIframeRef: ref<HTMLIFrameElement | null>(null)
})
await instance.handlePostMessagesCollabora(createMessageEvent({ MessageId: 'UI_Close' }, {}))
expect(onClose).not.toHaveBeenCalled()
})
})
UI_Close is a clever probe: the unfixed handler calls both notifyMentionedUsers() and onClose(), so both assertions fail if the event gets through.
What I like most about the whole test design: it asserts observable behaviour. No callback. No modal removal. No WebDAV write. Not internal flags. That's exactly what a regression test for a security fix should pin down.
Your postMessage checklist
If your frontend uses postMessage, this list is short and unforgiving.
Every
addEventListener('message', ...)is a public API endpoint.event.datais untrusted input in the strongest sense: any window that can reach you can set it to any structured-cloneable value.Check
event.originwith exact equality. Not a prefix, suffix or substring.startsWith('https://example.com')happily matcheshttps://example.com.attacker.test. Compute the expected value from your own config (new URL(...).origin) instead of hardcoding it.Check
event.sourceagainst the exactWindowProxyyou expect.iframe.contentWindow, or the reference returned by your ownwindow.open(). Compare identity, not URLs. This is the check that stops a foreign page holding a reference to your window, which is precisely the PoC scenario. Where you own both ends, use both checks:sourcebinds the browsing context,originbinds the origin, and they fail in different cases.Validate the shape of
event.data. Anamefield is a routing hint. If the payload drives a write, a navigation or a permission change, parse it defensively and reject anything malformed. Thedata?.namechange in this PR is a small example of that habit.Scope the listener's lifetime. Register on mount, remove on unmount. OpenCloud already did this, which is why the exposure was limited to an open picker. Keep doing it, but don't mistake it for authentication.
Remember which way
targetOriginpoints. On the sending side it restricts who may receive. On the receiving side it tells you nothing about who sent. Prefer an explicit origin over'*'for outbound messages too. (That's a separate concern; this PR deliberately fixes the inbound side only.) If you control both ends and need a truly private channel,MessageChannelgives you a port no third window can post to.Test the negative case as a first-class behaviour.
not.toHaveBeenCalled()for a foreign source and a foreign origin. That's what keeps your fix alive after the next refactor.
From fix commit to three releases in one week
The finding was reported privately to the OpenCloud maintainers before anything went public. PR #4289 credits it explicitly: "Security finding reported by zerox80. Thank you very much!" I'm not reproducing the private report, the private evidence link or any instance-specific data here.
| When (UTC) | What happened |
|---|---|
| 2026-11-04 14:38 | Fix commit c4ef9619… authored (Benedikt Kulmann). |
| 2026-11-05 07:19 |
PR #4289 opened by kulmann against main, labelled Type:Bug, Type:Security, backport-required. |
| 2026-11-05 07:58 | #4289 merged by AlexAndBear (one commit, 12 files). |
| 2026-11-05 08:53 → 09:57 |
PR #4295, the manual backport to stable-7.1, opened and merged. The automatic backport had conflicts. |
| 2026-11-05 09:24 → 10:14 | Follow-up issue #4296 and PR #4297 close the same class of gap for delegated embed-mode tokens. A neighbouring entry point, not part of this finding. |
| 2026-11-11 09:46 → 11:34 |
PR #4431 ports the security fixes, including #4289, to stable-4.2. |
| 2026-11-11 11:39–11:49 | 🚀 Releases 4.2.3, 7.1.6 and 8.2.2 published. |
Which build has the fix?
Check the release notes:
-
8.2.2 lists it under
### 🔒 Security: fix: verify the sender of postMessage events in picker modals and external apps [#4289]. - 7.1.6 lists the backport #4295.
- 4.2.3 names #4431, whose body says it's a "backport of #4289", rather than naming the postMessage fix directly.
- The root
CHANGELOG.mdcarries the same entries. - A prerelease 8.2.2-beta.1 was published on 9 November with empty release notes; the fix commit is an ancestor of that tag.
A few honest caveats
- Public sources don't attach an affected version label to this issue. The versions above are the patched ones. I reproduced the behaviour on a rolling build of my own instance, and I won't turn that into a general affected-version claim.
- At the time of writing, no CVE and no GitHub Security Advisory are attached to this finding. The two advisories published on 11 November 2026 in
opencloud-eu/webcover unrelated XSS issues. - I'm not assigning a CVSS score or CWE number, and this post contains no turnkey exploit: only message shapes and a description of a local test page.
Thank you
To kulmann for the quick fix, to AlexAndBear for the merge and the backport, and to the reviewers. Private report → merged fix with regression tests → stable-branch backports → three patched releases. That's how it's supposed to work, and it's genuinely nice to see it work.
The moral, in one line
datatells you what a message says. Onlyoriginandsourcetell you who said it. Check who, before you listen to what.
References
The fix
- PR #4289: fix: verify the sender of postMessage events in picker modals and external apps · full diff
- Backport #4295 to stable-7.1 · aggregate port #4431 to stable-4.2 · follow-up #4297 · issue #4296
- Release notes: 8.2.2 · 7.1.6 · 4.2.3 · CHANGELOG.md
Source before the fix (71c5c57)
- LocationPickerModal.vue · SaveAsModal.vue · FilePickerModal.vue · App.vue · useCollaboraPostMessages.ts
Source at the fix (c4ef961)
- helpers/postMessage.ts · LocationPickerModal.vue · SaveAsModal.vue · FilePickerModal.vue · App.vue · useCollaboraPostMessages.ts · postMessage.spec.ts
Unchanged neighbouring code at c4ef961
Background reading
Top comments (0)