Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 270x 270x 270x 270x 270x 89x 89x 89x 89x 89x 89x 89x 216x 115x 115x 216x 89x 89x 1x 1x 1x 33x 33x 1x 1x 1x 1x 1x 1x 1x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 28x 1x 1x 28x 28x 1x 1x 28x 28x 6x 6x 28x 20x 20x 20x 20x 20x 20x 28x 1x 1x 28x 28x 1x 1x 28x 28x 6x 6x 28x 12x 28x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 28x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 26x 26x 27x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 1x 1x 1x 1x 1x 1x 1x 1x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 25x 25x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 24x 26x 20x 20x 26x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 26x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 1x 1x 24x 1x 1x 24x 2x 2x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 3x 3x 2x 3x 1x 1x 3x 20x 3x 1x 1x 1x 3x 20x 20x 1x 1x 1x 1x 1x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 2x 18x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 20x 20x 20x 2x 2x 20x 19x 19x 20x 1x 1x 1x 1x 1x 1x 1x 19x 15x 15x 19x 4x 1x 3x 19x 19x 19x 19x 3x 3x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 27x 27x 27x 27x 27x 27x 27x 27x 27x 12x 12x 27x 27x 27x 3x 3x 27x 9x 18x 3x 3x 18x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 1x 11x 1x 10x 10x 1x 9x 12x 9x 9x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 3x 1x 1x 3x 9x 9x 8x 9x 1x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 2x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 11x 11x 12x 1x 1x 1x 1x 1x 1x 1x 1x 12x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 1x 1x 12x 11x 12x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 11x 11x 12x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 12x 12x 12x 24x 24x 1x 1x 1x 1x 1x 1x 150x 150x 150x 133x 133x 150x 150x | "use strict";
/**
* Trusted host-side request broker.
*
* Every HTTP request made by the sandboxed SDK arrives here as a bridge
* message tagged with the SDK binding that issued it. Before anything is
* sent upstream the broker:
*
* 1. authorises the operation for the request principal (audited);
* 2. checks the request matches that operation (method and path template)
* and targets the configured base URL (network policy);
* 3. strips agent-supplied credential headers and query parameters;
* 4. resolves the operation's security requirement into credentials;
* 5. performs the request with manual redirect handling, following only
* permitted redirects and never forwarding credentials cross-origin;
* 6. bounds the response size and removes Set-Cookie headers.
*
* @module upstream/broker
*/
import type { AuthorizationPolicy } from "../server/authorization.js";
import type {
BridgeFetchRequest,
BridgeFetchResult,
ExecutionError,
} from "../executor/types.js";
import type { Logs } from "../logging/logger.js";
import { sanitizeError } from "../util/redact.js";
import type {
OperationBinding,
Principal,
SecuritySchemeInfo,
} from "../types.js";
import { UpstreamAuthError } from "./credentials.js";
import type { CredentialProvider } from "./types.js";
import { trimTrailingSlashes } from "../util/path.js";
import { resolveSecurity } from "./security.js";
/** Network and size policy for upstream calls. */
export interface NetworkPolicy {
baseUrl: string;
/** Extra origins redirects may target (credentials are not forwarded). */
allowedOrigins: string[];
followRedirects: boolean;
maxRedirects: number;
timeoutMs: number;
maxResponseBytes: number;
maxRequestBytes: number;
}
/** Per-execution context for the broker. */
export interface BrokerContext {
principal: Principal;
executionId: string;
requestId?: string;
logs: Logs;
}
const HOP_BY_HOP = new Set([
"connection",
"keep-alive",
"transfer-encoding",
"te",
"trailer",
"upgrade",
"host",
"content-length",
"proxy-connection",
]);
const ALWAYS_STRIPPED = new Set([
"authorization",
"proxy-authorization",
"cookie",
]);
const RESPONSE_STRIPPED = new Set(["set-cookie", "set-cookie2"]);
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
/** A refused request: the bridge result returned to the sandbox. */
type Refusal = Extract<BridgeFetchResult, { ok: false }>;
/** The authorisation policy's decision for an allowed operation. */
type Decision = ReturnType<AuthorizationPolicy["decide"]>;
/** Credentials resolved for an operation's security requirement. */
type AppliedSecurity = Awaited<ReturnType<typeof resolveSecurity>>;
/** A request body, decoded. */
type Body = Uint8Array | string | undefined;
/** One SDK operation call as it moves through the broker's steps. */
interface Call {
op: OperationBinding;
/** The operation's path template as a URL path matcher. */
re: PathMatcher;
ctx: BrokerContext;
signal: AbortSignal;
/** Fields identifying the operation in audit records. */
audit: {
operation: string;
operationId?: string;
httpMethod: string;
pathTemplate: string;
};
}
/** Where the request goes, once checked. */
interface Target {
url: URL;
method: string;
/** Request headers, set once credentials are applied. */
headers?: Record<string, string>;
}
/** Request headers without agent-supplied credentials. */
interface Stripped {
headers: Record<string, string>;
/** Names of the credential headers and query parameters removed. */
names: string[];
}
/** A response received from the API. */
interface Sent {
response: Response;
/** When the request was first sent, in milliseconds. */
started: number;
}
/**
* The longest request URL the broker accepts, in characters. Longer URLs are
* refused before any matching, with `permission_denied` (`url_too_long`) and
* a `network.destination_denied` audit record, so no request can make path
* checks slow.
*/
export const MAX_URL_LENGTH = 8192;
/** Matches concrete URL paths against one OpenAPI path template. */
export interface PathMatcher {
test(path: string): boolean;
}
/** One part of a template segment: literal text, or a `{parameter}`. */
type Piece = { literal: string } | { param: true };
/**
* Compile a path template into a matcher over URL paths. A parameter matches
* one or more characters other than `/`, as `[^/]+` would, and one trailing
* slash is allowed. Matching works segment by segment without regular
* expressions, so it takes linear time whatever the path: a template with
* several parameters in one segment, such as `/files/{name}.{ext}`, cannot
* be made to backtrack.
*
* This replaces a regular expression with `[^/]+` for each parameter. Against
* a template with several parameters in one segment, that regex backtracked
* quadratically on a long request path, and since the broker runs in the
* server's own process, one request could block the server for minutes.
* Paths are now matched in linear time, and request URLs over
* `MAX_URL_LENGTH` (8,192 characters) are refused before matching.
*
* @param {String} basePath - base URL path without trailing slash
* @param {String} template - OpenAPI path template
* @return {Object} matcher with a `test(path)` method
*/
export function compilePathTemplate(
basePath: string,
template: string,
): PathMatcher {
const segments = template.split("/").map(_segmentPieces);
return {
test: (path: string) => {
if (!path.startsWith(basePath)) {
return false;
}
const rest = path.slice(basePath.length);
return (
_matchSegments(rest, segments) ||
(rest.endsWith("/") && _matchSegments(rest.slice(0, -1), segments))
);
},
};
}
/**
* The literal text and parameters of one template segment, in order. A `{`
* without a matching `}`, or with another `{` or nothing before it, is
* literal text.
*
* @private
*/
function _segmentPieces(segment: string): Piece[] {
const pieces: Piece[] = [];
const literal = (text: string) => {
const last = pieces[pieces.length - 1];
if (last && "literal" in last) {
last.literal += text;
} else if (text) {
pieces.push({ literal: text });
}
};
let i = 0;
while (i < segment.length) {
const open = segment.indexOf("{", i);
const close = open === -1 ? -1 : segment.indexOf("}", open + 1);
if (close === -1) {
literal(segment.slice(i));
break;
}
const inner = segment.indexOf("{", open + 1);
if ((inner !== -1 && inner < close) || close === open + 1) {
const next = inner !== -1 && inner < close ? inner : close + 1;
literal(segment.slice(i, next));
i = next;
continue;
}
literal(segment.slice(i, open));
pieces.push({ param: true });
i = close + 1;
}
return pieces;
}
/**
* Whether a path, split on `/`, matches the template's segments one for one.
*
* @private
*/
function _matchSegments(path: string, segments: Piece[][]): boolean {
const parts = path.split("/");
return (
parts.length === segments.length &&
parts.every((part, i) => _matchSegment(part, segments[i]))
);
}
/**
* Whether one path segment matches a template segment: its literal text in
* order, with one or more characters for each parameter. Literals are found
* leftmost first, which decides a match in linear time.
*
* @private
*/
function _matchSegment(part: string, pieces: Piece[]): boolean {
let start = 0;
let end = part.length;
let first = 0;
let last = pieces.length;
const head = pieces[0];
if (head && "literal" in head) {
if (!part.startsWith(head.literal)) {
return false;
}
start = head.literal.length;
first = 1;
}
const tail = pieces[last - 1];
if (last > first && tail && "literal" in tail) {
if (!part.endsWith(tail.literal) || end - tail.literal.length < start) {
return false;
}
end -= tail.literal.length;
last -= 1;
}
return _matchMiddle(part, pieces.slice(first, last), start, end);
}
/**
* Whether `part[start, end)` matches pieces that begin and end with a
* parameter (or are empty, matching only an empty range).
*
* @private
*/
function _matchMiddle(
part: string,
pieces: Piece[],
start: number,
end: number,
): boolean {
let pos = start;
let need = 0;
for (const piece of pieces) {
if (!("literal" in piece)) {
need += 1;
continue;
}
const at = part.indexOf(piece.literal, pos + need);
if (at === -1 || at + piece.literal.length > end) {
return false;
}
pos = at + piece.literal.length;
need = 0;
}
return need === 0 ? pos === end : end - pos >= need;
}
/**
* Host-side broker for sandboxed SDK requests.
*/
export class RequestBroker {
private readonly ops = new Map<
string,
{ op: OperationBinding; re: PathMatcher }
>();
private readonly base: URL;
private readonly basePath: string;
private readonly allowedOrigins: Set<string>;
private readonly credentialNames: {
headers: Set<string>;
query: Set<string>;
};
/**
* @param {Object} opts - broker options
*/
constructor(
private readonly opts: {
operations: OperationBinding[];
schemes: Record<string, SecuritySchemeInfo>;
provider: CredentialProvider;
policy: AuthorizationPolicy;
network: NetworkPolicy;
fetchImpl?: typeof fetch;
},
) {
this.base = new URL(opts.network.baseUrl);
this.basePath = trimTrailingSlashes(this.base.pathname);
for (const op of opts.operations) {
this.ops.set(op.id, {
op,
re: compilePathTemplate(this.basePath, op.path),
});
}
this.allowedOrigins = new Set([
this.base.origin,
...opts.network.allowedOrigins.map((o) => new URL(o).origin),
]);
const headers = new Set<string>();
const query = new Set<string>();
for (const s of Object.values(opts.schemes)) {
if (s.type === "apiKey" && s.paramName) {
(s.in === "query" ? query : headers).add(s.paramName.toLowerCase());
}
}
this.credentialNames = { headers, query };
}
/** Base path the sandboxed SDK must use. */
get sdkBasePath(): string {
return `${this.base.origin}${this.basePath}`;
}
/**
* Build an error result.
*
* @private
*/
private _err(error: ExecutionError): Refusal {
return { ok: false, error };
}
/**
* Handle one bridge fetch: each step either passes its result on or
* refuses the request.
*
* @param {Object} req - bridge request
* @param {Object} ctx - broker context
* @param {AbortSignal} signal - aborted when the execution ends
* @return {Promise} bridge result
*/
async handle(
req: BridgeFetchRequest,
ctx: BrokerContext,
signal: AbortSignal,
): Promise<BridgeFetchResult> {
const call = this._call(req, ctx, signal);
if (_refused(call)) {
return call;
}
const decision = this._authorize(call);
if (_refused(decision)) {
return decision;
}
const target = this._destination(call, req);
if (_refused(target)) {
return target;
}
const stripped = this._stripCredentials(req, target);
const applied = await this._applyCredentials(
call,
decision,
target,
stripped,
);
if (_refused(applied)) {
return applied;
}
const body = this._body(call, req);
if (_refused(body)) {
return body;
}
const sent = await this._send(call, { ...target, body }, applied);
if (_refused(sent)) {
return sent;
}
this._invalidateRejected(call, sent.response, applied);
return this._readResponse(call, sent);
}
/**
* Find the operation of the SDK binding that sent the request. An unknown
* binding can only come from agent code writing bridge messages itself.
*
* @private
*/
private _call(
req: BridgeFetchRequest,
ctx: BrokerContext,
signal: AbortSignal,
): Call | Refusal {
const entry = this.ops.get(req.binding);
if (!entry) {
ctx.logs.audit(
"execution.boundary_violation",
"denied",
{
reason: "unknown_binding",
binding: String(req.binding).slice(0, 120),
},
"warn",
);
return this._err({
type: "permission_denied",
reason: "unknown_binding",
message: "Request did not come from a known SDK binding",
});
}
const { op, re } = entry;
return {
op,
re,
ctx,
signal,
audit: {
operation: op.id,
operationId: op.operationId,
httpMethod: op.httpMethod,
pathTemplate: op.path,
},
};
}
/**
* Step 1: authorise the operation, for every attempted SDK operation.
*
* Each attempt gets exactly one decision record: denied here, a denied
* destination or a credential failure in a later step, or allowed once
* credentials are applied.
*
* @private
*/
private _authorize(call: Call): Decision | Refusal {
const decision = this.opts.policy.decide(call.ctx.principal, call.op);
if (decision.allowed) {
return decision;
}
call.ctx.logs.audit(
"authorization.denied",
"denied",
{
...call.audit,
policyId: decision.policyId,
reason: decision.reason,
},
"warn",
);
return this._err({
type: "permission_denied",
reason: "authorization_denied",
operation: call.op.id,
message: `You are not permitted to call ${call.op.id}`,
});
}
/**
* Step 2: the request must match the operation (method and path template)
* and target the configured base URL.
*
* @private
*/
private _destination(call: Call, req: BridgeFetchRequest): Target | Refusal {
if (String(req.url).length > MAX_URL_LENGTH) {
call.ctx.logs.audit(
"network.destination_denied",
"denied",
{ ...call.audit, reason: "url_too_long", limit: MAX_URL_LENGTH },
"warn",
);
return this._err({
type: "permission_denied",
reason: "url_too_long",
message: `Request URL is longer than ${MAX_URL_LENGTH} characters`,
});
}
let url: URL;
try {
url = new URL(req.url);
} catch {
call.ctx.logs.audit(
"network.destination_denied",
"denied",
{ ...call.audit, reason: "invalid_url" },
"warn",
);
return this._err({
type: "permission_denied",
reason: "invalid_url",
message: "Invalid request URL",
});
}
const method = String(req.method).toUpperCase();
const reason = this._destinationMismatch(call, url, method);
if (!reason) {
return { url, method };
}
call.ctx.logs.audit(
"network.destination_denied",
"denied",
{
operation: call.op.id,
httpMethod: method,
pathTemplate: call.op.path,
reason,
destinationOrigin: url.origin,
},
"warn",
);
return this._err({
type: "permission_denied",
reason: "network_destination_denied",
operation: call.op.id,
message: `Request to ${url.origin} does not match ${call.op.httpMethod} ${call.op.path} on the configured API base URL`,
});
}
/**
* Why a request does not match its operation, or undefined when it does.
* A URL with user info never matches.
*
* @private
*/
private _destinationMismatch(
call: Call,
url: URL,
method: string,
): string | undefined {
if (url.origin !== this.base.origin) {
return "origin_not_allowed";
}
if (method !== call.op.httpMethod) {
return "method_mismatch";
}
if (!call.re.test(url.pathname) || url.username || url.password) {
return "path_mismatch";
}
return undefined;
}
/**
* Step 3: drop agent-supplied credentials (headers and query parameters)
* and hop-by-hop headers. The URL's credential query parameters are
* removed in place.
*
* @private
*/
private _stripCredentials(req: BridgeFetchRequest, target: Target): Stripped {
const headers: Record<string, string> = {};
const names: string[] = [];
for (const [k, v] of Object.entries(req.headers ?? {})) {
const lk = k.toLowerCase();
if (this._isCredentialHeader(lk)) {
names.push(lk);
} else if (!HOP_BY_HOP.has(lk)) {
headers[k] = String(v);
}
}
for (const name of [...target.url.searchParams.keys()]) {
if (this.credentialNames.query.has(name.toLowerCase())) {
target.url.searchParams.delete(name);
names.push(`query:${name}`);
}
}
return { headers, names };
}
/**
* Whether a (lower-case) header name carries credentials.
*
* @private
*/
private _isCredentialHeader(name: string): boolean {
return ALWAYS_STRIPPED.has(name) || this.credentialNames.headers.has(name);
}
/**
* Step 4: resolve the operation's security requirement into credentials,
* record the allowed decision and apply the credentials to the request.
*
* @private
*/
private async _applyCredentials(
call: Call,
decision: Decision,
target: Target,
stripped: Stripped,
): Promise<AppliedSecurity | Refusal> {
const { ctx, op } = call;
const strippedCredentials =
stripped.names.length > 0
? { strippedCredentials: stripped.names.slice(0, 10) }
: {};
let applied: AppliedSecurity;
try {
applied = await resolveSecurity(
op.security,
this.opts.schemes,
this.opts.provider,
{
principal: ctx.principal,
operation: op,
executionId: ctx.executionId,
requestId: ctx.requestId,
logs: ctx.logs,
signal: call.signal,
},
);
} catch (err) {
const auth = err instanceof UpstreamAuthError ? err : undefined;
const reason = auth?.reason ?? "credential_error";
ctx.logs.audit(
"credential.lookup_failed",
"failure",
{
...call.audit,
...strippedCredentials,
provider: this.opts.provider.id,
reason,
},
"warn",
);
return this._err({
type: "upstream_auth_error",
reason,
operation: op.id,
message: auth?.message ?? "Upstream credentials are unavailable",
});
}
ctx.logs.audit(
"authorization.allowed",
"allowed",
{
...call.audit,
...strippedCredentials,
policyId: decision.policyId,
reason: decision.reason,
provider: this.opts.provider.id,
schemes: applied.schemes,
unauthenticated: applied.schemes.length === 0,
},
stripped.names.length > 0 ? "warn" : "info",
);
for (const [k, v] of Object.entries(applied.query)) {
target.url.searchParams.set(k, v);
}
Object.assign(stripped.headers, applied.headers);
target.headers = stripped.headers;
return applied;
}
/**
* Step 5: decode the request body and enforce its size limit.
*
* @private
*/
private _body(call: Call, req: BridgeFetchRequest): Body | Refusal {
if (req.body === null || req.body === undefined) {
return undefined;
}
const body =
req.bodyEncoding === "base64"
? Buffer.from(req.body, "base64")
: req.body;
const size =
typeof body === "string" ? Buffer.byteLength(body) : body.byteLength;
const limit = this.opts.network.maxRequestBytes;
if (size <= limit) {
return body;
}
call.ctx.logs.audit(
"execution.resource_limit",
"denied",
{ ...call.audit, limit: "maxRequestBytes", value: limit },
"warn",
);
return this._err({
type: "resource_limit",
reason: "request_too_large",
message: `Request body exceeds ${limit} bytes`,
});
}
/**
* Step 6: send the request, following only redirects the network policy
* permits, within the upstream timeout.
*
* @private
*/
private async _send(
call: Call,
request: Target & { body: Body },
applied: AppliedSecurity,
): Promise<Sent | Refusal> {
const started = Date.now();
const timeout = AbortSignal.timeout(this.opts.network.timeoutMs);
const signal = AbortSignal.any([call.signal, timeout]);
const fetchImpl = this.opts.fetchImpl ?? fetch;
const current = { ...request };
try {
for (let hop = 0; ; hop++) {
const response = await fetchImpl(current.url, {
method: current.method,
headers: current.headers,
body: current.body as RequestInit["body"],
redirect: "manual",
signal,
});
const next = _redirectLocation(response, current.url);
if (!next) {
return { response, started };
}
await response.body?.cancel();
const refused = this._checkRedirect(call, next, hop, current.method);
if (refused) {
return refused;
}
this._followRedirect(call, current, response.status, next, applied);
}
} catch (err) {
return this._unreachable(call, err, timeout, started);
}
}
/**
* Refuse a redirect the network policy does not permit.
*
* @private
*/
private _checkRedirect(
call: Call,
next: URL,
hop: number,
method: string,
): Refusal | undefined {
const network = this.opts.network;
const reason = !network.followRedirects
? "redirects_disabled"
: hop >= network.maxRedirects
? "too_many_redirects"
: !/^https?:$/.test(next.protocol) ||
!this.allowedOrigins.has(next.origin)
? "origin_not_allowed"
: undefined;
if (!reason) {
return undefined;
}
call.ctx.logs.audit(
"network.redirect_denied",
"denied",
{
operation: call.op.id,
httpMethod: method,
pathTemplate: call.op.path,
destinationOrigin: next.origin,
reason,
},
"warn",
);
return this._err({
type: "permission_denied",
reason: "redirect_denied",
operation: call.op.id,
message: `The API redirected to ${next.origin}, which the network policy does not allow`,
});
}
/**
* Prepare the request for a permitted redirect: never forward credentials
* to another origin, and turn the request into a GET where HTTP says so.
*
* @private
*/
private _followRedirect(
call: Call,
current: Target & { body: Body },
status: number,
next: URL,
applied: AppliedSecurity,
): void {
call.ctx.logs.op("debug", "upstream.call.redirected", {
operation: call.op.id,
status,
sameOrigin: next.origin === this.base.origin,
});
if (next.origin !== this.base.origin) {
current.headers = Object.fromEntries(
Object.entries(current.headers ?? {}).filter(
([k]) => !this._isCredentialHeader(k.toLowerCase()),
),
);
for (const name of Object.keys(applied.query)) {
next.searchParams.delete(name);
}
}
if (
status === 303 ||
((status === 301 || status === 302) && current.method === "POST")
) {
current.method = "GET";
current.body = undefined;
}
current.url = next;
}
/**
* Report a request that failed before any response: timeout, end of the
* execution, or a network error.
*
* @private
*/
private _unreachable(
call: Call,
err: unknown,
timeout: AbortSignal,
started: number,
): Refusal {
const timedOut = timeout.aborted && !call.signal.aborted;
call.ctx.logs.op("warn", "upstream.call.failed", {
operation: call.op.id,
httpMethod: call.op.httpMethod,
pathTemplate: call.op.path,
durationMs: Date.now() - started,
reason: timedOut
? "timeout"
: call.signal.aborted
? "execution_ended"
: "network_error",
error: sanitizeError(err).name,
});
return this._err({
type: "upstream_unreachable",
reason: timedOut ? "upstream_timeout" : "network_error",
operation: call.op.id,
message: timedOut
? `The API did not respond within ${this.opts.network.timeoutMs} ms`
: "The API could not be reached",
});
}
/**
* Discard cached OAuth tokens the API rejected, so the next call obtains
* a new one.
*
* @private
*/
private _invalidateRejected(
call: Call,
response: Response,
applied: AppliedSecurity,
): void {
if (response.status !== 401) {
return;
}
for (const s of applied.schemes) {
if (this.opts.schemes[s]?.type === "oauth2") {
this.opts.provider.invalidate(s, {
principal: call.ctx.principal,
operation: call.op,
logs: call.ctx.logs,
});
}
}
}
/**
* Step 7: read the response within its size limit, without Set-Cookie
* headers.
*
* @private
*/
private async _readResponse(
call: Call,
sent: Sent,
): Promise<BridgeFetchResult> {
const { response, started } = sent;
const body = await this._readBody(call, response);
if (_refused(body)) {
return body;
}
const headers: Array<[string, string]> = [];
response.headers.forEach((v, k) => {
if (!RESPONSE_STRIPPED.has(k.toLowerCase())) {
headers.push([k, v]);
}
});
call.ctx.logs.op("info", "upstream.call.completed", {
operation: call.op.id,
httpMethod: call.op.httpMethod,
pathTemplate: call.op.path,
status: response.status,
durationMs: Date.now() - started,
responseBytes: body.byteLength,
outcome: response.ok ? "success" : "failure",
});
return {
ok: true,
status: response.status,
statusText: response.statusText,
headers,
body: body.toString("base64"),
};
}
/**
* Read a response body, refusing it once it exceeds the size limit.
*
* @private
*/
private async _readBody(
call: Call,
response: Response,
): Promise<Buffer | Refusal> {
const limit = this.opts.network.maxResponseBytes;
const chunks: Uint8Array[] = [];
let total = 0;
const reader = response.body?.getReader();
for (let r = await reader?.read(); r && !r.done; r = await reader!.read()) {
total += r.value.byteLength;
if (total > limit) {
await reader!.cancel();
call.ctx.logs.audit(
"execution.resource_limit",
"denied",
{ ...call.audit, limit: "maxResponseBytes", value: limit },
"warn",
);
return this._err({
type: "resource_limit",
reason: "response_too_large",
operation: call.op.id,
message: `The API response exceeded ${limit} bytes`,
});
}
chunks.push(r.value);
}
return Buffer.concat(chunks);
}
}
/**
* The next URL of a redirect response, or undefined when the response is
* not a redirect.
*
* @private
*/
function _redirectLocation(response: Response, current: URL): URL | undefined {
if (!REDIRECT_STATUSES.has(response.status)) {
return undefined;
}
const location = response.headers.get("location");
return location ? new URL(location, current) : undefined;
}
/**
* Whether a step refused the request.
*
* @private
*/
function _refused(value: unknown): value is Refusal {
return (
typeof value === "object" &&
value !== null &&
(value as { ok?: unknown }).ok === false
);
}
|