Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bidi][js] Add authentication handlers #14345

Merged
merged 2 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 53 additions & 6 deletions javascript/node/selenium-webdriver/bidi/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,22 @@ const { ContinueResponseParameters } = require('./continueResponseParameters')
const { ContinueRequestParameters } = require('./continueRequestParameters')
const { ProvideResponseParameters } = require('./provideResponseParameters')

const NetworkEvent = {
BEFORE_REQUEST_SENT: 'network.beforeRequestSent',
RESPONSE_STARTED: 'network.responseStarted',
RESPONSE_COMPLETED: 'network.responseCompleted',
AUTH_REQUIRED: 'network.authRequired',
FETCH_ERROR: 'network.fetchError',
}

/**
* Represents all commands and events of Network module.
* Described in https://w3c.github.io/webdriver-bidi/#module-network.
*/
class Network {
#callbackId = 0
#listener

/**
* Represents a Network object.
* @constructor
Expand All @@ -35,6 +46,43 @@ class Network {
constructor(driver, browsingContextIds) {
this._driver = driver
this._browsingContextIds = browsingContextIds
this.#listener = new Map()
this.#listener.set(NetworkEvent.AUTH_REQUIRED, new Map())
this.#listener.set(NetworkEvent.BEFORE_REQUEST_SENT, new Map())
this.#listener.set(NetworkEvent.FETCH_ERROR, new Map())
this.#listener.set(NetworkEvent.RESPONSE_STARTED, new Map())
this.#listener.set(NetworkEvent.RESPONSE_COMPLETED, new Map())
}

addCallback(eventType, callback) {
const id = ++this.#callbackId

const eventCallbackMap = this.#listener.get(eventType)
eventCallbackMap.set(id, callback)
return id
}

removeCallback(id) {
let hasId = false
for (const [, callbacks] of this.#listener) {
if (callbacks.has(id)) {
callbacks.delete(id)
hasId = true
}
}

if (!hasId) {
throw Error(`Callback with id ${id} not found`)
}
}

invokeCallbacks(eventType, data) {
const callbacks = this.#listener.get(eventType)
if (callbacks) {
for (const [, callback] of callbacks) {
callback(data)
}
}
}

async init() {
Expand Down Expand Up @@ -75,10 +123,10 @@ class Network {
* Subscribes to the 'network.authRequired' event and handles it with the provided callback.
*
* @param {Function} callback - The callback function to handle the event.
* @returns {Promise<void>} - A promise that resolves when the subscription is successful.
* @returns {Promise<number>} - A promise that resolves when the subscription is successful.
*/
async authRequired(callback) {
await this.subscribeAndHandleEvent('network.authRequired', callback)
return await this.subscribeAndHandleEvent('network.authRequired', callback)
}

/**
Expand All @@ -97,10 +145,8 @@ class Network {
} else {
await this.bidi.subscribe(eventType)
}
await this._on(callback)
}
let id = this.addCallback(eventType, callback)

async _on(callback) {
this.ws = await this.bidi.socket
this.ws.on('message', (event) => {
const { params } = JSON.parse(Buffer.from(event.toString()))
Expand Down Expand Up @@ -134,9 +180,10 @@ class Network {
params.errorText,
)
}
callback(response)
this.invokeCallbacks(eventType, response)
}
})
return id
}

/**
Expand Down
78 changes: 78 additions & 0 deletions javascript/node/selenium-webdriver/lib/network.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

const network = require('../bidi/network')
const { InterceptPhase } = require('../bidi/interceptPhase')
const { AddInterceptParameters } = require('../bidi/addInterceptParameters')

class Network {
#driver
#network
#callBackInterceptIdMap = new Map()

constructor(driver) {
this.#driver = driver
}

// This should be done in the constructor.
// But since it needs to call async methods we cannot do that in the constructor.
// We can have a separate async method that initialises the Script instance.
// However, that pattern does not allow chaining the methods as we would like the user to use it.
// Since it involves awaiting to get the instance and then another await to call the method.
// Using this allows the user to do this "await driver.network.addAuthenticationHandler(callback)"
async #init() {
if (this.#network !== undefined) {
return
}
this.#network = await network(this.#driver)
}

async addAuthenticationHandler(username, password) {
await this.#init()

const interceptId = await this.#network.addIntercept(new AddInterceptParameters(InterceptPhase.AUTH_REQUIRED))

const id = await this.#network.authRequired(async (event) => {
await this.#network.continueWithAuth(event.request.request, username, password)
})

this.#callBackInterceptIdMap.set(id, interceptId)
return id
}

async removeAuthenticationHandler(id) {
await this.#init()

const interceptId = this.#callBackInterceptIdMap.get(id)

await this.#network.removeIntercept(interceptId)
await this.#network.removeCallback(id)

this.#callBackInterceptIdMap.delete(id)
}

async clearAuthenticationHandlers() {
for (const [key, value] of this.#callBackInterceptIdMap.entries()) {
await this.#network.removeIntercept(value)
await this.#network.removeCallback(key)
}

this.#callBackInterceptIdMap.clear()
}
}

module.exports = Network
12 changes: 12 additions & 0 deletions javascript/node/selenium-webdriver/lib/webdriver.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const BIDI = require('../bidi')
const { PinnedScript } = require('./pinnedScript')
const JSZip = require('jszip')
const Script = require('./script')
const Network = require('./network')

// Capability names that are defined in the W3C spec.
const W3C_CAPABILITY_NAMES = new Set([
Expand Down Expand Up @@ -656,6 +657,7 @@ function filterNonW3CCaps(capabilities) {
*/
class WebDriver {
#script = undefined
#network = undefined
/**
* @param {!(./session.Session|IThenable<!./session.Session>)} session Either
* a known session or a promise that will be resolved to a session.
Expand Down Expand Up @@ -1116,6 +1118,16 @@ class WebDriver {
return this.#script
}

network() {
// The Network maintains state of the callbacks.
// Returning a new instance of the same driver will not work while removing callbacks.
if (this.#network === undefined) {
this.#network = new Network(this)
}

return this.#network
}

validatePrintPageParams(keys, object) {
let page = {}
let margin = {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ suite(

await driver.get(Pages.logEntryAdded)

assert.strictEqual(counter, 1)
assert.strictEqual(counter >= 1, true)
})

it('can continue response', async function () {
Expand All @@ -145,7 +145,7 @@ suite(

await driver.get(Pages.logEntryAdded)

assert.strictEqual(counter, 1)
assert.strictEqual(counter >= 1, true)
})

it('can provide response', async function () {
Expand All @@ -160,7 +160,7 @@ suite(

await driver.get(Pages.logEntryAdded)

assert.strictEqual(counter, 1)
assert.strictEqual(counter >= 1, true)
})
})
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

'use strict'

const assert = require('node:assert')
const { Browser } = require('selenium-webdriver')
const { Pages, suite } = require('../../lib/test')
const until = require('selenium-webdriver/lib/until')
const { By } = require('selenium-webdriver')

suite(
function (env) {
let driver

beforeEach(async function () {
driver = await env.builder().build()
})

afterEach(async function () {
await driver.quit()
})

describe('script()', function () {
it('can add authentication handler', async function () {
await driver.network().addAuthenticationHandler('genie', 'bottle')
await driver.get(Pages.basicAuth)

await driver.wait(until.elementLocated(By.css('pre')))
let source = await driver.getPageSource()
assert.equal(source.includes('Access granted'), true)
})

it('can remove authentication handler', async function () {
const id = await driver.network().addAuthenticationHandler('genie', 'bottle')

await driver.network().removeAuthenticationHandler(id)

try {
await driver.get(Pages.basicAuth)
await driver.wait(until.elementLocated(By.css('pre')))
assert.fail('Page should not be loaded')
} catch (e) {
assert.strictEqual(e.name, 'UnexpectedAlertOpenError')
}
})

it('can clear authentication handlers', async function () {
await driver.network().addAuthenticationHandler('genie', 'bottle')

await driver.network().addAuthenticationHandler('bottle', 'genie')

await driver.network().clearAuthenticationHandlers()

try {
await driver.get(Pages.basicAuth)
await driver.wait(until.elementLocated(By.css('pre')))
assert.fail('Page should not be loaded')
} catch (e) {
assert.strictEqual(e.name, 'UnexpectedAlertOpenError')
}
})
})
},
{ browsers: [Browser.FIREFOX] },
)
Loading