Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions cypress/e2e/direct.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,48 @@ describe('Direct editing (legacy)', function() {
})
})

describe('PostMessage origin security', function() {
it('rejects messages from an unexpected origin', function() {
createDirectEditingLink(randUser, fileId)
.then((token) => {
cy.nextcloudTestingAppConfigSet('richdocuments', 'uiDefaults-UIMode', 'classic')
cy.logout()
cy.visit(token, {
onBeforeLoad(win) {
cy.spy(win, 'postMessage').as('postMessage')
},
})
cy.waitForCollabora(false)
cy.waitForPostMessage('App_LoadingStatus', { Status: 'Document_Loaded' })

cy.window().then(win => {
cy.spy(win.console, 'warn').as('consoleWarn')
})
cy.dispatchMessageFromOrigin('https://evil.example.com', { MessageId: 'Action_Save', Values: {} })
cy.get('@consoleWarn').should('have.been.calledWith',
'PostMessageService: rejected message from unexpected origin',
'https://evil.example.com'
)
})
})

it('sends messages with the Collabora targetOrigin', function() {
createDirectEditingLink(randUser, fileId)
.then((token) => {
cy.nextcloudTestingAppConfigSet('richdocuments', 'uiDefaults-UIMode', 'classic')
cy.logout()
cy.visit(token)
cy.waitForCollabora(false)
cy.get('[data-cy="coolframe"]').then($iframe => {
const collaboraOrigin = $iframe[0].contentWindow.location.origin
cy.spy($iframe[0].contentWindow, 'postMessage').as('postMessage')
cy.dispatchMessageFromOrigin(collaboraOrigin, { MessageId: 'App_LoadingStatus', Values: { Status: 'Document_Loaded' } })
cy.waitForPostMessage('Host_PostmessageReady', undefined, { targetOrigin: collaboraOrigin })
})
})
})
})

