@celljs/ta-gateway 4.15.2 → 4.17.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.
Files changed (81) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/command-sandbox.d.ts +1 -0
  4. package/esm/node/command-sandbox.js +10 -1
  5. package/esm/node/docker-engine.d.ts +10 -1
  6. package/esm/node/docker-engine.js +18 -1
  7. package/esm/node/docker-sandbox.d.ts +13 -1
  8. package/esm/node/docker-sandbox.js +35 -2
  9. package/esm/node/egress-proxy.d.ts +98 -0
  10. package/esm/node/egress-proxy.js +428 -0
  11. package/esm/node/environments.d.ts +5 -0
  12. package/esm/node/environments.js +7 -3
  13. package/esm/node/gateway-cli.js +12 -5
  14. package/esm/node/gateway-exec.d.ts +19 -0
  15. package/esm/node/gateway-exec.js +65 -0
  16. package/esm/node/gateway-policy.d.ts +7 -1
  17. package/esm/node/gateway-policy.js +12 -2
  18. package/esm/node/gateway-quotas.d.ts +15 -2
  19. package/esm/node/gateway-quotas.js +51 -3
  20. package/esm/node/gateway-server.d.ts +43 -1
  21. package/esm/node/gateway-server.js +179 -10
  22. package/esm/node/gateway-service-util.d.ts +41 -0
  23. package/esm/node/gateway-service-util.js +178 -0
  24. package/esm/node/gateway-service.d.ts +13 -41
  25. package/esm/node/gateway-service.js +41 -176
  26. package/esm/node/gateway-socket.d.ts +1 -1
  27. package/esm/node/gateway-socket.js +1 -1
  28. package/esm/node/index.d.ts +4 -0
  29. package/esm/node/index.js +4 -0
  30. package/esm/node/kubernetes-api.d.ts +35 -0
  31. package/esm/node/kubernetes-api.js +115 -0
  32. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  33. package/esm/node/kubernetes-sandbox.js +279 -0
  34. package/esm/node/local-sandbox.d.ts +1 -0
  35. package/esm/node/local-sandbox.js +2 -1
  36. package/esm/node/model-proxy.d.ts +105 -0
  37. package/esm/node/model-proxy.js +435 -0
  38. package/esm/node/sandbox-provider.d.ts +17 -0
  39. package/esm/node/sandbox-provider.js +2 -1
  40. package/esm/node/tenant-store.d.ts +22 -0
  41. package/esm/node/tenant-store.js +25 -0
  42. package/lib/node/command-sandbox.d.ts +1 -0
  43. package/lib/node/command-sandbox.js +10 -1
  44. package/lib/node/docker-engine.d.ts +10 -1
  45. package/lib/node/docker-engine.js +18 -1
  46. package/lib/node/docker-sandbox.d.ts +13 -1
  47. package/lib/node/docker-sandbox.js +35 -2
  48. package/lib/node/egress-proxy.d.ts +99 -0
  49. package/lib/node/egress-proxy.js +433 -0
  50. package/lib/node/environments.d.ts +5 -0
  51. package/lib/node/environments.js +7 -3
  52. package/lib/node/gateway-cli.js +12 -5
  53. package/lib/node/gateway-exec.d.ts +20 -0
  54. package/lib/node/gateway-exec.js +69 -0
  55. package/lib/node/gateway-policy.d.ts +7 -1
  56. package/lib/node/gateway-policy.js +12 -2
  57. package/lib/node/gateway-quotas.d.ts +15 -2
  58. package/lib/node/gateway-quotas.js +51 -3
  59. package/lib/node/gateway-server.d.ts +43 -1
  60. package/lib/node/gateway-server.js +177 -8
  61. package/lib/node/gateway-service-util.d.ts +42 -0
  62. package/lib/node/gateway-service-util.js +182 -0
  63. package/lib/node/gateway-service.d.ts +13 -41
  64. package/lib/node/gateway-service.js +63 -199
  65. package/lib/node/gateway-socket.d.ts +1 -1
  66. package/lib/node/gateway-socket.js +10 -10
  67. package/lib/node/index.d.ts +4 -0
  68. package/lib/node/index.js +4 -0
  69. package/lib/node/kubernetes-api.d.ts +36 -0
  70. package/lib/node/kubernetes-api.js +120 -0
  71. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  72. package/lib/node/kubernetes-sandbox.js +283 -0
  73. package/lib/node/local-sandbox.d.ts +1 -0
  74. package/lib/node/local-sandbox.js +2 -1
  75. package/lib/node/model-proxy.d.ts +106 -0
  76. package/lib/node/model-proxy.js +440 -0
  77. package/lib/node/sandbox-provider.d.ts +17 -0
  78. package/lib/node/sandbox-provider.js +2 -1
  79. package/lib/node/tenant-store.d.ts +22 -0
  80. package/lib/node/tenant-store.js +25 -0
  81. package/package.json +4 -4
