api-session-spec.js 26 KB

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