-
Notifications
You must be signed in to change notification settings - Fork 61
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 proxy
option
#614
Merged
+400
−172
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
fb8002b
feat: Support `proxy` option
d-goog 81d551b
refactor: Do not override user-provided `agent`
d-goog a102f1b
docs: correction
d-goog 7d4a27e
feat: Support `no_proxy` complete URL matching
d-goog 3fb49c6
test: Add proxy tests
d-goog 39c5bdf
docs: corrections
d-goog File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,7 +31,6 @@ import { | |
} from './common'; | ||
import {getRetryConfig} from './retry'; | ||
import {PassThrough, Stream, pipeline} from 'stream'; | ||
import {HttpsProxyAgent as httpsProxyAgent} from 'https-proxy-agent'; | ||
import {v4} from 'uuid'; | ||
|
||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
|
@@ -64,54 +63,11 @@ function getHeader(options: GaxiosOptions, header: string): string | undefined { | |
return undefined; | ||
} | ||
|
||
let HttpsProxyAgent: any; | ||
|
||
function loadProxy() { | ||
const proxy = | ||
process?.env?.HTTPS_PROXY || | ||
process?.env?.https_proxy || | ||
process?.env?.HTTP_PROXY || | ||
process?.env?.http_proxy; | ||
if (proxy) { | ||
HttpsProxyAgent = httpsProxyAgent; | ||
} | ||
|
||
return proxy; | ||
} | ||
|
||
loadProxy(); | ||
|
||
function skipProxy(url: string | URL) { | ||
const noProxyEnv = process.env.NO_PROXY ?? process.env.no_proxy; | ||
if (!noProxyEnv) { | ||
return false; | ||
} | ||
const noProxyUrls = noProxyEnv.split(','); | ||
const parsedURL = url instanceof URL ? url : new URL(url); | ||
return !!noProxyUrls.find(url => { | ||
if (url.startsWith('*.') || url.startsWith('.')) { | ||
url = url.replace(/^\*\./, '.'); | ||
return parsedURL.hostname.endsWith(url); | ||
} else { | ||
return url === parsedURL.origin || url === parsedURL.hostname; | ||
} | ||
}); | ||
} | ||
|
||
// Figure out if we should be using a proxy. Only if it's required, load | ||
// the https-proxy-agent module as it adds startup cost. | ||
function getProxy(url: string | URL) { | ||
// If there is a match between the no_proxy env variables and the url, then do not proxy | ||
if (skipProxy(url)) { | ||
return undefined; | ||
// If there is not a match between the no_proxy env variables and the url, check to see if there should be a proxy | ||
} else { | ||
return loadProxy(); | ||
} | ||
} | ||
|
||
export class Gaxios { | ||
protected agentCache = new Map<string, Agent | ((parsedUrl: URL) => Agent)>(); | ||
protected agentCache = new Map< | ||
string | URL, | ||
Agent | ((parsedUrl: URL) => Agent) | ||
>(); | ||
|
||
/** | ||
* Default HTTP options that will be used for every HTTP request. | ||
|
@@ -131,15 +87,15 @@ export class Gaxios { | |
* @param opts Set of HTTP options that will be used for this HTTP request. | ||
*/ | ||
async request<T = any>(opts: GaxiosOptions = {}): GaxiosPromise<T> { | ||
opts = this.validateOpts(opts); | ||
opts = await this.#prepareRequest(opts); | ||
return this._request(opts); | ||
} | ||
|
||
private async _defaultAdapter<T>( | ||
opts: GaxiosOptions | ||
): Promise<GaxiosResponse<T>> { | ||
const fetchImpl = opts.fetchImplementation || fetch; | ||
const res = (await fetchImpl(opts.url!, opts)) as FetchResponse; | ||
const res = (await fetchImpl(opts.url, opts)) as FetchResponse; | ||
const data = await this.getResponseData(opts, res); | ||
return this.translateResponse<T>(opts, res, data); | ||
} | ||
|
@@ -228,11 +184,59 @@ export class Gaxios { | |
} | ||
} | ||
|
||
#urlMayUseProxy( | ||
url: string | URL, | ||
noProxy: GaxiosOptions['noProxy'] = [] | ||
): boolean { | ||
const candidate = new URL(url); | ||
const noProxyList = [...noProxy]; | ||
const noProxyEnvList = | ||
(process.env.NO_PROXY ?? process.env.no_proxy)?.split(',') || []; | ||
|
||
for (const rule of noProxyEnvList) { | ||
noProxyList.push(rule.trim()); | ||
} | ||
|
||
for (const rule of noProxyList) { | ||
// Match regex | ||
if (rule instanceof RegExp) { | ||
if (rule.test(candidate.toString())) { | ||
return false; | ||
} | ||
} | ||
// Match URL | ||
else if (rule instanceof URL) { | ||
if (rule.origin === candidate.origin) { | ||
return false; | ||
} | ||
} | ||
// Match string regex | ||
else if (rule.startsWith('*.') || rule.startsWith('.')) { | ||
const cleanedRule = rule.replace(/^\*\./, '.'); | ||
if (candidate.hostname.endsWith(cleanedRule)) { | ||
return false; | ||
} | ||
} | ||
// Basic string match | ||
else if ( | ||
rule === candidate.origin || | ||
rule === candidate.hostname || | ||
rule === candidate.href | ||
) { | ||
return false; | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
|
||
/** | ||
* Validates the options, and merges them with defaults. | ||
* @param opts The original options passed from the client. | ||
* Validates the options, merges them with defaults, and prepare request. | ||
* | ||
* @param options The original options passed from the client. | ||
* @returns Prepared options, ready to make a request | ||
*/ | ||
private validateOpts(options: GaxiosOptions): GaxiosOptions { | ||
async #prepareRequest(options: GaxiosOptions): Promise<GaxiosOptions> { | ||
const opts = extend(true, {}, this.defaults, options); | ||
if (!opts.url) { | ||
throw new Error('URL is required.'); | ||
|
@@ -318,36 +322,39 @@ export class Gaxios { | |
} | ||
opts.method = opts.method || 'GET'; | ||
|
||
const proxy = getProxy(opts.url); | ||
if (proxy) { | ||
const proxy = | ||
opts.proxy || | ||
process?.env?.HTTPS_PROXY || | ||
process?.env?.https_proxy || | ||
process?.env?.HTTP_PROXY || | ||
process?.env?.http_proxy; | ||
const urlMayUseProxy = this.#urlMayUseProxy(opts.url, opts.noProxy); | ||
|
||
if (opts.agent) { | ||
// don't do any of the following options - use the user-provided agent. | ||
} else if (proxy && urlMayUseProxy) { | ||
const HttpsProxyAgent = await Gaxios.#getProxyAgent(); | ||
|
||
if (this.agentCache.has(proxy)) { | ||
opts.agent = this.agentCache.get(proxy); | ||
} else { | ||
// Proxy is being used in conjunction with mTLS. | ||
if (opts.cert && opts.key) { | ||
const parsedURL = new URL(proxy); | ||
opts.agent = new HttpsProxyAgent({ | ||
port: parsedURL.port, | ||
host: parsedURL.host, | ||
protocol: parsedURL.protocol, | ||
cert: opts.cert, | ||
key: opts.key, | ||
}); | ||
} else { | ||
opts.agent = new HttpsProxyAgent(proxy); | ||
} | ||
this.agentCache.set(proxy, opts.agent!); | ||
opts.agent = new HttpsProxyAgent(proxy, { | ||
cert: opts.cert, | ||
key: opts.key, | ||
}); | ||
|
||
this.agentCache.set(proxy, opts.agent); | ||
} | ||
} else if (opts.cert && opts.key) { | ||
// Configure client for mTLS: | ||
// Configure client for mTLS | ||
if (this.agentCache.has(opts.key)) { | ||
opts.agent = this.agentCache.get(opts.key); | ||
} else { | ||
opts.agent = new HTTPSAgent({ | ||
cert: opts.cert, | ||
key: opts.key, | ||
}); | ||
this.agentCache.set(opts.key, opts.agent!); | ||
this.agentCache.set(opts.key, opts.agent); | ||
} | ||
} | ||
|
||
|
@@ -459,4 +466,23 @@ export class Gaxios { | |
} | ||
yield finale; | ||
} | ||
|
||
/** | ||
* A cache for the lazily-loaded proxy agent. | ||
* | ||
* Should use {@link Gaxios[#getProxyAgent]} to retrieve. | ||
*/ | ||
// using `import` to dynamically import the types here | ||
static #proxyAgent?: typeof import('https-proxy-agent').HttpsProxyAgent; | ||
|
||
/** | ||
* Imports, caches, and returns a proxy agent - if not already imported | ||
* | ||
* @returns A proxy agent | ||
*/ | ||
static async #getProxyAgent() { | ||
this.#proxyAgent ||= (await import('https-proxy-agent')).HttpsProxyAgent; | ||
|
||
return this.#proxyAgent; | ||
} | ||
Comment on lines
+469
to
+487
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This may have the convenient side-effect of preventing See npx esbuild ./build/src/index.js --platform=node --bundle --outfile=out.js Related: |
||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking at the following link I do not believe mTLS was working for proxied requests previously:
This was due to
HttpsProxyAgent
beingany
at the timeThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Woah, if I'm reading this right how did it work at all? Looks like the first parameter should have been
Uri | URL
, not an object. Nice catch.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep! Never worked at all 😔