Skip to content
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
27 changes: 27 additions & 0 deletions .changeset/tiny-years-bake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
'@evervault/sdk': minor
---

Extend Relay outbound/forward proxy support in Node to include the ability to filter requests by path using `decryptionDomains`.

Requests can be filtered at the path level by appending an absolute or wildcard path to the decryption domains option, following similar wildcard logic to the domains
themselves. For example:

```js
// Existing behaviour will be observed, proxying requests to the host 'api.com'.
const ev = new Evervault('app_uuid', 'api_key', {
decryptionDomains: ['api.com']
});

// Will only proxy requests to host 'api.com' which have a path starting with '/users/'.
const ev = new Evervault('app_uuid', 'api_key', {
decryptionDomains: ['api.com/users/*']
});

// Will only proxy requests to host 'api.com' which have an exact path of '/settings'.
const ev = new Evervault('app_uuid', 'api_key', {
decryptionDomains: ['api.com/settings']
});
```

This change is compatible with the existing hostname wildcard behaviour of `decryptionDomains`.
103 changes: 103 additions & 0 deletions e2e/outboundRelay.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
const { expect } = require('chai');
const Evervault = require('../lib');
const {
http: { proxiedMarker, certHostname },
} = require('../lib/config');
const axios = require('axios');
const { v4 } = require('uuid');

Expand Down Expand Up @@ -32,6 +35,106 @@ describe('Outbound Relay Test', () => {
expect(body.request.string).to.equal(false);
expect(body.request.number).to.equal(false);
expect(body.request.boolean).to.equal(false);
expect(response.request[proxiedMarker]).to.equal(true);
});
});

context('Enable Outbound Relay with decryption domains', () => {
it('Proxies the listed domains correctly, ignoring others', async () => {
const payload = {
string: 'some_string',
number: 1234567890,
boolean: true,
};

await evervaultClient.enableOutboundRelay({
decryptionDomains: ['httpbin.org'],
});

const [httpbinRes, syntheticRes] = await Promise.allSettled([
axios.post('https://httpbin.org/post', payload),
axios.get(syntheticEndpointUrl),
]);

// We don't need these requests to succeed, we just need them to be attempted so we can check if the symbol was set
// so we can check the proxy marker on either value or reason.
expect(
(httpbinRes.value ?? httpbinRes.reason).request[proxiedMarker]
).to.equal(true);
expect(
(syntheticRes.value ?? syntheticRes.reason).request[proxiedMarker]
).to.equal(false);
});

it('Ignores domains to always ignore even when set in decryption domains', async () => {
const caHost = new URL(certHostname).hostname;
await evervaultClient.enableOutboundRelay({
decryptionDomains: [caHost],
});

const caResponse = await axios.get(certHostname);

expect(caResponse.request[proxiedMarker]).to.equal(false);
});
});

context(
'Enable Outbound Relay with decryption domains including paths',
() => {
it('Filters requests by path', async () => {
const payload = {
string: 'some_string',
number: 1234567890,
boolean: true,
};

await evervaultClient.enableOutboundRelay({
decryptionDomains: ['httpbin.org/post'],
});

const [postRes, getRes] = await Promise.allSettled([
axios.post('https://httpbin.org/post', payload),
axios.get('https://httpbin.org/get'),
]);

expect(
(postRes.value ?? postRes.reason).request[proxiedMarker]
).to.equal(true);
expect((getRes.value ?? getRes.reason).request[proxiedMarker]).to.equal(
false
);
});
}
);

