A full-featured download manager.
fix(downloads): omit synthesized authorization headers (#2276)
Dr_rOot7f26cfde04be
diff --git a/src/core/engine/aria2/aria2-adapter.test.ts b/src/core/engine/aria2/aria2-adapter.test.tsindex afa80415..d6723adb 100644--- a/src/core/engine/aria2/aria2-adapter.test.ts+++ b/src/core/engine/aria2/aria2-adapter.test.ts@@ -573,7 +573,7 @@ describe('Aria2Adapter', () => {['https://example.com/file'],[],expect.objectContaining({- header: expect.arrayContaining(['Cookie: ', 'Authorization: ']),+ header: ['Cookie: ', 'Accept: */*'],'no-netrc': 'true',}))@@ -613,7 +613,7 @@ describe('Aria2Adapter', () => {)})- it('adds empty Cookie and Authorization only for the safe profile', async () => {+ it('isolates ambient credentials without synthesizing Authorization', async () => {const rpc = createMockRpc()vi.mocked(rpc.addUri).mockResolvedValue('profile-gid')const adapter = new Aria2Adapter(rpc)@@ -628,7 +628,11 @@ describe('Aria2Adapter', () => {expect(rpc.addUri).toHaveBeenCalledWith(['https://example.com/file'],expect.objectContaining({- header: ['Cookie: ', 'Authorization: ', 'Accept: */*'],+ header: ['Cookie: ', 'Accept: */*'],+ 'no-netrc': 'true',+ 'http-user': '',+ 'http-passwd': '',+ 'http-auth-challenge': 'false',}))})diff --git a/src/core/engine/aria2/aria2-adapter.ts b/src/core/engine/aria2/aria2-adapter.tsindex d815a6c3..a0b0e910 100644--- a/src/core/engine/aria2/aria2-adapter.ts+++ b/src/core/engine/aria2/aria2-adapter.ts@@ -456,15 +456,13 @@ export class Aria2Adapter implements EngineAdapter {}const requestHeaders = Object.entries(params.headers ?? {})if (metadataProfile === DIRECT_RESOURCE_METADATA_PROFILE) {- // An empty custom field suppresses aria2's built-in Cookie/AuthConfig- // values while preserving the exact field presence mirrored by Undici.- // Explicit task values always win.+ // An empty Cookie field suppresses aria2's process-wide CookieStorage.+ // Authorization is omitted unless explicitly supplied: the scalar+ // options below disable ambient credentials without sending an empty+ // authentication header, which signed artifact URLs may reject.if (!hasRequestHeader(requestHeaders, 'cookie')) {requestHeaders.push(['Cookie', ''])}- if (!hasRequestHeader(requestHeaders, 'authorization')) {- requestHeaders.push(['Authorization', ''])- }}if (params.uris.every((uri) => /^https?:\/\//i.test(uri)) &&diff --git a/src/core/engine/engine-adapter.ts b/src/core/engine/engine-adapter.tsindex a8ce0a88..3cc4dc97 100644--- a/src/core/engine/engine-adapter.ts+++ b/src/core/engine/engine-adapter.ts@@ -38,7 +38,7 @@ export type DownloadResumePolicy = 'none' | 'checkpoint' | 'sequential-prefix'* credentials.*/export const DIRECT_RESOURCE_METADATA_PROFILE =- 'aria2-http-baseline-v1' as const+ 'aria2-http-baseline-v2' as constexport type DirectResourceMetadataProfile =typeof DIRECT_RESOURCE_METADATA_PROFILEdiff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex ad5ff489..c21de5d5 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -2423,7 +2423,6 @@ describe('handleCreateTask plugin-hook chain (Plan C / T15)', () => {'X-Plugin: on','User-Agent: rewritten','Cookie: ',- 'Authorization: ','Accept: */*',])expect(options['all-proxy']).toBe('http://proxy.example:1080')diff --git a/src/core/task/direct-resource-validator.proxy.test.ts b/src/core/task/direct-resource-validator.proxy.test.tsindex 40087b3e..b050a49a 100644--- a/src/core/task/direct-resource-validator.proxy.test.ts+++ b/src/core/task/direct-resource-validator.proxy.test.ts@@ -26,6 +26,9 @@ import path from 'node:path'import { pathToFileURL } from 'node:url'import { Server as ProxyServer } from 'proxy-chain'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { Aria2Adapter } from '../engine/aria2/aria2-adapter'+import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'+import { DIRECT_RESOURCE_METADATA_PROFILE } from '../engine/engine-adapter'import { DirectResourceValidatorService } from './direct-resource-validator'const LOOPBACK_HOST = '127.0.0.1'@@ -271,6 +274,11 @@ describe('DirectResourceValidatorService proxy runtime', () => {return}if (request.url === '/artifacts/latest') {+ if (request.headers.authorization === '') {+ response.writeHead(400)+ response.end()+ return+ }response.writeHead(200, {'Content-Disposition': `attachment; filename="${REMOTE_FILENAME}"`,'Content-Length': '4096',@@ -381,6 +389,89 @@ describe('DirectResourceValidatorService proxy runtime', () => {expect(originHeaders[0]).not.toHaveProperty('sec-fetch-mode')})+ bundledAria2Test.each([+ { headers: undefined, authorization: undefined },+ {+ headers: { aUtHoRiZaTiOn: 'Bearer explicit-task-token' },+ authorization: 'Bearer explicit-task-token',+ },+ ])(+ 'probes and downloads artifacts without synthesizing Authorization ($authorization)',+ async ({ headers, authorization }) => {+ const outputDir = mkdtempSync(+ path.join(os.tmpdir(), 'motrix-aria2-authorization-')+ )+ try {+ const service = new DirectResourceValidatorService()+ await expect(+ service.probe(`${originUrl}/stable`, { headers })+ ).resolves.toMatchObject({ filename: REMOTE_FILENAME })++ const addUri = vi.fn<Aria2RpcClient['addUri']>(+ async (uris, options = {}) => {+ await new Promise<void>((resolve, reject) => {+ execFile(+ bundledAria2Path,+ [+ '--no-conf=true',+ '--console-log-level=error',+ '--summary-interval=0',+ '--all-proxy=',+ '--http-proxy=',+ '--https-proxy=',+ ...Object.entries(options).flatMap(([name, value]) =>+ (Array.isArray(value) ? value : [value]).map(+ (entry) => `--${name}=${entry}`+ )+ ),+ ...uris,+ ],+ { timeout: 10_000 },+ (error) => (error ? reject(error) : resolve())+ )+ })+ return 'artifact-gid'+ }+ )+ const adapter = new Aria2Adapter({+ addUri,+ onBtDownloadComplete: vi.fn(),+ onDownloadComplete: vi.fn(),+ onDownloadError: vi.fn(),+ } as unknown as Aria2RpcClient)+ adapter.setDirectResourceMetadataProfile(+ DIRECT_RESOURCE_METADATA_PROFILE+ )+ await adapter.createDownload({+ uris: [`${originUrl}/stable`],+ saveDir: outputDir,+ filename: 'artifact.zip',+ headers,+ directResourceMetadataProfile: DIRECT_RESOURCE_METADATA_PROFILE,+ })++ expect(readFileSync(path.join(outputDir, 'artifact.zip'))).toEqual(+ Buffer.alloc(4096)+ )+ expect(originRequests).toEqual([+ 'GET /stable',+ 'GET /artifacts/latest',+ 'GET /stable',+ 'GET /artifacts/latest',+ ])+ for (const requestHeaders of originHeaders) {+ if (authorization === undefined) {+ expect(requestHeaders).not.toHaveProperty('authorization')+ } else {+ expect(requestHeaders.authorization).toBe(authorization)+ }+ }+ } finally {+ rmSync(outputDir, { recursive: true, force: true })+ }+ }+ )+it('honors aria2 CIDR bypass without touching the configured proxy', async () => {const globalFetch = vi.spyOn(globalThis, 'fetch')@@ -548,11 +639,7 @@ describe('DirectResourceValidatorService proxy runtime', () => {originRequests.length = 0originHeaders.length = 0await expect(- runAria2Sequence('pinned-empty-cookie', [- 'Cookie: ',- 'Authorization: ',- 'Accept: */*',- ])+ runAria2Sequence('pinned-empty-cookie', ['Cookie: ', 'Accept: */*'])).resolves.toEqual(['baseline-variant', 'baseline-variant'])expect(originRequests).toEqual(['GET /cookie-start',@@ -560,9 +647,9 @@ describe('DirectResourceValidatorService proxy runtime', () => {'GET /cookie-final',])expect(originHeaders.at(-1)).toMatchObject({- authorization: '',cookie: '',})+ expect(originHeaders.at(-1)).not.toHaveProperty('authorization')} finally {rmSync(outputDir, { recursive: true, force: true })}diff --git a/src/core/task/direct-resource-validator.test.ts b/src/core/task/direct-resource-validator.test.tsindex b2a2f37a..af212711 100644--- a/src/core/task/direct-resource-validator.test.ts+++ b/src/core/task/direct-resource-validator.test.ts@@ -206,7 +206,6 @@ describe('DirectResourceValidatorService', () => {headers: {accept: 'application/octet-stream','accept-encoding': 'deflate, gzip',- authorization: '',cookie: '','user-agent': 'Motrix/2.0','want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',@@ -267,7 +266,6 @@ describe('DirectResourceValidatorService', () => {headers: {accept: '*/*','accept-encoding': 'deflate, gzip',- authorization: '',cookie: '','want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',},@@ -398,7 +396,6 @@ describe('DirectResourceValidatorService', () => {headers: {accept: '*/*','accept-encoding': 'deflate, gzip',- authorization: '',cookie: '','want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',},@@ -519,7 +516,6 @@ describe('DirectResourceValidatorService', () => {headers: {accept: '*/*','accept-encoding': 'deflate, gzip',- authorization: '',cookie: '','user-agent': 'Motrix/2.0','want-digest': 'SHA-512;q=1, SHA-256;q=1, SHA;q=0.1',diff --git a/src/core/task/direct-resource-validator.ts b/src/core/task/direct-resource-validator.tsindex dd2c1303..afa0ba72 100644--- a/src/core/task/direct-resource-validator.ts+++ b/src/core/task/direct-resource-validator.ts@@ -765,11 +765,10 @@ function probeHeaders(if (!Object.hasOwn(result, 'want-digest')) {result['want-digest'] = ARIA2_WANT_DIGEST}- // Metadata-eligible aria2 tasks carry the same empty custom fields. Their- // presence suppresses aria2's process-wide CookieStorage and AuthConfig- // factories without replacing an explicit task credential.+ // Mirror the empty Cookie field that suppresses aria2's CookieStorage.+ // Neither client synthesizes Authorization; aria2 disables ambient auth+ // through task options, and explicit task headers are preserved above.if (!Object.hasOwn(result, 'cookie')) result.cookie = ''- if (!Object.hasOwn(result, 'authorization')) result.authorization = ''return result}