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

feat: support network.continueResponse authorization #1961

Merged
merged 4 commits into from
Mar 14, 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
61 changes: 40 additions & 21 deletions src/bidiMapper/domains/network/NetworkProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,24 +101,45 @@ export class NetworkProcessor {
async continueResponse(
params: Network.ContinueResponseParameters
): Promise<EmptyResult> {
const networkId = params.request;
const {statusCode, reasonPhrase, headers} = params;
const request = this.#getBlockedRequestOrFail(networkId, [
Network.InterceptPhase.ResponseStarted,
]);
const {request: networkId, statusCode, reasonPhrase, headers} = params;

const responseHeaders: Protocol.Fetch.HeaderEntry[] | undefined =
cdpFetchHeadersFromBidiNetworkHeaders(headers);

// TODO: Set / expand.
// ; Step 10. cookies
// ; Step 11. credentials
const request = this.#getBlockedRequestOrFail(networkId, [
Network.InterceptPhase.AuthRequired,
Network.InterceptPhase.ResponseStarted,
]);

await request.continueResponse({
responseCode: statusCode,
responsePhrase: reasonPhrase,
responseHeaders,
});
if (request.interceptPhase === Network.InterceptPhase.AuthRequired) {
if (params.credentials) {
await Promise.all([
request.waitNextPhase,
request.continueWithAuth({
response: 'ProvideCredentials',
username: params.credentials.username,
password: params.credentials.password,
}),
]);
} else {
// We need to use `ProvideCredentials`
// As `Default` may cancel the request
await request.continueWithAuth({
response: 'ProvideCredentials',
});
return {};
}
}

if (request.interceptPhase === Network.InterceptPhase.ResponseStarted) {
// TODO: Set / expand.
// ; Step 10. cookies
await request.continueResponse({
responseCode: statusCode,
responsePhrase: reasonPhrase,
responseHeaders,
});
}

