ActivityPub-federated video streaming platform using P2P directly in your web browser
Owner/admin can bypass download enabled setting
Chocobozzz9a47cfce79f4
diff --git a/packages/tests/src/api/videos/video-download-enabled.ts b/packages/tests/src/api/videos/video-download-enabled.tsindex 50a1d87104..a24173eaaa 100644--- a/packages/tests/src/api/videos/video-download-enabled.ts+++ b/packages/tests/src/api/videos/video-download-enabled.ts@@ -1,7 +1,7 @@/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */import { getHLS } from '@peertube/peertube-core-utils'-import { HttpStatusCode, PeerTubeProblemDocument } from '@peertube/peertube-models'+import { HttpStatusCode, PeerTubeProblemDocument, UserRole } from '@peertube/peertube-models'import {PeerTubeServer,cleanupTests,@@ -66,6 +66,41 @@ describe('Test video downloads enabled/disabled', function () {}await server.videos.generateDownload({+ token: null,+ videoId: videoUUID,+ videoFileIds: generateFileIds,+ expectedStatus: HttpStatusCode.FORBIDDEN_403+ })+ })++ it('Should allow admin/owner/editors to download video files even if download is disabled', async function () {+ // Download is still disabled from the previous test+ const { webVideoUrl, hlsVideoUrl, generateFileIds } = await getVideoUrls()++ const adminToken = await server.users.generateUserAndToken('admin2', UserRole.ADMINISTRATOR)+ const editorToken = await server.channelCollaborators.createEditor('editor1', server.store.channel.name)++ // Owner of the video is the root account, which uploaded it+ for (const token of [ server.accessToken, adminToken, editorToken ]) {+ await makeRawRequest({ url: webVideoUrl, token, expectedStatus: HttpStatusCode.OK_200 })+ await makeRawRequest({ url: hlsVideoUrl, token, expectedStatus: HttpStatusCode.OK_200 })++ await server.videos.generateDownload({+ token,+ videoId: videoUUID,+ videoFileIds: generateFileIds,+ expectedStatus: HttpStatusCode.OK_200+ })+ }++ // A basic user that does not manage the channel must not bypass the setting+ const userToken = await server.users.generateUserAndToken('user1')++ await makeRawRequest({ url: webVideoUrl, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })+ await makeRawRequest({ url: hlsVideoUrl, token: userToken, expectedStatus: HttpStatusCode.FORBIDDEN_403 })++ await server.videos.generateDownload({+ token: userToken,videoId: videoUUID,videoFileIds: generateFileIds,expectedStatus: HttpStatusCode.FORBIDDEN_403diff --git a/packages/tests/src/shared/streaming-playlists.ts b/packages/tests/src/shared/streaming-playlists.tsindex 7cef232676..af86c8718d 100644--- a/packages/tests/src/shared/streaming-playlists.ts+++ b/packages/tests/src/shared/streaming-playlists.ts@@ -243,10 +243,10 @@ export async function completeCheckHlsPlaylist (options: {}for (const server of options.servers) {- const videoDetails = await server.videos.getWithToken({ id: videoUUID })- const isOrigin = videoDetails.account.host === server.host+ const video = await server.videos.getWithToken({ id: videoUUID })+ const isOrigin = video.account.host === server.host- const requiresAuth = videoDetails.privacy.id === VideoPrivacy.PRIVATE || videoDetails.privacy.id === VideoPrivacy.INTERNAL+ const requiresAuth = video.privacy.id === VideoPrivacy.PRIVATE || video.privacy.id === VideoPrivacy.INTERNALconst privatePath = requiresAuth? 'private/'@@ -255,18 +255,18 @@ export async function completeCheckHlsPlaylist (options: {? server.accessToken: undefined- const baseUrl = `http://${videoDetails.account.host}`+ const baseUrl = `http://${video.account.host}`- expect(videoDetails.streamingPlaylists).to.have.lengthOf(1)+ expect(video.streamingPlaylists).to.have.lengthOf(1)- const hlsPlaylist = videoDetails.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)+ const hlsPlaylist = video.streamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)expect(hlsPlaylist).to.not.be.undefinedconst hlsFiles = hlsPlaylist.filesexpect(hlsFiles).to.have.lengthOf(hlsResolutions.length)- if (hlsOnly) expect(videoDetails.files).to.have.lengthOf(0)- else expect(videoDetails.files).to.have.lengthOf(webVideoResolutions.length)+ if (hlsOnly) expect(video.files).to.have.lengthOf(0)+ else expect(video.files).to.have.lengthOf(webVideoResolutions.length)// Check JSON filesfor (const resolution of hlsResolutions) {@@ -281,7 +281,7 @@ export async function completeCheckHlsPlaylist (options: {objectStorageBaseUrl,requiresAuth,server,- videoDetails,+ video,privatePath,baseUrl,token@@ -290,7 +290,7 @@ export async function completeCheckHlsPlaylist (options: {// Check captionsfor (const caption of captions) {- await checkHLSCaption({ caption, objectStorageBaseUrl, videoDetails, privatePath, baseUrl, token })+ await checkHLSCaption({ caption, objectStorageBaseUrl, video, privatePath, baseUrl, token })}// Check master playlist@@ -367,7 +367,7 @@ export async function completeCheckHlsPlaylist (options: {if (isOrigin) {const sqlCommand = new SQLCommand(server)- await checkPlaylistInfohash({ video: videoDetails, sqlCommand, files: hlsFiles })+ await checkPlaylistInfohash({ video: video, sqlCommand, files: hlsFiles })await sqlCommand.cleanup()}}@@ -441,7 +441,7 @@ async function checkHLSResolution (options: {objectStorageBaseUrl: string | undefinedrequiresAuth: booleanserver: PeerTubeServer- videoDetails: VideoDetails+ video: VideoDetailsprivatePath: stringbaseUrl: stringtoken: string | undefined@@ -455,7 +455,7 @@ async function checkHLSResolution (options: {objectStorageBaseUrl,requiresAuth,server,- videoDetails,+ video,privatePath,baseUrl,token@@ -502,42 +502,46 @@ async function checkHLSResolution (options: {if (objectStorageBaseUrl && requiresAuth) {expect(file.fileUrl).to.match(new RegExp(- `${server.url}/object-storage-proxy/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}-fragmented.mp4`+ `${server.url}/object-storage-proxy/streaming-playlists/hls/${privatePath}${video.uuid}/${nameReg}-fragmented.mp4`))} else if (objectStorageBaseUrl) {expectStartWith(file.fileUrl, objectStorageBaseUrl)} else {expect(file.fileUrl).to.match(- new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}-fragmented.mp4`)+ new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${video.uuid}/${nameReg}-fragmented.mp4`))}await Promise.all([makeRawRequest({ url: file.torrentUrl, token, expectedStatus: HttpStatusCode.OK_200 }),- makeRawRequest({ url: file.torrentDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 }),makeRawRequest({ url: file.metadataUrl, token, expectedStatus: HttpStatusCode.OK_200 }),- makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 }),-- makeRawRequest({- url: file.fileDownloadUrl,- token,- expectedStatus: objectStorageBaseUrl- ? HttpStatusCode.FOUND_302- : HttpStatusCode.OK_200- })+ makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 })])++ if (video.downloadEnabled) {+ await Promise.all([+ makeRawRequest({ url: file.torrentDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 }),+ makeRawRequest({+ url: file.fileDownloadUrl,+ token,+ expectedStatus: objectStorageBaseUrl+ ? HttpStatusCode.FOUND_302+ : HttpStatusCode.OK_200+ })+ ])+ }}async function checkHLSCaption (options: {caption: VideoCaptionobjectStorageBaseUrl: string | undefined- videoDetails: VideoDetails+ video: VideoDetailsprivatePath: stringbaseUrl: stringtoken: string | undefined}) {- const { caption, objectStorageBaseUrl, videoDetails, privatePath, baseUrl, token } = options+ const { caption, objectStorageBaseUrl, video, privatePath, baseUrl, token } = optionsexpect(caption.fileUrl).to.existexpect(caption.m3u8Url).to.exist@@ -549,7 +553,7 @@ async function checkHLSCaption (options: {const nameReg = basename(caption.fileUrl).replace(/\.vtt$/, '.m3u8')expect(caption.m3u8Url).to.match(- new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${videoDetails.uuid}/${nameReg}`)+ new RegExp(`${baseUrl}/static/streaming-playlists/hls/${privatePath}${video.uuid}/${nameReg}`))}@@ -557,6 +561,6 @@ async function checkHLSCaption (options: {const { text } = await makeRawRequest({ url: caption.m3u8Url, token, expectedStatus: HttpStatusCode.OK_200 })expect(text).to.match(new RegExp(`^#EXTM3U`))- expect(text).to.include(`#EXT-X-TARGETDURATION:${videoDetails.duration}`)+ expect(text).to.include(`#EXT-X-TARGETDURATION:${video.duration}`)expect(text).to.include(caption.fileUrl)}diff --git a/packages/tests/src/shared/videos.ts b/packages/tests/src/shared/videos.tsindex 932864d33a..a559ca6293 100644--- a/packages/tests/src/shared/videos.ts+++ b/packages/tests/src/shared/videos.ts@@ -105,17 +105,22 @@ export async function completeWebVideoFilesCheck (options: {await Promise.all([makeRawRequest({ url: file.torrentUrl, token, expectedStatus: HttpStatusCode.OK_200 }),- makeRawRequest({ url: file.torrentDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 }),makeRawRequest({ url: file.metadataUrl, token, expectedStatus: HttpStatusCode.OK_200 }),- makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 }),- makeRawRequest({- url: file.fileDownloadUrl,- token,- expectedStatus: objectStorageBaseUrl- ? HttpStatusCode.FOUND_302- : HttpStatusCode.OK_200- })+ makeRawRequest({ url: file.fileUrl, token, expectedStatus: HttpStatusCode.OK_200 })])++ if (video.downloadEnabled) {+ await Promise.all([+ makeRawRequest({ url: file.torrentDownloadUrl, token, expectedStatus: HttpStatusCode.OK_200 }),+ makeRawRequest({+ url: file.fileDownloadUrl,+ token,+ expectedStatus: objectStorageBaseUrl+ ? HttpStatusCode.FOUND_302+ : HttpStatusCode.OK_200+ })+ ])+ }}expect(file.resolution.id).to.equal(attributeFile.resolution)diff --git a/server/core/controllers/download.ts b/server/core/controllers/download.tsindex 244e73d3a5..2cc213eea5 100644--- a/server/core/controllers/download.ts+++ b/server/core/controllers/download.ts@@ -1,7 +1,7 @@import { forceNumber, maxBy } from '@peertube/peertube-core-utils'-import { FileStorage, HttpStatusCode, VideoResolution, VideoStreamingPlaylistType } from '@peertube/peertube-models'+import { FileStorage, HttpStatusCode, UserRight, VideoResolution, VideoStreamingPlaylistType } from '@peertube/peertube-models'import { exists } from '@server/helpers/custom-validators/misc.js'-import { parseRangeHeader } from '@server/helpers/express-utils.js'+import { getAuthUser, parseRangeHeader } from '@server/helpers/express-utils.js'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import { generateRequestStream } from '@server/helpers/requests.js'import { ThrottleStream } from '@server/helpers/stream-throttle.js'@@ -17,7 +17,9 @@ import { Hooks } from '@server/lib/plugins/hooks.js'import { VideoStatsManager } from '@server/lib/stats/video-stats-manager.js'import { VideoDownload } from '@server/lib/video-download.js'import { VideoPathManager } from '@server/lib/video-path-manager.js'+import { checkCanManageChannel } from '@server/middlewares/validators/shared/video-channels.js'import { VideoFileModel } from '@server/models/video/video-file.js'+import { VideoModel } from '@server/models/video/video.js'import { MStreamingPlaylist, MStreamingPlaylistVideo, MUserExport, MVideo, MVideoFile, MVideoFull } from '@server/types/models/index.js'import { MVideoSource } from '@server/types/models/video/video-source.js'import { create as createContentDisposition } from 'content-disposition'@@ -107,7 +109,8 @@ async function downloadTorrent (req: express.Request, res: express.Response) {const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(req.params.filename)if (!file) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)- const video = file.getVideo()+ const video = await VideoModel.loadFull(file.getVideo().id)+ if (!video) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)const path = video.isLocal()? join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename)@@ -367,37 +370,61 @@ type AllowedResult = {}function isTorrentDownloadAllowed (object: {- video: MVideo+ req: express.Request+ res: express.Response+ video: MVideoFulltorrentPath: string-}): AllowedResult {- if (object.video.downloadEnabled !== true) {- return { allowed: false, errorMessage: 'Video download is disabled for this video' }- }-- return { allowed: true }+}): Promise<AllowedResult> {+ return commonDownloadAllowed(object)}function isVideoDownloadAllowed (object: {- video: MVideo+ req: express.Request+ res: express.Response+ video: MVideoFullvideoFile: MVideoFilestreamingPlaylist?: MStreamingPlaylist-}): AllowedResult {- if (object.video.downloadEnabled !== true) {- return { allowed: false, errorMessage: 'Video download is disabled for this video' }- }-- return { allowed: true }+}): Promise<AllowedResult> {+ return commonDownloadAllowed(object)}function isGeneratedVideoDownloadAllowed (object: {- video: MVideo+ req: express.Request+ res: express.Response+ video: MVideoFullvideoFiles: MVideoFile[]-}): AllowedResult {- if (object.video.downloadEnabled !== true) {- return { allowed: false, errorMessage: 'Video download is disabled for this video' }+}): Promise<AllowedResult> {+ return commonDownloadAllowed(object)+}++async function commonDownloadAllowed (object: {+ req: express.Request+ res: express.Response+ video: MVideoFull+}): Promise<AllowedResult> {+ const { req, res, video } = object++ const user = getAuthUser(res)++ if (video.downloadEnabled === true) {+ return { allowed: true }+ }++ if (+ await checkCanManageChannel({+ user,+ req,+ res: null, // Don't send a response here, we want to return the result to the caller+ checkCanManage: true,+ checkIsOwner: false,+ channel: video.VideoChannel,+ specialRight: UserRight.SEE_ALL_VIDEOS+ })+ ) {+ return { allowed: true }}- return { allowed: true }+ return { allowed: false, errorMessage: req.t('Video download is disabled for this video') }}// ---------------------------------------------------------------------------