@highstate/k8s 0.9.13 → 0.9.15

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 (55) hide show
  1. package/dist/{chunk-QLQ3QVGT.js → chunk-KBWGED2C.js} +15 -10
  2. package/dist/chunk-KBWGED2C.js.map +1 -0
  3. package/dist/{chunk-5S4JPM4M.js → chunk-MKFBWTVZ.js} +36 -4
  4. package/dist/chunk-MKFBWTVZ.js.map +1 -0
  5. package/dist/chunk-P2UABKGA.js +1664 -0
  6. package/dist/chunk-P2UABKGA.js.map +1 -0
  7. package/dist/chunk-PZ5AY32C.js +10 -0
  8. package/dist/{chunk-VL7Z5FJQ.js → chunk-QMWFPJQB.js} +23 -3
  9. package/dist/chunk-QMWFPJQB.js.map +1 -0
  10. package/dist/{chunk-6L67WIZW.js → chunk-YRC7EI6X.js} +23 -3
  11. package/dist/chunk-YRC7EI6X.js.map +1 -0
  12. package/dist/{chunk-Y3LZSX7I.js → chunk-YUMBUWA4.js} +23 -1
  13. package/dist/chunk-YUMBUWA4.js.map +1 -0
  14. package/dist/deployment-KOZNZXJA.js +10 -0
  15. package/dist/highstate.manifest.json +8 -8
  16. package/dist/index.js +17 -18
  17. package/dist/index.js.map +1 -1
  18. package/dist/stateful-set-H5BR3H5D.js +10 -0
  19. package/dist/stateful-set-H5BR3H5D.js.map +1 -0
  20. package/dist/units/access-point/index.js +2 -0
  21. package/dist/units/access-point/index.js.map +1 -1
  22. package/dist/units/cert-manager/index.js +6 -3
  23. package/dist/units/cert-manager/index.js.map +1 -1
  24. package/dist/units/cluster-dns/index.js +2 -0
  25. package/dist/units/cluster-dns/index.js.map +1 -1
  26. package/dist/units/cluster-patch/index.js +2 -0
  27. package/dist/units/cluster-patch/index.js.map +1 -1
  28. package/dist/units/dns01-issuer/index.js +2 -1
  29. package/dist/units/dns01-issuer/index.js.map +1 -1
  30. package/dist/units/existing-cluster/index.js +3 -1
  31. package/dist/units/existing-cluster/index.js.map +1 -1
  32. package/dist/units/gateway-api/index.js +2 -1
  33. package/dist/units/gateway-api/index.js.map +1 -1
  34. package/package.json +10 -9
  35. package/src/cluster.ts +14 -9
  36. package/src/deployment.ts +34 -0
  37. package/src/helm.ts +38 -2
  38. package/src/network-policy.ts +2 -5
  39. package/src/shared.ts +3 -0
  40. package/src/stateful-set.ts +34 -0
  41. package/src/workload.ts +22 -3
  42. package/dist/chunk-5S4JPM4M.js.map +0 -1
  43. package/dist/chunk-6L67WIZW.js.map +0 -1
  44. package/dist/chunk-QLQ3QVGT.js.map +0 -1
  45. package/dist/chunk-SARVLQZY.js +0 -876
  46. package/dist/chunk-SARVLQZY.js.map +0 -1
  47. package/dist/chunk-VL7Z5FJQ.js.map +0 -1
  48. package/dist/chunk-WEKIQRCZ.js +0 -792
  49. package/dist/chunk-WEKIQRCZ.js.map +0 -1
  50. package/dist/chunk-Y3LZSX7I.js.map +0 -1
  51. package/dist/deployment-QTPBNKO5.js +0 -10
  52. package/dist/stateful-set-K4GV7ZTK.js +0 -10
  53. package/src/custom.ts +0 -104
  54. /package/dist/{deployment-QTPBNKO5.js.map → chunk-PZ5AY32C.js.map} +0 -0
  55. /package/dist/{stateful-set-K4GV7ZTK.js.map → deployment-KOZNZXJA.js.map} +0 -0
