Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.
TypeScript cloud-alternativecollaborationcollaborative-editingdropboxfile-serverfile-sharingfile-storagefile-syncfull-text-searchhomelabnextcloudon-premiseopen-sourceprivacy-firstprivate-cloudrealtimesecureself-hostedstorage-serverwebdav
fix(backend:onlyoffice): validate document download origin
johavend0de7787ed6e
diff --git a/backend/src/applications/files/editors/only-office/only-office-environment.decorator.ts b/backend/src/applications/files/editors/only-office/only-office-environment.decorator.tsindex 190ef0bc..aeeea876 100644--- a/backend/src/applications/files/editors/only-office/only-office-environment.decorator.ts+++ b/backend/src/applications/files/editors/only-office/only-office-environment.decorator.ts@@ -1,9 +1,10 @@-import { applyDecorators, SetMetadata, UseGuards } from '@nestjs/common'+import { applyDecorators, SetMetadata, UseGuards, UseInterceptors } from '@nestjs/common'+import { ContextInterceptor } from '../../../../infrastructure/context/interceptors/context.interceptor'import { SpaceGuard } from '../../../spaces/guards/space.guard'import { ONLY_OFFICE_CONTEXT } from './only-office.constants'import { OnlyOfficeGuard } from './only-office.guard'export const OnlyOfficeContext = () => SetMetadata(ONLY_OFFICE_CONTEXT, true)export const OnlyOfficeEnvironment = () => {- return applyDecorators(OnlyOfficeContext(), UseGuards(OnlyOfficeGuard, SpaceGuard))+ return applyDecorators(OnlyOfficeContext(), UseInterceptors(ContextInterceptor), UseGuards(OnlyOfficeGuard, SpaceGuard))}diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.tsindex c30ab577..b01b951e 100644--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.spec.ts@@ -31,6 +31,7 @@ describe(OnlyOfficeManager.name, () => {let jwtService: Mocked<JwtService>let filesLockManager: Mocked<FilesLockManager>let onlyOfficeEnabled: boolean+ let onlyOfficeExternalServer: stringconst mockUser = {id: 1,@@ -64,7 +65,9 @@ describe(OnlyOfficeManager.name, () => {beforeEach(async () => {onlyOfficeEnabled = configuration.applications.files.editors.onlyoffice.enabled+ onlyOfficeExternalServer = configuration.applications.files.editors.onlyoffice.externalServerconfiguration.applications.files.editors.onlyoffice.enabled = true+ configuration.applications.files.editors.onlyoffice.externalServer = nullconst module: TestingModule = await Test.createTestingModule({providers: [@@ -120,6 +123,7 @@ describe(OnlyOfficeManager.name, () => {afterEach(() => {configuration.applications.files.editors.onlyoffice.enabled = onlyOfficeEnabled+ configuration.applications.files.editors.onlyoffice.externalServer = onlyOfficeExternalServervi.clearAllMocks()})@@ -246,6 +250,7 @@ describe(OnlyOfficeManager.name, () => {describe('callBack', () => {const mockToken = 'mock-callback-token'+ const mockDocumentUrl = 'http://localhost:3000/onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'beforeEach(() => {filesLockManager.removeLock.mockResolvedValue(undefined)@@ -259,40 +264,43 @@ describe(OnlyOfficeManager.name, () => {vi.mocked(filesUtils.removeFiles).mockResolvedValue(undefined)})- it('should handle status 1 (document being edited)', async () => {- jwtService.verifyAsync.mockResolvedValue({- status: 1,- actions: [],- users: ['1']- })-- const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)-- expect(result).toEqual({ error: 0 })- })+ const mockSuccessfulDownload = () => {+ httpService.axiosRef.mockResolvedValue({+ data: Readable.from(['mock content']),+ headers: { 'content-length': '12' },+ status: 200,+ statusText: 'OK',+ config: {} as any+ } as AxiosResponse)+ }- it('should handle status 2 (document closed with changes)', async () => {+ const expectSuccessfulSaveCallback = async (url: string, callbackData: Record<string, any> = {}) => {jwtService.verifyAsync.mockResolvedValue({status: 2,actions: [],users: [],notmodified: false,- url: 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'+ url,+ ...callbackData})-- const mockStream = Readable.from(['mock content'])- httpService.axiosRef.mockResolvedValue({- data: mockStream,- headers: { 'content-length': '12' },- status: 200,- statusText: 'OK',- config: {} as any- } as AxiosResponse)+ mockSuccessfulDownload()const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)expect(result).toEqual({ error: 0 })- expect(httpService.axiosRef).toHaveBeenCalled()+ expect(httpService.axiosRef).toHaveBeenCalledWith(expect.objectContaining({ url, maxRedirects: 0 }))+ }++ it('should allow internal container document downloads when external server is not configured', async () => {+ const internalDocumentUrl = 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'+ await expectSuccessfulSaveCallback(internalDocumentUrl)+ })++ it('should allow document downloads from the external server origin with a rewritten path', async () => {+ ;(service as any).externalOnlyOfficeServer = 'https://office.example.com/onlyoffice'+ const rewrittenPathUrl =+ 'https://office.example.com/cache/files/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'+ await expectSuccessfulSaveCallback(rewrittenPathUrl)})it('should handle status 2 (document closed without changes)', async () => {@@ -310,25 +318,7 @@ describe(OnlyOfficeManager.name, () => {})it('should handle status 3 (error saving document)', async () => {- jwtService.verifyAsync.mockResolvedValue({- status: 3,- actions: [],- url: 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'- })-- const mockStream = Readable.from(['mock content'])- httpService.axiosRef.mockResolvedValue({- data: mockStream,- headers: { 'content-length': '12' },- status: 200,- statusText: 'OK',- config: {} as any- } as AxiosResponse)-- const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)-- expect(result).toEqual({ error: 0 })- expect(httpService.axiosRef).toHaveBeenCalled()+ await expectSuccessfulSaveCallback(mockDocumentUrl, { status: 3 })})it('should handle status 4 (document closed with no changes)', async () => {@@ -343,45 +333,11 @@ describe(OnlyOfficeManager.name, () => {})it('should handle status 6 (force save)', async () => {- jwtService.verifyAsync.mockResolvedValue({- status: 6,- actions: [],- url: 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'- })-- const mockStream = Readable.from(['mock content'])- httpService.axiosRef.mockResolvedValue({- data: mockStream,- headers: { 'content-length': '12' },- status: 200,- statusText: 'OK',- config: {} as any- } as AxiosResponse)-- const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)-- expect(result).toEqual({ error: 0 })+ await expectSuccessfulSaveCallback(mockDocumentUrl, { status: 6 })})it('should handle status 7 (error force saving)', async () => {- jwtService.verifyAsync.mockResolvedValue({- status: 7,- actions: [],- url: 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'- })-- const mockStream = Readable.from(['mock content'])- httpService.axiosRef.mockResolvedValue({- data: mockStream,- headers: { 'content-length': '12' },- status: 200,- statusText: 'OK',- config: {} as any- } as AxiosResponse)-- const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)-- expect(result).toEqual({ error: 0 })+ await expectSuccessfulSaveCallback(mockDocumentUrl, { status: 7 })})it('should handle user connect action (type 1)', async () => {@@ -428,7 +384,7 @@ describe(OnlyOfficeManager.name, () => {status: 2,actions: [],notmodified: false,- url: 'http://onlyoffice/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'+ url: mockDocumentUrl})httpService.axiosRef.mockRejectedValue(new Error('Network error'))@@ -438,6 +394,22 @@ describe(OnlyOfficeManager.name, () => {expect(result.error).not.toBe(0)})+ it('should reject document downloads from unexpected hosts when external server is configured', async () => {+ ;(service as any).externalOnlyOfficeServer = 'http://localhost:3000/onlyoffice'+ jwtService.verifyAsync.mockResolvedValue({+ status: 2,+ actions: [],+ users: [],+ notmodified: false,+ url: 'http://internal-service.local/document.docx?md5=abc123&expires=1739400549&shardkey=-33120641&filename=document.docx'+ })++ const result = await service.callBack(mockUser, mockSpaceEnv, mockToken)++ expect(result).toEqual({ error: 'document download url is not allowed' })+ expect(httpService.axiosRef).not.toHaveBeenCalled()+ })+it('should throw error when file lock creation fails', async () => {jwtService.verifyAsync.mockResolvedValue({status: 1,@@ -452,8 +424,4 @@ describe(OnlyOfficeManager.name, () => {expect(result.error).not.toBe(0)})})-- it('should be defined', () => {- expect(service).toBeDefined()- })})diff --git a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts b/backend/src/applications/files/editors/only-office/only-office-manager.service.tsindex c7859c7e..fd21d814 100644--- a/backend/src/applications/files/editors/only-office/only-office-manager.service.ts+++ b/backend/src/applications/files/editors/only-office/only-office-manager.service.ts@@ -330,7 +330,8 @@ export class OnlyOfficeManager {https://onlyoffice-server.com/cache/files/data/-33120641_7158/output.pptx/output.pptx?md5=duFHKC-5d47s-RRcYn3hAw&expires=1739400549&shardkey=-33120641&filename=output.pptx*/- const urlParams = new URLSearchParams(url.split('?').at(-1))+ const callbackDownloadUrl = this.parseDocumentServerDownloadUrl(url)+ const urlParams = callbackDownloadUrl.searchParams// it is not the md5 of the file but the md5 generated by the combination of the elements of the urlconst md5: string = urlParams.get('md5')const tmpFilePath = await uniqueFilePathFromDir(path.join(os.tmpdir(), `${md5}-${urlParams.get('filename')}`))@@ -339,15 +340,15 @@ export class OnlyOfficeManager {const localExtension = path.extname(space.realPath).slice(1)const remoteExtension = path.extname(urlParams.get('filename')).slice(1)- let downloadUrl: string+ let finalDownloadUrl = url+ let finalParsedDownloadUrl = callbackDownloadUrlif (localExtension !== remoteExtension && !ONLY_OFFICE_CONVERT_EXTENSIONS.ALLOW_AUTO.has(localExtension)) {if (ONLY_OFFICE_CONVERT_EXTENSIONS.FROM.has(remoteExtension) && ONLY_OFFICE_CONVERT_EXTENSIONS.TO.has(localExtension)) {- downloadUrl = await this.convertDocument(urlParams.get('shardkey'), url, remoteExtension, localExtension, space.url)+ finalDownloadUrl = await this.convertDocument(urlParams.get('shardkey'), url, remoteExtension, localExtension, space.url)+ finalParsedDownloadUrl = this.parseDocumentServerDownloadUrl(finalDownloadUrl)} else {throw new Error(`document cannot be converted from ${remoteExtension} -> ${localExtension} : ${space.url}`)}- } else {- downloadUrl = url}// download file@@ -355,13 +356,18 @@ export class OnlyOfficeManager {try {res = await this.http.axiosRef({method: HTTP_METHOD.GET,- url: downloadUrl,+ url: finalDownloadUrl,responseType: 'stream',+ maxRedirects: 0,httpsAgent: new https.Agent({ rejectUnauthorized: this.rejectUnauthorized })})await writeFromStream(tmpFilePath, res.data)} catch (e) {- throw new Error(`unable to get document : ${e.message}`)+ this.logger.error({+ tag: this.saveDocument.name,+ msg: `failed to download document from ${finalParsedDownloadUrl.origin}${finalParsedDownloadUrl.pathname} : ${space.url} - ${e.message}`+ })+ throw new Error(`unable to download document : ${e.message}`)}// try to verify the downloaded size@@ -385,6 +391,39 @@ export class OnlyOfficeManager {}}+ private parseDocumentServerDownloadUrl(downloadUrl: string): URL {+ let parsedUrl: URL+ try {+ parsedUrl = new URL(downloadUrl)+ } catch {+ this.logger.warn({ tag: this.parseDocumentServerDownloadUrl.name, msg: 'document download url is invalid' })+ throw new Error('document download url is invalid')+ }++ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {+ this.logger.warn({ tag: this.parseDocumentServerDownloadUrl.name, msg: `document download url protocol is not allowed: ${parsedUrl.protocol}` })+ throw new Error('document download url protocol is not allowed')+ }++ // Host validation is only enforced when an explicit externalServer is configured.+ // Without externalServer, local Docker/proxy deployments may legitimately return+ // internal container URLs (for example http://onlyoffice/...), so host validation is skipped.+ // With externalServer, we only compare origins to avoid breaking reverse proxies that rewrite paths.+ if (!this.externalOnlyOfficeServer) {+ return parsedUrl+ }++ const documentServerUrl = new URL(this.externalOnlyOfficeServer)+ if (parsedUrl.origin !== documentServerUrl.origin) {+ this.logger.warn({+ tag: this.parseDocumentServerDownloadUrl.name,+ msg: `document download origin is not allowed: ${parsedUrl.origin} (expected: ${documentServerUrl.origin})`+ })+ throw new Error('document download url is not allowed')+ }+ return parsedUrl+ }+private async convertDocument(id: string, url: string, fileType: string, outputType: string, spaceUrl: string): Promise<string> {const key: string = `${id}-${crypto.randomBytes(20).toString('hex')}`.slice(0, 20).replace('-', '_')const payload: OnlyOfficeConvertForm = {