Skip to content

Commit d9327b4

Browse files
committed
wip
1 parent 7869159 commit d9327b4

File tree

5 files changed

+213
-13
lines changed

5 files changed

+213
-13
lines changed

src/cdp/cdp.zig

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,12 +477,16 @@ pub fn BrowserContext(comptime CDP_T: type) type {
477477
self.cdp.browser.notification.unregister(.http_response_header_done, self);
478478
}
479479

480-
pub fn fetchEnable(self: *Self) !void {
480+
pub fn fetchEnable(self: *Self, authRequests: bool) !void {
481481
try self.cdp.browser.notification.register(.http_request_intercept, self, onHttpRequestIntercept);
482+
if (authRequests) {
483+
try self.cdp.browser.notification.register(.http_request_auth_required, self, onHttpRequestAuthRequired);
484+
}
482485
}
483486

484487
pub fn fetchDisable(self: *Self) void {
485488
self.cdp.browser.notification.unregister(.http_request_intercept, self);
489+
self.cdp.browser.notification.unregister(.http_request_auth_required, self);
486490
}
487491

488492
pub fn onPageRemove(ctx: *anyopaque, _: Notification.PageRemove) !void {
@@ -548,6 +552,12 @@ pub fn BrowserContext(comptime CDP_T: type) type {
548552
try gop.value_ptr.appendSlice(arena, try arena.dupe(u8, msg.data));
549553
}
550554

555+
pub fn onHttpRequestAuthRequired(ctx: *anyopaque, data: *const Notification.RequestAuthRequired) !void {
556+
const self: *Self = @alignCast(@ptrCast(ctx));
557+
defer self.resetNotificationArena();
558+
try @import("domains/fetch.zig").requestAuthRequired(self.notification_arena, self, data);
559+
}
560+
551561
fn resetNotificationArena(self: *Self) void {
552562
defer _ = self.cdp.notification_arena.reset(.{ .retain_with_limit = 1024 * 64 });
553563
}

src/cdp/domains/fetch.zig

Lines changed: 101 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,14 @@ pub fn processMessage(cmd: anytype) !void {
3232
continueRequest,
3333
failRequest,
3434
fulfillRequest,
35+
continueWithAuth,
3536
}, cmd.input.action) orelse return error.UnknownMethod;
3637

3738
switch (action) {
3839
.disable => return disable(cmd),
3940
.enable => return enable(cmd),
4041
.continueRequest => return continueRequest(cmd),
42+
.continueWithAuth => return continueWithAuth(cmd),
4143
.failRequest => return failRequest(cmd),
4244
.fulfillRequest => return fulfillRequest(cmd),
4345
}
@@ -144,12 +146,8 @@ fn enable(cmd: anytype) !void {
144146
return cmd.sendResult(null, .{});
145147
}
146148

147-
if (params.handleAuthRequests) {
148-
log.warn(.cdp, "not implemented", .{ .feature = "Fetch.enable handleAuthRequests is not supported yet" });
149-
}
150-
151149
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
152-
try bc.fetchEnable();
150+
try bc.fetchEnable(params.handleAuthRequests);
153151

154152
return cmd.sendResult(null, .{});
155153
}
@@ -276,6 +274,60 @@ fn continueRequest(cmd: anytype) !void {
276274
return cmd.sendResult(null, .{});
277275
}
278276