@@ -1,792 +0,0 @@
1
- import {
2
- commonExtraArgs,
3
- getProvider,
4
- mapMetadata,
5
- mapNamespaceLikeToNamespaceName,
6
- mapNamespaceNameToSelector,
7
- mapSelectorLikeToSelector,
8
- resourceIdToString
9
- } from "./chunk-Y3LZSX7I.js";
10
-
11
- // src/service.ts
12
- import { core } from "@pulumi/kubernetes";
13
- import {
14
- ComponentResource,
15
- normalize,
16
- output
17
- } from "@highstate/pulumi";
18
- import { omit, uniqueBy } from "remeda";
19
- import { deepmerge } from "deepmerge-ts";
20
- import { filterEndpoints, l4EndpointToString, parseL3Endpoint } from "@highstate/common";
21
- var serviceExtraArgs = [...commonExtraArgs, "port", "ports", "external"];
22
- function hasServiceMetadata(endpoint) {
23
- return endpoint.metadata?.k8sService !== void 0;
24
- }
25
- function getServiceMetadata(endpoint) {
26
- return endpoint.metadata?.k8sService;
27
- }
28
- function withServiceMetadata(endpoint, metadata) {
29
- return {
30
- ...endpoint,
31
- metadata: {
32
- ...endpoint.metadata,
33
- k8sService: metadata
34
- }
35
- };
36
- }
37
- function isFromCluster(endpoint, cluster) {
38
- return getServiceMetadata(endpoint)?.clusterId === cluster.id;
39
- }
40
- var Service = class extends ComponentResource {
41
- constructor(type, name, args, opts, cluster, metadata, spec, status) {
42
- super(type, name, args, opts);
43
- this.cluster = cluster;
44
- this.metadata = metadata;
45
- this.spec = spec;
46
- this.status = status;
47
- }
48
- /**
49
- * The Highstate service entity.
50
- */
51
- get entity() {
52
- return output({
53
- type: "k8s.service",
54
- clusterId: this.cluster.id,
55
- metadata: this.metadata,
56
- endpoints: this.endpoints
57
- });
58
- }
59
- static create(name, args, opts) {
60
- return new CreatedService(name, args, opts);
61
- }
62
- static wrap(name, service, cluster, opts) {
63
- return new WrappedService(name, service, cluster, opts);
64
- }
65
- static get(name, id, cluster, opts) {
66
- return new ExternalService(name, id, cluster, opts);
67
- }
68
- static of(name, entity, cluster, opts) {
69
- return new ExternalService(
70
- name,
71
- output(entity).metadata,
72
- output({ cluster, entity }).apply(({ cluster: cluster2, entity: entity2 }) => {
73
- if (cluster2.id !== entity2.clusterId) {
74
- throw new Error(
75
- `Cluster mismatch when wrapping service "${name}": "${cluster2.id}" != "${entity2.clusterId}"`
76
- );
77
- }
78
- return cluster2;
79
- }),
80
- opts
81
- );
82
- }
83
- /**
84
- * Returns the endpoints of the service applying the given filter.
85
- *
86
- * If no filter is specified, the default behavior of `filterEndpoints` is used.
87
- *
88
- * @param filter If specified, the endpoints are filtered based on the given filter.
89
- * @returns The endpoints of the service.
90
- */
91
- filterEndpoints(filter) {
92
- return output({ endpoints: this.endpoints }).apply(({ endpoints }) => {
93
- return filterEndpoints(endpoints, filter);
94
- });
95
- }
96
- /**
97
- * Returns the endpoints of the service including both internal and external endpoints.
98
- */
99
- get endpoints() {
100
- return output({
101
- cluster: this.cluster,
102
- metadata: this.metadata,
103
- spec: this.spec,
104
- status: this.status
105
- }).apply(({ cluster, metadata, spec, status }) => {
106
- const endpointMetadata = {
107
- k8sService: {
108
- clusterId: cluster.id,
109
- name: metadata.name,
110
- namespace: metadata.namespace,
111
- selector: spec.selector,
112
- targetPort: spec.ports[0].targetPort ?? spec.ports[0].port
113
- }
114
- };
115
- const clusterIpEndpoints = spec.clusterIPs?.map((ip) => ({
116
- ...parseL3Endpoint(ip),
117
- visibility: "internal",
118
- port: spec.ports[0].port,
119
- protocol: spec.ports[0].protocol?.toLowerCase(),
120
- metadata: endpointMetadata
121
- }));
122
- if (clusterIpEndpoints.length > 0) {
123
- clusterIpEndpoints.unshift({
124
- type: "hostname",
125
- visibility: "internal",
126
- hostname: `${metadata.name}.${metadata.namespace}.svc.cluster.local`,
127
- port: spec.ports[0].port,
128
- protocol: spec.ports[0].protocol?.toLowerCase(),
129
- metadata: endpointMetadata
130
- });
131
- }
132
- const nodePortEndpoints = spec.type === "NodePort" ? cluster.endpoints.map((endpoint) => ({
133
- ...endpoint,
134
- port: spec.ports[0].nodePort,
135
- protocol: spec.ports[0].protocol?.toLowerCase(),
136
- metadata: endpointMetadata
137
- })) : [];
138
- const loadBalancerEndpoints = spec.type === "LoadBalancer" ? status.loadBalancer?.ingress?.map((endpoint) => ({
139
- ...parseL3Endpoint(endpoint.ip ?? endpoint.hostname),
140
- port: spec.ports[0].port,
141
- protocol: spec.ports[0].protocol?.toLowerCase(),
142
- metadata: endpointMetadata
143
- })) : [];
144
- return uniqueBy(
145
- [
146
- ...clusterIpEndpoints ?? [],
147
- ...loadBalancerEndpoints ?? [],
148
- ...nodePortEndpoints ?? []
149
- ],
150
- (endpoint) => l4EndpointToString(endpoint)
151
- );
152
- });
153
- }
154
- };
155
- var CreatedService = class extends Service {
156
- constructor(name, args, opts) {
157
- const service = output(args).apply((args2) => {
158
- return new core.v1.Service(
159
- name,
160
- {
161
- metadata: mapMetadata(args2, name),
162
- spec: deepmerge(
163
- {
164
- ports: normalize(args2.port, args2.ports),
165
- externalIPs: args2.external ? args2.externalIPs ?? args2.cluster.externalIps : args2.cluster.externalIps,
166
- type: getServiceType(args2, args2.cluster)
167
- },
168
- omit(args2, serviceExtraArgs)
169
- )
170
- },
171
- { parent: this, ...opts }
172
- );
173
- });
174
- super(
175
- "highstate:k8s:Service",
176
- name,
177
- args,
178
- opts,
179
- output(args.cluster),
180
- service.metadata,
181
- service.spec,
182
- service.status
183
- );
184
- }
185
- };
186
- var WrappedService = class extends Service {
187
- constructor(name, service, cluster, opts) {
188
- super(
189
- "highstate:k8s:WrappedService",
190
- name,
191
- { service, clusterInfo: cluster },
192
- opts,
193
- output(cluster),
194
- output(service).metadata,
195
- output(service).spec,
196
- output(service).status
197
- );
198
- }
199
- };
200
- var ExternalService = class extends Service {
201
- constructor(name, id, cluster, opts) {
202
- const service = output(id).apply((id2) => {
203
- return core.v1.Service.get(
204
- //
205
- name,
206
- resourceIdToString(id2),
207
- { ...opts, parent: this }
208
- );
209
- });
210
- super(
211
- "highstate:k8s:ExternalService",
212
- name,
213
- { id, cluster },
214
- opts,
215
- output(cluster),
216
- service.metadata,
217
- service.spec,
218
- service.status
219
- );
220
- }
221
- };
222
- function mapContainerPortToServicePort(port) {
223
- return {
224
- name: port.name,
225
- port: port.containerPort,
226
- targetPort: port.containerPort,
227
- protocol: port.protocol
228
- };
229
- }
230
- function mapServiceToLabelSelector(service) {
231
- return {
232
- matchLabels: service.spec.selector
233
- };
234
- }
235
- function getServiceType(service, cluster) {
236
- if (service?.type) {
237
- return service.type;
238
- }
239
- if (!service?.external) {
240
- return "ClusterIP";
241
- }
242
- return cluster.quirks?.externalServiceType === "LoadBalancer" ? "LoadBalancer" : "NodePort";
243
- }
244
-
245
- // src/gateway/http-route.ts
246
- import {
247
- ComponentResource as ComponentResource2,
248
- normalize as normalize2,
249
- output as output3
250
- } from "@highstate/pulumi";
251
- import { gateway } from "@highstate/gateway-api";
252
- import { map, pipe } from "remeda";
253
-
254
- // src/gateway/backend.ts
255
- import "@pulumi/kubernetes";
256
- import { output as output2 } from "@highstate/pulumi";
257
- function resolveBackendRef(ref) {
258
- if (Service.isInstance(ref)) {
259
- return output2({
260
- name: ref.metadata.name,
261
- namespace: ref.metadata.namespace,
262
- port: ref.spec.ports[0].port
263
- });
264
- }
265
- if ("service" in ref) {
266
- const service = output2(ref.service);
267
- return output2({
268
- name: service.metadata.name,
269
- namespace: service.metadata.namespace,
270
- port: ref.port
271
- });
272
- }
273
- return output2({
274
- name: ref.name,
275
- namespace: ref.namespace,
276
- port: ref.port
277
- });
278
- }
279
-
280
- // src/gateway/http-route.ts
281
- var HttpRoute = class extends ComponentResource2 {
282
- /**
283
- * The underlying Kubernetes resource.
284
- */
285
- route;
286
- constructor(name, args, opts) {
287
- super("highstate:k8s:HttpRoute", name, args, opts);
288
- this.route = output3({
289
- args,
290
- gatewayNamespace: output3(args.gateway).metadata.namespace
291
- }).apply(async ({ args: args2, gatewayNamespace }) => {
292
- return new gateway.v1.HTTPRoute(
293
- name,
294
- {
295
- metadata: mapMetadata(
296
- {
297
- ...args2,
298
- namespace: gatewayNamespace
299
- },
300
- name
301
- ),
302
- spec: {
303
- hostnames: normalize2(args2.hostname, args2.hostnames),
304
- parentRefs: [
305
- {
306
- name: args2.gateway.metadata.name
307
- }
308
- ],
309
- rules: normalize2(args2.rule, args2.rules).map((rule) => ({
310
- timeouts: rule.timeouts,
311
- matches: pipe(
312
- normalize2(rule.match, rule.matches),
313
- map(mapHttpRouteRuleMatch),
314
- addDefaultPathMatch
315
- ),
316
- filters: normalize2(rule.filter, rule.filters),
317
- backendRefs: rule.backend ? [resolveBackendRef(rule.backend)] : void 0
318
- }))
319
- }
320
- },
321
- {
322
- ...opts,
323
- parent: this,
324
- provider: await getProvider(args2.cluster)
325
- }
326
- );
327
- });
328
- }
329
- };
330
- function addDefaultPathMatch(matches) {
331
- return matches.length ? matches : [{ path: { type: "PathPrefix", value: "/" } }];
332
- }
333
- function mapHttpRouteRuleMatch(match) {
334
- if (typeof match === "string") {
335
- return { path: { type: "PathPrefix", value: match } };
336
- }
337
- return match;
338
- }
339
-
340
- // src/network.ts
341
- import { filterEndpoints as filterEndpoints2 } from "@highstate/common";
342
- function getBestEndpoint(endpoints, cluster) {
343
- if (!endpoints.length) {
344
- return void 0;
345
- }
346
- if (endpoints.length === 1) {
347
- return endpoints[0];
348
- }
349
- if (!cluster) {
350
- return filterEndpoints2(endpoints)[0];
351
- }
352
- const clusterEndpoint = endpoints.find((endpoint) => isFromCluster(endpoint, cluster));
353
- if (clusterEndpoint) {
354
- return clusterEndpoint;
355
- }
356
- return filterEndpoints2(endpoints)[0];
357
- }
358
- function requireBestEndpoint(endpoints, cluster) {
359
- const endpoint = getBestEndpoint(endpoints, cluster);
360
- if (!endpoint) {
361
- throw new Error(`No best endpoint found for cluster "${cluster.name}" (${cluster.id})`);
362
- }
363
- return endpoint;
364
- }
365
-
366
- // src/network-policy.ts
367
- import { networking } from "@pulumi/kubernetes";
368
- import {
369
- ComponentResource as ComponentResource3,
370
- interpolate,
371
- normalize as normalize3,
372
- output as output4
373
- } from "@highstate/pulumi";
374
- import { capitalize, flat, groupBy, merge, mergeDeep, uniqueBy as uniqueBy2 } from "remeda";
375
- import "@highstate/library";
376
- import {
377
- l34EndpointToString,
378
- l3EndpointToCidr,
379
- parseL34Endpoint
380
- } from "@highstate/common";
381
- var NetworkPolicy = class _NetworkPolicy extends ComponentResource3 {
382
- /**
383
- * The underlying network policy resource.
384
- */
385
- networkPolicy;
386
- constructor(name, args, opts) {
387
- super("k8s:network-policy", name, args, opts);
388
- const normalizedArgs = output4(args).apply((args2) => {
389
- const ingressRules = normalize3(args2.ingressRule, args2.ingressRules);
390
- const egressRules = normalize3(args2.egressRule, args2.egressRules);
391
- const extraEgressRules = [];
392
- if (args2.allowKubeDns) {
393
- extraEgressRules.push({
394
- namespaces: ["kube-system"],
395
- selectors: [{ matchLabels: { "k8s-app": "kube-dns" } }],
396
- ports: [{ port: 53, protocol: "UDP" }],
397
- all: false,
398
- cidrs: [],
399
- fqdns: [],
400
- services: []
401
- });
402
- }
403
- return {
404
- ...args2,
405
- podSelector: args2.selector ? mapSelectorLikeToSelector(args2.selector) : {},
406
- isolateEgress: args2.isolateEgress ?? false,
407
- isolateIngress: args2.isolateIngress ?? false,
408
- allowKubeApiServer: args2.allowKubeApiServer ?? false,
409
- ingressRules: ingressRules.flatMap((rule) => {
410
- const endpoints = normalize3(
411
- args2.ingressRule?.fromEndpoint,
412
- args2.ingressRule?.fromEndpoints
413
- );
414
- const parsedEndpoints = endpoints.map(parseL34Endpoint);
415
- const endpointsNamespaces = groupBy(parsedEndpoints, (endpoint) => {
416
- const namespace = isFromCluster(endpoint, args2.cluster) ? endpoint.metadata.k8sService.namespace : "";
417
- return namespace;
418
- });
419
- const l3OnlyRule = endpointsNamespaces[""] ? _NetworkPolicy.getRuleFromEndpoint(void 0, endpointsNamespaces[""], args2.cluster) : void 0;
420
- const otherRules = Object.entries(endpointsNamespaces).filter(([key]) => key !== "").map(([, endpoints2]) => {
421
- return _NetworkPolicy.getRuleFromEndpoint(void 0, endpoints2, args2.cluster);
422
- });
423
- return [
424
- {
425
- all: rule.fromAll ?? false,
426
- cidrs: normalize3(rule.fromCidr, rule.fromCidrs).concat(l3OnlyRule?.cidrs ?? []),
427
- fqdns: [],
428
- services: normalize3(rule.fromService, rule.fromServices),
429
- namespaces: normalize3(rule.fromNamespace, rule.fromNamespaces),
430
- selectors: normalize3(rule.fromSelector, rule.fromSelectors),
431
- ports: normalize3(rule.toPort, rule.toPorts)
432
- },
433
- ...otherRules
434
- ].filter((rule2) => !_NetworkPolicy.isEmptyRule(rule2));
435
- }),
436
- egressRules: egressRules.flatMap((rule) => {
437
- const endpoints = normalize3(args2.egressRule?.toEndpoint, args2.egressRule?.toEndpoints);
438
- const parsedEndpoints = endpoints.map(parseL34Endpoint);
439
- const endpointsByPortsAnsNamespaces = groupBy(parsedEndpoints, (endpoint) => {
440
- const namespace = isFromCluster(endpoint, args2.cluster) ? endpoint.metadata.k8sService.namespace : "";
441
- const port = isFromCluster(endpoint, args2.cluster) ? endpoint.metadata.k8sService.targetPort : endpoint.port;
442
- return `${port ?? "0"}:${namespace}`;
443
- });
444
- const l3OnlyRule = endpointsByPortsAnsNamespaces["0:"] ? _NetworkPolicy.getRuleFromEndpoint(
445
- void 0,
446
- endpointsByPortsAnsNamespaces["0:"],
447
- args2.cluster
448
- ) : void 0;
449
- const otherRules = Object.entries(endpointsByPortsAnsNamespaces).filter(([key]) => key !== "0:").map(([key, endpoints2]) => {
450
- const [port] = key.split(":");
451
- const portNumber = parseInt(port, 10);
452
- const portValue = isNaN(portNumber) ? port : portNumber;
453
- return _NetworkPolicy.getRuleFromEndpoint(portValue, endpoints2, args2.cluster);
454
- });
455
- return [
456
- {
457
- all: rule.toAll ?? false,
458
- cidrs: normalize3(rule.toCidr, rule.toCidrs).concat(l3OnlyRule?.cidrs ?? []),
459
- fqdns: normalize3(rule.toFqdn, rule.toFqdns).concat(l3OnlyRule?.fqdns ?? []),
460
- services: normalize3(rule.toService, rule.toServices),
461
- namespaces: normalize3(rule.toNamespace, rule.toNamespaces),
462
- selectors: normalize3(rule.toSelector, rule.toSelectors),
463
- ports: normalize3(rule.toPort, rule.toPorts)
464
- },
465
- ...otherRules
466
- ].filter((rule2) => !_NetworkPolicy.isEmptyRule(rule2));
467
- }).concat(extraEgressRules)
468
- };
469
- });
470
- this.networkPolicy = output4(
471
- normalizedArgs.apply(async (args2) => {
472
- return output4(
473
- this.create(name, args2, {
474
- ...opts,
475
- parent: this,
476
- provider: await getProvider(args2.cluster)
477
- })
478
- );
479
- })
480
- );
481
- }
482
- static mapCidrFromEndpoint(result) {
483
- if (result.type === "ipv4") {
484
- return `${result.address}/32`;
485
- }
486
- return `${result.address}/128`;
487
- }
488
- static getRuleFromEndpoint(port, endpoints, cluster) {
489
- const ports = port ? [{ port, protocol: endpoints[0].protocol?.toUpperCase() }] : [];
490
- const cidrs = endpoints.filter((endpoint) => !isFromCluster(endpoint, cluster)).filter((endpoint) => endpoint.type === "ipv4" || endpoint.type === "ipv6").map(_NetworkPolicy.mapCidrFromEndpoint);
491
- const fqdns = endpoints.filter((endpoint) => endpoint.type === "hostname").map((endpoint) => endpoint.hostname);
492
- const selectors = endpoints.filter((endpoint) => isFromCluster(endpoint, cluster)).map((endpoint) => endpoint.metadata.k8sService.selector);
493
- const namespace = endpoints.filter((endpoint) => isFromCluster(endpoint, cluster)).map((endpoint) => getServiceMetadata(endpoint)?.namespace)[0];
494
- return {
495
- all: false,
496
- cidrs,
497
- fqdns,
498
- services: [],
499
- namespaces: namespace ? [namespace] : [],
500
- selectors,
501
- ports
502
- };
503
- }
504
- static isEmptyRule(rule) {
505
- return !rule.all && rule.cidrs.length === 0 && rule.fqdns.length === 0 && rule.services.length === 0 && rule.namespaces.length === 0 && rule.selectors.length === 0 && rule.ports.length === 0;
506
- }
507
- static create(name, args, opts) {
508
- return output4(args).apply(async (args2) => {
509
- const cni = args2.cluster.cni;
510
- if (cni === "other") {
511
- return new NativeNetworkPolicy(name, args2, opts);
512
- }
513
- const implName = `${capitalize(cni)}NetworkPolicy`;
514
- const implModule = await import(`@highstate/${cni}`);
515
- const implClass = implModule[implName];
516
- if (!implClass) {
517
- throw new Error(`No implementation found for ${cni}`);
518
- }
519
- return new implClass(name, args2, opts);
520
- });
521
- }
522
- static isolate(namespace, cluster, opts) {
523
- return _NetworkPolicy.create(
524
- "isolate",
525
- {
526
- namespace,
527
- cluster,
528
- description: "By default, deny all traffic to/from the namespace.",
529
- isolateEgress: true,
530
- isolateIngress: true
531
- },
532
- opts
533
- );
534
- }
535
- static allowInsideNamespace(namespace, cluster, opts) {
536
- return _NetworkPolicy.create(
537
- "allow-inside-namespace",
538
- {
539
- namespace,
540
- cluster,
541
- description: "Allow all traffic inside the namespace.",
542
- selector: {},
543
- ingressRule: { fromNamespace: namespace },
544
- egressRule: { toNamespace: namespace }
545
- },
546
- opts
547
- );
548
- }
549
- static allowKubeApiServer(namespace, cluster, opts) {
550
- return _NetworkPolicy.create(
551
- "allow-kube-api-server",
552
- {
553
- namespace,
554
- cluster,
555
- description: "Allow all traffic to the Kubernetes API server from the namespace.",
556
- allowKubeApiServer: true
557
- },
558
- opts
559
- );
560
- }
561
- static allowKubeDns(namespace, cluster, opts) {
562
- return _NetworkPolicy.create(
563
- "allow-kube-dns",
564
- {
565
- namespace,
566
- cluster,
567
- description: "Allow all traffic to the Kubernetes DNS server from the namespace.",
568
- allowKubeDns: true
569
- },
570
- opts
571
- );
572
- }
573
- static allowAllEgress(namespace, cluster, opts) {
574
- return _NetworkPolicy.create(
575
- "allow-all-egress",
576
- {
577
- namespace,
578
- cluster,
579
- description: "Allow all egress traffic from the namespace.",
580
- egressRule: { toAll: true }
581
- },
582
- opts
583
- );
584
- }
585
- static allowAllIngress(namespace, cluster, opts) {
586
- return _NetworkPolicy.create(
587
- "allow-all-ingress",
588
- {
589
- namespace,
590
- cluster,
591
- description: "Allow all ingress traffic to the namespace.",
592
- ingressRule: { fromAll: true }
593
- },
594
- opts
595
- );
596
- }
597
- static allowEgressToEndpoint(endpoint, namespace, cluster, opts) {
598
- const parsedEndpoint = parseL34Endpoint(endpoint);
599
- return _NetworkPolicy.create(
600
- `allow-egress-to-${l34EndpointToString(parsedEndpoint).replace(":", "-")}`,
601
- {
602
- namespace,
603
- cluster,
604
- description: interpolate`Allow egress traffic to "${l34EndpointToString(parsedEndpoint)}" from the namespace.`,
605
- egressRule: { toEndpoint: endpoint }
606
- },
607
- opts
608
- );
609
- }
610
- static allowEgressToBestEndpoint(endpoints, namespace, cluster, opts) {
611
- return output4({ endpoints, cluster }).apply(({ endpoints: endpoints2, cluster: cluster2 }) => {
612
- const bestEndpoint = requireBestEndpoint(endpoints2.map(parseL34Endpoint), cluster2);
613
- return _NetworkPolicy.allowEgressToEndpoint(bestEndpoint, namespace, cluster2, opts);
614
- });
615
- }
616
- static allowIngressFromEndpoint(endpoint, namespace, cluster, opts) {
617
- const parsedEndpoint = parseL34Endpoint(endpoint);
618
- return _NetworkPolicy.create(
619
- `allow-ingress-from-${l34EndpointToString(parsedEndpoint)}`,
620
- {
621
- namespace,
622
- cluster,
623
- description: interpolate`Allow ingress traffic from "${l34EndpointToString(parsedEndpoint)}" to the namespace.`,
624
- ingressRule: { fromEndpoint: endpoint }
625
- },
626
- opts
627
- );
628
- }
629
- };
630
- var NativeNetworkPolicy = class _NativeNetworkPolicy extends NetworkPolicy {
631
- create(name, args, opts) {
632
- const ingress = _NativeNetworkPolicy.createIngressRules(args);
633
- const egress = _NativeNetworkPolicy.createEgressRules(args);
634
- const policyTypes = [];
635
- if (ingress.length > 0 || args.isolateIngress) {
636
- policyTypes.push("Ingress");
637
- }
638
- if (egress.length > 0 || args.isolateEgress) {
639
- policyTypes.push("Egress");
640
- }
641
- return new networking.v1.NetworkPolicy(
642
- name,
643
- {
644
- metadata: mergeDeep(mapMetadata(args, name), {
645
- annotations: args.description ? { "kubernetes.io/description": args.description } : void 0
646
- }),
647
- spec: {
648
- podSelector: args.podSelector,
649
- ingress,
650
- egress,
651
- policyTypes
652
- }
653
- },
654
- opts
655
- );
656
- }
657
- static fallbackIpBlock = {
658
- cidr: "0.0.0.0/0",
659
- except: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
660
- };
661
- static fallbackDnsRule = {
662
- to: [
663
- {
664
- namespaceSelector: { matchLabels: { "kubernetes.io/metadata.name": "kube-system" } },
665
- podSelector: { matchLabels: { "k8s-app": "kube-dns" } }
666
- }
667
- ],
668
- ports: [{ port: 53, protocol: "UDP" }]
669
- };
670
- static createIngressRules(args) {
671
- return uniqueBy2(
672
- args.ingressRules.map((rule) => ({
673
- from: rule.all ? [] : _NativeNetworkPolicy.createRulePeers(rule),
674
- ports: _NativeNetworkPolicy.mapPorts(rule.ports)
675
- })),
676
- (rule) => JSON.stringify(rule)
677
- );
678
- }
679
- static createEgressRules(args) {
680
- const extraRules = [];
681
- const needKubeDns = args.egressRules.some((rule) => rule.fqdns.length > 0);
682
- if (needKubeDns) {
683
- extraRules.push(_NativeNetworkPolicy.fallbackDnsRule);
684
- }
685
- const needFallback = args.egressRules.some(
686
- (rule) => rule.fqdns.some((fqdn) => !fqdn.endsWith(".cluster.local"))
687
- );
688
- if (needFallback) {
689
- extraRules.push({ to: [{ ipBlock: _NativeNetworkPolicy.fallbackIpBlock }] });
690
- }
691
- if (args.allowKubeApiServer) {
692
- const { quirks, apiEndpoints } = args.cluster;
693
- if (quirks?.fallbackKubeApiAccess) {
694
- extraRules.push({
695
- to: [{ ipBlock: { cidr: `${quirks?.fallbackKubeApiAccess.serverIp}/32` } }],
696
- ports: [{ port: quirks?.fallbackKubeApiAccess.serverPort, protocol: "TCP" }]
697
- });
698
- } else {
699
- const rules = apiEndpoints.filter((endpoint) => endpoint.type !== "hostname").map((endpoint) => ({
700
- to: [{ ipBlock: { cidr: l3EndpointToCidr(endpoint) } }],
701
- ports: [{ port: endpoint.port, protocol: "TCP" }]
702
- }));
703
- extraRules.push(...rules);
704
- }
705
- }
706
- return uniqueBy2(
707
- args.egressRules.map((rule) => {
708
- return {
709
- to: rule.all ? [] : _NativeNetworkPolicy.createRulePeers(rule),
710
- ports: _NativeNetworkPolicy.mapPorts(rule.ports)
711
- };
712
- }).filter((rule) => rule.to !== void 0).concat(extraRules),
713
- (rule) => JSON.stringify(rule)
714
- );
715
- }
716
- static createRulePeers(args) {
717
- const peers = uniqueBy2(
718
- [
719
- ..._NativeNetworkPolicy.createCidrPeers(args),
720
- ..._NativeNetworkPolicy.createServicePeers(args),
721
- ..._NativeNetworkPolicy.createSelectorPeers(args)
722
- ],
723
- (peer) => JSON.stringify(peer)
724
- );
725
- return peers.length > 0 ? peers : void 0;
726
- }
727
- static createCidrPeers(args) {
728
- return args.cidrs.map((cidr) => ({ ipBlock: { cidr } }));
729
- }
730
- static createServicePeers(args) {
731
- return args.services.map((service) => {
732
- const selector = mapServiceToLabelSelector(service);
733
- return {
734
- namespaceSelector: mapNamespaceNameToSelector(service.metadata.namespace),
735
- podSelector: selector
736
- };
737
- });
738
- }
739
- static createSelectorPeers(args) {
740
- const selectorPeers = args.selectors.map((selector) => ({
741
- podSelector: mapSelectorLikeToSelector(selector)
742
- }));
743
- const namespacePeers = args.namespaces.map(_NativeNetworkPolicy.createNamespacePeer);
744
- if (namespacePeers.length === 0) {
745
- return selectorPeers;
746
- }
747
- if (selectorPeers.length === 0) {
748
- return namespacePeers;
749
- }
750
- return flat(
751
- selectorPeers.map((selectorPeer) => {
752
- return namespacePeers.map((namespacePeer) => merge(selectorPeer, namespacePeer));
753
- })
754
- );
755
- }
756
- static createNamespacePeer(namespace) {
757
- const namespaceName = mapNamespaceLikeToNamespaceName(namespace);
758
- const namespaceSelector = mapNamespaceNameToSelector(namespaceName);
759
- return { namespaceSelector };
760
- }
761
- static mapPorts(ports) {
762
- return ports.map((port) => {
763
- if ("port" in port) {
764
- return {
765
- port: port.port,
766
- protocol: port.protocol ?? "TCP"
767
- };
768
- }
769
- return {
770
- port: port.range[0],
771
- endPort: port.range[1],
772
- protocol: port.protocol ?? "TCP"
773
- };
774
- });
775
- }
776
- };
777
-
778
- export {
779
- hasServiceMetadata,
780
- getServiceMetadata,
781
- withServiceMetadata,
782
- isFromCluster,
783
- Service,
784
- mapContainerPortToServicePort,
785
- mapServiceToLabelSelector,
786
- getServiceType,
787
- HttpRoute,
788
- getBestEndpoint,
789
- requireBestEndpoint,
790
- NetworkPolicy
791
- };
792
- //# sourceMappingURL=chunk-WEKIQRCZ.js.map