return {};
}
Expand Down Expand Up @@ -164,12 +185,12 @@ export class NetworkProcessor {
request: networkId,
}: Network.FailRequestParameters): Promise<EmptyResult> {
const request = this.#getRequestOrFail(networkId);
if (request.currentInterceptPhase === Network.InterceptPhase.AuthRequired) {
if (request.interceptPhase === Network.InterceptPhase.AuthRequired) {
throw new InvalidArgumentException(
`Request '${networkId}' in 'authRequired' phase cannot be failed`
);
}
if (!request.currentInterceptPhase) {
if (!request.interceptPhase) {
throw new NoSuchRequestException(
`No blocked request found for network id '${networkId}'`
);
Expand Down Expand Up @@ -205,6 +226,7 @@ export class NetworkProcessor {
Network.InterceptPhase.ResponseStarted,
Network.InterceptPhase.AuthRequired,
]);

await request.provideResponse({
responseCode: statusCode ?? request.statusCode,
responsePhrase: reasonPhrase,
Expand Down Expand Up @@ -245,17 +267,14 @@ export class NetworkProcessor {
phases: Network.InterceptPhase[]
): NetworkRequest {
const request = this.#getRequestOrFail(id);
if (!request.currentInterceptPhase) {
if (!request.interceptPhase) {
throw new NoSuchRequestException(
`No blocked request found for network id '${id}'`
);
}
if (
request.currentInterceptPhase &&
!phases.includes(request.currentInterceptPhase)
) {
if (request.interceptPhase && !phases.includes(request.interceptPhase)) {
throw new InvalidArgumentException(
`Blocked request for network id '${id}' is in '${request.currentInterceptPhase}' phase`
`Blocked request for network id '${id}' is in '${request.interceptPhase}' phase`
);
}

Expand Down
22 changes: 19 additions & 3 deletions src/bidiMapper/domains/network/NetworkRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
type NetworkEvent,
} from '../../../protocol/protocol.js';
import {assert} from '../../../utils/assert.js';
import {Deferred} from '../../../utils/Deferred.js';
import {LogType, type LoggerFn} from '../../../utils/log.js';
import type {CdpTarget} from '../context/CdpTarget.js';
import type {EventManager} from '../session/EventManager.js';
Expand Down Expand Up @@ -94,6 +95,8 @@ export class NetworkRequest {
[ChromiumBidi.Network.EventNames.ResponseStarted]: false,
};

waitNextPhase = new Deferred<void>();

constructor(
id: Network.Request,
eventManager: EventManager,
Expand Down Expand Up @@ -121,7 +124,7 @@ export class NetworkRequest {
/**
* When blocked returns the phase for it
*/
get currentInterceptPhase(): Network.InterceptPhase | undefined {
get interceptPhase(): Network.InterceptPhase | undefined {
return this.#interceptPhase;
}

Expand Down Expand Up @@ -162,6 +165,11 @@ export class NetworkRequest {
return Boolean(this.#request.info);
}

#phaseChanged() {
this.waitNextPhase.resolve();
this.waitNextPhase = new Deferred();
}

#interceptsInPhase(phase: Network.InterceptPhase) {
if (!this.#cdpTarget.isSubscribedTo(`network.${phase}`)) {
return new Set();
Expand Down Expand Up @@ -281,6 +289,7 @@ export class NetworkRequest {
this.#emitEventsIfReady({
hasFailed: true,
});

this.#emitEvent(() => {
return {
method: ChromiumBidi.Network.EventNames.FetchError,
Expand Down Expand Up @@ -309,6 +318,7 @@ export class NetworkRequest {
// CDP https://chromedevtools.github.io/devtools-protocol/tot/Fetch/#event-requestPaused
if (event.responseStatusCode || event.responseErrorReason) {
this.#response.paused = event;

if (this.#isBlockedInPhase(Network.InterceptPhase.ResponseStarted)) {
this.#interceptPhase = Network.InterceptPhase.ResponseStarted;
} else {
Expand All @@ -329,6 +339,7 @@ export class NetworkRequest {
onAuthRequired(event: Protocol.Fetch.AuthRequiredEvent) {
this.#fetchId = event.requestId;
this.#request.auth = event;

if (this.#isBlockedInPhase(Network.InterceptPhase.AuthRequired)) {
this.#interceptPhase = Network.InterceptPhase.AuthRequired;
} else {
Expand Down Expand Up @@ -446,10 +457,15 @@ export class NetworkRequest {
return;
}

if (this.#isIgnoredEvent() || this.#emittedEvents[event.method]) {
if (
this.#isIgnoredEvent() ||
(this.#emittedEvents[event.method] &&
// Special case this event can be emitted multiple times
event.method !== ChromiumBidi.Network.EventNames.AuthRequired)
) {
return;
}

this.#phaseChanged();
this.#emittedEvents[event.method] = true;
this.#eventManager.registerEvent(
Object.assign(event, {
Expand Down
31 changes: 25 additions & 6 deletions src/bidiMapper/domains/network/NetworkStorage.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ function logger(...args: any[]) {
}

describe('NetworkStorage', () => {
let processedEvents = new Map<
let processedEvents: [
ChromiumBidi.Event['method'],
ChromiumBidi.Event['params']
>();
ChromiumBidi.Event['params'],
][] = [];
let eventManager!: EventManager;
let networkStorage!: NetworkStorage;
let cdpClient!: CdpClient;
Expand All @@ -54,11 +54,19 @@ describe('NetworkStorage', () => {
async function getEvent(name: ChromiumBidi.Event['method']) {
await new Promise((resolve) => setTimeout(resolve, 0));

return processedEvents.get(name);
return processedEvents
.reverse()
.find(([method]) => method === name)
?.at(1);
}
async function getEvents(name: ChromiumBidi.Event['method']) {
await new Promise((resolve) => setTimeout(resolve, 0));

return processedEvents.filter(([method]) => method === name);
}

beforeEach(() => {
processedEvents = new Map();
processedEvents = [];
const browsingContextStorage = new BrowsingContextStorage();
const cdpTarget = new MockCdpTarget(logger) as unknown as CdpTarget;
const browsingContext = {
Expand All @@ -72,7 +80,7 @@ describe('NetworkStorage', () => {
processingQueue = new ProcessingQueue<OutgoingMessage>(
async ({message}) => {
if (message.type === 'event') {
processedEvents.set(message.method, message.params);
processedEvents.push([message.method, message.params]);
}
return await Promise.resolve();
},
Expand Down Expand Up @@ -310,5 +318,16 @@ describe('NetworkStorage', () => {
'request.method': 'GET',
});
});

it('should work report multiple authRequired', async () => {
const request = new MockCdpNetworkEvents(cdpClient);

request.authRequired();
let events = await getEvents('network.authRequired');
expect(events).to.have.length(1);
request.authRequired();
events = await getEvents('network.authRequired');
expect(events).to.have.length(2);
});
});
});

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
[action.py]
[test_default]
expected: FAIL

[test_provideCredentials_wrong_credentials]
expected: FAIL
Loading