@celljs/ta-gateway 4.16.0 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +5 -2
- package/README.md +5 -2
- package/esm/node/docker-engine.d.ts +5 -1
- package/esm/node/docker-engine.js +7 -1
- package/esm/node/docker-sandbox.d.ts +10 -1
- package/esm/node/docker-sandbox.js +24 -5
- package/esm/node/egress-proxy.d.ts +98 -0
- package/esm/node/egress-proxy.js +428 -0
- package/esm/node/environments.d.ts +5 -2
- package/esm/node/environments.js +4 -2
- package/esm/node/gateway-cli.js +13 -6
- package/esm/node/gateway-policy.d.ts +6 -1
- package/esm/node/gateway-policy.js +10 -1
- package/esm/node/gateway-quotas.d.ts +6 -1
- package/esm/node/gateway-quotas.js +17 -0
- package/esm/node/gateway-server.d.ts +35 -1
- package/esm/node/gateway-server.js +150 -16
- package/esm/node/gateway-service-util.d.ts +41 -0
- package/esm/node/gateway-service-util.js +178 -0
- package/esm/node/gateway-service.d.ts +5 -41
- package/esm/node/gateway-service.js +19 -173
- package/esm/node/gateway-socket.d.ts +1 -1
- package/esm/node/gateway-socket.js +1 -1
- package/esm/node/index.d.ts +4 -0
- package/esm/node/index.js +4 -0
- package/esm/node/kubernetes-api.d.ts +35 -0
- package/esm/node/kubernetes-api.js +115 -0
- package/esm/node/kubernetes-sandbox.d.ts +198 -0
- package/esm/node/kubernetes-sandbox.js +279 -0
- package/esm/node/sandbox-provider.d.ts +11 -1
- package/esm/node/sandbox-provider.js +2 -1
- package/esm/node/tenant-store.d.ts +15 -0
- package/esm/node/tenant-store.js +15 -0
- package/lib/node/docker-engine.d.ts +5 -1
- package/lib/node/docker-engine.js +7 -1
- package/lib/node/docker-sandbox.d.ts +10 -1
- package/lib/node/docker-sandbox.js +24 -5
- package/lib/node/egress-proxy.d.ts +99 -0
- package/lib/node/egress-proxy.js +433 -0
- package/lib/node/environments.d.ts +5 -2
- package/lib/node/environments.js +4 -2
- package/lib/node/gateway-cli.js +13 -6
- package/lib/node/gateway-policy.d.ts +6 -1
- package/lib/node/gateway-policy.js +10 -1
- package/lib/node/gateway-quotas.d.ts +6 -1
- package/lib/node/gateway-quotas.js +17 -0
- package/lib/node/gateway-server.d.ts +35 -1
- package/lib/node/gateway-server.js +148 -14
- package/lib/node/gateway-service-util.d.ts +42 -0
- package/lib/node/gateway-service-util.js +182 -0
- package/lib/node/gateway-service.d.ts +5 -41
- package/lib/node/gateway-service.js +41 -196
- package/lib/node/gateway-socket.d.ts +1 -1
- package/lib/node/gateway-socket.js +10 -10
- package/lib/node/index.d.ts +4 -0
- package/lib/node/index.js +4 -0
- package/lib/node/kubernetes-api.d.ts +36 -0
- package/lib/node/kubernetes-api.js +120 -0
- package/lib/node/kubernetes-sandbox.d.ts +199 -0
- package/lib/node/kubernetes-sandbox.js +283 -0
- package/lib/node/sandbox-provider.d.ts +11 -1
- package/lib/node/sandbox-provider.js +2 -1
- package/lib/node/tenant-store.d.ts +15 -0
- package/lib/node/tenant-store.js +15 -0
- package/package.json +4 -4
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.DockerSandbox = exports.DockerSandboxUtil = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
4
5
|
const docker_engine_1 = require("./docker-engine");
|
|
5
6
|
const sandbox_provider_1 = require("./sandbox-provider");
|
|
6
7
|
var DockerSandboxUtil;
|
|
7
8
|
(function (DockerSandboxUtil) {
|
|
9
|
+
/** The label of a container that tells the environment the gateway gave it. */
|
|
10
|
+
DockerSandboxUtil.ENV_LABEL = 'cell.ta.env';
|
|
11
|
+
/** Of the environment the gateway gives a sandbox, whatever its order. */
|
|
12
|
+
function envHash(env) {
|
|
13
|
+
const entries = Object.entries(env !== null && env !== void 0 ? env : {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
14
|
+
return (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(entries)).digest('hex').slice(0, 16);
|
|
15
|
+
}
|
|
16
|
+
DockerSandboxUtil.envHash = envHash;
|
|
17
|
+
/**
|
|
18
|
+
* Whether a container was made with the environment the gateway gives it now: by its label, so that a variable
|
|
19
|
+
* taken away (the way out turned off) counts too; one made before the label, by its variables.
|
|
20
|
+
*/
|
|
21
|
+
function sameEnv(config, want) {
|
|
22
|
+
var _a;
|
|
23
|
+
const made = (_a = config === null || config === void 0 ? void 0 : config.Labels) === null || _a === void 0 ? void 0 : _a[DockerSandboxUtil.ENV_LABEL];
|
|
24
|
+
return made !== undefined ? made === envHash(want) : hasEnv(config === null || config === void 0 ? void 0 : config.Env, want);
|
|
25
|
+
}
|
|
26
|
+
DockerSandboxUtil.sameEnv = sameEnv;
|
|
8
27
|
/** Whether a container has each variable of `env` as it is. */
|
|
9
28
|
function hasEnv(have, want) {
|
|
10
29
|
const set = new Set(have !== null && have !== void 0 ? have : []);
|
|
@@ -65,11 +84,11 @@ class DockerSandbox {
|
|
|
65
84
|
this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
|
|
66
85
|
}
|
|
67
86
|
async start(tenant) {
|
|
68
|
-
var _a, _b, _c
|
|
87
|
+
var _a, _b, _c;
|
|
69
88
|
const name = this.containerName(tenant);
|
|
70
89
|
let container = await this.engine.inspect(name);
|
|
71
|
-
if (container && !DockerSandboxUtil.
|
|
72
|
-
// Made
|
|
90
|
+
if (container && !DockerSandboxUtil.sameEnv(container.Config, tenant.env)) {
|
|
91
|
+
// Made with another environment (the models of the gateway, its way out): made again, its volume kept.
|
|
73
92
|
await this.engine.remove(name);
|
|
74
93
|
container = undefined;
|
|
75
94
|
}
|
|
@@ -83,7 +102,7 @@ class DockerSandbox {
|
|
|
83
102
|
await this.engine.start(name);
|
|
84
103
|
container = await this.engine.inspect(name);
|
|
85
104
|
}
|
|
86
|
-
const port = (
|
|
105
|
+
const port = (_c = (_b = (_a = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _a === void 0 ? void 0 : _a[PORT]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.HostPort;
|
|
87
106
|
if (!port) {
|
|
88
107
|
throw new Error(`The container ${name} publishes no port for ${PORT}.`);
|
|
89
108
|
}
|
|
@@ -110,7 +129,7 @@ class DockerSandbox {
|
|
|
110
129
|
// What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
|
|
111
130
|
Hostname: DockerSandboxUtil.hostname(tenant.account),
|
|
112
131
|
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
|
|
113
|
-
Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
|
|
132
|
+
Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account, [DockerSandboxUtil.ENV_LABEL]: DockerSandboxUtil.envHash(tenant.env) },
|
|
114
133
|
ExposedPorts: { [PORT]: {} },
|
|
115
134
|
HostConfig: {
|
|
116
135
|
PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
2
|
+
import { BlockList } from 'node:net';
|
|
3
|
+
import type { Duplex } from 'node:stream';
|
|
4
|
+
import type { TaEgressRefusal } from '@celljs/ta-protocol';
|
|
5
|
+
/** `egress` of sandboxes.json: true, or the private networks the sandboxes may reach too. */
|
|
6
|
+
export type EgressConfig = boolean | {
|
|
7
|
+
networks?: string[];
|
|
8
|
+
};
|
|
9
|
+
export interface EgressSettings {
|
|
10
|
+
enabled: boolean;
|
|
11
|
+
/** Private networks (CIDR) the sandboxes may reach too: never this machine, loopback or link-local. */
|
|
12
|
+
networks: string[];
|
|
13
|
+
}
|
|
14
|
+
export declare class EgressConfigError extends Error {
|
|
15
|
+
}
|
|
16
|
+
/** Where a sandbox wants to go. */
|
|
17
|
+
export interface EgressTarget {
|
|
18
|
+
host: string;
|
|
19
|
+
port: number;
|
|
20
|
+
}
|
|
21
|
+
/** Whom the credentials of a request are: their hosts (none: any public host), or why they are refused. */
|
|
22
|
+
export type EgressAuthorization = {
|
|
23
|
+
tenantId: string;
|
|
24
|
+
hosts?: string[];
|
|
25
|
+
} | {
|
|
26
|
+
status: 403 | 407;
|
|
27
|
+
message: string;
|
|
28
|
+
};
|
|
29
|
+
export interface EgressHooks {
|
|
30
|
+
authorize(user: string, password: string): EgressAuthorization;
|
|
31
|
+
}
|
|
32
|
+
export declare namespace EgressProxyUtil {
|
|
33
|
+
function settings(config: EgressConfig | undefined): EgressSettings;
|
|
34
|
+
/** `10.0.0.0/8`, `fd00::/8` or one address, as a list to check addresses against. */
|
|
35
|
+
function networksOf(networks: readonly string[]): BlockList;
|
|
36
|
+
/** The hosts an owner lets members reach, cleaned: lower-case, one each, at most 200. */
|
|
37
|
+
function hosts(value: unknown): string[];
|
|
38
|
+
/** The user and password of `Proxy-Authorization: Basic …`. */
|
|
39
|
+
function credentials(header: string | undefined): {
|
|
40
|
+
user: string;
|
|
41
|
+
password: string;
|
|
42
|
+
} | undefined;
|
|
43
|
+
/** `host:port` of CONNECT, `[::1]:443` too. */
|
|
44
|
+
function target(authority: string, fallbackPort: number): EgressTarget | undefined;
|
|
45
|
+
/** Why the policy refuses the target: not among its hosts, or a port of none of them; none: any public host, on 80 and 443. */
|
|
46
|
+
function refusal(hosts: readonly string[] | undefined, target: EgressTarget): 'host' | 'port' | undefined;
|
|
47
|
+
/** `::ffff:10.0.0.1` is 10.0.0.1. */
|
|
48
|
+
function plain(address: string): string;
|
|
49
|
+
/** Whether a sandbox may reach the address: a public one, or one of `networks`; never this machine. */
|
|
50
|
+
function reachable(address: string, networks: BlockList, own?: ReadonlySet<string>): boolean;
|
|
51
|
+
function ownAddresses(): Set<string>;
|
|
52
|
+
/**
|
|
53
|
+
* What a sandbox goes out with: the proxy of the gateway at `url`, by the credentials of its epoch, for the
|
|
54
|
+
* commands that read the variables of a proxy (curl, git, npm, pip, apt, and Node.js with NODE_USE_ENV_PROXY);
|
|
55
|
+
* the gateway itself, for its models, directly.
|
|
56
|
+
*/
|
|
57
|
+
function env(url: string, user: string, password: string): Record<string, string>;
|
|
58
|
+
function sameSecret(given: string, known: string): boolean;
|
|
59
|
+
function headers(given: IncomingHttpHeaders): Record<string, string | string[]>;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The way out of the sandboxes (docs/design/ta-cloud.md 3.5): an HTTP proxy on the port of the gateway, CONNECT
|
|
63
|
+
* for https and absolute URLs for http. A sandbox comes with the credentials of its tenant and epoch (those of
|
|
64
|
+
* a sandbox replaced since are refused); the gateway reaches only public addresses (and the private networks of
|
|
65
|
+
* the configuration), resolved once and checked, never this machine nor the metadata service; members only the
|
|
66
|
+
* hosts of the policy. It counts the bytes each tenant moved, and keeps the latest refusals for the console.
|
|
67
|
+
*/
|
|
68
|
+
export declare class EgressProxy {
|
|
69
|
+
readonly settings: EgressSettings;
|
|
70
|
+
protected readonly hooks: EgressHooks;
|
|
71
|
+
protected readonly networks: BlockList;
|
|
72
|
+
protected readonly pending: Map<string, number>;
|
|
73
|
+
protected readonly refusals: Map<string, TaEgressRefusal[]>;
|
|
74
|
+
constructor(settings: EgressSettings, hooks: EgressHooks);
|
|
75
|
+
get enabled(): boolean;
|
|
76
|
+
/** The bytes moved since the last time, by tenant. */
|
|
77
|
+
flush(): Map<string, number>;
|
|
78
|
+
/** The latest refusals of a tenant, newest first. */
|
|
79
|
+
refused(tenantId: string): TaEgressRefusal[];
|
|
80
|
+
/** CONNECT: a tunnel to the target, once its tenant may reach it. */
|
|
81
|
+
connect(request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
|
|
82
|
+
/** An absolute `http://` URL: the request forwarded, once its tenant may reach the host. */
|
|
83
|
+
request(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
84
|
+
protected authorize(request: IncomingMessage): EgressAuthorization;
|
|
85
|
+
/** The address to connect to, resolved once and checked (no rebinding between the check and the connection), or why not. */
|
|
86
|
+
protected resolve(who: {
|
|
87
|
+
tenantId: string;
|
|
88
|
+
hosts?: string[];
|
|
89
|
+
}, target: EgressTarget): Promise<string | {
|
|
90
|
+
status: number;
|
|
91
|
+
message: string;
|
|
92
|
+
}>;
|
|
93
|
+
protected reachable(address: string, own: ReadonlySet<string>): boolean;
|
|
94
|
+
protected refuse(tenantId: string, target: EgressTarget, reason: TaEgressRefusal['reason']): void;
|
|
95
|
+
protected count(tenantId: string, bytes: number): void;
|
|
96
|
+
protected reply(socket: Duplex, status: number, message: string): void;
|
|
97
|
+
protected end(response: ServerResponse, status: number, message: string): void;
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=egress-proxy.d.ts.map
|
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EgressProxy = exports.EgressProxyUtil = exports.EgressConfigError = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const promises_1 = require("node:dns/promises");
|
|
6
|
+
const node_http_1 = require("node:http");
|
|
7
|
+
const node_net_1 = require("node:net");
|
|
8
|
+
const node_os_1 = require("node:os");
|
|
9
|
+
const node_stream_1 = require("node:stream");
|
|
10
|
+
class EgressConfigError extends Error {
|
|
11
|
+
}
|
|
12
|
+
exports.EgressConfigError = EgressConfigError;
|
|
13
|
+
const PORTS = new Set([80, 443]);
|
|
14
|
+
/** Of a tenant, the refusals kept to show. */
|
|
15
|
+
const REFUSALS = 10;
|
|
16
|
+
const CONNECT_TIMEOUT_MS = 15000;
|
|
17
|
+
const HOP_BY_HOP = new Set([
|
|
18
|
+
'connection',
|
|
19
|
+
'keep-alive',
|
|
20
|
+
'proxy-authenticate',
|
|
21
|
+
'proxy-authorization',
|
|
22
|
+
'proxy-connection',
|
|
23
|
+
'te',
|
|
24
|
+
'trailer',
|
|
25
|
+
'transfer-encoding',
|
|
26
|
+
'upgrade',
|
|
27
|
+
]);
|
|
28
|
+
const PATTERN = /^(\*|(\*\.)?[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)*)(:(\d{1,5}|\*))?$/;
|
|
29
|
+
/** Never reached through the gateway: this machine, link-local (the metadata service), multicast, reserved. */
|
|
30
|
+
const NEVER = new node_net_1.BlockList();
|
|
31
|
+
for (const [network, prefix] of [
|
|
32
|
+
['0.0.0.0', 8],
|
|
33
|
+
['127.0.0.0', 8],
|
|
34
|
+
['169.254.0.0', 16],
|
|
35
|
+
['224.0.0.0', 4],
|
|
36
|
+
['240.0.0.0', 4],
|
|
37
|
+
]) {
|
|
38
|
+
NEVER.addSubnet(network, prefix, 'ipv4');
|
|
39
|
+
}
|
|
40
|
+
for (const [network, prefix] of [
|
|
41
|
+
['::', 128],
|
|
42
|
+
['::1', 128],
|
|
43
|
+
['fe80::', 10],
|
|
44
|
+
['ff00::', 8],
|
|
45
|
+
]) {
|
|
46
|
+
NEVER.addSubnet(network, prefix, 'ipv6');
|
|
47
|
+
}
|
|
48
|
+
/** Private networks, where the machine's neighbours and the other sandboxes are: only those of the configuration. */
|
|
49
|
+
const PRIVATE = new node_net_1.BlockList();
|
|
50
|
+
for (const [network, prefix] of [
|
|
51
|
+
['10.0.0.0', 8],
|
|
52
|
+
['172.16.0.0', 12],
|
|
53
|
+
['192.168.0.0', 16],
|
|
54
|
+
['100.64.0.0', 10],
|
|
55
|
+
['198.18.0.0', 15],
|
|
56
|
+
]) {
|
|
57
|
+
PRIVATE.addSubnet(network, prefix, 'ipv4');
|
|
58
|
+
}
|
|
59
|
+
for (const [network, prefix] of [
|
|
60
|
+
['fc00::', 7],
|
|
61
|
+
['64:ff9b::', 96],
|
|
62
|
+
]) {
|
|
63
|
+
PRIVATE.addSubnet(network, prefix, 'ipv6');
|
|
64
|
+
}
|
|
65
|
+
var EgressProxyUtil;
|
|
66
|
+
(function (EgressProxyUtil) {
|
|
67
|
+
function settings(config) {
|
|
68
|
+
var _a;
|
|
69
|
+
if (config === undefined || config === false) {
|
|
70
|
+
return { enabled: false, networks: [] };
|
|
71
|
+
}
|
|
72
|
+
if (config === true) {
|
|
73
|
+
return { enabled: true, networks: [] };
|
|
74
|
+
}
|
|
75
|
+
if (typeof config !== 'object' || config === null || (config.networks !== undefined && !Array.isArray(config.networks))) {
|
|
76
|
+
throw new EgressConfigError('"egress" of sandboxes.json is true, false or { "networks": ["10.0.0.0/8"] }.');
|
|
77
|
+
}
|
|
78
|
+
const networks = (_a = config.networks) !== null && _a !== void 0 ? _a : [];
|
|
79
|
+
networksOf(networks);
|
|
80
|
+
return { enabled: true, networks };
|
|
81
|
+
}
|
|
82
|
+
EgressProxyUtil.settings = settings;
|
|
83
|
+
/** `10.0.0.0/8`, `fd00::/8` or one address, as a list to check addresses against. */
|
|
84
|
+
function networksOf(networks) {
|
|
85
|
+
const list = new node_net_1.BlockList();
|
|
86
|
+
for (const network of networks) {
|
|
87
|
+
const [address, bits, ...rest] = String(network).trim().split('/');
|
|
88
|
+
const family = (0, node_net_1.isIP)(address);
|
|
89
|
+
const max = family === 6 ? 128 : 32;
|
|
90
|
+
const prefix = bits === undefined ? max : Number(bits);
|
|
91
|
+
if (!family || rest.length > 0 || !Number.isInteger(prefix) || prefix < 0 || prefix > max || (bits !== undefined && !/^\d+$/.test(bits))) {
|
|
92
|
+
throw new EgressConfigError(`"${network}" of egress.networks is no network: write it as 10.0.0.0/8, or one address.`);
|
|
93
|
+
}
|
|
94
|
+
list.addSubnet(address, prefix, family === 6 ? 'ipv6' : 'ipv4');
|
|
95
|
+
}
|
|
96
|
+
return list;
|
|
97
|
+
}
|
|
98
|
+
EgressProxyUtil.networksOf = networksOf;
|
|
99
|
+
/** The hosts an owner lets members reach, cleaned: lower-case, one each, at most 200. */
|
|
100
|
+
function hosts(value) {
|
|
101
|
+
var _a;
|
|
102
|
+
if (!Array.isArray(value) || value.length > 200) {
|
|
103
|
+
throw new EgressConfigError('The hosts are a list of at most 200.');
|
|
104
|
+
}
|
|
105
|
+
const hosts = new Set();
|
|
106
|
+
for (const item of value) {
|
|
107
|
+
const host = typeof item === 'string' ? item.trim().toLowerCase().replace(/\.$/, '') : '';
|
|
108
|
+
if (!host) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const port = (_a = /:(\d+)$/.exec(host)) === null || _a === void 0 ? void 0 : _a[1];
|
|
112
|
+
if (!PATTERN.test(host) || (port !== undefined && (Number(port) < 1 || Number(port) > 65535))) {
|
|
113
|
+
throw new EgressConfigError(`"${item}" is no host: write example.com, *.example.com or example.com:8443.`);
|
|
114
|
+
}
|
|
115
|
+
hosts.add(host);
|
|
116
|
+
}
|
|
117
|
+
return [...hosts];
|
|
118
|
+
}
|
|
119
|
+
EgressProxyUtil.hosts = hosts;
|
|
120
|
+
/** The user and password of `Proxy-Authorization: Basic …`. */
|
|
121
|
+
function credentials(header) {
|
|
122
|
+
var _a;
|
|
123
|
+
const match = /^Basic\s+(\S+)$/i.exec((_a = header === null || header === void 0 ? void 0 : header.trim()) !== null && _a !== void 0 ? _a : '');
|
|
124
|
+
if (!match) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const text = Buffer.from(match[1], 'base64').toString('utf8');
|
|
128
|
+
const colon = text.indexOf(':');
|
|
129
|
+
return colon < 0 ? undefined : { user: decodeURIComponent(text.slice(0, colon)), password: decodeURIComponent(text.slice(colon + 1)) };
|
|
130
|
+
}
|
|
131
|
+
EgressProxyUtil.credentials = credentials;
|
|
132
|
+
/** `host:port` of CONNECT, `[::1]:443` too. */
|
|
133
|
+
function target(authority, fallbackPort) {
|
|
134
|
+
var _a;
|
|
135
|
+
const match = /^(?:\[([0-9a-f:.]+)\]|([^\s:/[\]]+))(?::(\d{1,5}))?$/i.exec(authority.trim());
|
|
136
|
+
if (!match) {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
const port = match[3] === undefined ? fallbackPort : Number(match[3]);
|
|
140
|
+
if (port < 1 || port > 65535) {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
return { host: ((_a = match[1]) !== null && _a !== void 0 ? _a : match[2]).toLowerCase().replace(/\.$/, ''), port };
|
|
144
|
+
}
|
|
145
|
+
EgressProxyUtil.target = target;
|
|
146
|
+
/** Why the policy refuses the target: not among its hosts, or a port of none of them; none: any public host, on 80 and 443. */
|
|
147
|
+
function refusal(hosts, target) {
|
|
148
|
+
if (!hosts || hosts.length === 0) {
|
|
149
|
+
return PORTS.has(target.port) ? undefined : 'port';
|
|
150
|
+
}
|
|
151
|
+
let named = false;
|
|
152
|
+
for (const pattern of hosts) {
|
|
153
|
+
const colon = pattern.lastIndexOf(':');
|
|
154
|
+
const name = colon < 0 ? pattern : pattern.slice(0, colon);
|
|
155
|
+
const port = colon < 0 ? undefined : pattern.slice(colon + 1);
|
|
156
|
+
const matches = name === '*' || name === target.host || (name.startsWith('*.') && target.host.endsWith(name.slice(1)));
|
|
157
|
+
if (!matches) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
named = true;
|
|
161
|
+
if (port === '*' || (port === undefined ? PORTS.has(target.port) : Number(port) === target.port)) {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return named ? 'port' : 'host';
|
|
166
|
+
}
|
|
167
|
+
EgressProxyUtil.refusal = refusal;
|
|
168
|
+
/** `::ffff:10.0.0.1` is 10.0.0.1. */
|
|
169
|
+
function plain(address) {
|
|
170
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
|
|
171
|
+
return mapped ? mapped[1] : address;
|
|
172
|
+
}
|
|
173
|
+
EgressProxyUtil.plain = plain;
|
|
174
|
+
/** Whether a sandbox may reach the address: a public one, or one of `networks`; never this machine. */
|
|
175
|
+
function reachable(address, networks, own = ownAddresses()) {
|
|
176
|
+
const ip = plain(address);
|
|
177
|
+
const family = (0, node_net_1.isIP)(ip);
|
|
178
|
+
if (!family) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
const type = family === 6 ? 'ipv6' : 'ipv4';
|
|
182
|
+
if (own.has(ip) || NEVER.check(ip, type)) {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
return !PRIVATE.check(ip, type) || networks.check(ip, type);
|
|
186
|
+
}
|
|
187
|
+
EgressProxyUtil.reachable = reachable;
|
|
188
|
+
function ownAddresses() {
|
|
189
|
+
return new Set(Object.values((0, node_os_1.networkInterfaces)())
|
|
190
|
+
.flat()
|
|
191
|
+
.map(each => { var _a; return plain((_a = each === null || each === void 0 ? void 0 : each.address) !== null && _a !== void 0 ? _a : '').toLowerCase(); })
|
|
192
|
+
.filter(Boolean));
|
|
193
|
+
}
|
|
194
|
+
EgressProxyUtil.ownAddresses = ownAddresses;
|
|
195
|
+
/**
|
|
196
|
+
* What a sandbox goes out with: the proxy of the gateway at `url`, by the credentials of its epoch, for the
|
|
197
|
+
* commands that read the variables of a proxy (curl, git, npm, pip, apt, and Node.js with NODE_USE_ENV_PROXY);
|
|
198
|
+
* the gateway itself, for its models, directly.
|
|
199
|
+
*/
|
|
200
|
+
function env(url, user, password) {
|
|
201
|
+
const base = new URL(url);
|
|
202
|
+
// The port always written: curl takes 1080 for a proxy without one, where URL leaves out the default 80.
|
|
203
|
+
const port = base.port || (base.protocol === 'https:' ? '443' : '80');
|
|
204
|
+
const proxy = `${base.protocol}//${encodeURIComponent(user)}:${encodeURIComponent(password)}@${base.hostname}:${port}`;
|
|
205
|
+
const direct = ['localhost', '127.0.0.1', '::1', new URL(url).hostname].filter((each, index, all) => all.indexOf(each) === index).join(',');
|
|
206
|
+
return {
|
|
207
|
+
HTTP_PROXY: proxy,
|
|
208
|
+
HTTPS_PROXY: proxy,
|
|
209
|
+
http_proxy: proxy,
|
|
210
|
+
https_proxy: proxy,
|
|
211
|
+
NO_PROXY: direct,
|
|
212
|
+
no_proxy: direct,
|
|
213
|
+
NODE_USE_ENV_PROXY: '1',
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
EgressProxyUtil.env = env;
|
|
217
|
+
function sameSecret(given, known) {
|
|
218
|
+
const a = Buffer.from(given);
|
|
219
|
+
const b = Buffer.from(known);
|
|
220
|
+
return a.length === b.length && (0, node_crypto_1.timingSafeEqual)(a, b);
|
|
221
|
+
}
|
|
222
|
+
EgressProxyUtil.sameSecret = sameSecret;
|
|
223
|
+
function headers(given) {
|
|
224
|
+
const kept = {};
|
|
225
|
+
for (const [name, value] of Object.entries(given)) {
|
|
226
|
+
if (value !== undefined && !HOP_BY_HOP.has(name.toLowerCase())) {
|
|
227
|
+
kept[name] = value;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return kept;
|
|
231
|
+
}
|
|
232
|
+
EgressProxyUtil.headers = headers;
|
|
233
|
+
})(EgressProxyUtil || (exports.EgressProxyUtil = EgressProxyUtil = {}));
|
|
234
|
+
/**
|
|
235
|
+
* The way out of the sandboxes (docs/design/ta-cloud.md 3.5): an HTTP proxy on the port of the gateway, CONNECT
|
|
236
|
+
* for https and absolute URLs for http. A sandbox comes with the credentials of its tenant and epoch (those of
|
|
237
|
+
* a sandbox replaced since are refused); the gateway reaches only public addresses (and the private networks of
|
|
238
|
+
* the configuration), resolved once and checked, never this machine nor the metadata service; members only the
|
|
239
|
+
* hosts of the policy. It counts the bytes each tenant moved, and keeps the latest refusals for the console.
|
|
240
|
+
*/
|
|
241
|
+
class EgressProxy {
|
|
242
|
+
constructor(settings, hooks) {
|
|
243
|
+
this.settings = settings;
|
|
244
|
+
this.hooks = hooks;
|
|
245
|
+
this.pending = new Map();
|
|
246
|
+
this.refusals = new Map();
|
|
247
|
+
this.networks = EgressProxyUtil.networksOf(settings.networks);
|
|
248
|
+
}
|
|
249
|
+
get enabled() {
|
|
250
|
+
return this.settings.enabled;
|
|
251
|
+
}
|
|
252
|
+
/** The bytes moved since the last time, by tenant. */
|
|
253
|
+
flush() {
|
|
254
|
+
const moved = new Map(this.pending);
|
|
255
|
+
this.pending.clear();
|
|
256
|
+
return moved;
|
|
257
|
+
}
|
|
258
|
+
/** The latest refusals of a tenant, newest first. */
|
|
259
|
+
refused(tenantId) {
|
|
260
|
+
var _a;
|
|
261
|
+
return (_a = this.refusals.get(tenantId)) !== null && _a !== void 0 ? _a : [];
|
|
262
|
+
}
|
|
263
|
+
/** CONNECT: a tunnel to the target, once its tenant may reach it. */
|
|
264
|
+
async connect(request, socket, head) {
|
|
265
|
+
var _a;
|
|
266
|
+
socket.on('error', () => socket.destroy());
|
|
267
|
+
const who = this.authorize(request);
|
|
268
|
+
if ('status' in who) {
|
|
269
|
+
this.reply(socket, who.status, who.message);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const target = EgressProxyUtil.target((_a = request.url) !== null && _a !== void 0 ? _a : '', 443);
|
|
273
|
+
if (!target) {
|
|
274
|
+
this.reply(socket, 400, 'ta gateway: CONNECT takes host:port.');
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const address = await this.resolve(who, target);
|
|
278
|
+
if (typeof address !== 'string') {
|
|
279
|
+
this.reply(socket, address.status, address.message);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const upstream = (0, node_net_1.connect)({ host: address, port: target.port });
|
|
283
|
+
let open = false;
|
|
284
|
+
let moved = head.length;
|
|
285
|
+
upstream.setTimeout(CONNECT_TIMEOUT_MS, () => upstream.destroy(new Error('timed out')));
|
|
286
|
+
upstream.once('connect', () => {
|
|
287
|
+
open = true;
|
|
288
|
+
upstream.setTimeout(0);
|
|
289
|
+
socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
290
|
+
if (head.length > 0) {
|
|
291
|
+
upstream.write(head);
|
|
292
|
+
}
|
|
293
|
+
upstream.on('data', chunk => (moved += chunk.length));
|
|
294
|
+
socket.on('data', chunk => (moved += chunk.length));
|
|
295
|
+
upstream.pipe(socket);
|
|
296
|
+
socket.pipe(upstream);
|
|
297
|
+
});
|
|
298
|
+
upstream.once('error', error => {
|
|
299
|
+
if (!open) {
|
|
300
|
+
this.reply(socket, 502, `ta gateway: ${target.host}:${target.port} did not answer: ${error.message}`);
|
|
301
|
+
}
|
|
302
|
+
socket.destroy();
|
|
303
|
+
});
|
|
304
|
+
upstream.once('close', () => socket.destroy());
|
|
305
|
+
socket.once('close', () => {
|
|
306
|
+
upstream.destroy();
|
|
307
|
+
this.count(who.tenantId, moved);
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/** An absolute `http://` URL: the request forwarded, once its tenant may reach the host. */
|
|
311
|
+
async request(request, response) {
|
|
312
|
+
var _a;
|
|
313
|
+
const who = this.authorize(request);
|
|
314
|
+
if ('status' in who) {
|
|
315
|
+
this.end(response, who.status, who.message);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
let url;
|
|
319
|
+
try {
|
|
320
|
+
url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '');
|
|
321
|
+
}
|
|
322
|
+
catch (_b) {
|
|
323
|
+
this.end(response, 400, 'ta gateway: not a URL.');
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const target = url.protocol === 'http:' ? EgressProxyUtil.target(url.host, 80) : undefined;
|
|
327
|
+
if (!target) {
|
|
328
|
+
this.end(response, 400, 'ta gateway: only http:// is forwarded this way; https goes by CONNECT.');
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
const address = await this.resolve(who, target);
|
|
332
|
+
if (typeof address !== 'string') {
|
|
333
|
+
this.end(response, address.status, address.message);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
let moved = 0;
|
|
337
|
+
await new Promise(resolve => {
|
|
338
|
+
const outgoing = (0, node_http_1.request)({
|
|
339
|
+
host: address,
|
|
340
|
+
port: target.port,
|
|
341
|
+
method: request.method,
|
|
342
|
+
path: `${url.pathname}${url.search}`,
|
|
343
|
+
headers: { ...EgressProxyUtil.headers(request.headers), host: url.host },
|
|
344
|
+
setHost: false,
|
|
345
|
+
}, incoming => {
|
|
346
|
+
var _a;
|
|
347
|
+
response.writeHead((_a = incoming.statusCode) !== null && _a !== void 0 ? _a : 502, EgressProxyUtil.headers(incoming.headers));
|
|
348
|
+
incoming.on('data', chunk => (moved += chunk.length));
|
|
349
|
+
(0, node_stream_1.pipeline)(incoming, response, () => resolve());
|
|
350
|
+
});
|
|
351
|
+
outgoing.setTimeout(CONNECT_TIMEOUT_MS * 4, () => outgoing.destroy(new Error('timed out')));
|
|
352
|
+
outgoing.once('error', error => {
|
|
353
|
+
if (!response.headersSent) {
|
|
354
|
+
this.end(response, 502, `ta gateway: ${target.host} did not answer: ${error.message}`);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
response.destroy();
|
|
358
|
+
}
|
|
359
|
+
resolve();
|
|
360
|
+
});
|
|
361
|
+
request.on('data', chunk => (moved += chunk.length));
|
|
362
|
+
request.pipe(outgoing);
|
|
363
|
+
});
|
|
364
|
+
this.count(who.tenantId, moved);
|
|
365
|
+
}
|
|
366
|
+
authorize(request) {
|
|
367
|
+
if (!this.enabled) {
|
|
368
|
+
return { status: 403, message: 'ta gateway: this gateway is no proxy ("egress" of sandboxes.json is off).' };
|
|
369
|
+
}
|
|
370
|
+
const credentials = EgressProxyUtil.credentials(request.headers['proxy-authorization']);
|
|
371
|
+
return credentials
|
|
372
|
+
? this.hooks.authorize(credentials.user, credentials.password)
|
|
373
|
+
: { status: 407, message: 'ta gateway: a sandbox of the gateway goes out with the credentials of HTTPS_PROXY.' };
|
|
374
|
+
}
|
|
375
|
+
/** The address to connect to, resolved once and checked (no rebinding between the check and the connection), or why not. */
|
|
376
|
+
async resolve(who, target) {
|
|
377
|
+
const refusal = EgressProxyUtil.refusal(who.hosts, target);
|
|
378
|
+
if (refusal) {
|
|
379
|
+
this.refuse(who.tenantId, target, refusal);
|
|
380
|
+
return {
|
|
381
|
+
status: 403,
|
|
382
|
+
message: refusal === 'host'
|
|
383
|
+
? `ta gateway: ${target.host} is not among the hosts the gateway lets sandboxes reach; an administrator adds it in the console (Policy).`
|
|
384
|
+
: `ta gateway: port ${target.port} of ${target.host} is not let out: 80 and 443 only, unless the policy names it (${target.host}:${target.port}).`,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
let addresses;
|
|
388
|
+
try {
|
|
389
|
+
addresses = (0, node_net_1.isIP)(target.host) ? [target.host] : (await (0, promises_1.lookup)(target.host, { all: true, verbatim: true })).map(each => each.address);
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
return { status: 502, message: `ta gateway: cannot resolve ${target.host}: ${error.message}` };
|
|
393
|
+
}
|
|
394
|
+
const own = EgressProxyUtil.ownAddresses();
|
|
395
|
+
const address = addresses.find(each => this.reachable(each, own));
|
|
396
|
+
if (!address) {
|
|
397
|
+
this.refuse(who.tenantId, target, 'network');
|
|
398
|
+
return { status: 403, message: `ta gateway: ${target.host} is in a private network or on this machine, which sandboxes do not reach.` };
|
|
399
|
+
}
|
|
400
|
+
return EgressProxyUtil.plain(address);
|
|
401
|
+
}
|
|
402
|
+
reachable(address, own) {
|
|
403
|
+
return EgressProxyUtil.reachable(address, this.networks, own);
|
|
404
|
+
}
|
|
405
|
+
refuse(tenantId, target, reason) {
|
|
406
|
+
var _a, _b;
|
|
407
|
+
const host = PORTS.has(target.port) ? target.host : `${target.host}:${target.port}`;
|
|
408
|
+
const list = (_a = this.refusals.get(tenantId)) !== null && _a !== void 0 ? _a : [];
|
|
409
|
+
const known = list.find(each => each.host === host && each.reason === reason);
|
|
410
|
+
const entry = { host, reason, at: Date.now(), count: ((_b = known === null || known === void 0 ? void 0 : known.count) !== null && _b !== void 0 ? _b : 0) + 1 };
|
|
411
|
+
this.refusals.set(tenantId, [entry, ...list.filter(each => each !== known)].slice(0, REFUSALS));
|
|
412
|
+
}
|
|
413
|
+
count(tenantId, bytes) {
|
|
414
|
+
var _a;
|
|
415
|
+
if (bytes > 0) {
|
|
416
|
+
this.pending.set(tenantId, ((_a = this.pending.get(tenantId)) !== null && _a !== void 0 ? _a : 0) + bytes);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
reply(socket, status, message) {
|
|
420
|
+
const body = Buffer.from(`${message}\n`);
|
|
421
|
+
const challenge = status === 407 ? 'Proxy-Authenticate: Basic realm="ta gateway"\r\n' : '';
|
|
422
|
+
socket.end(`HTTP/1.1 ${status} ${node_http_1.STATUS_CODES[status]}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${body.length}\r\nConnection: close\r\n${challenge}\r\n${body}`);
|
|
423
|
+
}
|
|
424
|
+
end(response, status, message) {
|
|
425
|
+
response.writeHead(status, {
|
|
426
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
427
|
+
...(status === 407 ? { 'Proxy-Authenticate': 'Basic realm="ta gateway"' } : {}),
|
|
428
|
+
});
|
|
429
|
+
response.end(`${message}\n`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
exports.EgressProxy = EgressProxy;
|
|
433
|
+
//# sourceMappingURL=egress-proxy.js.map
|
|
@@ -48,8 +48,11 @@ export declare class Environments {
|
|
|
48
48
|
protected readonly running: Map<string, Running>;
|
|
49
49
|
/** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
|
|
50
50
|
guard?: (tenant: Tenant) => string | undefined;
|
|
51
|
-
/**
|
|
52
|
-
|
|
51
|
+
/**
|
|
52
|
+
* More of the environment of a sandbox the gateway starts: what reaches the models of the gateway and its way
|
|
53
|
+
* out. `fresh`: the provider has no sandbox of the tenant, and makes one now.
|
|
54
|
+
*/
|
|
55
|
+
envOf?: (tenant: Tenant, provider: SandboxProvider, fresh: boolean) => Record<string, string> | undefined;
|
|
53
56
|
constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
|
|
54
57
|
default?: string;
|
|
55
58
|
own: boolean;
|
package/lib/node/environments.js
CHANGED
|
@@ -314,8 +314,10 @@ class Environments {
|
|
|
314
314
|
var _a;
|
|
315
315
|
var _b;
|
|
316
316
|
const { provider, own } = this.provider(tenant);
|
|
317
|
-
const
|
|
318
|
-
const
|
|
317
|
+
const sandbox = EnvironmentsUtil.sandboxTenant(tenant);
|
|
318
|
+
const fresh = !own && this.envOf ? (await provider.state(sandbox).catch(() => 'missing')) === 'missing' : false;
|
|
319
|
+
const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider, fresh);
|
|
320
|
+
const endpoint = await provider.start({ ...sandbox, ...(env ? { env } : {}) });
|
|
319
321
|
await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
|
|
320
322
|
return endpoint;
|
|
321
323
|
})();
|