277+
fn continueWithAuth(cmd: anytype) !void {
278+
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
279+
const params = (try cmd.params(struct {
280+
requestId: []const u8, // "INTERCEPT-{d}"
281+
authChallengeResponse: struct {
282+
response: []const u8,
283+
username: ?[]const u8 = null,
284+
password: ?[]const u8 = null,
285+
},
286+
})) orelse return error.InvalidParams;
287+
288+
const page = bc.session.currentPage() orelse return error.PageNotLoaded;
289+
290+
var intercept_state = &bc.intercept_state;
291+
const request_id = try idFromRequestId(params.requestId);
292+
const transfer = intercept_state.remove(request_id) orelse return error.RequestNotFound;
293+
294+
log.debug(.cdp, "request intercept", .{
295+
.state = "continue with auth",
296+
.id = transfer.id,
297+
.response = params.authChallengeResponse.response,
298+
});
299+
300+
if (!std.mem.eql(u8, params.authChallengeResponse.response, "ProvideCredentials")) {
301+
transfer.abort();
302+
transfer.deinit();
303+
return cmd.sendResult(null, .{});
304+
}
305+
306+
// cancel the request, deinit the transfer on error.
307+
errdefer {
308+
transfer.abort();
309+
transfer.deinit();
310+
}
311+
312+
const username = params.authChallengeResponse.username orelse "";
313+
const password = params.authChallengeResponse.password orelse "";
314+
315+
// restart the request with the provided credentials.
316+
// we need to duplicate the cre
317+
const arena = transfer.arena.allocator();
318+
transfer.updateCredentials(
319+
try std.fmt.allocPrintZ(arena, "{s}:{s}", .{ username, password }),
320+
);
321+
322+
try bc.cdp.browser.http_client.process(transfer);
323+
324+
if (intercept_state.empty()) {
325+
page.request_intercepted = false;
326+
}
327+
328+
return cmd.sendResult(null, .{});
329+
}
330+
279331
fn fulfillRequest(cmd: anytype) !void {
280332
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
281333

@@ -346,6 +398,50 @@ fn failRequest(cmd: anytype) !void {
346398
return cmd.sendResult(null, .{});
347399
}
348400

401+
pub fn requestAuthRequired(arena: Allocator, bc: anytype, intercept: *const Notification.RequestAuthRequired) !void {
402+
// unreachable because we _have_ to have a page.
403+
const session_id = bc.session_id orelse unreachable;
404+
const target_id = bc.target_id orelse unreachable;
405+
const page = bc.session.currentPage() orelse unreachable;
406+
407+
// We keep it around to wait for modifications to the request.
408+
// NOTE: we assume whomever created the request created it with a lifetime of the Page.
409+
// TODO: What to do when receiving replies for a previous page's requests?
410+
411+
const transfer = intercept.transfer;
412+
try bc.intercept_state.put(transfer);
413+
414+
const challenge = transfer._auth_challenge orelse return error.NullAuthChallenge;
415+
416+
try bc.cdp.sendEvent("Fetch.authRequired", .{
417+
.requestId = try std.fmt.allocPrint(arena, "INTERCEPT-{d}", .{transfer.id}),
418+
.request = network.TransferAsRequestWriter.init(transfer),
419+
.frameId = target_id,
420+
.resourceType = switch (transfer.req.resource_type) {
421+
.script => "Script",
422+
.xhr => "XHR",
423+
.document => "Document",
424+
},
425+
.authChallenge = .{
426+
.source = if (challenge.source == .server) "Server" else "Proxy",
427+
.origin = "", // TODO get origin, could be the proxy address for example.
428+
.scheme = if (challenge.scheme == .digest) "digest" else "basic",
429+
.realm = challenge.realm,
430+
},
431+
.networkId = try std.fmt.allocPrint(arena, "REQ-{d}", .{transfer.id}),
432+
}, .{ .session_id = session_id });
433+
434+
log.debug(.cdp, "request auth required", .{
435+
.state = "paused",
436+
.id = transfer.id,
437+
.url = transfer.uri,
438+
});
439+
// Await continueWithAuth
440+
441+
intercept.wait_for_interception.* = true;
442+
page.request_intercepted = true;
443+
}
444+
349445
// Get u64 from requestId which is formatted as: "INTERCEPT-{d}"
350446
fn idFromRequestId(request_id: []const u8) !u64 {
351447
if (!std.mem.startsWith(u8, request_id, "INTERCEPT-")) {

src/http/Client.zig

Lines changed: 93 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,11 @@ fn makeRequest(self: *Client, handle: *Handle, transfer: *Transfer) !void {
325325
}
326326

327327
try errorCheck(c.curl_easy_setopt(easy, c.CURLOPT_PRIVATE, transfer));
328+
329+
// add credentials
330+
if (req.credentials) |creds| {
331+
try errorCheck(c.curl_easy_setopt(easy, c.CURLOPT_PROXYUSERPWD, creds.ptr));
332+
}
328333
}
329334

330335
// Once soon as this is called, our "perform" loop is responsible for
@@ -365,13 +370,32 @@ fn perform(self: *Client, timeout_ms: c_int) !void {
365370
const easy = msg.easy_handle.?;
366371
const transfer = try Transfer.fromEasy(easy);
367372

373+
// In case of auth challenge
374+
if (transfer._auth_challenge != null) {
375+
if (transfer.client.notification) |notification| {
376+
log.debug(.http, "TRY INTERCEPT", .{});
377+
var wait_for_interception = false;
378+
notification.dispatch(.http_request_auth_required, &.{ .transfer = transfer, .wait_for_interception = &wait_for_interception });
379+
if (wait_for_interception) {
380+
log.debug(.http, "WAIT FOR INTERCEPT", .{});
381+
// the request is put on hold to be intercepted.
382+
// In this case we ignore callbacks for now.
383+
// Note: we don't deinit transfer on purpose: we want to keep
384+
// using it for the following request.
385+
self.endTransfer(transfer);
386+
continue;
387+
}
388+
}
389+
}
390+
368391
// release it ASAP so that it's available; some done_callbacks
369392
// will load more resources.
370393
self.endTransfer(transfer);
371394

372395
defer transfer.deinit();
373396

374397
if (errorCheck(msg.data.result)) {
398+
375399
// In case of request w/o data, we need to call the header done
376400
// callback now.
377401
if (!transfer._header_done_called) {
@@ -542,6 +566,7 @@ pub const Request = struct {
542566
body: ?[]const u8 = null,
543567
cookie_jar: *CookieJar,
544568
resource_type: ResourceType,
569+
credentials: ?[:0]const u8 = null,
545570

546571
// arbitrary data that can be associated with this request
547572
ctx: *anyopaque = undefined,
@@ -559,6 +584,44 @@ pub const Request = struct {
559584
};
560585
};
561586

587+
pub const AuthChallenge = struct {
588+
source: enum { server, proxy },
589+
scheme: enum { basic, digest },
590+
realm: []const u8,
591+
592+
pub fn parse(header: []const u8) !AuthChallenge {
593+
var ac: AuthChallenge = .{
594+
.source = undefined,
595+
.realm = "TODO", // TODO parser and set realm
596+
.scheme = undefined,
597+
};
598+
599+
const sep = std.mem.indexOfPos(u8, header, 0, ": ") orelse return error.InvalidHeader;
600+
const hname = header[0..sep];
601+
const hvalue = header[sep + 2 ..];
602+
603+
if (std.ascii.eqlIgnoreCase("WWW-Authenticate", hname)) {
604+
ac.source = .server;
605+
} else if (std.ascii.eqlIgnoreCase("Proxy-Authenticate", hname)) {
606+
ac.source = .proxy;
607+
} else {
608+
return error.InvalidAuthChallenge;
609+
}
610+
611+
const pos = std.mem.indexOfPos(u8, std.mem.trim(u8, hvalue, std.ascii.whitespace[0..]), 0, " ") orelse hvalue.len;
612+
const _scheme = hvalue[0..pos];
613+
if (std.ascii.eqlIgnoreCase(_scheme, "basic")) {
614+
ac.scheme = .basic;
615+
} else if (std.ascii.eqlIgnoreCase(_scheme, "digest")) {
616+
ac.scheme = .digest;
617+
} else {
618+
return error.UnknownAuthChallengeScheme;
619+
}
620+
621+
return ac;
622+
}
623+
};
624+
562625
pub const Transfer = struct {
563626
arena: ArenaAllocator,
564627
id: usize = 0,
@@ -582,9 +645,9 @@ pub const Transfer = struct {
582645
_handle: ?*Handle = null,
583646

584647
_redirecting: bool = false,
585-
_forbidden: bool = false,
648+
_auth_challenge: ?AuthChallenge = null,
586649

587-
fn deinit(self: *Transfer) void {
650+
pub fn deinit(self: *Transfer) void {
588651
self.req.headers.deinit();
589652
if (self._handle) |handle| {
590653
self.client.handles.release(handle);
@@ -633,6 +696,10 @@ pub const Transfer = struct {
633696
self.req.url = url;
634697
}
635698

699+
pub fn updateCredentials(self: *Transfer, userpwd: [:0]const u8) void {
700+
self.req.credentials = userpwd;
701+
}
702+
636703
pub fn replaceRequestHeaders(self: *Transfer, allocator: Allocator, headers: []const Http.Header) !void {
637704
self.req.headers.deinit();
638705

@@ -782,20 +849,40 @@ pub const Transfer = struct {
782849
transfer._redirecting = false;
783850

784851
if (status == 401 or status == 407) {
785-
transfer._forbidden = true;
852+
// The auth challenge must be parsed from a following
853+
// WWW-Authenticate or Proxy-Authenticate header.
854+
transfer._auth_challenge = .{
855+
.source = undefined,
856+
.scheme = undefined,
857+
.realm = undefined,
858+
};
786859
return buf_len;
787860
}
788-
transfer._forbidden = false;
861+
transfer._auth_challenge = null;
789862

790863
transfer.bytes_received = buf_len;
791864
return buf_len;
792865
}
793866

794-
if (transfer._redirecting == false and transfer._forbidden == false) {
867+
if (transfer._redirecting == false and transfer._auth_challenge != null) {
795868
transfer.bytes_received += buf_len;
796869
}
797870

798871
if (buf_len != 2) {
872+
if (transfer._auth_challenge != null) {
873+
// try to parse auth challenge.
874+
if (std.ascii.startsWithIgnoreCase(header, "WWW-Authenticate") or
875+
std.ascii.startsWithIgnoreCase(header, "Proxy-Authenticate"))
876+
{
877+
const ac = AuthChallenge.parse(header) catch |err| {
878+
// We can't parse the auth challenge
879+
log.err(.http, "parse auth challenge", .{ .err = err, .header = header });
880+
// Should we cancel the request? I don't think so.
881+
return buf_len;
882+
};
883+
transfer._auth_challenge = ac;
884+
}
885+
}
799886
return buf_len;
800887
}
801888

@@ -823,7 +910,7 @@ pub const Transfer = struct {
823910
return c.CURL_WRITEFUNC_ERROR;
824911
};
825912

826-
if (transfer._redirecting) {
913+
if (transfer._redirecting or transfer._auth_challenge != null) {
827914
return chunk_len;
828915
}
829916

src/http/Http.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ pub const c = @cImport({
2222
@cInclude("curl/curl.h");
2323
});
2424

25-
pub const ENABLE_DEBUG = false;
25+
pub const ENABLE_DEBUG = true;
2626
pub const Client = @import("Client.zig");
2727
pub const Transfer = Client.Transfer;
2828

src/notification.zig

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ pub const Notification = struct {
6464
http_request_start: List = .{},
6565
http_request_intercept: List = .{},
6666
http_request_done: List = .{},
67+
http_request_auth_required: List = .{},
6768
http_response_data: List = .{},
6869
http_response_header_done: List = .{},
6970
notification_created: List = .{},
@@ -77,6 +78,7 @@ pub const Notification = struct {
7778
http_request_fail: *const RequestFail,
7879
http_request_start: *const RequestStart,
7980
http_request_intercept: *const RequestIntercept,
81+
http_request_auth_required: *const RequestAuthRequired,
8082
http_request_done: *const RequestDone,
8183
http_response_data: *const ResponseData,
8284
http_response_header_done: *const ResponseHeaderDone,
@@ -106,6 +108,11 @@ pub const Notification = struct {
106108
wait_for_interception: *bool,
107109
};
108110

111+
pub const RequestAuthRequired = struct {
112+
transfer: *Transfer,
113+
wait_for_interception: *bool,
114+
};
115+
109116
pub const ResponseData = struct {
110117
data: []const u8,
111118
transfer: *Transfer,

0 commit comments

Comments
 (0)