pepr 0.24.1 → 0.26.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/dist/cli.js CHANGED
@@ -291,11 +291,154 @@ function watcherService(name2) {
291
291
 
292
292
  // src/lib/assets/pods.ts
293
293
  var import_zlib = require("zlib");
294
- var namespace = {
295
- apiVersion: "v1",
296
- kind: "Namespace",
297
- metadata: { name: "pepr-system" }
294
+
295
+ // src/lib/helpers.ts
296
+ var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
297
+ var import_fs2 = require("fs");
298
+ var import_commander = __toESM(require("commander"));
299
+ var createRBACMap = (capabilities) => {
300
+ return capabilities.reduce((acc, capability) => {
301
+ capability.bindings.forEach((binding) => {
302
+ const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;
303
+ acc["pepr.dev/v1/peprstore"] = {
304
+ verbs: ["create", "get", "patch", "watch"],
305
+ plural: "peprstores"
306
+ };
307
+ if (!acc[key] && binding.isWatch) {
308
+ acc[key] = {
309
+ verbs: ["watch"],
310
+ plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
311
+ };
312
+ }
313
+ });
314
+ return acc;
315
+ }, {});
298
316
  };
317
+ async function createDirectoryIfNotExists(path) {
318
+ try {
319
+ await import_fs2.promises.access(path);
320
+ } catch (error) {
321
+ if (error.code === "ENOENT") {
322
+ await import_fs2.promises.mkdir(path, { recursive: true });
323
+ } else {
324
+ throw error;
325
+ }
326
+ }
327
+ }
328
+ function hasEveryOverlap(array1, array2) {
329
+ if (!Array.isArray(array1) || !Array.isArray(array2)) {
330
+ return false;
331
+ }
332
+ return array1.every((element) => array2.includes(element));
333
+ }
334
+ function hasAnyOverlap(array1, array2) {
335
+ if (!Array.isArray(array1) || !Array.isArray(array2)) {
336
+ return false;
337
+ }
338
+ return array1.some((element) => array2.includes(element));
339
+ }
340
+ function ignoredNamespaceConflict(ignoreNamespaces, bindingNamespaces) {
341
+ return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);
342
+ }
343
+ function bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces) {
344
+ if (!capabilityNamespaces) {
345
+ return false;
346
+ }
347
+ return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);
348
+ }
349
+ function generateWatchNamespaceError(ignoredNamespaces, bindingNamespaces, capabilityNamespaces) {
350
+ let err = "";
351
+ if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {
352
+ err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(
353
+ ", "
354
+ )}] bindingNamespaces: [${bindingNamespaces.join(", ")}].`;
355
+ }
356
+ if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {
357
+ err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(
358
+ ", "
359
+ )}] capabilityNamespaces:$[${capabilityNamespaces.join(", ")}].`;
360
+ }
361
+ return err.replace(/\.([^ ])/g, ". $1");
362
+ }
363
+ function namespaceComplianceValidator(capability, ignoredNamespaces) {
364
+ const { namespaces: capabilityNamespaces, bindings, name: name2 } = capability;
365
+ const bindingNamespaces = bindings.flatMap((binding) => binding.filters.namespaces);
366
+ const namespaceError = generateWatchNamespaceError(
367
+ ignoredNamespaces ? ignoredNamespaces : [],
368
+ bindingNamespaces,
369
+ capabilityNamespaces ? capabilityNamespaces : []
370
+ );
371
+ if (namespaceError !== "") {
372
+ throw new Error(
373
+ `Error in ${name2} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`
374
+ );
375
+ }
376
+ }
377
+ async function checkDeploymentStatus(namespace2) {
378
+ const deployments = await (0, import_kubernetes_fluent_client.K8s)(import_kubernetes_fluent_client.kind.Deployment).InNamespace(namespace2).Get();
379
+ let status = false;
380
+ let readyCount = 0;
381
+ for (const deployment2 of deployments.items) {
382
+ const readyReplicas = deployment2.status?.readyReplicas ? deployment2.status?.readyReplicas : 0;
383
+ if (deployment2.status?.readyReplicas !== deployment2.spec?.replicas) {
384
+ logger_default.info(
385
+ `Waiting for deployment ${deployment2.metadata?.name} rollout to finish: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
386
+ );
387
+ } else {
388
+ logger_default.info(
389
+ `Deployment ${deployment2.metadata?.name} rolled out: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
390
+ );
391
+ readyCount++;
392
+ }
393
+ }
394
+ if (readyCount === deployments.items.length) {
395
+ status = true;
396
+ }
397
+ return status;
398
+ }
399
+ async function namespaceDeploymentsReady(namespace2 = "pepr-system") {
400
+ logger_default.info(`Checking ${namespace2} deployments status...`);
401
+ let ready = false;
402
+ while (!ready) {
403
+ ready = await checkDeploymentStatus(namespace2);
404
+ if (ready) {
405
+ return ready;
406
+ }
407
+ await new Promise((resolve4) => setTimeout(resolve4, 1e3));
408
+ }
409
+ logger_default.info(`All ${namespace2} deployments are ready`);
410
+ }
411
+ function secretOverLimit(str) {
412
+ const encoder = new TextEncoder();
413
+ const encoded = encoder.encode(str);
414
+ const sizeInBytes = encoded.length;
415
+ const oneMiBInBytes = 1048576;
416
+ return sizeInBytes > oneMiBInBytes;
417
+ }
418
+ var parseTimeout = (value, previous) => {
419
+ const parsedValue = parseInt(value, 10);
420
+ const floatValue = parseFloat(value);
421
+ if (isNaN(parsedValue)) {
422
+ throw new import_commander.default.InvalidArgumentError("Not a number.");
423
+ } else if (parsedValue !== floatValue) {
424
+ throw new import_commander.default.InvalidArgumentError("Value must be an integer.");
425
+ } else if (parsedValue < 1 || parsedValue > 30) {
426
+ throw new import_commander.default.InvalidArgumentError("Number must be between 1 and 30.");
427
+ }
428
+ return parsedValue;
429
+ };
430
+
431
+ // src/lib/assets/pods.ts
432
+ function namespace(namespaceLabels) {
433
+ return {
434
+ apiVersion: "v1",
435
+ kind: "Namespace",
436
+ metadata: {
437
+ name: "pepr-system",
438
+ labels: namespaceLabels ?? {}
439
+ }
440
+ };
441
+ }
299
442
  function watcher(assets, hash) {
300
443
  const { name: name2, image, capabilities, config } = assets;
301
444
  let hasSchedule = false;
@@ -317,9 +460,13 @@ function watcher(assets, hash) {
317
460
  metadata: {
318
461
  name: app,
319
462
  namespace: "pepr-system",
463
+ annotations: {
464
+ "pepr.dev/description": config.description || ""
465
+ },
320
466
  labels: {
321
467
  app,
322
- "pepr.dev/controller": "watcher"
468
+ "pepr.dev/controller": "watcher",
469
+ "pepr.dev/uuid": config.uuid
323
470
  }
324
471
  },
325
472
  spec: {
@@ -438,9 +585,13 @@ function deployment(assets, hash) {
438
585
  metadata: {
439
586
  name: name2,
440
587
  namespace: "pepr-system",
588
+ annotations: {
589
+ "pepr.dev/description": config.description || ""
590
+ },
441
591
  labels: {
442
592
  app,
443
- "pepr.dev/controller": "admission"
593
+ "pepr.dev/controller": "admission",
594
+ "pepr.dev/uuid": config.uuid
444
595
  }
445
596
  },
446
597
  spec: {
@@ -562,18 +713,25 @@ function deployment(assets, hash) {
562
713
  function moduleSecret(name2, data, hash) {
563
714
  const compressed = (0, import_zlib.gzipSync)(data);
564
715
  const path = `module-${hash}.js.gz`;
565
- return {
566
- apiVersion: "v1",
567
- kind: "Secret",
568
- metadata: {
569
- name: `${name2}-module`,
570
- namespace: "pepr-system"
571
- },
572
- type: "Opaque",
573
- data: {
574
- [path]: compressed.toString("base64")
575
- }
576
- };
716
+ const compressedData = compressed.toString("base64");
717
+ if (secretOverLimit(compressedData)) {
718
+ const error = new Error(`Module secret for ${name2} is over the 1MB limit`);
719
+ console.error("Uncaught Exception:", error);
720
+ process.exit(1);
721
+ } else {
722
+ return {
723
+ apiVersion: "v1",
724
+ kind: "Secret",
725
+ metadata: {
726
+ name: `${name2}-module`,
727
+ namespace: "pepr-system"
728
+ },
729
+ type: "Opaque",
730
+ data: {
731
+ [path]: compressed.toString("base64")
732
+ }
733
+ };
734
+ }
577
735
  }
578
736
  function genEnv(config, watchMode = false) {
579
737
  const env = [
@@ -589,122 +747,6 @@ function genEnv(config, watchMode = false) {
589
747
  return env;
590
748
  }
591
749
 
592
- // src/lib/helpers.ts
593
- var import_kubernetes_fluent_client = require("kubernetes-fluent-client");
594
- var import_fs2 = require("fs");
595
- var createRBACMap = (capabilities) => {
596
- return capabilities.reduce((acc, capability) => {
597
- capability.bindings.forEach((binding) => {
598
- const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;
599
- acc["pepr.dev/v1/peprstore"] = {
600
- verbs: ["create", "get", "patch", "watch"],
601
- plural: "peprstores"
602
- };
603
- if (!acc[key] && binding.isWatch) {
604
- acc[key] = {
605
- verbs: ["watch"],
606
- plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`
607
- };
608
- }
609
- });
610
- return acc;
611
- }, {});
612
- };
613
- async function createDirectoryIfNotExists(path) {
614
- try {
615
- await import_fs2.promises.access(path);
616
- } catch (error) {
617
- if (error.code === "ENOENT") {
618
- await import_fs2.promises.mkdir(path, { recursive: true });
619
- } else {
620
- throw error;
621
- }
622
- }
623
- }
624
- function hasEveryOverlap(array1, array2) {
625
- if (!Array.isArray(array1) || !Array.isArray(array2)) {
626
- return false;
627
- }
628
- return array1.every((element) => array2.includes(element));
629
- }
630
- function hasAnyOverlap(array1, array2) {
631
- if (!Array.isArray(array1) || !Array.isArray(array2)) {
632
- return false;
633
- }
634
- return array1.some((element) => array2.includes(element));
635
- }
636
- function ignoredNamespaceConflict(ignoreNamespaces, bindingNamespaces) {
637
- return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);
638
- }
639
- function bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces) {
640
- if (!capabilityNamespaces) {
641
- return false;
642
- }
643
- return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);
644
- }
645
- function generateWatchNamespaceError(ignoredNamespaces, bindingNamespaces, capabilityNamespaces) {
646
- let err = "";
647
- if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {
648
- err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(
649
- ", "
650
- )}] bindingNamespaces: [${bindingNamespaces.join(", ")}].`;
651
- }
652
- if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {
653
- err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(
654
- ", "
655
- )}] capabilityNamespaces:$[${capabilityNamespaces.join(", ")}].`;
656
- }
657
- return err.replace(/\.([^ ])/g, ". $1");
658
- }
659
- function namespaceComplianceValidator(capability, ignoredNamespaces) {
660
- const { namespaces: capabilityNamespaces, bindings, name: name2 } = capability;
661
- const bindingNamespaces = bindings.flatMap((binding) => binding.filters.namespaces);
662
- const namespaceError = generateWatchNamespaceError(
663
- ignoredNamespaces ? ignoredNamespaces : [],
664
- bindingNamespaces,
665
- capabilityNamespaces ? capabilityNamespaces : []
666
- );
667
- if (namespaceError !== "") {
668
- throw new Error(
669
- `Error in ${name2} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`
670
- );
671
- }
672
- }
673
- async function checkDeploymentStatus(namespace2) {
674
- const deployments = await (0, import_kubernetes_fluent_client.K8s)(import_kubernetes_fluent_client.kind.Deployment).InNamespace(namespace2).Get();
675
- let status = false;
676
- let readyCount = 0;
677
- for (const deployment2 of deployments.items) {
678
- const readyReplicas = deployment2.status?.readyReplicas ? deployment2.status?.readyReplicas : 0;
679
- if (deployment2.status?.readyReplicas !== deployment2.spec?.replicas) {
680
- logger_default.info(
681
- `Waiting for deployment ${deployment2.metadata?.name} rollout to finish: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
682
- );
683
- } else {
684
- logger_default.info(
685
- `Deployment ${deployment2.metadata?.name} rolled out: ${readyReplicas} of ${deployment2.spec?.replicas} replicas are available`
686
- );
687
- readyCount++;
688
- }
689
- }
690
- if (readyCount === deployments.items.length) {
691
- status = true;
692
- }
693
- return status;
694
- }
695
- async function namespaceDeploymentsReady(namespace2 = "pepr-system") {
696
- logger_default.info(`Checking ${namespace2} deployments status...`);
697
- let ready = false;
698
- while (!ready) {
699
- ready = await checkDeploymentStatus(namespace2);
700
- if (ready) {
701
- return ready;
702
- }
703
- await new Promise((resolve4) => setTimeout(resolve4, 1e3));
704
- }
705
- logger_default.info(`All ${namespace2} deployments are ready`);
706
- }
707
-
708
750
  // src/lib/assets/rbac.ts
709
751
  function clusterRole(name2, capabilities, rbacMode = "") {
710
752
  const rbacMap = createRBACMap(capabilities);
@@ -865,7 +907,7 @@ async function generateWebhookRules(assets, isMutateWebhook) {
865
907
  for (const capability of capabilities) {
866
908
  console.info(`Module ${config.uuid} has capability: ${capability.name}`);
867
909
  for (const binding of capability.bindings) {
868
- const { event, kind: kind5, isMutate, isValidate } = binding;
910
+ const { event, kind: kind6, isMutate, isValidate } = binding;
869
911
  if (isMutateWebhook && !isMutate) {
870
912
  continue;
871
913
  }
@@ -878,10 +920,10 @@ async function generateWebhookRules(assets, isMutateWebhook) {
878
920
  } else {
879
921
  operations.push(event);
880
922
  }
881
- const resource = kind5.plural || `${kind5.kind.toLowerCase()}s`;
923
+ const resource = kind6.plural || `${kind6.kind.toLowerCase()}s`;
882
924
  const ruleObject = {
883
- apiGroups: [kind5.group],
884
- apiVersions: [kind5.version || "*"],
925
+ apiGroups: [kind6.group],
926
+ apiVersions: [kind6.version || "*"],
885
927
  operations,
886
928
  resources: [resource]
887
929
  };
@@ -953,7 +995,7 @@ async function deploy(assets, force, webhookTimeout) {
953
995
  logger_default.info("Establishing connection to Kubernetes");
954
996
  const { name: name2, host, path } = assets;
955
997
  logger_default.info("Applying pepr-system namespace");
956
- await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(namespace);
998
+ await (0, import_kubernetes_fluent_client3.K8s)(import_kubernetes_fluent_client3.kind.Namespace).Apply(namespace(assets.config.customLabels?.namespace));
957
999
  const mutateWebhook = await webhookConfig(assets, "mutate", webhookTimeout);
958
1000
  if (mutateWebhook) {
959
1001
  logger_default.info("Applying mutating webhook");
@@ -1088,11 +1130,11 @@ async function allYaml(assets, rbacMode) {
1088
1130
  const { name: name2, tls, apiToken, path } = assets;
1089
1131
  const code = await import_fs4.promises.readFile(path);
1090
1132
  const hash = import_crypto2.default.createHash("sha256").update(code).digest("hex");
1091
- const mutateWebhook = await webhookConfig(assets, "mutate");
1092
- const validateWebhook = await webhookConfig(assets, "validate");
1133
+ const mutateWebhook = await webhookConfig(assets, "mutate", assets.config.webhookTimeout);
1134
+ const validateWebhook = await webhookConfig(assets, "validate", assets.config.webhookTimeout);
1093
1135
  const watchDeployment = watcher(assets, hash);
1094
1136
  const resources = [
1095
- namespace,
1137
+ namespace(assets.config.customLabels?.namespace),
1096
1138
  clusterRole(name2, assets.capabilities, rbacMode),
1097
1139
  clusterRoleBinding(name2),
1098
1140
  serviceAccount(name2),
@@ -1102,7 +1144,6 @@ async function allYaml(assets, rbacMode) {
1102
1144
  service(name2),
1103
1145
  watcherService(name2),
1104
1146
  moduleSecret(name2, code, hash),
1105
- peprStoreCRD,
1106
1147
  storeRole(name2),
1107
1148
  storeRoleBinding(name2)
1108
1149
  ];
@@ -1357,7 +1398,7 @@ var gitIgnore = "# Ignore node_modules and Pepr build artifacts\nnode_modules\nd
1357
1398
  var readmeMd = '# Pepr Module\n\nThis is a Pepr Module. [Pepr](https://github.com/defenseunicorns/pepr) is a type-safe Kubernetes middleware system.\n\nThe `capabilities` directory contains all the capabilities for this module. By default,\na capability is a single typescript file in the format of `capability-name.ts` that is\nimported in the root `pepr.ts` file as `import { HelloPepr } from "./capabilities/hello-pepr";`.\nBecause this is typescript, you can organize this however you choose, e.g. creating a sub-folder\nper-capability or common logic in shared files or folders.\n\nExample Structure:\n\n```\nModule Root\n\u251C\u2500\u2500 package.json\n\u251C\u2500\u2500 pepr.ts\n\u2514\u2500\u2500 capabilities\n \u251C\u2500\u2500 example-one.ts\n \u251C\u2500\u2500 example-three.ts\n \u2514\u2500\u2500 example-two.ts\n```\n';
1358
1399
  var peprTS = 'import { PeprModule } from "pepr";\n// cfg loads your pepr configuration from package.json\nimport cfg from "./package.json";\n\n// HelloPepr is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\nimport { HelloPepr } from "./capabilities/hello-pepr";\n\n/**\n * This is the main entrypoint for this Pepr module. It is run when the module is started.\n * This is where you register your Pepr configurations and capabilities.\n */\nnew PeprModule(cfg, [\n // "HelloPepr" is a demo capability that is included with Pepr. Comment or delete the line below to remove it.\n HelloPepr,\n\n // Your additional capabilities go here\n]);\n';
1359
1400
  var helloPeprTS = 'import {\n Capability,\n K8s,\n Log,\n PeprMutateRequest,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n} from "pepr";\n\n/**\n * The HelloPepr Capability is an example capability to demonstrate some general concepts of Pepr.\n * To test this capability you run `pepr dev`and then run the following command:\n * `kubectl apply -f capabilities/hello-pepr.samples.yaml`\n */\nexport const HelloPepr = new Capability({\n name: "hello-pepr",\n description: "A simple example capability to show how things work.",\n namespaces: ["pepr-demo", "pepr-demo-2"],\n});\n\n// Use the \'When\' function to create a new action, use \'Store\' to persist data\nconst { When, Store } = HelloPepr;\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action removes the label `remove-me` when a Namespace is created.\n * Note we don\'t need to specify the namespace here, because we\'ve already specified\n * it in the Capability definition above.\n */\nWhen(a.Namespace)\n .IsCreated()\n .Mutate(ns => ns.RemoveLabel("remove-me"));\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Watch Action with K8s SSA (Namespace) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action watches for the `pepr-demo-2` namespace to be created, then creates a ConfigMap with\n * the name `pepr-ssa-demo` and adds the namespace UID to the ConfigMap data. Because Pepr uses\n * server-side apply for this operation, the ConfigMap will be created or updated if it already exists.\n */\nWhen(a.Namespace)\n .IsCreated()\n .WithName("pepr-demo-2")\n .Watch(async ns => {\n Log.info("Namespace pepr-demo-2 was created.");\n\n try {\n // Apply the ConfigMap using K8s server-side apply\n await K8s(kind.ConfigMap).Apply({\n metadata: {\n name: "pepr-ssa-demo",\n namespace: "pepr-demo-2",\n },\n data: {\n "ns-uid": ns.metadata.uid,\n },\n });\n } catch (error) {\n // You can use the Log object to log messages to the Pepr controller pod\n Log.error(error, "Failed to apply ConfigMap using server-side apply.");\n }\n\n // You can share data between actions using the Store, including between different types of actions\n Store.setItem("watch-data", "This data was stored by a Watch Action.");\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 1) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is a single action. They can be in the same file or put imported from other files.\n * In this example, when a ConfigMap is created with the name `example-1`, then add a label and annotation.\n *\n * Equivalent to manually running:\n * `kubectl label configmap example-1 pepr=was-here`\n * `kubectl annotate configmap example-1 pepr.dev=annotations-work-too`\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request\n .SetLabel("pepr", "was-here")\n .SetAnnotation("pepr.dev", "annotations-work-too");\n\n // Use the Store to persist data between requests and Pepr controller pods\n Store.setItem("example-1", "was-here");\n\n // This data is written asynchronously and can be read back via `Store.getItem()` or `Store.subscribe()`\n Store.setItem("example-1-data", JSON.stringify(request.Raw.data));\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate & Validate Actions (CM Example 2) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This combines 3 different types of actions: \'Mutate\', \'Validate\', and \'Watch\'. The order\n * of the actions is required, but each action is optional. In this example, when a ConfigMap is created\n * with the name `example-2`, then add a label and annotation, validate that the ConfigMap has the label\n * `pepr`, and log the request.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n // This Mutate Action will mutate the request before it is persisted to the cluster\n\n // Use `request.Merge()` to merge the new data with the existing data\n request.Merge({\n metadata: {\n labels: {\n pepr: "was-here",\n },\n annotations: {\n "pepr.dev": "annotations-work-too",\n },\n },\n });\n })\n .Validate(request => {\n // This Validate Action will validate the request before it is persisted to the cluster\n\n // Approve the request if the ConfigMap has the label \'pepr\'\n if (request.HasLabel("pepr")) {\n return request.Approve();\n }\n\n // Otherwise, deny the request with an error message (optional)\n return request.Deny("ConfigMap must have label \'pepr\'");\n })\n .Watch((cm, phase) => {\n // This Watch Action will watch the ConfigMap after it has been persisted to the cluster\n Log.info(cm, `ConfigMap was ${phase} with the name example-2`);\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 2a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action shows a simple validation that will deny any ConfigMap that has the\n * annotation `evil`. Note that the `Deny()` function takes an optional second parameter that is a\n * user-defined status code to return.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .Validate(request => {\n if (request.HasAnnotation("evil")) {\n return request.Deny("No evil CM annotations allowed.", 400);\n }\n\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 3) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action combines different styles. Unlike the previous actions, this one will look\n * for any ConfigMap in the `pepr-demo` namespace that has the label `change=by-label` during either\n * CREATE or UPDATE. Note that all conditions added such as `WithName()`, `WithLabel()`, `InNamespace()`,\n * are ANDs so all conditions must be true for the request to be processed.\n */\nWhen(a.ConfigMap)\n .IsCreatedOrUpdated()\n .WithLabel("change", "by-label")\n .Mutate(request => {\n // The K8s object e are going to mutate\n const cm = request.Raw;\n\n // Get the username and uid of the K8s request\n const { username, uid } = request.Request.userInfo;\n\n // Store some data about the request in the configmap\n cm.data["username"] = username;\n cm.data["uid"] = uid;\n\n // You can still mix other ways of making changes too\n request.SetAnnotation("pepr.dev", "making-waves");\n });\n\n// This action validates the label `change=by-label` is deleted\nWhen(a.ConfigMap)\n .IsDeleted()\n .WithLabel("change", "by-label")\n .Validate(request => {\n // Log and then always approve the request\n Log.info("CM with label \'change=by-label\' was deleted.");\n return request.Approve();\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action show how you can use the `Mutate()` function without an inline function.\n * This is useful if you want to keep your actions small and focused on a single task,\n * or if you want to reuse the same function in multiple actions.\n */\nWhen(a.ConfigMap).IsCreated().WithName("example-4").Mutate(example4Cb);\n\n// This function uses the complete type definition, but is not required.\nfunction example4Cb(cm: PeprMutateRequest<a.ConfigMap>) {\n cm.SetLabel("pepr.dev/first", "true");\n cm.SetLabel("pepr.dev/second", "true");\n cm.SetLabel("pepr.dev/third", "true");\n}\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 4a) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This is the same as Example 4, except this only operates on a CM in the `pepr-demo-2` namespace.\n * Note because the Capability defines namespaces, the namespace specified here must be one of those.\n * Alternatively, you can remove the namespace from the Capability definition and specify it here.\n */\nWhen(a.ConfigMap)\n .IsCreated()\n .InNamespace("pepr-demo-2")\n .WithName("example-4a")\n .Mutate(example4Cb);\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (CM Example 5) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This action is a bit more complex. It will look for any ConfigMap in the `pepr-demo`\n * namespace that has the label `chuck-norris` during CREATE. When it finds one, it will fetch a\n * random Chuck Norris joke from the API and add it to the ConfigMap. This is a great example of how\n * you can use Pepr to make changes to your K8s objects based on external data.\n *\n * Note the use of the `async` keyword. This is required for any action that uses `await` or `fetch()`.\n *\n * Also note we are passing a type to the `fetch()` function. This is optional, but it will help you\n * avoid mistakes when working with the data returned from the API. You can also use the `as` keyword to\n * cast the data returned from the API.\n *\n * These are equivalent:\n * ```ts\n * const joke = await fetch<TheChuckNorrisJoke>("https://api.chucknorris.io/jokes/random?category=dev");\n * const joke = await fetch("https://api.chucknorris.io/jokes/random?category=dev") as TheChuckNorrisJoke;\n * ```\n *\n * Alternatively, you can drop the type completely:\n *\n * ```ts\n * fetch("https://api.chucknorris.io/jokes/random?category=dev")\n * ```\n */\ninterface TheChuckNorrisJoke {\n icon_url: string;\n id: string;\n url: string;\n value: string;\n}\n\nWhen(a.ConfigMap)\n .IsCreated()\n .WithLabel("chuck-norris")\n .Mutate(async change => {\n // Try/catch is not needed as a response object will always be returned\n const response = await fetch<TheChuckNorrisJoke>(\n "https://api.chucknorris.io/jokes/random?category=dev",\n );\n\n // Instead, check the `response.ok` field\n if (response.ok) {\n // Add the Chuck Norris joke to the configmap\n change.Raw.data["chuck-says"] = response.data.value;\n return;\n }\n\n // You can also assert on different HTTP response codes\n if (response.status === fetchStatus.NOT_FOUND) {\n // Do something else\n return;\n }\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Secret Base64 Handling) *\n * ---------------------------------------------------------------------------------------------------\n *\n * The K8s JS client provides incomplete support for base64 encoding/decoding handling for secrets,\n * unlike the GO client. To make this less painful, Pepr automatically handles base64 encoding/decoding\n * secret data before and after the action is executed.\n */\nWhen(a.Secret)\n .IsCreated()\n .WithName("secret-1")\n .Mutate(request => {\n const secret = request.Raw;\n\n // This will be encoded at the end of all processing back to base64: "Y2hhbmdlLXdpdGhvdXQtZW5jb2Rpbmc="\n secret.data.magic = "change-without-encoding";\n\n // You can modify the data directly, and it will be encoded at the end of all processing\n secret.data.example += " - modified by Pepr";\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Untyped Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * Out of the box, Pepr supports all the standard Kubernetes objects. However, you can also create\n * your own types. This is useful if you are working with an Operator that creates custom resources.\n * There are two ways to do this, the first is to use the `When()` function with a `GenericKind`,\n * the second is to create a new class that extends `GenericKind` and use the `RegisterKind()` function.\n *\n * This example shows how to use the `When()` function with a `GenericKind`. Note that you\n * must specify the `group`, `version`, and `kind` of the object (if applicable). This is how Pepr knows\n * if the action should be triggered or not. Since we are using a `GenericKind`,\n * Pepr will not be able to provide any intellisense for the object, so you will need to refer to the\n * Kubernetes API documentation for the object you are working with.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-1\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```\n */\nWhen(a.GenericKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n})\n .IsCreated()\n .WithName("example-1")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr without type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * ---------------------------------------------------------------------------------------------------\n * Mutate Action (Typed Custom Resource) *\n * ---------------------------------------------------------------------------------------------------\n *\n * This example shows how to use the `RegisterKind()` function to create a new type. This is useful\n * if you are working with an Operator that creates custom resources and you want to have intellisense\n * for the object. Note that you must specify the `group`, `version`, and `kind` of the object (if applicable)\n * as this is how Pepr knows if the action should be triggered or not.\n *\n * Once you register a new Kind with Pepr, you can use the `When()` function with the new Kind. Ideally,\n * you should register custom Kinds at the top of your Capability file or Pepr Module so they are available\n * to all actions, but we are putting it here for demonstration purposes.\n *\n * You will need to wait for the CRD in `hello-pepr.samples.yaml` to be created, then you can apply\n *\n * ```yaml\n * apiVersion: pepr.dev/v1\n * kind: Unicorn\n * metadata:\n * name: example-2\n * namespace: pepr-demo\n * spec:\n * message: replace-me\n * counter: 0\n * ```*\n */\nclass UnicornKind extends a.GenericKind {\n spec: {\n /**\n * JSDoc comments can be added to explain more details about the field.\n *\n * @example\n * ```ts\n * request.Raw.spec.message = "Hello Pepr!";\n * ```\n * */\n message: string;\n counter: number;\n };\n}\n\nRegisterKind(UnicornKind, {\n group: "pepr.dev",\n version: "v1",\n kind: "Unicorn",\n});\n\nWhen(UnicornKind)\n .IsCreated()\n .WithName("example-2")\n .Mutate(request => {\n request.Merge({\n spec: {\n message: "Hello Pepr with type data!",\n counter: Math.random(),\n },\n });\n });\n\n/**\n * A callback function that is called once the Pepr Store is fully loaded.\n */\nStore.onReady(data => {\n Log.info(data, "Pepr Store Ready");\n});\n';
1360
- var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.24.1", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey:build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "git clone https://github.com/defenseunicorns/pepr-upgrade-test.git", "test:journey-wasm": "npm run test:journey:k3d && npm run test:journey:build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@types/ramda": "0.29.10", express: "4.18.2", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.1.0", pino: "8.18.0", "pino-pretty": "10.3.1", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "18.6.0", "@commitlint/config-conventional": "18.6.0", "@jest/globals": "29.7.0", "@types/eslint": "8.56.2", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.1", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
1401
+ var packageJSON = { name: "pepr", description: "Kubernetes application engine", author: "Defense Unicorns", homepage: "https://github.com/defenseunicorns/pepr", license: "Apache-2.0", bin: "dist/cli.js", repository: "defenseunicorns/pepr", engines: { node: ">=18.0.0" }, version: "0.26.0", main: "dist/lib.js", types: "dist/lib.d.ts", scripts: { "gen-data-json": "node hack/build-template-data.js", prebuild: "rm -fr dist/* && npm run gen-data-json", build: "tsc && node build.mjs", test: "npm run test:unit && npm run test:journey", "test:unit": "npm run gen-data-json && jest src --coverage --detectOpenHandles --coverageDirectory=./coverage", "test:journey": "npm run test:journey:k3d && npm run test:journey:build && npm run test:journey:image && npm run test:journey:run", "test:journey:prep": "git clone https://github.com/defenseunicorns/pepr-upgrade-test.git", "test:journey-wasm": "npm run test:journey:k3d && npm run test:journey:build && npm run test:journey:image && npm run test:journey:run-wasm", "test:journey:k3d": "k3d cluster delete pepr-dev && k3d cluster create pepr-dev --k3s-arg '--debug@server:0' --wait && kubectl rollout status deployment -n kube-system", "test:journey:build": "npm run build && npm pack", "test:journey:image": "docker buildx build --tag pepr:dev . && k3d image import pepr:dev -c pepr-dev", "test:journey:run": "jest --detectOpenHandles journey/entrypoint.test.ts && npm run test:journey:prep && npm run test:journey:upgrade", "test:journey:run-wasm": "jest --detectOpenHandles journey/entrypoint-wasm.test.ts", "test:journey:upgrade": "npm run test:journey:k3d && npm run test:journey:image && jest --detectOpenHandles journey/pepr-upgrade.test.ts", "format:check": "eslint src && prettier src --check", "format:fix": "eslint src --fix && prettier src --write" }, dependencies: { "@types/ramda": "0.29.10", express: "4.18.2", "fast-json-patch": "3.1.1", "kubernetes-fluent-client": "2.1.3", pino: "8.18.0", "pino-pretty": "10.3.1", "prom-client": "15.1.0", ramda: "0.29.1" }, devDependencies: { "@commitlint/cli": "18.6.1", "@commitlint/config-conventional": "18.6.2", "@jest/globals": "29.7.0", "@types/eslint": "8.56.2", "@types/express": "4.17.21", "@types/node": "18.x.x", "@types/node-forge": "1.3.11", "@types/prompts": "2.4.9", "@types/uuid": "9.0.8", jest: "29.7.0", nock: "13.5.1", "ts-jest": "29.1.2" }, peerDependencies: { "@typescript-eslint/eslint-plugin": "6.15.0", "@typescript-eslint/parser": "6.15.0", commander: "11.1.0", esbuild: "0.19.10", eslint: "8.56.0", "node-forge": "1.3.1", prettier: "3.1.1", prompts: "2.4.2", typescript: "5.3.3", uuid: "9.0.1" } };
1361
1402
 
1362
1403
  // src/templates/pepr.code-snippets.json
1363
1404
  var pepr_code_snippets_default = {
@@ -1463,6 +1504,10 @@ function genPkgJSON(opts, pgkVerOverride) {
1463
1504
  name: opts.name.trim(),
1464
1505
  uuid: pgkVerOverride ? "static-test" : uuid,
1465
1506
  onError: opts.errorBehavior,
1507
+ webhookTimeout: 10,
1508
+ customLabels: {
1509
+ namespace: {}
1510
+ },
1466
1511
  alwaysIgnore: {
1467
1512
  namespaces: [],
1468
1513
  labels: []
@@ -1585,18 +1630,30 @@ async function peprFormat(validateOnly) {
1585
1630
  }
1586
1631
 
1587
1632
  // src/cli/build.ts
1588
- var import_commander = require("commander");
1633
+ var import_commander2 = require("commander");
1589
1634
  var peprTS2 = "pepr.ts";
1590
1635
  var outputDir = "dist";
1591
1636
  function build_default(program2) {
1592
1637
  program2.command("build").description("Build a Pepr Module for deployment").option("-e, --entry-point [file]", "Specify the entry point file to build with.", peprTS2).option(
1593
1638
  "-n, --no-embed",
1594
1639
  "Disables embedding of deployment files into output module. Useful when creating library modules intended solely for reuse/distribution via NPM."
1640
+ ).option(
1641
+ "-i, --custom-image [custom-image]",
1642
+ "Custom Image: Use custom image for Admission and Watch Deployments."
1595
1643
  ).option(
1596
1644
  "-r, --registry-info [<registry>/<username>]",
1597
1645
  "Registry Info: Image registry and username. Note: You must be signed into the registry"
1598
- ).option("-o, --output-dir [output directory]", "Define where to place build output").addOption(
1599
- new import_commander.Option("--rbac-mode [admin|scoped]", "Rbac Mode: admin, scoped (default: admin)").choices(["admin", "scoped"]).default("admin")
1646
+ ).option("-o, --output-dir [output directory]", "Define where to place build output").option(
1647
+ "--timeout [timeout]",
1648
+ "How long the API server should wait for a webhook to respond before treating the call as a failure",
1649
+ parseTimeout
1650
+ ).addOption(
1651
+ new import_commander2.Option(
1652
+ "--registry <GitHub|Iron Bank>",
1653
+ "Container registry: Choose container registry for deployment manifests. Can't be used with --custom-image."
1654
+ ).choices(["GitHub", "Iron Bank"])
1655
+ ).addOption(
1656
+ new import_commander2.Option("--rbac-mode [admin|scoped]", "Rbac Mode: admin, scoped (default: admin)").choices(["admin", "scoped"]).default("admin")
1600
1657
  ).action(async (opts) => {
1601
1658
  if (opts.outputDir) {
1602
1659
  outputDir = opts.outputDir;
@@ -1608,11 +1665,21 @@ function build_default(program2) {
1608
1665
  const { cfg, path, uuid } = await buildModule(void 0, opts.entryPoint, opts.embed);
1609
1666
  const { includedFiles } = cfg.pepr;
1610
1667
  let image = "";
1668
+ if (opts.customImage) {
1669
+ if (opts.registry) {
1670
+ console.error(`Custom Image and registry cannot be used together.`);
1671
+ process.exit(1);
1672
+ }
1673
+ image = opts.customImage;
1674
+ }
1675
+ if (opts.timeout !== void 0) {
1676
+ cfg.pepr.webhookTimeout = opts.timeout;
1677
+ }
1611
1678
  if (opts.registryInfo !== void 0) {
1612
1679
  console.info(`Including ${includedFiles.length} files in controller image.`);
1613
- image = `${opts.registryInfo}/custom-pepr-controller:${cfg.dependencies.pepr}`;
1680
+ image = `${opts.registryInfo}/custom-pepr-controller:${cfg.pepr.peprVersion}`;
1614
1681
  if (includedFiles.length > 0) {
1615
- await createDockerfile(cfg.dependencies.pepr, cfg.description, includedFiles);
1682
+ await createDockerfile(cfg.pepr.peprVersion, cfg.description, includedFiles);
1616
1683
  (0, import_child_process2.execSync)(`docker build --tag ${image} -f Dockerfile.controller .`, { stdio: "inherit" });
1617
1684
  (0, import_child_process2.execSync)(`docker push ${image}`, { stdio: "inherit" });
1618
1685
  }
@@ -1629,6 +1696,14 @@ function build_default(program2) {
1629
1696
  },
1630
1697
  path
1631
1698
  );
1699
+ if (opts?.registry == "Iron Bank") {
1700
+ console.warn(
1701
+ `
1702
+ This command assumes the latest release. Pepr's Iron Bank image release cycle is dictated by renovate and is typically released a few days after the GitHub release.
1703
+ As an alternative you may consider custom --custom-image to target a specific image and version.`
1704
+ );
1705
+ image = `registry1.dso.mil/ironbank/opensource/defenseunicorns/pepr/controller:${cfg.pepr.peprVersion}`;
1706
+ }
1632
1707
  if (image !== "") {
1633
1708
  assets.image = image;
1634
1709
  }
@@ -2080,12 +2155,38 @@ function init_default(program2) {
2080
2155
  });
2081
2156
  }
2082
2157
 
2158
+ // src/cli/uuid.ts
2159
+ var import_kubernetes_fluent_client5 = require("kubernetes-fluent-client");
2160
+ function uuid_default(program2) {
2161
+ program2.command("uuid [uuid]").description("Module UUID(s) currently deployed in the cluster").action(async (uuid) => {
2162
+ const uuidTable = {};
2163
+ let deployments;
2164
+ if (!uuid) {
2165
+ deployments = await (0, import_kubernetes_fluent_client5.K8s)(import_kubernetes_fluent_client5.kind.Deployment).InNamespace("pepr-system").WithLabel("pepr.dev/uuid").Get();
2166
+ } else {
2167
+ deployments = await (0, import_kubernetes_fluent_client5.K8s)(import_kubernetes_fluent_client5.kind.Deployment).InNamespace("pepr-system").WithLabel("pepr.dev/uuid", uuid).Get();
2168
+ }
2169
+ deployments.items.map((deploy2) => {
2170
+ const uuid2 = deploy2.metadata?.labels?.["pepr.dev/uuid"] || "";
2171
+ const description = deploy2.metadata?.annotations?.["pepr.dev/description"] || "";
2172
+ if (uuid2 !== "") {
2173
+ uuidTable[uuid2] = description;
2174
+ }
2175
+ });
2176
+ console.log("UUID Description");
2177
+ console.log("--------------------------------------------");
2178
+ Object.entries(uuidTable).forEach(([uuid2, description]) => {
2179
+ console.log(`${uuid2} ${description}`);
2180
+ });
2181
+ });
2182
+ }
2183
+
2083
2184
  // src/cli/root.ts
2084
- var import_commander2 = require("commander");
2085
- var RootCmd = class extends import_commander2.Command {
2185
+ var import_commander3 = require("commander");
2186
+ var RootCmd = class extends import_commander3.Command {
2086
2187
  // eslint-disable-next-line class-methods-use-this
2087
2188
  createCommand(name2) {
2088
- const cmd = new import_commander2.Command(name2);
2189
+ const cmd = new import_commander3.Command(name2);
2089
2190
  cmd.option("-l, --log-level [level]", "Log level: debug, info, warn, error", "info");
2090
2191
  cmd.hook("preAction", (run) => {
2091
2192
  logger_default.level = run.opts().logLevel;
@@ -2175,4 +2276,5 @@ dev_default(program);
2175
2276
  update_default(program);
2176
2277
  format_default(program);
2177
2278
  monitor_default(program);
2279
+ uuid_default(program);
2178
2280
  program.parse();