it('Open a remotely shared file', () => {
cy.createRandomUser().then(shareRecipient => {
cy.login(randUser)
Expand Down
53 changes: 53 additions & 0 deletions cypress/e2e/open.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,56 @@ describe('Open PDF with richdocuments', () => {
cy.closeDocument()
})
})

describe('PostMessage origin security', function() {
let randUser

before(function() {
cy.createRandomUser().then(user => {
randUser = user
cy.login(user)
cy.uploadFile(user, 'document.odt', 'application/vnd.oasis.opendocument.text', '/document.odt')
})
})

beforeEach(function() {
cy.login(randUser)
})

it('rejects messages from an unexpected origin', function() {
cy.visit('/apps/files', {
onBeforeLoad(win) {
cy.spy(win, 'postMessage').as('postMessage')
},
})
cy.openFile('document.odt')
cy.waitForViewer()
cy.waitForCollabora()
cy.waitForPostMessage('App_LoadingStatus', { Status: 'Document_Loaded' })

cy.window().then(win => {
cy.spy(win.console, 'warn').as('consoleWarn')
})
cy.dispatchMessageFromOrigin('https://evil.example.com', { MessageId: 'Action_Save', Values: {} })
cy.get('@consoleWarn').should('have.been.calledWith',
'PostMessageService: rejected message from unexpected origin',
'https://evil.example.com'
)
cy.closeDocument()
})

it('sends messages with the Collabora targetOrigin', function() {
cy.visit('/apps/files')
cy.openFile('document.odt')
cy.waitForViewer()
cy.waitForCollabora()
cy.get('[data-cy="coolframe"]').then($iframe => {
const collaboraOrigin = $iframe[0].contentWindow.location.origin
cy.spy($iframe[0].contentWindow, 'postMessage').as('postMessage')
cy.dispatchMessageFromOrigin(collaboraOrigin, { MessageId: 'App_LoadingStatus', Values: { Status: 'Document_Loaded' } })
cy.waitForPostMessage('Host_PostmessageReady', undefined, { targetOrigin: collaboraOrigin })
})

cy.closeDocument()
})
})
60 changes: 51 additions & 9 deletions cypress/support/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,18 +276,51 @@ Cypress.Commands.add('waitForCollabora', (wrapped = false, federated = false) =>
return cy.get('@loleafletframe')
})

Cypress.Commands.add('waitForPostMessage', (messageId, values = undefined) => {
Cypress.Commands.add('waitForPostMessage', (messageId, expectedValues = undefined, options = {}) => {
const { targetOrigin } = options
const checkExpectedValues = (message, values) => {
for (const [key, value] of Object.entries(values)) {
if (!message.Values[key] || message.Values[key] !== value) {
return false
}
}

return true
}

cy.get('@postMessage', { timeout: 20000 }).should(spy => {
const calls = spy.getCalls()
const findMatchingCall = calls.find(call => call.args[0].indexOf('"MessageId":"' + messageId + '"') !== -1)
if (!findMatchingCall) {
return expect(findMatchingCall).to.not.be.undefined
const messagesMatchingId = []

// Find all messages matching the given ID
// We do it this way to avoid the shallow copy of Array.filter()
for (const call of calls) {
if (call.args[0].includes(`"MessageId":"${messageId}"`)) {
messagesMatchingId.push({ message: JSON.parse(call.args[0]), call })
}
}
if (!values) {
const object = JSON.parse(findMatchingCall.args[0])
values.forEach(value => {
expect(object.Values).to.have.property(value, values[value])
})

expect(messagesMatchingId.length).to.be.greaterThan(0)

if (expectedValues) {
const messagesMatchingValues = []

for (const { message } of messagesMatchingId) {
if (checkExpectedValues(message, expectedValues)) {
messagesMatchingValues.push(message)
}
}

expect(messagesMatchingValues.length).to.be.greaterThan(0)
}

if (targetOrigin) {
for (const { call } of messagesMatchingId) {
expect(call.args[1]).to.equal(
targetOrigin,
`Expected targetOrigin for ${messageId} to be ${targetOrigin}`,
)
}
}
})
})
Expand Down Expand Up @@ -323,3 +356,12 @@ Cypress.Commands.add('uploadSystemTemplate', () => {
}, { force: true })
cy.get('#richdocuments-templates li').contains('systemtemplate.otp')
})

Cypress.Commands.add('dispatchMessageFromOrigin', (origin, message) => {
cy.window().then(win => {
win.dispatchEvent(new win.MessageEvent('message', {
origin,
data: JSON.stringify(message),
}))
})
})
17 changes: 15 additions & 2 deletions src/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
const checkProxyStatus = () => {
checkingProxyStatus = true
const url = Config.get('urlsrc').slice(0, Config.get('urlsrc').indexOf('proxy.php') + 'proxy.php'.length)
$.get(url + '?status').done(function(val) {

Check warning on line 35 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
if (val && val.status && val.status !== 'OK') {
if (val.status === 'starting' || val.status === 'stopped') {
document.getElementById('proxyLoadingIcon').classList.add('icon-loading-small')
Expand Down Expand Up @@ -145,8 +145,8 @@
showViewer(fileId, title) {
// remove previous viewer, if open, and set a new one
if (documentsMain.isViewerMode) {
$('#revViewer').remove()

Check warning on line 148 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
$('#revViewerContainer').prepend($('<div id="revViewer">'))

Check warning on line 149 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0

Check warning on line 149 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
}

const urlsrc = getWopiUrl({ fileId, title, readOnly: true, closeButton: !documentsMain.hideCloseButton })
Expand All @@ -169,12 +169,12 @@
// iframe that contains the Collabora Online Viewer
const frame = '<iframe data-cy="coolframe" id="loleafletframe" name="loleafletframe_viewer" allowfullscreen allow="clipboard-read *; clipboard-write *" nonce="' + btoa(getRequestToken()) + '" style="width:100%;height:100%;position:absolute;" title="' + loadState('richdocuments', 'productName', 'Nextcloud Office') + '"/>'

$('#revViewer').append(form)

Check warning on line 172 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
$('#revViewer').append(frame)

Check warning on line 173 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
$('#loleafletframe_viewer').focus()

Check warning on line 174 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0

// submit that
$('#loleafletform_viewer').submit()

Check warning on line 177 in src/document.js

View workflow job for this annotation

GitHub Actions / NPM lint

The global property or function $ was deprecated in Nextcloud 19.0.0
documentsMain.isViewerMode = true
// for closing revision mode
$('#revViewerContainer .closeButton').click(function(e) {
Expand Down Expand Up @@ -554,7 +554,20 @@
initSession() {
PostMessages.sendPostMessage('parent', 'loading')

documentsMain.urlsrc = Config.get('urlsrc')
const urlsrc = Config.get('urlsrc')
if (urlsrc) {
try {
PostMessages.setAllowedOrigins([
new URL(urlsrc).origin,
window.location.origin,
])
PostMessages.setTargetOrigins({
loolframe: new URL(urlsrc).origin,
parent: window.location.origin,
})
} catch (e) {}
}
documentsMain.urlsrc = urlsrc
documentsMain.fullPath = Config.get('path')
documentsMain.token = Config.get('token')
documentsMain.tokenTtl = Config.get('token_ttl') * 1000
Expand Down Expand Up @@ -600,7 +613,7 @@
documentsMain.UI.hideEditor()
documentsMain.openLocally()

PostMessages.sendPostMessage('parent', 'close', '*')
PostMessages.sendPostMessage('parent', 'close')
},

onCloseViewer() {
Expand Down
19 changes: 17 additions & 2 deletions src/services/postMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,37 @@ interface WindowCallbackHandler { (): Window}
export default class PostMessageService {
private readonly targets: {[name: string]: (Window|WindowCallbackHandler)};
private postMessageHandlers: Function[] = [];
private allowedOrigins: string[] = [];
private targetOrigins: {[name: string]: string} = {};

constructor(targets: {[name: string]: (Window|WindowCallbackHandler)}) {
this.targets = targets
window.addEventListener('message', (event: {source: MessageEventSource, data: any, origin: string}) => {
if (this.allowedOrigins.length > 0 && !this.allowedOrigins.includes(event.origin)) {
console.warn('PostMessageService: rejected message from unexpected origin', event.origin)
return
}
this.handlePostMessage(event.data)
}, false)
}

sendPostMessage(target: string, message: any, targetOrigin: string = '*') {
setAllowedOrigins(origins: string[]): void {
this.allowedOrigins = origins
}

setTargetOrigins(origins: {[name: string]: string}): void {
this.targetOrigins = origins
}

sendPostMessage(target: string, message: any, targetOrigin?: string) {
let targetElement: Window;
if (typeof this.targets[target] === 'function') {
targetElement = (this.targets[target] as WindowCallbackHandler)()
} else {
targetElement = this.targets[target] as Window
}
targetElement.postMessage(message, targetOrigin)
const origin = targetOrigin ?? this.targetOrigins[target] ?? '*'
targetElement.postMessage(message, origin)
console.debug('PostMessageService.sendPostMessage', target, message)
}

Expand Down
12 changes: 12 additions & 0 deletions src/view/Office.vue
Original file line number Diff line number Diff line change
Expand Up @@ -323,13 +323,25 @@ export default {
})

if (data.federatedUrl) {
try {
this.postMessage.setAllowedOrigins([new URL(data.federatedUrl).origin, window.location.origin])
this.postMessage.setTargetOrigins({ FRAME_DOCUMENT: new URL(data.federatedUrl).origin })
} catch (e) {
console.warn('[richdocuments] Could not derive origin from federatedUrl', e)
}
this.$set(this.formData, 'action', data.federatedUrl)
this.$nextTick(() => this.$refs.form.submit())
this.loading = LOADING_STATE.DOCUMENT_READY
return
}

Config.update('urlsrc', data.urlSrc)
try {
this.postMessage.setAllowedOrigins([new URL(data.urlSrc).origin, window.location.origin])
this.postMessage.setTargetOrigins({ FRAME_DOCUMENT: new URL(data.urlSrc).origin })
} catch (e) {
console.warn('[richdocuments] Could not derive Collabora origin from urlsrc', e)
}
Config.update('wopi_callback_url', loadState('richdocuments', 'wopi_callback_url', ''))

const forceReadOnly = this.isEmbedded && !this.hasWidgetEditingEnabled
Expand Down
Loading