api-session-spec.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. const assert = require('assert')
  2. const http = require('http')
  3. const https = require('https')
  4. const path = require('path')
  5. const fs = require('fs')
  6. const send = require('send')
  7. const auth = require('basic-auth')
  8. const {closeWindow} = require('./window-helpers')
  9. const {ipcRenderer, remote} = require('electron')
  10. const {ipcMain, session, BrowserWindow, net} = remote
  11. /* The whole session API doesn't use standard callbacks */
  12. /* eslint-disable standard/no-callback-literal */
  13. describe('session module', () => {
  14. let fixtures = path.resolve(__dirname, 'fixtures')
  15. let w = null
  16. let webview = null
  17. const url = 'http://127.0.0.1'
  18. beforeEach(() => {
  19. w = new BrowserWindow({
  20. show: false,
  21. width: 400,
  22. height: 400
  23. })
  24. })
  25. afterEach(() => {
  26. if (webview != null) {
  27. if (!document.body.contains(webview)) {
  28. document.body.appendChild(webview)
  29. }
  30. webview.remove()
  31. }
  32. return closeWindow(w).then(() => { w = null })
  33. })
  34. describe('session.defaultSession', () => {
  35. it('returns the default session', () => {
  36. assert.equal(session.defaultSession, session.fromPartition(''))
  37. })
  38. })
  39. describe('session.fromPartition(partition, options)', () => {
  40. it('returns existing session with same partition', () => {
  41. assert.equal(session.fromPartition('test'), session.fromPartition('test'))
  42. })
  43. it('created session is ref-counted', () => {
  44. const partition = 'test2'
  45. const userAgent = 'test-agent'
  46. const ses1 = session.fromPartition(partition)
  47. ses1.setUserAgent(userAgent)
  48. assert.equal(ses1.getUserAgent(), userAgent)
  49. ses1.destroy()
  50. const ses2 = session.fromPartition(partition)
  51. assert.notEqual(ses2.getUserAgent(), userAgent)
  52. })
  53. })
  54. describe('ses.cookies', () => {
  55. it('should get cookies', (done) => {
  56. const server = http.createServer((req, res) => {
  57. res.setHeader('Set-Cookie', ['0=0'])
  58. res.end('finished')
  59. server.close()
  60. })
  61. server.listen(0, '127.0.0.1', () => {
  62. const port = server.address().port
  63. w.loadURL(`${url}:${port}`)
  64. w.webContents.on('did-finish-load', () => {
  65. w.webContents.session.cookies.get({url}, (error, list) => {
  66. if (error) return done(error)
  67. for (let i = 0; i < list.length; i++) {
  68. const cookie = list[i]
  69. if (cookie.name === '0') {
  70. if (cookie.value === '0') {
  71. return done()
  72. } else {
  73. return done(`cookie value is ${cookie.value} while expecting 0`)
  74. }
  75. }
  76. }
  77. done('Can\'t find cookie')
  78. })
  79. })
  80. })
  81. })
  82. it('calls back with an error when setting a cookie with missing required fields', (done) => {
  83. session.defaultSession.cookies.set({
  84. url: '',
  85. name: '1',
  86. value: '1'
  87. }, (error) => {
  88. assert.equal(error.message, 'Setting cookie failed')
  89. done()
  90. })
  91. })
  92. it('should over-write the existent cookie', (done) => {
  93. session.defaultSession.cookies.set({
  94. url,
  95. name: '1',
  96. value: '1'
  97. }, (error) => {
  98. if (error) return done(error)
  99. session.defaultSession.cookies.get({url}, (error, list) => {
  100. if (error) return done(error)
  101. for (let i = 0; i < list.length; i++) {
  102. const cookie = list[i]
  103. if (cookie.name === '1') {
  104. if (cookie.value === '1') {
  105. return done()
  106. } else {
  107. return done(`cookie value is ${cookie.value} while expecting 1`)
  108. }
  109. }
  110. }
  111. done('Can\'t find cookie')
  112. })
  113. })
  114. })
  115. it('should remove cookies', (done) => {
  116. session.defaultSession.cookies.set({
  117. url: url,
  118. name: '2',
  119. value: '2'
  120. }, (error) => {
  121. if (error) return done(error)
  122. session.defaultSession.cookies.remove(url, '2', () => {
  123. session.defaultSession.cookies.get({url}, (error, list) => {
  124. if (error) return done(error)
  125. for (let i = 0; i < list.length; i++) {
  126. const cookie = list[i]
  127. if (cookie.name === '2') return done('Cookie not deleted')
  128. }
  129. done()
  130. })
  131. })
  132. })
  133. })
  134. it('should set cookie for standard scheme', (done) => {
  135. const standardScheme = remote.getGlobal('standardScheme')
  136. const origin = standardScheme + '://fake-host'
  137. session.defaultSession.cookies.set({
  138. url: origin,
  139. name: 'custom',
  140. value: '1'
  141. }, (error) => {
  142. if (error) return done(error)
  143. session.defaultSession.cookies.get({url: origin}, (error, list) => {
  144. if (error) return done(error)
  145. assert.equal(list.length, 1)
  146. assert.equal(list[0].name, 'custom')
  147. assert.equal(list[0].value, '1')
  148. assert.equal(list[0].domain, 'fake-host')
  149. done()
  150. })
  151. })
  152. })
  153. it('emits a changed event when a cookie is added or removed', (done) => {
  154. const {cookies} = session.fromPartition('cookies-changed')
  155. cookies.once('changed', (event, cookie, cause, removed) => {
  156. assert.equal(cookie.name, 'foo')
  157. assert.equal(cookie.value, 'bar')
  158. assert.equal(cause, 'explicit')
  159. assert.equal(removed, false)
  160. cookies.once('changed', (event, cookie, cause, removed) => {
  161. assert.equal(cookie.name, 'foo')
  162. assert.equal(cookie.value, 'bar')
  163. assert.equal(cause, 'explicit')
  164. assert.equal(removed, true)
  165. done()
  166. })
  167. cookies.remove(url, 'foo', (error) => {
  168. if (error) return done(error)
  169. })
  170. })
  171. cookies.set({
  172. url: url,
  173. name: 'foo',
  174. value: 'bar'
  175. }, (error) => {
  176. if (error) return done(error)
  177. })
  178. })
  179. describe('ses.cookies.flushStore(callback)', () => {
  180. it('flushes the cookies to disk and invokes the callback when done', (done) => {
  181. session.defaultSession.cookies.set({
  182. url: url,
  183. name: 'foo',
  184. value: 'bar'
  185. }, (error) => {
  186. if (error) return done(error)
  187. session.defaultSession.cookies.flushStore(() => {
  188. done()
  189. })
  190. })
  191. })
  192. })
  193. })
  194. describe('ses.clearStorageData(options)', () => {
  195. fixtures = path.resolve(__dirname, 'fixtures')
  196. it('clears localstorage data', (done) => {
  197. ipcMain.on('count', (event, count) => {
  198. ipcMain.removeAllListeners('count')
  199. assert.equal(count, 0)
  200. done()
  201. })
  202. w.loadURL('file://' + path.join(fixtures, 'api', 'localstorage.html'))
  203. w.webContents.on('did-finish-load', () => {
  204. const options = {
  205. origin: 'file://',
  206. storages: ['localstorage'],
  207. quotas: ['persistent']
  208. }
  209. w.webContents.session.clearStorageData(options, () => {
  210. w.webContents.send('getcount')
  211. })
  212. })
  213. })
  214. })
  215. describe('will-download event', () => {
  216. beforeEach(() => {
  217. if (w != null) w.destroy()
  218. w = new BrowserWindow({
  219. show: false,
  220. width: 400,
  221. height: 400
  222. })
  223. })
  224. it('can cancel default download behavior', (done) => {
  225. const mockFile = Buffer.alloc(1024)
  226. const contentDisposition = 'inline; filename="mockFile.txt"'
  227. const downloadServer = http.createServer((req, res) => {
  228. res.writeHead(200, {
  229. 'Content-Length': mockFile.length,
  230. 'Content-Type': 'application/plain',
  231. 'Content-Disposition': contentDisposition
  232. })
  233. res.end(mockFile)
  234. downloadServer.close()
  235. })
  236. downloadServer.listen(0, '127.0.0.1', () => {
  237. const port = downloadServer.address().port
  238. const url = `http://127.0.0.1:${port}/`
  239. ipcRenderer.sendSync('set-download-option', false, true)
  240. w.loadURL(url)
  241. ipcRenderer.once('download-error', (event, downloadUrl, filename, error) => {
  242. assert.equal(downloadUrl, url)
  243. assert.equal(filename, 'mockFile.txt')
  244. assert.equal(error, 'Object has been destroyed')
  245. done()
  246. })
  247. })
  248. })
  249. })
  250. describe('DownloadItem', () => {
  251. const mockPDF = Buffer.alloc(1024 * 1024 * 5)
  252. const protocolName = 'custom-dl'
  253. let contentDisposition = 'inline; filename="mock.pdf"'
  254. const downloadFilePath = path.join(fixtures, 'mock.pdf')
  255. const downloadServer = http.createServer((req, res) => {
  256. if (req.url === '/?testFilename') contentDisposition = 'inline'
  257. res.writeHead(200, {
  258. 'Content-Length': mockPDF.length,
  259. 'Content-Type': 'application/pdf',
  260. 'Content-Disposition': contentDisposition
  261. })
  262. res.end(mockPDF)
  263. downloadServer.close()
  264. })
  265. const assertDownload = (event, state, url, mimeType,
  266. receivedBytes, totalBytes, disposition,
  267. filename, port, savePath, isCustom) => {
  268. assert.equal(state, 'completed')
  269. assert.equal(filename, 'mock.pdf')
  270. assert.equal(savePath, path.join(__dirname, 'fixtures', 'mock.pdf'))
  271. if (isCustom) {
  272. assert.equal(url, `${protocolName}://item`)
  273. } else {
  274. assert.equal(url, `http://127.0.0.1:${port}/`)
  275. }
  276. assert.equal(mimeType, 'application/pdf')
  277. assert.equal(receivedBytes, mockPDF.length)
  278. assert.equal(totalBytes, mockPDF.length)
  279. assert.equal(disposition, contentDisposition)
  280. assert(fs.existsSync(downloadFilePath))
  281. fs.unlinkSync(downloadFilePath)
  282. }
  283. it('can download using WebContents.downloadURL', (done) => {
  284. downloadServer.listen(0, '127.0.0.1', () => {
  285. const port = downloadServer.address().port
  286. ipcRenderer.sendSync('set-download-option', false, false)
  287. w.webContents.downloadURL(`${url}:${port}`)
  288. ipcRenderer.once('download-done', (event, state, url,
  289. mimeType, receivedBytes,
  290. totalBytes, disposition,
  291. filename, savePath) => {
  292. assertDownload(event, state, url, mimeType, receivedBytes,
  293. totalBytes, disposition, filename, port, savePath)
  294. done()
  295. })
  296. })
  297. })
  298. it('can download from custom protocols using WebContents.downloadURL', (done) => {
  299. const protocol = session.defaultSession.protocol
  300. downloadServer.listen(0, '127.0.0.1', () => {
  301. const port = downloadServer.address().port
  302. const handler = (ignoredError, callback) => {
  303. callback({url: `${url}:${port}`})
  304. }
  305. protocol.registerHttpProtocol(protocolName, handler, (error) => {
  306. if (error) return done(error)
  307. ipcRenderer.sendSync('set-download-option', false, false)
  308. w.webContents.downloadURL(`${protocolName}://item`)
  309. ipcRenderer.once('download-done', (event, state, url,
  310. mimeType, receivedBytes,
  311. totalBytes, disposition,
  312. filename, savePath) => {
  313. assertDownload(event, state, url, mimeType, receivedBytes,
  314. totalBytes, disposition, filename, port, savePath,
  315. true)
  316. done()
  317. })
  318. })
  319. })
  320. })
  321. it('can download using WebView.downloadURL', (done) => {
  322. downloadServer.listen(0, '127.0.0.1', () => {
  323. const port = downloadServer.address().port
  324. ipcRenderer.sendSync('set-download-option', false, false)
  325. webview = new WebView()
  326. webview.src = `file://${fixtures}/api/blank.html`
  327. webview.addEventListener('did-finish-load', () => {
  328. webview.downloadURL(`${url}:${port}/`)
  329. })
  330. ipcRenderer.once('download-done', (event, state, url,
  331. mimeType, receivedBytes,
  332. totalBytes, disposition,
  333. filename, savePath) => {
  334. assertDownload(event, state, url, mimeType, receivedBytes,
  335. totalBytes, disposition, filename, port, savePath)
  336. document.body.removeChild(webview)
  337. done()
  338. })
  339. document.body.appendChild(webview)
  340. })
  341. })
  342. it('can cancel download', (done) => {
  343. downloadServer.listen(0, '127.0.0.1', () => {
  344. const port = downloadServer.address().port
  345. ipcRenderer.sendSync('set-download-option', true, false)
  346. w.webContents.downloadURL(`${url}:${port}/`)
  347. ipcRenderer.once('download-done', (event, state, url,
  348. mimeType, receivedBytes,
  349. totalBytes, disposition,
  350. filename) => {
  351. assert.equal(state, 'cancelled')
  352. assert.equal(filename, 'mock.pdf')
  353. assert.equal(mimeType, 'application/pdf')
  354. assert.equal(receivedBytes, 0)
  355. assert.equal(totalBytes, mockPDF.length)
  356. assert.equal(disposition, contentDisposition)
  357. done()
  358. })
  359. })
  360. })
  361. it('can generate a default filename', function (done) {
  362. if (process.env.APPVEYOR === 'True') {
  363. // FIXME(alexeykuzmin): Skip the test.
  364. // this.skip()
  365. return done()
  366. }
  367. downloadServer.listen(0, '127.0.0.1', () => {
  368. const port = downloadServer.address().port
  369. ipcRenderer.sendSync('set-download-option', true, false)
  370. w.webContents.downloadURL(`${url}:${port}/?testFilename`)
  371. ipcRenderer.once('download-done', (event, state, url,
  372. mimeType, receivedBytes,
  373. totalBytes, disposition,
  374. filename) => {
  375. assert.equal(state, 'cancelled')
  376. assert.equal(filename, 'download.pdf')
  377. assert.equal(mimeType, 'application/pdf')
  378. assert.equal(receivedBytes, 0)
  379. assert.equal(totalBytes, mockPDF.length)
  380. assert.equal(disposition, contentDisposition)
  381. done()
  382. })
  383. })
  384. })
  385. describe('when a save path is specified and the URL is unavailable', () => {
  386. it('does not display a save dialog and reports the done state as interrupted', (done) => {
  387. ipcRenderer.sendSync('set-download-option', false, false)
  388. ipcRenderer.once('download-done', (event, state) => {
  389. assert.equal(state, 'interrupted')
  390. done()
  391. })
  392. w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`)
  393. })
  394. })
  395. })
  396. describe('ses.protocol', () => {
  397. const partitionName = 'temp'
  398. const protocolName = 'sp'
  399. const partitionProtocol = session.fromPartition(partitionName).protocol
  400. const protocol = session.defaultSession.protocol
  401. const handler = (ignoredError, callback) => {
  402. callback({data: 'test', mimeType: 'text/html'})
  403. }
  404. beforeEach((done) => {
  405. if (w != null) w.destroy()
  406. w = new BrowserWindow({
  407. show: false,
  408. webPreferences: {
  409. partition: partitionName
  410. }
  411. })
  412. partitionProtocol.registerStringProtocol(protocolName, handler, (error) => {
  413. done(error != null ? error : undefined)
  414. })
  415. })
  416. afterEach((done) => {
  417. partitionProtocol.unregisterProtocol(protocolName, () => done())
  418. })
  419. it('does not affect defaultSession', (done) => {
  420. protocol.isProtocolHandled(protocolName, (result) => {
  421. assert.equal(result, false)
  422. partitionProtocol.isProtocolHandled(protocolName, (result) => {
  423. assert.equal(result, true)
  424. done()
  425. })
  426. })
  427. })
  428. xit('handles requests from partition', (done) => {
  429. w.webContents.on('did-finish-load', () => done())
  430. w.loadURL(`${protocolName}://fake-host`)
  431. })
  432. })
  433. describe('ses.setProxy(options, callback)', () => {
  434. it('allows configuring proxy settings', (done) => {
  435. const config = {proxyRules: 'http=myproxy:80'}
  436. session.defaultSession.setProxy(config, () => {
  437. session.defaultSession.resolveProxy('http://localhost', (proxy) => {
  438. assert.equal(proxy, 'PROXY myproxy:80')
  439. done()
  440. })
  441. })
  442. })
  443. it('allows bypassing proxy settings', (done) => {
  444. const config = {
  445. proxyRules: 'http=myproxy:80',
  446. proxyBypassRules: '<local>'
  447. }
  448. session.defaultSession.setProxy(config, () => {
  449. session.defaultSession.resolveProxy('http://localhost', (proxy) => {
  450. assert.equal(proxy, 'DIRECT')
  451. done()
  452. })
  453. })
  454. })
  455. })
  456. describe('ses.getBlobData(identifier, callback)', () => {
  457. it('returns blob data for uuid', (done) => {
  458. const scheme = 'temp'
  459. const protocol = session.defaultSession.protocol
  460. const url = `${scheme}://host`
  461. before(() => {
  462. if (w != null) w.destroy()
  463. w = new BrowserWindow({show: false})
  464. })
  465. after((done) => {
  466. protocol.unregisterProtocol(scheme, () => {
  467. closeWindow(w).then(() => {
  468. w = null
  469. done()
  470. })
  471. })
  472. })
  473. const postData = JSON.stringify({
  474. type: 'blob',
  475. value: 'hello'
  476. })
  477. const content = `<html>
  478. <script>
  479. const {webFrame} = require('electron')
  480. webFrame.registerURLSchemeAsPrivileged('${scheme}')
  481. let fd = new FormData();
  482. fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
  483. fetch('${url}', {method:'POST', body: fd });
  484. </script>
  485. </html>`
  486. protocol.registerStringProtocol(scheme, (request, callback) => {
  487. if (request.method === 'GET') {
  488. callback({data: content, mimeType: 'text/html'})
  489. } else if (request.method === 'POST') {
  490. let uuid = request.uploadData[1].blobUUID
  491. assert(uuid)
  492. session.defaultSession.getBlobData(uuid, (result) => {
  493. assert.equal(result.toString(), postData)
  494. done()
  495. })
  496. }
  497. }, (error) => {
  498. if (error) return done(error)
  499. w.loadURL(url)
  500. })
  501. })
  502. })
  503. describe('ses.setCertificateVerifyProc(callback)', () => {
  504. let server = null
  505. beforeEach((done) => {
  506. const certPath = path.join(__dirname, 'fixtures', 'certificates')
  507. const options = {
  508. key: fs.readFileSync(path.join(certPath, 'server.key')),
  509. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  510. ca: [
  511. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  512. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  513. ],
  514. requestCert: true,
  515. rejectUnauthorized: false
  516. }
  517. server = https.createServer(options, (req, res) => {
  518. res.writeHead(200)
  519. res.end('<title>hello</title>')
  520. })
  521. server.listen(0, '127.0.0.1', done)
  522. })
  523. afterEach(() => {
  524. session.defaultSession.setCertificateVerifyProc(null)
  525. server.close()
  526. })
  527. it('accepts the request when the callback is called with 0', (done) => {
  528. session.defaultSession.setCertificateVerifyProc(({hostname, certificate, verificationResult, errorCode}, callback) => {
  529. assert(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult), verificationResult)
  530. assert([-202, -200].includes(errorCode), errorCode)
  531. callback(0)
  532. })
  533. w.webContents.once('did-finish-load', () => {
  534. assert.equal(w.webContents.getTitle(), 'hello')
  535. done()
  536. })
  537. w.loadURL(`https://127.0.0.1:${server.address().port}`)
  538. })
  539. it('rejects the request when the callback is called with -2', (done) => {
  540. session.defaultSession.setCertificateVerifyProc(({hostname, certificate, verificationResult}, callback) => {
  541. assert.equal(hostname, '127.0.0.1')
  542. assert.equal(certificate.issuerName, 'Intermediate CA')
  543. assert.equal(certificate.subjectName, 'localhost')
  544. assert.equal(certificate.issuer.commonName, 'Intermediate CA')
  545. assert.equal(certificate.subject.commonName, 'localhost')
  546. assert.equal(certificate.issuerCert.issuer.commonName, 'Root CA')
  547. assert.equal(certificate.issuerCert.subject.commonName, 'Intermediate CA')
  548. assert.equal(certificate.issuerCert.issuerCert.issuer.commonName, 'Root CA')
  549. assert.equal(certificate.issuerCert.issuerCert.subject.commonName, 'Root CA')
  550. assert.equal(certificate.issuerCert.issuerCert.issuerCert, undefined)
  551. assert(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID'].includes(verificationResult), verificationResult)
  552. callback(-2)
  553. })
  554. const url = `https://127.0.0.1:${server.address().port}`
  555. w.webContents.once('did-finish-load', () => {
  556. assert.equal(w.webContents.getTitle(), url)
  557. done()
  558. })
  559. w.loadURL(url)
  560. })
  561. })
  562. describe('ses.createInterruptedDownload(options)', () => {
  563. it('can create an interrupted download item', (done) => {
  564. ipcRenderer.sendSync('set-download-option', true, false)
  565. const filePath = path.join(__dirname, 'fixtures', 'mock.pdf')
  566. const options = {
  567. path: filePath,
  568. urlChain: ['http://127.0.0.1/'],
  569. mimeType: 'application/pdf',
  570. offset: 0,
  571. length: 5242880
  572. }
  573. w.webContents.session.createInterruptedDownload(options)
  574. ipcRenderer.once('download-created', (event, state, urlChain,
  575. mimeType, receivedBytes,
  576. totalBytes, filename,
  577. savePath) => {
  578. assert.equal(state, 'interrupted')
  579. assert.deepEqual(urlChain, ['http://127.0.0.1/'])
  580. assert.equal(mimeType, 'application/pdf')
  581. assert.equal(receivedBytes, 0)
  582. assert.equal(totalBytes, 5242880)
  583. assert.equal(savePath, filePath)
  584. done()
  585. })
  586. })
  587. it('can be resumed', (done) => {
  588. const fixtures = path.join(__dirname, 'fixtures')
  589. const downloadFilePath = path.join(fixtures, 'logo.png')
  590. const rangeServer = http.createServer((req, res) => {
  591. let options = { root: fixtures }
  592. send(req, req.url, options)
  593. .on('error', (error) => { done(error) }).pipe(res)
  594. })
  595. ipcRenderer.sendSync('set-download-option', true, false, downloadFilePath)
  596. rangeServer.listen(0, '127.0.0.1', () => {
  597. const port = rangeServer.address().port
  598. const downloadUrl = `http://127.0.0.1:${port}/assets/logo.png`
  599. const callback = (event, state, url, mimeType,
  600. receivedBytes, totalBytes, disposition,
  601. filename, savePath, urlChain,
  602. lastModifiedTime, eTag) => {
  603. if (state === 'cancelled') {
  604. const options = {
  605. path: savePath,
  606. urlChain: urlChain,
  607. mimeType: mimeType,
  608. offset: receivedBytes,
  609. length: totalBytes,
  610. lastModified: lastModifiedTime,
  611. eTag: eTag
  612. }
  613. ipcRenderer.sendSync('set-download-option', false, false, downloadFilePath)
  614. w.webContents.session.createInterruptedDownload(options)
  615. } else {
  616. assert.equal(state, 'completed')
  617. assert.equal(filename, 'logo.png')
  618. assert.equal(savePath, downloadFilePath)
  619. assert.equal(url, downloadUrl)
  620. assert.equal(mimeType, 'image/png')
  621. assert.equal(receivedBytes, 14022)
  622. assert.equal(totalBytes, 14022)
  623. assert(fs.existsSync(downloadFilePath))
  624. fs.unlinkSync(downloadFilePath)
  625. rangeServer.close()
  626. ipcRenderer.removeListener('download-done', callback)
  627. done()
  628. }
  629. }
  630. ipcRenderer.on('download-done', callback)
  631. w.webContents.downloadURL(downloadUrl)
  632. })
  633. })
  634. })
  635. describe('ses.clearAuthCache(options[, callback])', () => {
  636. it('can clear http auth info from cache', (done) => {
  637. const ses = session.fromPartition('auth-cache')
  638. const server = http.createServer((req, res) => {
  639. const credentials = auth(req)
  640. if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
  641. res.statusCode = 401
  642. res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"')
  643. res.end()
  644. } else {
  645. res.end('authenticated')
  646. }
  647. })
  648. server.listen(0, '127.0.0.1', () => {
  649. const port = server.address().port
  650. function issueLoginRequest (attempt = 1) {
  651. if (attempt > 2) {
  652. server.close()
  653. return done()
  654. }
  655. const request = net.request({
  656. url: `http://127.0.0.1:${port}`,
  657. session: ses
  658. })
  659. request.on('login', (info, callback) => {
  660. attempt += 1
  661. assert.equal(info.scheme, 'basic')
  662. assert.equal(info.realm, 'Restricted')
  663. callback('test', 'test')
  664. })
  665. request.on('response', (response) => {
  666. let data = ''
  667. response.pause()
  668. response.on('data', (chunk) => {
  669. data += chunk
  670. })
  671. response.on('end', () => {
  672. assert.equal(data, 'authenticated')
  673. ses.clearAuthCache({type: 'password'}, () => {
  674. issueLoginRequest(attempt)
  675. })
  676. })
  677. response.on('error', (error) => { done(error) })
  678. response.resume()
  679. })
  680. // Internal api to bypass cache for testing.
  681. request.urlRequest._setLoadFlags(1 << 1)
  682. request.end()
  683. }
  684. issueLoginRequest()
  685. })
  686. })
  687. })
  688. describe('ses.setPermissionRequestHandler(handler)', () => {
  689. it('cancels any pending requests when cleared', (done) => {
  690. const ses = session.fromPartition('permissionTest')
  691. ses.setPermissionRequestHandler(() => {
  692. ses.setPermissionRequestHandler(null)
  693. })
  694. webview = new WebView()
  695. webview.addEventListener('ipc-message', (e) => {
  696. assert.equal(e.channel, 'message')
  697. assert.deepEqual(e.args, ['SecurityError'])
  698. done()
  699. })
  700. webview.src = `file://${fixtures}/pages/permissions/midi-sysex.html`
  701. webview.partition = 'permissionTest'
  702. webview.setAttribute('nodeintegration', 'on')
  703. document.body.appendChild(webview)
  704. })
  705. })
  706. })