context(
'Enable Outbound Relay with decryption domains including paths with wildcards',
() => {
it('Filters requests by path, respecting wildcards', async () => {
const payload = {
string: 'some_string',
number: 1234567890,
boolean: true,
};

await evervaultClient.enableOutboundRelay({
decryptionDomains: ['httpbin.org/post/*'],
});

const [matchingPostRes, failingPostRes] = await Promise.allSettled([
axios.post('https://httpbin.org/post/somewhere', payload),
axios.get('https://httpbin.org/post'),
]);

expect(
(matchingPostRes.value ?? matchingPostRes.reason).request[
proxiedMarker
]
).to.equal(true);
expect(
(failingPostRes.value ?? failingPostRes.reason).request[proxiedMarker]
).to.equal(false);
});
}
);
});
1 change: 1 addition & 0 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ module.exports = {
pcrProviderPollInterval:
process.env.EV_PCR_PROVIDER_POLL_INTERVAL ||
DEFAULT_PCR_PROVIDER_POLL_INTERVAL,
proxiedMarker: Symbol.for('request-proxied'),
},
encryption: {
secp256k1: {
Expand Down
1 change: 0 additions & 1 deletion lib/core/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const axios = require('axios');
* @param {string} appUuid
* @param {string} apiKey
* @param {import('../types').HttpConfig} config
* @returns
*/
module.exports = (appUuid, apiKey, config) => {
const request = (
Expand Down
53 changes: 18 additions & 35 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {
} = require('./core');
const { TokenCreationError } = require('./utils/errors');
const HttpsProxyAgent = require('./utils/proxyAgent');
const { importTarget, matchTarget } = require('./utils/domainTargets');

const originalRequest = https.request;

Expand Down Expand Up @@ -222,58 +223,40 @@ class EvervaultClient {
/**
* @private
* @param {string[]} decryptionDomains
* @returns {(domain: string) => boolean}
* @returns {(domain: string, path: string) => boolean}
*/
_decryptionDomainsFilter(decryptionDomains) {
return (domain) =>
const parsedDomains = decryptionDomains
.map((decryptionDomain) => importTarget(decryptionDomain))
.filter((importedTarget) => importedTarget != null);
return (domain, path) =>
this._isDecryptionDomain(
domain,
decryptionDomains,
path,
parsedDomains,
this._alwaysIgnoreDomains()
);
}

/**
* @private
* @param {string} domain
* @param {string[]} decryptionDomains
* @param {string} path
* @param {import('./utils/domainTargets').Target[]} decryptionDomains
* @param {string[]} alwaysIgnore
*/
_isDecryptionDomain(domain, decryptionDomains, alwaysIgnore) {
_isDecryptionDomain(domain, path, decryptionDomains, alwaysIgnore) {
if (alwaysIgnore.includes(domain)) return false;
return decryptionDomains.some((decryptionDomain) => {
if (decryptionDomain.charAt(0) === '*') {
return domain.endsWith(decryptionDomain.substring(1));
} else {
return decryptionDomain === domain;
}
});
return decryptionDomains.some((decryptionDomain) =>
matchTarget(domain, path, decryptionDomain)
);
}

/** @private @returns {(domain: string) => boolean} */
/** @private @returns {(domain: string, path: string) => boolean} */
_relayOutboundConfigDomainFilter() {
return (domain) => {
return this._isDecryptionDomain(
domain,
RelayOutboundConfig.getDecryptionDomains(),
this._alwaysIgnoreDomains()
);
};
}

/**
* @private
* @param {string} domain
* @param {string[]} exactDomains
* @param {string[]} endsWithDomains
* @returns {boolean}
*/
_exactOrEndsWith(domain, exactDomains, endsWithDomains) {
if (exactDomains.includes(domain)) return true;
for (let end of endsWithDomains) {
if (domain && domain.endsWith(end)) return true;
}
return false;
return this._decryptionDomainsFilter(
RelayOutboundConfig.getDecryptionDomains()
).bind(this);
}

/**
Expand Down
1 change: 1 addition & 0 deletions lib/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface HttpConfig {
pollInterval: string | number;
attestationDocPollInterval: string | number;
pcrProviderPollInterval: string | number;
proxiedMarker: Symbol;
}

export interface CurveConfig {
Expand Down
14 changes: 14 additions & 0 deletions lib/utils/domainTargets.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export type MatcherSpecificity = "wildcard" | "absolute";
export type MatcherType = "host" | "path";

export interface Target {
rawValue: string;
host: Matcher;
path?: Matcher;
}

export interface Matcher {
specificity: MatcherSpecificity;
type: MatcherType;
value: string;
}
114 changes: 114 additions & 0 deletions lib/utils/domainTargets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* Grouping of helpers and types to aid reasoning about destinations when intercepting outbound traffic.
*/

/**
* Apply the matching logic based on the matcher type and specificity.
* @param {string} givenValue
* @param {import("./domainTargets").Matcher} matcher
*/
function applyMatch(givenValue, matcher) {
if (matcher.specificity === 'absolute') {
return givenValue === matcher.value;
}
if (matcher.type === 'host') {
return givenValue.endsWith(matcher.value);
}
if (matcher.type === 'path') {
return givenValue.startsWith(matcher.value);
}
return false;
}

/**
* Apply a target matcher against the given host and path combination. If a path matcher is defined on the target, it will only match if *both* the host and path match.
* @param {string} requestedHost
* @param {string} requestedPath
* @param {import('./domainTargets').Target} target
*/
function matchTarget(requestedHost, requestedPath, target) {
if (target.path != null) {
return (
applyMatch(requestedHost, target.host) &&
applyMatch(requestedPath, target.path)
);
}
return applyMatch(requestedHost, target.host);
}

/**
* Check if the given hostname includes a protocol prefix.
* @param {string} val
* @returns {boolean}
*/
function startsWithProto(val) {
return val.startsWith('https://') || val.startsWith('http://');
}

/**
* Create a matcher object from a hostname string. If the hostname begins with an asterisk, it will be treated as a wildcard matcher.
* @param {string} host
* @return {import('./domainTargets').Matcher}
*/
function buildHostMatcher(host) {
const specificity = host.startsWith('*') ? 'wildcard' : 'absolute';
const value = specificity === 'wildcard' ? host.slice(1) : host;
return {
type: 'host',
specificity,
value,
};
}

/**
* Create a matcher object from a path string. If the string ends with an asterisk, it will be treated as a wildcard matcher.
* @param {string} path
* @return {import('./domainTargets').Matcher}
*/
function buildPathMatcher(path) {
const specificity = path.endsWith('*') ? 'wildcard' : 'absolute';
const value = specificity === 'wildcard' ? path.slice(0, -1) : path;
return {
type: 'path',
specificity,
value,
};
}

/**
* Convert a user provided input into a target matcher, lightly validating the input in the process.
* @param {unknown} rawInputValue
* @returns {import("./domainTargets").Target | null}
*/
function importTarget(rawInputValue) {
if (typeof rawInputValue !== 'string' || rawInputValue.length === 0) {
return null;
}

// Targets are expected to be domains with optional paths.
if (startsWithProto(rawInputValue)) {
return null;
}

const startPathIndex = rawInputValue.indexOf('/');
if (startPathIndex === -1) {
return {
rawValue: rawInputValue,
host: buildHostMatcher(rawInputValue),
};
}

const hostname = rawInputValue.slice(0, startPathIndex);
const path = rawInputValue.slice(startPathIndex);

return {
rawValue: rawInputValue,
host: buildHostMatcher(hostname),
path: buildPathMatcher(path),
};
}

module.exports = {
importTarget,
matchTarget,
};
Loading
Loading