@@ -15,6 +15,7 @@ export declare class CommandSandbox implements SandboxProvider {
15
15
  readonly id: string;
16
16
  readonly type = "command";
17
17
  readonly name: string;
18
+ readonly gatewayUrl?: string;
18
19
  protected readonly commands: {
19
20
  start: string;
20
21
  stop?: string;
@@ -30,6 +30,7 @@ class CommandSandbox {
30
30
  this.id = id;
31
31
  this.type = 'command';
32
32
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', id);
33
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
33
34
  const start = sandbox_provider_1.SandboxProviders.string(config, 'start');
34
35
  if (!start) {
35
36
  throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
@@ -72,7 +73,15 @@ class CommandSandbox {
72
73
  run(command, tenant, extra = {}) {
73
74
  return new Promise((resolve, reject) => {
74
75
  const child = (0, node_child_process_1.spawn)('sh', ['-c', command], {
75
- env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token, ...extra },
76
+ env: {
77
+ ...process.env,
78
+ ...this.env,
79
+ ...tenant.env,
80
+ TA_TENANT_ID: tenant.id,
81
+ TA_TENANT_ACCOUNT: tenant.account,
82
+ TA_SERVE_TOKEN: tenant.token,
83
+ ...extra,
84
+ },
76
85
  stdio: ['ignore', 'pipe', 'pipe'],
77
86
  });
78
87
  let stdout = '';
@@ -43,13 +43,22 @@ export declare class DockerEngine {
43
43
  } | undefined>;
44
44
  /** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
45
45
  logs(name: string, lines: number): Promise<string>;
46
- /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
46
+ /** Removed, its volumes kept; nothing when it is not there. */
47
+ remove(name: string): Promise<void>;
48
+ /**
49
+ * A bridge network, made when missing; `isolated`: its containers cannot reach each other. Its interface on the
50
+ * host has its name (when it fits one), for the firewall to name it (deploy/compose/isolate.sh: `-i ta-sandbox`).
51
+ */
47
52
  ensureNetwork(name: string, isolated: boolean): Promise<void>;
48
53
  /** Pulled when it is not here; one built here (ta:latest) is. */
49
54
  ensureImage(image: string): Promise<void>;
50
55
  }
51
56
  export interface DockerContainer {
52
57
  Id: string;
58
+ Config?: {
59
+ Env?: string[];
60
+ Labels?: Record<string, string>;
61
+ };
53
62
  State: {
54
63
  Running: boolean;
55
64
  Status: string;
@@ -136,7 +136,21 @@ class DockerEngine {
136
136
  throw error;
137
137
  }
138
138
  }
139
- /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
139
+ /** Removed, its volumes kept; nothing when it is not there. */
140
+ async remove(name) {
141
+ try {
142
+ await this.call('DELETE', `/containers/${encodeURIComponent(name)}?force=true`);
143
+ }
144
+ catch (error) {
145
+ if (!(error instanceof DockerError && error.status === 404)) {
146
+ throw error;
147
+ }
148
+ }
149
+ }
150
+ /**
151
+ * A bridge network, made when missing; `isolated`: its containers cannot reach each other. Its interface on the
152
+ * host has its name (when it fits one), for the firewall to name it (deploy/compose/isolate.sh: `-i ta-sandbox`).
153
+ */
140
154
  async ensureNetwork(name, isolated) {
141
155
  try {
142
156
  await this.call('GET', `/networks/${encodeURIComponent(name)}`);
@@ -148,6 +162,9 @@ class DockerEngine {
148
162
  }
149
163
  }
150
164
  const options = isolated ? { 'com.docker.network.bridge.enable_icc': 'false' } : {};
165
+ if (/^[a-zA-Z0-9_.-]{1,15}$/.test(name)) {
166
+ options['com.docker.network.bridge.name'] = name;
167
+ }
151
168
  await this.call('POST', '/networks/create', { Name: name, Driver: 'bridge', Options: options, Labels: { 'cell.ta.gateway': '1' } });
152
169
  }
153
170
  /** Pulled when it is not here; one built here (ta:latest) is. */
@@ -1,6 +1,17 @@
1
- import { DockerEngine } from './docker-engine';
1
+ import { type DockerContainer, DockerEngine } from './docker-engine';
2
2
  import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
3
3
  export declare namespace DockerSandboxUtil {
4
+ /** The label of a container that tells the environment the gateway gave it. */
5
+ const ENV_LABEL = "cell.ta.env";
6
+ /** Of the environment the gateway gives a sandbox, whatever its order. */
7
+ function envHash(env: Record<string, string> | undefined): string;
8
+ /**
9
+ * Whether a container was made with the environment the gateway gives it now: by its label, so that a variable
10
+ * taken away (the way out turned off) counts too; one made before the label, by its variables.
11
+ */
12
+ function sameEnv(config: DockerContainer['Config'], want: Record<string, string> | undefined): boolean;
13
+ /** Whether a container has each variable of `env` as it is. */
14
+ function hasEnv(have: string[] | undefined, want: Record<string, string> | undefined): boolean;
4
15
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
5
16
  function hostname(account: string): string;
6
17
  }
@@ -33,6 +44,7 @@ export declare class DockerSandbox implements SandboxProvider {
33
44
  protected readonly options: DockerSandboxOptions;
34
45
  readonly type = "docker";
35
46
  readonly name: string;
47
+ readonly gatewayUrl?: string;
36
48
  protected readonly engine: DockerEngine;
37
49
  static options(config: SandboxProviderConfig): DockerSandboxOptions;
38
50
  constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
@@ -1,10 +1,35 @@
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;
27
+ /** Whether a container has each variable of `env` as it is. */
28
+ function hasEnv(have, want) {
29
+ const set = new Set(have !== null && have !== void 0 ? have : []);
30
+ return Object.entries(want !== null && want !== void 0 ? want : {}).every(([key, value]) => set.has(`${key}=${value}`));
31
+ }
32
+ DockerSandboxUtil.hasEnv = hasEnv;
8
33
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
9
34
  function hostname(account) {
10
35
  const name = account
@@ -55,12 +80,18 @@ class DockerSandbox {
55
80
  this.options = options;
56
81
  this.type = 'docker';
57
82
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Docker');
83
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
58
84
  this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
59
85
  }
60
86
  async start(tenant) {
61
87
  var _a, _b, _c;
62
88
  const name = this.containerName(tenant);
63
89
  let container = await this.engine.inspect(name);
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.
92
+ await this.engine.remove(name);
93
+ container = undefined;
94
+ }
64
95
  if (!container) {
65
96
  await this.engine.ensureImage(this.options.image);
66
97
  await this.engine.ensureNetwork(this.options.network, true);
@@ -97,11 +128,13 @@ class DockerSandbox {
97
128
  Image: this.options.image,
98
129
  // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
99
130
  Hostname: DockerSandboxUtil.hostname(tenant.account),
100
- Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
101
- Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
131
+ Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
132
+ Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account, [DockerSandboxUtil.ENV_LABEL]: DockerSandboxUtil.envHash(tenant.env) },
102
133
  ExposedPorts: { [PORT]: {} },
103
134
  HostConfig: {
104
135
  PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
136
+ // The gateway, for the models it gives (TA_MODEL_PROXY_URL): the host, on Linux too.
137
+ ExtraHosts: ['host.docker.internal:host-gateway'],
105
138
  Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
106
139
  NetworkMode: this.options.network,
107
140
  Memory: this.options.memory,
@@ -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