pepr 0.40.0 → 0.42.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 (78) hide show
  1. package/README.md +11 -5
  2. package/dist/cli/build.d.ts.map +1 -1
  3. package/dist/cli/deploy.d.ts.map +1 -1
  4. package/dist/cli/init/templates.d.ts +2 -2
  5. package/dist/cli.js +228 -179
  6. package/dist/controller.js +52 -27
  7. package/dist/lib/assets/index.d.ts.map +1 -1
  8. package/dist/lib/capability.d.ts.map +1 -1
  9. package/dist/lib/controller/index.d.ts.map +1 -1
  10. package/dist/lib/controller/index.util.d.ts +10 -0
  11. package/dist/lib/controller/index.util.d.ts.map +1 -0
  12. package/dist/lib/controller/store.d.ts +1 -1
  13. package/dist/lib/deploymentChecks.d.ts +3 -0
  14. package/dist/lib/deploymentChecks.d.ts.map +1 -0
  15. package/dist/lib/enums.d.ts +5 -5
  16. package/dist/lib/enums.d.ts.map +1 -1
  17. package/dist/lib/filesystemService.d.ts +2 -0
  18. package/dist/lib/filesystemService.d.ts.map +1 -0
  19. package/dist/lib/filter/adjudicators/adjudicators.d.ts +73 -0
  20. package/dist/lib/filter/adjudicators/adjudicators.d.ts.map +1 -0
  21. package/dist/lib/filter/adjudicators/defaultTestObjects.d.ts +7 -0
  22. package/dist/lib/filter/adjudicators/defaultTestObjects.d.ts.map +1 -0
  23. package/dist/lib/helpers.d.ts +1 -4
  24. package/dist/lib/helpers.d.ts.map +1 -1
  25. package/dist/lib/schedule.d.ts.map +1 -1
  26. package/dist/lib/storage.d.ts +1 -1
  27. package/dist/lib/storage.d.ts.map +1 -1
  28. package/dist/lib/{logger.d.ts → telemetry/logger.d.ts} +1 -1
  29. package/dist/lib/telemetry/logger.d.ts.map +1 -0
  30. package/dist/lib/{metrics.d.ts → telemetry/metrics.d.ts} +3 -1
  31. package/dist/lib/telemetry/metrics.d.ts.map +1 -0
  32. package/dist/lib/types.d.ts +10 -9
  33. package/dist/lib/types.d.ts.map +1 -1
  34. package/dist/lib.d.ts +1 -1
  35. package/dist/lib.d.ts.map +1 -1
  36. package/dist/lib.js +151 -126
  37. package/dist/lib.js.map +4 -4
  38. package/dist/sdk/sdk.d.ts +3 -4
  39. package/dist/sdk/sdk.d.ts.map +1 -1
  40. package/package.json +5 -5
  41. package/src/cli/build.ts +2 -1
  42. package/src/cli/deploy.ts +2 -1
  43. package/src/cli/init/templates.ts +1 -1
  44. package/src/lib/assets/deploy.ts +1 -1
  45. package/src/lib/assets/destroy.ts +1 -1
  46. package/src/lib/assets/index.ts +102 -81
  47. package/src/lib/assets/webhooks.ts +2 -2
  48. package/src/lib/capability.ts +8 -9
  49. package/src/lib/controller/index.ts +32 -62
  50. package/src/lib/controller/index.util.ts +47 -0
  51. package/src/lib/controller/store.ts +2 -2
  52. package/src/lib/controller/storeCache.ts +1 -1
  53. package/src/lib/deploymentChecks.ts +43 -0
  54. package/src/lib/enums.ts +5 -5
  55. package/src/lib/filesystemService.ts +16 -0
  56. package/src/lib/filter/{adjudicators.ts → adjudicators/adjudicators.ts} +67 -35
  57. package/src/lib/filter/adjudicators/defaultTestObjects.ts +46 -0
  58. package/src/lib/filter/filter.ts +1 -1
  59. package/src/lib/finalizer.ts +1 -1
  60. package/src/lib/helpers.ts +31 -88
  61. package/src/lib/mutate-processor.ts +1 -1
  62. package/src/lib/queue.ts +1 -1
  63. package/src/lib/schedule.ts +8 -8
  64. package/src/lib/storage.ts +17 -17
  65. package/src/lib/{logger.ts → telemetry/logger.ts} +1 -1
  66. package/src/lib/{metrics.ts → telemetry/metrics.ts} +18 -17
  67. package/src/lib/types.ts +12 -9
  68. package/src/lib/utils.ts +1 -1
  69. package/src/lib/validate-processor.ts +1 -1
  70. package/src/lib/watch-processor.ts +8 -8
  71. package/src/lib.ts +1 -1
  72. package/src/runtime/controller.ts +1 -1
  73. package/src/sdk/sdk.ts +6 -9
  74. package/src/templates/capabilities/hello-pepr.ts +19 -9
  75. package/dist/lib/filter/adjudicators.d.ts +0 -69
  76. package/dist/lib/filter/adjudicators.d.ts.map +0 -1
  77. package/dist/lib/logger.d.ts.map +0 -1
  78. package/dist/lib/metrics.d.ts.map +0 -1
package/dist/lib.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib.ts", "../src/lib/capability.ts", "../src/lib/logger.ts", "../src/lib/module.ts", "../src/lib/controller/index.ts", "../src/lib/metrics.ts", "../src/lib/mutate-processor.ts", "../src/lib/errors.ts", "../src/lib/filter/adjudicators.ts", "../src/lib/filter/filter.ts", "../src/lib/mutate-request.ts", "../src/lib/utils.ts", "../src/lib/validate-request.ts", "../src/lib/validate-processor.ts", "../src/lib/controller/store.ts", "../src/lib/k8s.ts", "../src/lib/controller/storeCache.ts", "../src/lib/watch-processor.ts", "../src/lib/helpers.ts", "../src/sdk/sdk.ts", "../src/lib/finalizer.ts", "../src/lib/queue.ts", "../src/lib/storage.ts", "../src/lib/schedule.ts"],
4
- "sourcesContent": ["import { K8s, RegisterKind, kind as a, fetch, fetchStatus, kind } from \"kubernetes-fluent-client\";\nimport * as R from \"ramda\";\n\nimport { Capability } from \"./lib/capability\";\nimport Log from \"./lib/logger\";\nimport { PeprModule } from \"./lib/module\";\nimport { PeprMutateRequest } from \"./lib/mutate-request\";\nimport * as PeprUtils from \"./lib/utils\";\nimport { PeprValidateRequest } from \"./lib/validate-request\";\nimport * as sdk from \"./sdk/sdk\";\n\nexport {\n Capability,\n K8s,\n Log,\n PeprModule,\n PeprMutateRequest,\n PeprUtils,\n PeprValidateRequest,\n R,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n sdk,\n};\n", "/* eslint-disable max-statements */\n// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { GenericClass, GroupVersionKind, modelToGroupVersionKind } from \"kubernetes-fluent-client\";\nimport { pickBy } from \"ramda\";\nimport Log from \"./logger\";\nimport { isBuildMode, isDevMode, isWatchMode } from \"./module\";\nimport { PeprStore, Storage } from \"./storage\";\nimport { OnSchedule, Schedule } from \"./schedule\";\nimport { Event } from \"./enums\";\nimport {\n Binding,\n BindingFilter,\n BindingWithName,\n CapabilityCfg,\n CapabilityExport,\n MutateAction,\n MutateActionChain,\n ValidateAction,\n ValidateActionChain,\n WatchLogAction,\n FinalizeAction,\n FinalizeActionChain,\n WhenSelector,\n} from \"./types\";\nimport { addFinalizer } from \"./finalizer\";\n\nconst registerAdmission = isBuildMode() || !isWatchMode();\nconst registerWatch = isBuildMode() || isWatchMode() || isDevMode();\n\n/**\n * A capability is a unit of functionality that can be registered with the Pepr runtime.\n */\nexport class Capability implements CapabilityExport {\n #name: string;\n #description: string;\n #namespaces?: string[] | undefined;\n #bindings: Binding[] = [];\n #store = new Storage();\n #scheduleStore = new Storage();\n #registered = false;\n #scheduleRegistered = false;\n hasSchedule: boolean;\n\n /**\n * Run code on a schedule with the capability.\n *\n * @param schedule The schedule to run the code on\n * @returns\n */\n OnSchedule: (schedule: Schedule) => void = (schedule: Schedule) => {\n const { name, every, unit, run, startTime, completions } = schedule;\n this.hasSchedule = true;\n\n if (process.env.PEPR_WATCH_MODE === \"true\" || process.env.PEPR_MODE === \"dev\") {\n // Only create/watch schedule store if necessary\n\n // Create a new schedule\n const newSchedule: Schedule = {\n name,\n every,\n unit,\n run,\n startTime,\n completions,\n };\n\n this.#scheduleStore.onReady(() => {\n new OnSchedule(newSchedule).setStore(this.#scheduleStore);\n });\n }\n };\n\n public getScheduleStore() {\n return this.#scheduleStore;\n }\n\n /**\n * Store is a key-value data store that can be used to persist data that should be shared\n * between requests. Each capability has its own store, and the data is persisted in Kubernetes\n * in the `pepr-system` namespace.\n *\n * Note: You should only access the store from within an action.\n */\n Store: PeprStore = {\n clear: this.#store.clear,\n getItem: this.#store.getItem,\n removeItem: this.#store.removeItem,\n removeItemAndWait: this.#store.removeItemAndWait,\n setItem: this.#store.setItem,\n subscribe: this.#store.subscribe,\n onReady: this.#store.onReady,\n setItemAndWait: this.#store.setItemAndWait,\n };\n\n /**\n * ScheduleStore is a key-value data store used to persist schedule data that should be shared\n * between intervals. Each Schedule shares store, and the data is persisted in Kubernetes\n * in the `pepr-system` namespace.\n *\n * Note: There is no direct access to schedule store\n */\n ScheduleStore: PeprStore = {\n clear: this.#scheduleStore.clear,\n getItem: this.#scheduleStore.getItem,\n removeItemAndWait: this.#scheduleStore.removeItemAndWait,\n removeItem: this.#scheduleStore.removeItem,\n setItemAndWait: this.#scheduleStore.setItemAndWait,\n setItem: this.#scheduleStore.setItem,\n subscribe: this.#scheduleStore.subscribe,\n onReady: this.#scheduleStore.onReady,\n };\n\n get bindings() {\n return this.#bindings;\n }\n\n get name() {\n return this.#name;\n }\n\n get description() {\n return this.#description;\n }\n\n get namespaces() {\n return this.#namespaces || [];\n }\n\n constructor(cfg: CapabilityCfg) {\n this.#name = cfg.name;\n this.#description = cfg.description;\n this.#namespaces = cfg.namespaces;\n this.hasSchedule = false;\n\n Log.info(`Capability ${this.#name} registered`);\n Log.debug(cfg);\n }\n\n /**\n * Register the store with the capability. This is called automatically by the Pepr controller.\n */\n registerScheduleStore = (): Storage => {\n Log.info(`Registering schedule store for ${this.#name}`);\n\n if (this.#scheduleRegistered) {\n throw new Error(`Schedule store already registered for ${this.#name}`);\n }\n\n this.#scheduleRegistered = true;\n\n // Pass back any ready callback to the controller\n return this.#scheduleStore;\n };\n\n /**\n * Register the store with the capability. This is called automatically by the Pepr controller.\n *\n * @param store\n */\n registerStore = (): Storage => {\n Log.info(`Registering store for ${this.#name}`);\n\n if (this.#registered) {\n throw new Error(`Store already registered for ${this.#name}`);\n }\n\n this.#registered = true;\n\n // Pass back any ready callback to the controller\n return this.#store;\n };\n\n /**\n * The When method is used to register a action to be executed when a Kubernetes resource is\n * processed by Pepr. The action will be executed if the resource matches the specified kind and any\n * filters that are applied.\n *\n * @param model the KubernetesObject model to match\n * @param kind if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind\n * @returns\n */\n When = <T extends GenericClass>(model: T, kind?: GroupVersionKind): WhenSelector<T> => {\n const matchedKind = modelToGroupVersionKind(model.name);\n\n // If the kind is not specified and the model is not a KubernetesObject, throw an error\n if (!matchedKind && !kind) {\n throw new Error(`Kind not specified for ${model.name}`);\n }\n\n const binding: Binding = {\n model,\n // If the kind is not specified, use the matched kind from the model\n kind: kind || matchedKind,\n event: Event.Any,\n filters: {\n name: \"\",\n namespaces: [],\n regexNamespaces: [],\n regexName: \"\",\n labels: {},\n annotations: {},\n deletionTimestamp: false,\n },\n };\n\n const bindings = this.#bindings;\n const prefix = `${this.#name}: ${model.name}`;\n const commonChain = { WithLabel, WithAnnotation, WithDeletionTimestamp, Mutate, Validate, Watch, Reconcile, Alias };\n const isNotEmpty = (value: object) => Object.keys(value).length > 0;\n const log = (message: string, cbString: string) => {\n const filteredObj = pickBy(isNotEmpty, binding.filters);\n\n Log.info(`${message} configured for ${binding.event}`, prefix);\n Log.info(filteredObj, prefix);\n Log.debug(cbString, prefix);\n };\n\n function Validate(validateCallback: ValidateAction<T>): ValidateActionChain<T> {\n if (registerAdmission) {\n log(\"Validate Action\", validateCallback.toString());\n\n // Create the child logger\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" });\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isValidate: true,\n validateCallback: async (req, logger = aliasLogger) => {\n Log.info(`Executing validate action with alias: ${binding.alias || \"no alias provided\"}`);\n return await validateCallback(req, logger);\n },\n });\n }\n\n return { Watch, Reconcile };\n }\n\n function Mutate(mutateCallback: MutateAction<T>): MutateActionChain<T> {\n if (registerAdmission) {\n log(\"Mutate Action\", mutateCallback.toString());\n\n // Create the child logger\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" });\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isMutate: true,\n mutateCallback: async (req, logger = aliasLogger) => {\n Log.info(`Executing mutation action with alias: ${binding.alias || \"no alias provided\"}`);\n await mutateCallback(req, logger);\n },\n });\n }\n\n // Now only allow adding actions to the same binding\n return { Watch, Validate, Reconcile };\n }\n\n function Watch(watchCallback: WatchLogAction<T>): FinalizeActionChain<T> {\n if (registerWatch) {\n log(\"Watch Action\", watchCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isWatch: true,\n watchCallback: async (update, phase, logger = aliasLogger) => {\n Log.info(`Executing watch action with alias: ${binding.alias || \"no alias provided\"}`);\n await watchCallback(update, phase, logger);\n },\n });\n }\n return { Finalize };\n }\n\n function Reconcile(reconcileCallback: WatchLogAction<T>): FinalizeActionChain<T> {\n if (registerWatch) {\n log(\"Reconcile Action\", reconcileCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isWatch: true,\n isQueue: true,\n watchCallback: async (update, phase, logger = aliasLogger) => {\n Log.info(`Executing reconcile action with alias: ${binding.alias || \"no alias provided\"}`);\n await reconcileCallback(update, phase, logger);\n },\n });\n }\n return { Finalize };\n }\n\n function Finalize(finalizeCallback: FinalizeAction<T>): void {\n log(\"Finalize Action\", finalizeCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Add binding to inject Pepr finalizer during admission (Mutate)\n if (registerAdmission) {\n const mutateBinding = {\n ...binding,\n isMutate: true,\n isFinalize: true,\n event: Event.Any,\n mutateCallback: addFinalizer,\n };\n bindings.push(mutateBinding);\n }\n\n // Add binding to process finalizer callback / remove Pepr finalizer (Watch)\n if (registerWatch) {\n const watchBinding = {\n ...binding,\n isWatch: true,\n isFinalize: true,\n event: Event.Update,\n finalizeCallback: async (update: InstanceType<T>, logger = aliasLogger) => {\n Log.info(`Executing finalize action with alias: ${binding.alias || \"no alias provided\"}`);\n return await finalizeCallback(update, logger);\n },\n };\n bindings.push(watchBinding);\n }\n }\n\n function InNamespace(...namespaces: string[]): BindingWithName<T> {\n Log.debug(`Add namespaces filter ${namespaces}`, prefix);\n binding.filters.namespaces.push(...namespaces);\n return { ...commonChain, WithName, WithNameRegex };\n }\n\n function InNamespaceRegex(...namespaces: RegExp[]): BindingWithName<T> {\n Log.debug(`Add regex namespaces filter ${namespaces}`, prefix);\n binding.filters.regexNamespaces.push(...namespaces.map(regex => regex.source));\n return { ...commonChain, WithName, WithNameRegex };\n }\n\n function WithDeletionTimestamp(): BindingFilter<T> {\n Log.debug(\"Add deletionTimestamp filter\");\n binding.filters.deletionTimestamp = true;\n return commonChain;\n }\n\n function WithNameRegex(regexName: RegExp): BindingFilter<T> {\n Log.debug(`Add regex name filter ${regexName}`, prefix);\n binding.filters.regexName = regexName.source;\n return commonChain;\n }\n\n function WithName(name: string): BindingFilter<T> {\n Log.debug(`Add name filter ${name}`, prefix);\n binding.filters.name = name;\n return commonChain;\n }\n\n function WithLabel(key: string, value = \"\"): BindingFilter<T> {\n Log.debug(`Add label filter ${key}=${value}`, prefix);\n binding.filters.labels[key] = value;\n return commonChain;\n }\n\n function WithAnnotation(key: string, value = \"\"): BindingFilter<T> {\n Log.debug(`Add annotation filter ${key}=${value}`, prefix);\n binding.filters.annotations[key] = value;\n return commonChain;\n }\n\n function Alias(alias: string) {\n Log.debug(`Adding prefix alias ${alias}`, prefix);\n binding.alias = alias;\n return commonChain;\n }\n\n function bindEvent(event: Event) {\n binding.event = event;\n return {\n ...commonChain,\n InNamespace,\n InNamespaceRegex,\n WithName,\n WithNameRegex,\n WithDeletionTimestamp,\n Alias,\n };\n }\n\n return {\n IsCreatedOrUpdated: () => bindEvent(Event.CreateOrUpdate),\n IsCreated: () => bindEvent(Event.Create),\n IsUpdated: () => bindEvent(Event.Update),\n IsDeleted: () => bindEvent(Event.Delete),\n };\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Operation } from \"fast-json-patch\";\nimport { pino, stdTimeFunctions } from \"pino\";\nimport { Store } from \"./k8s\";\n\nconst isPrettyLog = process.env.PEPR_PRETTY_LOGS === \"true\";\nconst redactedValue = \"**redacted**\";\n\nconst pretty = {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n};\n\nconst transport = isPrettyLog ? pretty : undefined;\n// epochTime is the pino default\nconst pinoTimeFunction =\n process.env.PINO_TIME_STAMP === \"iso\" ? () => stdTimeFunctions.isoTime() : () => stdTimeFunctions.epochTime();\nconst Log = pino({\n transport,\n timestamp: pinoTimeFunction,\n});\n\nif (process.env.LOG_LEVEL) {\n Log.level = process.env.LOG_LEVEL;\n}\n\nexport function redactedStore(store: Store): Store {\n const redacted = process.env.PEPR_STORE_REDACT_VALUES === \"true\";\n return {\n ...store,\n data: Object.keys(store.data).reduce((acc: Record<string, string>, key: string) => {\n acc[key] = redacted ? redactedValue : store.data[key];\n return acc;\n }, {}),\n };\n}\n\nexport function redactedPatch(patch: Record<string, Operation> = {}): Record<string, Operation> {\n const redacted = process.env.PEPR_STORE_REDACT_VALUES === \"true\";\n\n if (!redacted) {\n return patch;\n }\n\n const redactedCache: Record<string, Operation> = {};\n\n Object.entries(patch).forEach(([key, operation]) => {\n const isRedacted = key.includes(\":\");\n const targetKey = isRedacted ? `${key.substring(0, key.lastIndexOf(\":\"))}:**redacted**` : key;\n\n const redactedOperation = isRedacted\n ? {\n ...operation,\n ...(Object.hasOwn(operation, \"value\") ? { value: redactedValue } : {}),\n }\n : operation;\n\n redactedCache[targetKey] = redactedOperation;\n });\n\n return redactedCache;\n}\n\nexport default Log;\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { clone } from \"ramda\";\nimport { Capability } from \"./capability\";\nimport { Controller } from \"./controller\";\nimport { ValidateError } from \"./errors\";\nimport { MutateResponse, ValidateResponse, WebhookIgnore } from \"./k8s\";\nimport { CapabilityExport, AdmissionRequest } from \"./types\";\nimport { setupWatch } from \"./watch-processor\";\nimport { Log } from \"../lib\";\nimport { V1PolicyRule as PolicyRule } from \"@kubernetes/client-node\";\n\n/** Custom Labels Type for package.json */\nexport interface CustomLabels {\n namespace?: Record<string, string>;\n}\n/** Global configuration for the Pepr runtime. */\nexport type ModuleConfig = {\n /** The Pepr version this module uses */\n peprVersion?: string;\n /** The user-defined version of the module */\n appVersion?: string;\n /** A unique identifier for this Pepr module. This is automatically generated by Pepr. */\n uuid: string;\n /** A description of the Pepr module and what it does. */\n description?: string;\n /** The webhookTimeout */\n webhookTimeout?: number;\n /** Reject K8s resource AdmissionRequests on error. */\n onError?: string;\n /** Configure global exclusions that will never be processed by Pepr. */\n alwaysIgnore: WebhookIgnore;\n /** Define the log level for the in-cluster controllers */\n logLevel?: string;\n /** Propagate env variables to in-cluster controllers */\n env?: Record<string, string>;\n /** Custom Labels for Kubernetes Objects */\n customLabels?: CustomLabels;\n /** Custom RBAC rules */\n rbac?: PolicyRule[];\n /** The RBAC mode; if \"scoped\", generates scoped rules, otherwise uses wildcard rules. */\n rbacMode?: string;\n};\n\nexport type PackageJSON = {\n description: string;\n pepr: ModuleConfig;\n};\n\nexport type PeprModuleOptions = {\n deferStart?: boolean;\n\n /** A user-defined callback to pre-process or intercept a Pepr request from K8s immediately before it is processed */\n beforeHook?: (req: AdmissionRequest) => void;\n\n /** A user-defined callback to post-process or intercept a Pepr response just before it is returned to K8s */\n afterHook?: (res: MutateResponse | ValidateResponse) => void;\n};\n\n// Track if this is a watch mode controller\nexport const isWatchMode = () => process.env.PEPR_WATCH_MODE === \"true\";\n\n// Track if Pepr is running in build mode\nexport const isBuildMode = () => process.env.PEPR_MODE === \"build\";\n\nexport const isDevMode = () => process.env.PEPR_MODE === \"dev\";\n\nexport class PeprModule {\n #controller!: Controller;\n\n /**\n * Create a new Pepr runtime\n *\n * @param config The configuration for the Pepr runtime\n * @param capabilities The capabilities to be loaded into the Pepr runtime\n * @param opts Options for the Pepr runtime\n */\n constructor({ description, pepr }: PackageJSON, capabilities: Capability[] = [], opts: PeprModuleOptions = {}) {\n const config: ModuleConfig = clone(pepr);\n config.description = description;\n\n // Need to validate at runtime since TS gets sad about parsing the package.json\n ValidateError(config.onError);\n\n // Handle build mode\n if (isBuildMode()) {\n // Fail if process.send is not defined\n if (!process.send) {\n throw new Error(\"process.send is not defined\");\n }\n\n const exportedCapabilities: CapabilityExport[] = [];\n\n // Send capability map to parent process\n for (const capability of capabilities) {\n // Convert the capability to a capability config\n exportedCapabilities.push({\n name: capability.name,\n description: capability.description,\n namespaces: capability.namespaces,\n bindings: capability.bindings,\n hasSchedule: capability.hasSchedule,\n });\n }\n\n // Send the capabilities back to the parent process\n process.send(exportedCapabilities);\n\n return;\n }\n\n this.#controller = new Controller(config, capabilities, opts.beforeHook, opts.afterHook, () => {\n // Wait for the controller to be ready before setting up watches\n if (isWatchMode() || isDevMode()) {\n try {\n setupWatch(capabilities, pepr?.alwaysIgnore?.namespaces);\n } catch (e) {\n Log.error(e, \"Error setting up watch\");\n process.exit(1);\n }\n }\n });\n\n // Stop processing if deferStart is set to true\n if (opts.deferStart) {\n return;\n }\n\n this.start();\n }\n\n /**\n * Start the Pepr runtime manually.\n * Normally this is called automatically when the Pepr module is instantiated, but can be called manually if `deferStart` is set to `true` in the constructor.\n *\n * @param port\n */\n start = (port = 3000) => {\n this.#controller.startServer(port);\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport express, { NextFunction } from \"express\";\nimport fs from \"fs\";\nimport https from \"https\";\n\nimport { Capability } from \"../capability\";\nimport { MutateResponse, ValidateResponse } from \"../k8s\";\nimport Log from \"../logger\";\nimport { metricsCollector, MetricsCollector } from \"../metrics\";\nimport { ModuleConfig, isWatchMode } from \"../module\";\nimport { mutateProcessor } from \"../mutate-processor\";\nimport { validateProcessor } from \"../validate-processor\";\nimport { StoreController } from \"./store\";\nimport { ResponseItem, AdmissionRequest } from \"../types\";\n\nif (!process.env.PEPR_NODE_WARNINGS) {\n process.removeAllListeners(\"warning\");\n}\nexport class Controller {\n // Track whether the server is running\n #running = false;\n\n // Metrics collector\n #metricsCollector = metricsCollector;\n\n // The token used to authenticate requests\n #token = \"\";\n\n // The express app instance\n readonly #app = express();\n\n // Initialized with the constructor\n readonly #config: ModuleConfig;\n readonly #capabilities: Capability[];\n readonly #beforeHook?: (req: AdmissionRequest) => void;\n readonly #afterHook?: (res: MutateResponse | ValidateResponse) => void;\n\n constructor(\n config: ModuleConfig,\n capabilities: Capability[],\n beforeHook?: (req: AdmissionRequest) => void,\n afterHook?: (res: MutateResponse | ValidateResponse) => void,\n onReady?: () => void,\n ) {\n this.#config = config;\n this.#capabilities = capabilities;\n\n // Initialize the Pepr store for each capability\n new StoreController(capabilities, `pepr-${config.uuid}-store`, () => {\n this.#bindEndpoints();\n onReady && onReady();\n Log.info(\"\u2705 Controller startup complete\");\n // Initialize the schedule store for each capability\n new StoreController(capabilities, `pepr-${config.uuid}-schedule`, () => {\n Log.info(\"\u2705 Scheduling processed\");\n });\n });\n\n // Middleware for logging requests\n this.#app.use(Controller.#logger);\n\n // Middleware for parsing JSON, limit to 2mb vs 100K for K8s compatibility\n this.#app.use(express.json({ limit: \"2mb\" }));\n\n if (beforeHook) {\n Log.info(`Using beforeHook: ${beforeHook}`);\n this.#beforeHook = beforeHook;\n }\n\n if (afterHook) {\n Log.info(`Using afterHook: ${afterHook}`);\n this.#afterHook = afterHook;\n }\n }\n\n /** Start the webhook server */\n startServer = (port: number) => {\n if (this.#running) {\n throw new Error(\"Cannot start Pepr module: Pepr module was not instantiated with deferStart=true\");\n }\n\n // Load SSL certificate and key\n const options = {\n key: fs.readFileSync(process.env.SSL_KEY_PATH || \"/etc/certs/tls.key\"),\n cert: fs.readFileSync(process.env.SSL_CERT_PATH || \"/etc/certs/tls.crt\"),\n };\n\n // Get the API token if not in watch mode\n if (!isWatchMode()) {\n // Get the API token from the environment variable or the mounted secret\n this.#token = process.env.PEPR_API_TOKEN || fs.readFileSync(\"/app/api-token/value\").toString().trim();\n Log.info(`Using API token: ${this.#token}`);\n\n if (!this.#token) {\n throw new Error(\"API token not found\");\n }\n }\n\n // Create HTTPS server\n const server = https.createServer(options, this.#app).listen(port);\n\n // Handle server listening event\n server.on(\"listening\", () => {\n Log.info(`Server listening on port ${port}`);\n // Track that the server is running\n this.#running = true;\n });\n\n // Handle EADDRINUSE errors\n server.on(\"error\", (e: { code: string }) => {\n if (e.code === \"EADDRINUSE\") {\n Log.info(\n `Address in use, retrying in 2 seconds. If this persists, ensure ${port} is not in use, e.g. \"lsof -i :${port}\"`,\n );\n setTimeout(() => {\n server.close();\n server.listen(port);\n }, 2000);\n }\n });\n\n // Listen for the SIGTERM signal and gracefully close the server\n process.on(\"SIGTERM\", () => {\n Log.info(\"Received SIGTERM, closing server\");\n server.close(() => {\n Log.info(\"Server closed\");\n process.exit(0);\n });\n });\n };\n\n #bindEndpoints = () => {\n // Health check endpoint\n this.#app.get(\"/healthz\", Controller.#healthz);\n\n // Metrics endpoint\n this.#app.get(\"/metrics\", this.#metrics);\n\n if (isWatchMode()) {\n return;\n }\n\n // Require auth for webhook endpoints\n this.#app.use([\"/mutate/:token\", \"/validate/:token\"], this.#validateToken);\n\n // Mutate endpoint\n this.#app.post(\"/mutate/:token\", this.#admissionReq(\"Mutate\"));\n\n // Validate endpoint\n this.#app.post(\"/validate/:token\", this.#admissionReq(\"Validate\"));\n };\n\n /**\n * Validate the token in the request path\n *\n * @param req The incoming request\n * @param res The outgoing response\n * @param next The next middleware function\n * @returns\n */\n #validateToken = (req: express.Request, res: express.Response, next: NextFunction) => {\n // Validate the token\n const { token } = req.params;\n if (token !== this.#token) {\n const err = `Unauthorized: invalid token '${token.replace(/[^\\w]/g, \"_\")}'`;\n Log.info(err);\n res.status(401).send(err);\n this.#metricsCollector.alert();\n return;\n }\n\n // Token is valid, continue\n next();\n };\n\n /**\n * Metrics endpoint handler\n *\n * @param req the incoming request\n * @param res the outgoing response\n */\n #metrics = async (req: express.Request, res: express.Response) => {\n try {\n res.send(await this.#metricsCollector.getMetrics());\n } catch (err) {\n Log.error(err, `Error getting metrics`);\n res.status(500).send(\"Internal Server Error\");\n }\n };\n\n /**\n * Admission request handler for both mutate and validate requests\n *\n * @param admissionKind the type of admission request\n * @returns the request handler\n */\n #admissionReq = (admissionKind: \"Mutate\" | \"Validate\") => {\n // Create the admission request handler\n return async (req: express.Request, res: express.Response) => {\n // Start the metrics timer\n const startTime = MetricsCollector.observeStart();\n\n try {\n // Get the request from the body or create an empty request\n const request: AdmissionRequest = req.body?.request || ({} as AdmissionRequest);\n\n // Run the before hook if it exists\n this.#beforeHook && this.#beforeHook(request || {});\n\n // Setup identifiers for logging\n const name = request?.name ? `/${request.name}` : \"\";\n const namespace = request?.namespace || \"\";\n const gvk = request?.kind || { group: \"\", version: \"\", kind: \"\" };\n\n const reqMetadata = {\n uid: request.uid,\n namespace,\n name,\n };\n\n Log.info({ ...reqMetadata, gvk, operation: request.operation, admissionKind }, \"Incoming request\");\n Log.debug({ ...reqMetadata, request }, \"Incoming request body\");\n\n // Process the request\n let response: MutateResponse | ValidateResponse[];\n\n // Call mutate or validate based on the admission kind\n if (admissionKind === \"Mutate\") {\n response = await mutateProcessor(this.#config, this.#capabilities, request, reqMetadata);\n } else {\n response = await validateProcessor(this.#config, this.#capabilities, request, reqMetadata);\n }\n\n // Run the after hook if it exists\n const responseList: ValidateResponse[] | MutateResponse[] = Array.isArray(response) ? response : [response];\n responseList.map(res => {\n this.#afterHook && this.#afterHook(res);\n // Log the response\n Log.info({ ...reqMetadata, res }, \"Check response\");\n });\n\n let kubeAdmissionResponse: ValidateResponse[] | MutateResponse | ResponseItem;\n\n if (admissionKind === \"Mutate\") {\n kubeAdmissionResponse = response;\n Log.debug({ ...reqMetadata, response }, \"Outgoing response\");\n res.send({\n apiVersion: \"admission.k8s.io/v1\",\n kind: \"AdmissionReview\",\n response: kubeAdmissionResponse,\n });\n } else {\n kubeAdmissionResponse =\n responseList.length === 0\n ? {\n uid: request.uid,\n allowed: true,\n status: { message: \"no in-scope validations -- allowed!\" },\n }\n : {\n uid: responseList[0].uid,\n allowed: responseList.filter(r => !r.allowed).length === 0,\n status: {\n message: (responseList as ValidateResponse[])\n .filter(rl => !rl.allowed)\n .map(curr => curr.status?.message)\n .join(\"; \"),\n },\n };\n res.send({\n apiVersion: \"admission.k8s.io/v1\",\n kind: \"AdmissionReview\",\n response: kubeAdmissionResponse,\n });\n }\n\n Log.debug({ ...reqMetadata, kubeAdmissionResponse }, \"Outgoing response\");\n\n this.#metricsCollector.observeEnd(startTime, admissionKind);\n } catch (err) {\n Log.error(err, `Error processing ${admissionKind} request`);\n res.status(500).send(\"Internal Server Error\");\n this.#metricsCollector.error();\n }\n };\n };\n\n /**\n * Middleware for logging requests\n *\n * @param req the incoming request\n * @param res the outgoing response\n * @param next the next middleware function\n */\n static #logger(req: express.Request, res: express.Response, next: express.NextFunction) {\n const startTime = Date.now();\n\n res.on(\"finish\", () => {\n const elapsedTime = Date.now() - startTime;\n const message = {\n uid: req.body?.request?.uid,\n method: req.method,\n url: req.originalUrl,\n status: res.statusCode,\n duration: `${elapsedTime} ms`,\n };\n\n Log.info(message);\n });\n\n next();\n }\n /**\n * Health check endpoint handler\n *\n * @param req the incoming request\n * @param res the outgoing response\n */\n static #healthz(req: express.Request, res: express.Response) {\n try {\n res.send(\"OK\");\n } catch (err) {\n Log.error(err, `Error processing health check`);\n res.status(500).send(\"Internal Server Error\");\n }\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\n/* eslint-disable class-methods-use-this */\n\nimport { performance } from \"perf_hooks\";\nimport promClient, { Counter, Registry, Gauge, Summary } from \"prom-client\";\nimport Log from \"./logger\";\n\nconst loggingPrefix = \"MetricsCollector\";\n\ninterface MetricNames {\n errors: string;\n alerts: string;\n mutate: string;\n validate: string;\n cacheMiss: string;\n resyncFailureCount: string;\n}\n\ninterface MetricArgs {\n name: string;\n help: string;\n registers: Registry[];\n labelNames?: string[];\n}\n\n/**\n * MetricsCollector class handles metrics collection using prom-client and performance hooks.\n */\nexport class MetricsCollector {\n #registry: Registry;\n #counters: Map<string, Counter<string>> = new Map();\n #gauges: Map<string, Gauge<string>> = new Map();\n #summaries: Map<string, Summary<string>> = new Map();\n #prefix: string;\n #cacheMissWindows: Map<string, number> = new Map();\n\n #metricNames: MetricNames = {\n errors: \"errors\",\n alerts: \"alerts\",\n mutate: \"mutate\",\n validate: \"validate\",\n cacheMiss: \"cache_miss\",\n resyncFailureCount: \"resync_failure_count\",\n };\n\n /**\n * Creates a MetricsCollector instance with prefixed metrics.\n * @param [prefix='pepr'] - The prefix for the metric names.\n */\n constructor(prefix = \"pepr\") {\n this.#registry = new Registry();\n this.#prefix = prefix;\n this.addCounter(this.#metricNames.errors, \"Mutation/Validate errors encountered\");\n this.addCounter(this.#metricNames.alerts, \"Mutation/Validate bad api token received\");\n this.addSummary(this.#metricNames.mutate, \"Mutation operation summary\");\n this.addSummary(this.#metricNames.validate, \"Validation operation summary\");\n this.addGauge(this.#metricNames.cacheMiss, \"Number of cache misses per window\", [\"window\"]);\n this.addGauge(this.#metricNames.resyncFailureCount, \"Number of failures per resync operation\", [\"count\"]);\n }\n\n #getMetricName = (name: string) => `${this.#prefix}_${name}`;\n\n #addMetric = <T extends Counter<string> | Gauge<string> | Summary<string>>(\n collection: Map<string, T>,\n MetricType: new (args: MetricArgs) => T,\n name: string,\n help: string,\n labelNames?: string[],\n ) => {\n if (collection.has(this.#getMetricName(name))) {\n Log.debug(`Metric for ${name} already exists`, loggingPrefix);\n return;\n }\n\n const metric = new MetricType({\n name: this.#getMetricName(name),\n help,\n registers: [this.#registry],\n labelNames,\n });\n\n collection.set(this.#getMetricName(name), metric);\n };\n\n addCounter = (name: string, help: string) => {\n this.#addMetric(this.#counters, promClient.Counter, name, help, []);\n };\n\n addSummary = (name: string, help: string) => {\n this.#addMetric(this.#summaries, promClient.Summary, name, help, []);\n };\n\n addGauge = (name: string, help: string, labelNames?: string[]) => {\n this.#addMetric(this.#gauges, promClient.Gauge, name, help, labelNames);\n };\n\n incCounter = (name: string) => {\n this.#counters.get(this.#getMetricName(name))?.inc();\n };\n\n incGauge = (name: string, labels?: Record<string, string>, value: number = 1) => {\n this.#gauges.get(this.#getMetricName(name))?.inc(labels || {}, value);\n };\n\n /**\n * Increments the error counter.\n */\n error = () => this.incCounter(this.#metricNames.errors);\n\n /**\n * Increments the alerts counter.\n */\n alert = () => this.incCounter(this.#metricNames.alerts);\n\n /**\n * Observes the duration since the provided start time and updates the summary.\n * @param startTime - The start time.\n * @param name - The metrics summary to increment.\n */\n observeEnd = (startTime: number, name: string = this.#metricNames.mutate) => {\n this.#summaries.get(this.#getMetricName(name))?.observe(performance.now() - startTime);\n };\n\n /**\n * Fetches the current metrics from the registry.\n * @returns The metrics.\n */\n getMetrics = () => this.#registry.metrics();\n\n /**\n * Returns the current timestamp from performance.now() method. Useful for start timing an operation.\n * @returns The timestamp.\n */\n static observeStart() {\n return performance.now();\n }\n\n /**\n * Increments the cache miss gauge for a given label.\n * @param label - The label for the cache miss.\n */\n incCacheMiss = (window: string) => {\n this.incGauge(this.#metricNames.cacheMiss, { window });\n };\n\n /**\n * Increments the retry count gauge.\n * @param count - The count to increment by.\n */\n incRetryCount = (count: string) => {\n this.incGauge(this.#metricNames.resyncFailureCount, { count });\n };\n\n /**\n * Initializes the cache miss gauge for a given label.\n * @param label - The label for the cache miss.\n */\n initCacheMissWindow = (window: string) => {\n this.#rollCacheMissWindows();\n this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.set({ window }, 0);\n this.#cacheMissWindows.set(window, 0);\n };\n\n /**\n * Manages the size of the cache miss gauge map.\n */\n #rollCacheMissWindows = () => {\n const maxCacheMissWindows = process.env.PEPR_MAX_CACHE_MISS_WINDOWS\n ? parseInt(process.env.PEPR_MAX_CACHE_MISS_WINDOWS, 10)\n : undefined;\n\n if (maxCacheMissWindows !== undefined && this.#cacheMissWindows.size >= maxCacheMissWindows) {\n const firstKey = this.#cacheMissWindows.keys().next().value;\n if (firstKey !== undefined) {\n this.#cacheMissWindows.delete(firstKey);\n }\n this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.remove({ window: firstKey });\n }\n };\n}\n\nexport const metricsCollector = new MetricsCollector(\"pepr\");\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport jsonPatch from \"fast-json-patch\";\nimport { kind } from \"kubernetes-fluent-client\";\n\nimport { Capability } from \"./capability\";\nimport { Errors } from \"./errors\";\nimport { shouldSkipRequest } from \"./filter/filter\";\nimport { MutateResponse } from \"./k8s\";\nimport { AdmissionRequest } from \"./types\";\nimport Log from \"./logger\";\nimport { ModuleConfig } from \"./module\";\nimport { PeprMutateRequest } from \"./mutate-request\";\nimport { base64Encode, convertFromBase64Map, convertToBase64Map } from \"./utils\";\n\nexport async function mutateProcessor(\n config: ModuleConfig,\n capabilities: Capability[],\n req: AdmissionRequest,\n reqMetadata: Record<string, string>,\n): Promise<MutateResponse> {\n const wrapped = new PeprMutateRequest(req);\n const response: MutateResponse = {\n uid: req.uid,\n warnings: [],\n allowed: false,\n };\n\n // Track whether any capability matched the request\n let matchedAction = false;\n\n // Track data fields that should be skipped during decoding\n let skipDecode: string[] = [];\n\n // If the resource is a secret, decode the data\n const isSecret = req.kind.version === \"v1\" && req.kind.kind === \"Secret\";\n if (isSecret) {\n skipDecode = convertFromBase64Map(wrapped.Raw as unknown as kind.Secret);\n }\n\n Log.info(reqMetadata, `Processing request`);\n\n for (const { name, bindings, namespaces } of capabilities) {\n const actionMetadata = { ...reqMetadata, name };\n for (const action of bindings) {\n // Skip this action if it's not a mutate action\n if (!action.mutateCallback) {\n continue;\n }\n\n // Continue to the next action without doing anything if this one should be skipped\n const shouldSkip = shouldSkipRequest(action, req, namespaces, config?.alwaysIgnore?.namespaces);\n if (shouldSkip !== \"\") {\n Log.debug(shouldSkip);\n continue;\n }\n\n const label = action.mutateCallback.name;\n Log.info(actionMetadata, `Processing mutation action (${label})`);\n matchedAction = true;\n\n // Add annotations to the request to indicate that the capability started processing\n // this will allow tracking of failed mutations that were permitted to continue\n const updateStatus = (status: string) => {\n // Only update the status if the request is a CREATE or UPDATE (we don't use CONNECT)\n if (req.operation === \"DELETE\") {\n return;\n }\n\n const identifier = `${config.uuid}.pepr.dev/${name}`;\n wrapped.Raw.metadata = wrapped.Raw.metadata || {};\n wrapped.Raw.metadata.annotations = wrapped.Raw.metadata.annotations || {};\n wrapped.Raw.metadata.annotations[identifier] = status;\n };\n\n updateStatus(\"started\");\n\n try {\n // Run the action\n await action.mutateCallback(wrapped);\n\n // Log on success\n Log.info(actionMetadata, `Mutation action succeeded (${label})`);\n\n // Add annotations to the request to indicate that the capability succeeded\n updateStatus(\"succeeded\");\n } catch (e) {\n updateStatus(\"warning\");\n response.warnings = response.warnings || [];\n\n const errorMessage = logMutateErrorMessage(e);\n\n // Log on failure\n Log.error(actionMetadata, `Action failed: ${errorMessage}`);\n response.warnings.push(`Action failed: ${errorMessage}`);\n\n switch (config.onError) {\n case Errors.reject:\n Log.error(actionMetadata, `Action failed: ${errorMessage}`);\n response.result = \"Pepr module configured to reject on error\";\n return response;\n\n case Errors.audit:\n response.auditAnnotations = response.auditAnnotations || {};\n response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;\n break;\n }\n }\n }\n }\n\n // If we've made it this far, the request is allowed\n response.allowed = true;\n\n // If no capability matched the request, exit early\n if (!matchedAction) {\n Log.info(reqMetadata, `No matching actions found`);\n return response;\n }\n\n // delete operations can't be mutate, just return before the transformation\n if (req.operation === \"DELETE\") {\n return response;\n }\n\n const transformed = wrapped.Raw;\n\n // Post-process the Secret requests to convert it back to the original format\n if (isSecret) {\n convertToBase64Map(transformed as unknown as kind.Secret, skipDecode);\n }\n\n // Compare the original request to the modified request to get the patches\n const patches = jsonPatch.compare(req.object, transformed);\n\n // Only add the patch if there are patches to apply\n if (patches.length > 0) {\n response.patchType = \"JSONPatch\";\n // Webhook must be base64-encoded\n // https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#response\n response.patch = base64Encode(JSON.stringify(patches));\n }\n\n // Remove the warnings array if it's empty\n if (response.warnings && response.warnings.length < 1) {\n delete response.warnings;\n }\n\n Log.debug({ ...reqMetadata, patches }, `Patches generated`);\n\n return response;\n}\n\nconst logMutateErrorMessage = (e: Error): string => {\n try {\n if (e.message && e.message !== \"[object Object]\") {\n return e.message;\n } else {\n throw new Error(\"An error occurred in the mutate action.\");\n }\n } catch (e) {\n return \"An error occurred with the mutate action.\";\n }\n};\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nexport const Errors = {\n audit: \"audit\",\n ignore: \"ignore\",\n reject: \"reject\",\n};\n\nexport const ErrorList = Object.values(Errors);\n\n/**\n * Validate the error or throw an error\n * @param error\n */\nexport function ValidateError(error = \"\") {\n if (!ErrorList.includes(error)) {\n throw new Error(`Invalid error: ${error}. Must be one of: ${ErrorList.join(\", \")}`);\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Event, Operation } from \"../enums\";\nimport { AdmissionRequest } from \"../../lib/types\";\nimport {\n __,\n allPass,\n any,\n anyPass,\n complement,\n curry,\n defaultTo,\n difference,\n equals,\n gt,\n length,\n not,\n nthArg,\n pipe,\n} from \"ramda\";\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\n\n/*\n Naming scheme:\n - AdmissionRequest - \"declares\" / \"neglects\"\n - KubernetesObject - \"carries\" / \"missing\"\n - Binding - \"defines\" / \"ignores\"\n*/\n\n/*\n AdmissionRequest collectors\n*/\nexport const declaredOperation = pipe(\n (request: AdmissionRequest<KubernetesObject>): Operation => request?.operation,\n defaultTo(\"\"),\n);\nexport const declaredGroup = pipe(\n (request: AdmissionRequest<KubernetesObject>): string => request?.kind?.group,\n defaultTo(\"\"),\n);\nexport const declaredVersion = pipe(\n (request: AdmissionRequest<KubernetesObject>): string | undefined => request?.kind?.version,\n defaultTo(\"\"),\n);\nexport const declaredKind = pipe(\n (request: AdmissionRequest<KubernetesObject>): string => request?.kind?.kind,\n defaultTo(\"\"),\n);\nexport const declaredUid = pipe((request: AdmissionRequest<KubernetesObject>): string => request?.uid, defaultTo(\"\"));\n\n/*\n KubernetesObject collectors\n*/\nexport const carriesDeletionTimestamp = pipe(\n kubernetesObject => !!kubernetesObject.metadata?.deletionTimestamp,\n defaultTo(false),\n);\nexport const missingDeletionTimestamp = complement(carriesDeletionTimestamp);\n\nexport const carriedKind = pipe(kubernetesObject => kubernetesObject?.metadata?.kind, defaultTo(\"not set\"));\nexport const carriedVersion = pipe(kubernetesObject => kubernetesObject?.metadata?.version, defaultTo(\"not set\"));\nexport const carriedName = pipe(kubernetesObject => kubernetesObject?.metadata?.name, defaultTo(\"\"));\nexport const carriesName = pipe(carriedName, equals(\"\"), not);\nexport const missingName = complement(carriesName);\n\nexport const carriedNamespace = pipe(kubernetesObject => kubernetesObject?.metadata?.namespace, defaultTo(\"\"));\nexport const carriesNamespace = pipe(carriedNamespace, equals(\"\"), not);\n\nexport const carriedAnnotations = pipe(kubernetesObject => kubernetesObject?.metadata?.annotations, defaultTo({}));\nexport const carriesAnnotations = pipe(carriedAnnotations, equals({}), not);\n\nexport const carriedLabels = pipe(kubernetesObject => kubernetesObject?.metadata?.labels, defaultTo({}));\nexport const carriesLabels = pipe(carriedLabels, equals({}), not);\n\n/*\n Binding collectors\n*/\n\nexport const definesDeletionTimestamp = pipe(binding => binding?.filters?.deletionTimestamp, defaultTo(false));\nexport const ignoresDeletionTimestamp = complement(definesDeletionTimestamp);\n\nexport const definedName = pipe(binding => binding?.filters?.name, defaultTo(\"\"));\nexport const definesName = pipe(definedName, equals(\"\"), not);\nexport const ignoresName = complement(definesName);\n\nexport const definedNameRegex = pipe(binding => binding?.filters?.regexName, defaultTo(\"\"));\nexport const definesNameRegex = pipe(definedNameRegex, equals(\"\"), not);\n\nexport const definedNamespaces = pipe(binding => binding?.filters?.namespaces, defaultTo([]));\nexport const definesNamespaces = pipe(definedNamespaces, equals([]), not);\n\nexport const definedNamespaceRegexes = pipe(binding => binding?.filters?.regexNamespaces, defaultTo([]));\nexport const definesNamespaceRegexes = pipe(definedNamespaceRegexes, equals([]), not);\n\nexport const definedAnnotations = pipe(binding => binding?.filters?.annotations, defaultTo({}));\nexport const definesAnnotations = pipe(definedAnnotations, equals({}), not);\n\nexport const definedLabels = pipe(binding => binding?.filters?.labels, defaultTo({}));\nexport const definesLabels = pipe(definedLabels, equals({}), not);\n\nexport const definedEvent = pipe(binding => binding?.event, defaultTo(\"\"));\nexport const definesDelete = pipe(definedEvent, equals(Operation.DELETE));\n\nexport const definedGroup = pipe(binding => binding?.kind?.group, defaultTo(\"\"));\nexport const definesGroup = pipe(definedGroup, equals(\"\"), not);\n\nexport const definedVersion = pipe(binding => binding?.kind?.version, defaultTo(\"\"));\nexport const definesVersion = pipe(definedVersion, equals(\"\"), not);\n\nexport const definedKind = pipe(binding => binding?.kind?.kind, defaultTo(\"\"));\nexport const definesKind = pipe(definedKind, equals(\"\"), not);\n\nexport const definedCategory = pipe(binding => {\n // prettier-ignore\n return (\n binding.isFinalize ? \"Finalize\" :\n binding.isWatch ? \"Watch\" :\n binding.isMutate ? \"Mutate\" :\n binding.isValidate ? \"Validate\" :\n \"\"\n );\n});\n\nexport const definedCallback = pipe(binding => {\n // prettier-ignore\n return (\n binding.isFinalize ? binding.finalizeCallback :\n binding.isWatch ? binding.watchCallback :\n binding.isMutate ? binding.mutateCallback :\n binding.isValidate ? binding.validateCallback:\n null\n );\n});\nexport const definedCallbackName = pipe(definedCallback, defaultTo({ name: \"\" }), callback => callback.name);\n\n/*\n post-collection comparitors\n*/\nexport const mismatchedDeletionTimestamp = allPass([\n pipe(nthArg(0), definesDeletionTimestamp),\n pipe(nthArg(1), missingDeletionTimestamp),\n]);\n\nexport const mismatchedName = allPass([\n pipe(nthArg(0), definesName),\n pipe((binding, kubernetesObject) => definedName(binding) !== carriedName(kubernetesObject)),\n]);\n\nexport const mismatchedNameRegex = allPass([\n pipe(nthArg(0), definesNameRegex),\n pipe((binding, kubernetesObject) => new RegExp(definedNameRegex(binding)).test(carriedName(kubernetesObject)), not),\n]);\n\nexport const bindsToKind = curry(\n allPass([pipe(nthArg(0), definedKind, equals(\"\"), not), pipe((binding, kind) => definedKind(binding) === kind)]),\n);\nexport const bindsToNamespace = curry(pipe(bindsToKind(__, \"Namespace\")));\nexport const misboundNamespace = allPass([bindsToNamespace, definesNamespaces]);\n\nexport const mismatchedNamespace = allPass([\n pipe(nthArg(0), definesNamespaces),\n pipe((binding, kubernetesObject) => definedNamespaces(binding).includes(carriedNamespace(kubernetesObject)), not),\n]);\n\nexport const mismatchedNamespaceRegex = allPass([\n pipe(nthArg(0), definesNamespaceRegexes),\n pipe((binding, kubernetesObject) =>\n pipe(\n any((regEx: string) => new RegExp(regEx).test(carriedNamespace(kubernetesObject))),\n not,\n )(definedNamespaceRegexes(binding)),\n ),\n]);\n\nexport const metasMismatch = pipe(\n (defined, carried) => {\n const result = { defined, carried, unalike: {} };\n\n result.unalike = Object.entries(result.defined)\n .map(([key, value]) => {\n const keyMissing = !Object.hasOwn(result.carried, key);\n const noValue = !value;\n const valMissing = !result.carried[key];\n const valDiffers = result.carried[key] !== result.defined[key];\n\n // prettier-ignore\n return (\n keyMissing ? { [key]: value } :\n noValue ? {} :\n valMissing ? { [key]: value } :\n valDiffers ? { [key]: value } :\n {}\n )\n })\n .reduce((acc, cur) => ({ ...acc, ...cur }), {});\n\n return result.unalike;\n },\n unalike => Object.keys(unalike).length > 0,\n);\n\nexport const mismatchedAnnotations = allPass([\n pipe(nthArg(0), definesAnnotations),\n pipe((binding, kubernetesObject) => metasMismatch(definedAnnotations(binding), carriedAnnotations(kubernetesObject))),\n]);\n\nexport const mismatchedLabels = allPass([\n pipe(nthArg(0), definesLabels),\n pipe((binding, kubernetesObject) => metasMismatch(definedLabels(binding), carriedLabels(kubernetesObject))),\n]);\n\nexport const uncarryableNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), carriesNamespace),\n pipe((namespaceSelector, kubernetesObject) => namespaceSelector.includes(carriedNamespace(kubernetesObject)), not),\n]);\n\nexport const missingCarriableNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe((namespaceSelector: string[], kubernetesObject: KubernetesObject): boolean =>\n kubernetesObject.kind === \"Namespace\"\n ? !namespaceSelector.includes(kubernetesObject.metadata!.name!)\n : !carriesNamespace(kubernetesObject),\n ),\n]);\n\nexport const carriesIgnoredNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), carriesNamespace),\n pipe((namespaceSelector, kubernetesObject) => namespaceSelector.includes(carriedNamespace(kubernetesObject))),\n]);\n\nexport const unbindableNamespaces = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), definesNamespaces),\n pipe(\n (namespaceSelector, binding) => difference(definedNamespaces(binding), namespaceSelector),\n length,\n equals(0),\n not,\n ),\n]);\n\nexport const misboundDeleteWithDeletionTimestamp = allPass([definesDelete, definesDeletionTimestamp]);\n\nexport const operationMatchesEvent = anyPass([\n pipe(nthArg(1), equals(Event.Any)),\n pipe((operation, event) => operation === event),\n pipe((operation, event) => (operation ? event.includes(operation) : false)),\n]);\n\nexport const mismatchedEvent = pipe(\n (binding, request) => operationMatchesEvent(declaredOperation(request), definedEvent(binding)),\n not,\n);\n\nexport const mismatchedGroup = allPass([\n pipe(nthArg(0), definesGroup),\n pipe((binding, request) => definedGroup(binding) !== declaredGroup(request)),\n]);\n\nexport const mismatchedVersion = allPass([\n pipe(nthArg(0), definesVersion),\n pipe((binding, request) => definedVersion(binding) !== declaredVersion(request)),\n]);\n\nexport const mismatchedKind = allPass([\n pipe(nthArg(0), definesKind),\n pipe((binding, request) => definedKind(binding) !== declaredKind(request)),\n]);\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { AdmissionRequest, Binding } from \"../types\";\nimport { Operation } from \"../enums\";\nimport {\n carriesIgnoredNamespace,\n carriedName,\n definedEvent,\n declaredOperation,\n definedName,\n definedGroup,\n declaredGroup,\n definedVersion,\n declaredVersion,\n definedKind,\n declaredKind,\n definedNamespaces,\n carriedNamespace,\n definedLabels,\n carriedLabels,\n definedAnnotations,\n carriedAnnotations,\n definedNamespaceRegexes,\n definedNameRegex,\n misboundDeleteWithDeletionTimestamp,\n mismatchedDeletionTimestamp,\n mismatchedAnnotations,\n mismatchedLabels,\n mismatchedName,\n mismatchedNameRegex,\n mismatchedNamespace,\n mismatchedNamespaceRegex,\n mismatchedEvent,\n mismatchedGroup,\n mismatchedVersion,\n mismatchedKind,\n missingCarriableNamespace,\n unbindableNamespaces,\n uncarryableNamespace,\n} from \"./adjudicators\";\n\n/**\n * shouldSkipRequest determines if a request should be skipped based on the binding filters.\n *\n * @param binding the action binding\n * @param req the incoming request\n * @returns\n */\nexport function shouldSkipRequest(\n binding: Binding,\n req: AdmissionRequest,\n capabilityNamespaces: string[],\n ignoredNamespaces?: string[],\n): string {\n const prefix = \"Ignoring Admission Callback:\";\n const obj = (req.operation === Operation.DELETE ? req.oldObject : req.object)!;\n\n // prettier-ignore\n return (\n misboundDeleteWithDeletionTimestamp(binding) ?\n `${prefix} Cannot use deletionTimestamp filter on a DELETE operation.` :\n\n mismatchedDeletionTimestamp(binding, obj) ?\n `${prefix} Binding defines deletionTimestamp but Object does not carry it.` :\n\n mismatchedEvent(binding, req) ?\n (\n `${prefix} Binding defines event '${definedEvent(binding)}' but ` +\n `Request declares '${declaredOperation(req)}'.`\n ) :\n\n mismatchedName(binding, obj) ?\n `${prefix} Binding defines name '${definedName(binding)}' but Object carries '${carriedName(obj)}'.` :\n\n mismatchedGroup(binding, req) ?\n (\n `${prefix} Binding defines group '${definedGroup(binding)}' but ` +\n `Request declares '${declaredGroup(req)}'.`\n ) :\n\n mismatchedVersion(binding, req) ?\n (\n `${prefix} Binding defines version '${definedVersion(binding)}' but ` +\n `Request declares '${declaredVersion(req)}'.`\n ) :\n\n mismatchedKind(binding, req) ?\n (\n `${prefix} Binding defines kind '${definedKind(binding)}' but ` +\n `Request declares '${declaredKind(req)}'.`\n ) :\n\n unbindableNamespaces(capabilityNamespaces, binding) ?\n (\n `${prefix} Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n uncarryableNamespace(capabilityNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n mismatchedNamespace(binding, obj) ?\n (\n `${prefix} Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedLabels(binding, obj) ?\n (\n `${prefix} Binding defines labels '${JSON.stringify(definedLabels(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedLabels(obj))}'.`\n ) :\n\n mismatchedAnnotations(binding, obj) ?\n (\n `${prefix} Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedAnnotations(obj))}'.`\n ) :\n\n mismatchedNamespaceRegex(binding, obj) ?\n (\n `${prefix} Binding defines namespace regexes ` +\n `'${JSON.stringify(definedNamespaceRegexes(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedNameRegex(binding, obj) ?\n (\n `${prefix} Binding defines name regex '${definedNameRegex(binding)}' ` +\n `but Object carries '${carriedName(obj)}'.`\n ) :\n\n carriesIgnoredNamespace(ignoredNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.`\n ) :\n\n missingCarriableNamespace(capabilityNamespaces, obj) ? \n (\n `${prefix} Object does not carry a namespace ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n \"\"\n );\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { AdmissionRequest, DeepPartial } from \"./types\";\nimport { Operation } from \"./enums\";\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\nimport { clone, mergeDeepRight } from \"ramda\";\n\n// PeprMutateRequest class for mutation request handling\nexport class PeprMutateRequest<T extends KubernetesObject> {\n Raw: T;\n #input: AdmissionRequest<T>;\n\n get PermitSideEffects() {\n return !this.#input.dryRun;\n }\n\n get IsDryRun() {\n return this.#input.dryRun;\n }\n\n get OldResource() {\n return this.#input.oldObject;\n }\n\n get Request() {\n return this.#input;\n }\n\n constructor(input: AdmissionRequest<T>) {\n this.#input = input;\n // If this is a DELETE operation, use the oldObject instead\n if (input.operation.toUpperCase() === Operation.DELETE) {\n this.Raw = clone(input.oldObject as T);\n } else {\n // Otherwise, use the incoming object\n this.Raw = clone(input.object);\n }\n\n if (!this.Raw) {\n throw new Error(\"Unable to load the request object into PeprRequest.Raw\");\n }\n }\n\n Merge = (obj: DeepPartial<T>) => {\n this.Raw = mergeDeepRight(this.Raw, obj) as unknown as T;\n };\n\n SetLabel = (key: string, value: string) => {\n const ref = this.Raw;\n ref.metadata = ref.metadata ?? {};\n ref.metadata.labels = ref.metadata.labels ?? {};\n ref.metadata.labels[key] = value;\n return this;\n };\n\n SetAnnotation = (key: string, value: string) => {\n const ref = this.Raw;\n ref.metadata = ref.metadata ?? {};\n ref.metadata.annotations = ref.metadata.annotations ?? {};\n ref.metadata.annotations[key] = value;\n return this;\n };\n\n RemoveLabel = (key: string) => {\n if (this.Raw.metadata?.labels?.[key]) {\n delete this.Raw.metadata.labels[key];\n }\n return this;\n };\n\n RemoveAnnotation = (key: string) => {\n if (this.Raw.metadata?.annotations?.[key]) {\n delete this.Raw.metadata.annotations[key];\n }\n return this;\n };\n\n HasLabel = (key: string) => {\n return this.Raw.metadata?.labels?.[key] !== undefined;\n };\n\n HasAnnotation = (key: string) => {\n return this.Raw.metadata?.annotations?.[key] !== undefined;\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport Log from \"./logger\";\n\n/** Test if a string is ascii or not */\nexport const isAscii = /^[\\s\\x20-\\x7E]*$/;\n\n/**\n * Encode all ascii values in a map to base64\n * @param obj The object to encode\n * @param skip A list of keys to skip encoding\n */\nexport function convertToBase64Map(obj: { data?: Record<string, string> }, skip: string[]) {\n obj.data = obj.data ?? {};\n for (const key in obj.data) {\n const value = obj.data[key];\n // Only encode ascii values\n obj.data[key] = skip.includes(key) ? value : base64Encode(value);\n }\n}\n\n/**\n * Decode all ascii values in a map from base64 to utf-8\n * @param obj The object to decode\n * @returns A list of keys that were skipped\n */\nexport function convertFromBase64Map(obj: { data?: Record<string, string> }) {\n const skip: string[] = [];\n\n obj.data = obj.data ?? {};\n for (const key in obj.data) {\n if (obj.data[key] === undefined) {\n obj.data[key] = \"\";\n } else {\n const decoded = base64Decode(obj.data[key]);\n if (isAscii.test(decoded)) {\n // Only decode ascii values\n obj.data[key] = decoded;\n } else {\n skip.push(key);\n }\n }\n }\n Log.debug(`Non-ascii data detected in keys: ${skip}, skipping automatic base64 decoding`);\n return skip;\n}\n\n/** Decode a base64 string */\nexport function base64Decode(data: string) {\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/** Encode a string to base64 */\nexport function base64Encode(data: string) {\n return Buffer.from(data).toString(\"base64\");\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\n/* eslint-disable class-methods-use-this */\n\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\n\nimport { clone } from \"ramda\";\nimport { AdmissionRequest } from \"./types\";\nimport { ValidateActionResponse } from \"./types\";\nimport { Operation } from \"./enums\";\n\n/**\n * The RequestWrapper class provides methods to modify Kubernetes objects in the context\n * of a mutating webhook request.\n */\nexport class PeprValidateRequest<T extends KubernetesObject> {\n Raw: T;\n\n #input: AdmissionRequest<T>;\n\n /**\n * Provides access to the old resource in the request if available.\n * @returns The old Kubernetes resource object or null if not available.\n */\n get OldResource() {\n return this.#input.oldObject;\n }\n\n /**\n * Provides access to the request object.\n * @returns The request object containing the Kubernetes resource.\n */\n get Request() {\n return this.#input;\n }\n\n /**\n * Creates a new instance of the Action class.\n * @param input - The request object containing the Kubernetes resource to modify.\n */\n constructor(input: AdmissionRequest<T>) {\n this.#input = input;\n\n // If this is a DELETE operation, use the oldObject instead\n if (input.operation.toUpperCase() === Operation.DELETE) {\n this.Raw = clone(input.oldObject as T);\n } else {\n // Otherwise, use the incoming object\n this.Raw = clone(input.object);\n }\n\n if (!this.Raw) {\n throw new Error(\"unable to load the request object into PeprRequest.Raw\");\n }\n }\n\n /**\n * Check if a label exists on the Kubernetes resource.\n *\n * @param key the label key to check\n * @returns\n */\n HasLabel = (key: string) => {\n return this.Raw.metadata?.labels?.[key] !== undefined;\n };\n\n /**\n * Check if an annotation exists on the Kubernetes resource.\n *\n * @param key the annotation key to check\n * @returns\n */\n HasAnnotation = (key: string) => {\n return this.Raw.metadata?.annotations?.[key] !== undefined;\n };\n\n /**\n * Create a validation response that allows the request.\n *\n * @returns The validation response.\n */\n Approve = (): ValidateActionResponse => {\n return {\n allowed: true,\n };\n };\n\n /**\n * Create a validation response that denies the request.\n *\n * @param statusMessage Optional status message to return to the user.\n * @param statusCode Optional status code to return to the user.\n * @returns The validation response.\n */\n Deny = (statusMessage?: string, statusCode?: number): ValidateActionResponse => {\n return {\n allowed: false,\n statusCode,\n statusMessage,\n };\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { kind } from \"kubernetes-fluent-client\";\n\nimport { Capability } from \"./capability\";\nimport { shouldSkipRequest } from \"./filter/filter\";\nimport { ValidateResponse } from \"./k8s\";\nimport { AdmissionRequest } from \"./types\";\nimport Log from \"./logger\";\nimport { convertFromBase64Map } from \"./utils\";\nimport { PeprValidateRequest } from \"./validate-request\";\nimport { ModuleConfig } from \"./module\";\n\nexport async function validateProcessor(\n config: ModuleConfig,\n capabilities: Capability[],\n req: AdmissionRequest,\n reqMetadata: Record<string, string>,\n): Promise<ValidateResponse[]> {\n const wrapped = new PeprValidateRequest(req);\n const response: ValidateResponse[] = [];\n\n // If the resource is a secret, decode the data\n const isSecret = req.kind.version === \"v1\" && req.kind.kind === \"Secret\";\n if (isSecret) {\n convertFromBase64Map(wrapped.Raw as unknown as kind.Secret);\n }\n\n Log.info(reqMetadata, `Processing validation request`);\n\n for (const { name, bindings, namespaces } of capabilities) {\n const actionMetadata = { ...reqMetadata, name };\n\n for (const action of bindings) {\n // Skip this action if it's not a validation action\n if (!action.validateCallback) {\n continue;\n }\n\n const localResponse: ValidateResponse = {\n uid: req.uid,\n allowed: true, // Assume it's allowed until a validation check fails\n };\n\n // Continue to the next action without doing anything if this one should be skipped\n const shouldSkip = shouldSkipRequest(action, req, namespaces, config?.alwaysIgnore?.namespaces);\n if (shouldSkip !== \"\") {\n Log.debug(shouldSkip);\n continue;\n }\n\n const label = action.validateCallback.name;\n Log.info(actionMetadata, `Processing validation action (${label})`);\n\n try {\n // Run the validation callback, if it fails set allowed to false\n const resp = await action.validateCallback(wrapped);\n localResponse.allowed = resp.allowed;\n\n // If the validation callback returned a status code or message, set it in the Response\n if (resp.statusCode || resp.statusMessage) {\n localResponse.status = {\n code: resp.statusCode || 400,\n message: resp.statusMessage || `Validation failed for ${name}`,\n };\n }\n\n Log.info(actionMetadata, `Validation action complete (${label}): ${resp.allowed ? \"allowed\" : \"denied\"}`);\n } catch (e) {\n // If any validation throws an error, note the failure in the Response\n Log.error(actionMetadata, `Action failed: ${JSON.stringify(e)}`);\n localResponse.allowed = false;\n localResponse.status = {\n code: 500,\n message: `Action failed with error: ${JSON.stringify(e)}`,\n };\n return [localResponse];\n }\n response.push(localResponse);\n }\n }\n\n return response;\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Operation } from \"fast-json-patch\";\nimport { K8s } from \"kubernetes-fluent-client\";\nimport { startsWith } from \"ramda\";\n\nimport { Capability } from \"../capability\";\nimport { Store } from \"../k8s\";\nimport Log, { redactedPatch, redactedStore } from \"../logger\";\nimport { DataOp, DataSender, DataStore, Storage } from \"../storage\";\nimport { fillStoreCache, sendUpdatesAndFlushCache } from \"./storeCache\";\n\nconst namespace = \"pepr-system\";\nexport const debounceBackoff = 5000;\n\nexport class StoreController {\n #name: string;\n #stores: Record<string, Storage> = {};\n #sendDebounce: NodeJS.Timeout | undefined;\n #onReady?: () => void;\n\n constructor(capabilities: Capability[], name: string, onReady?: () => void) {\n this.#onReady = onReady;\n\n this.#name = name;\n\n const setStorageInstance = (registrationFunction: () => Storage, name: string) => {\n const scheduleStore = registrationFunction();\n\n // Bind the store sender to the capability\n scheduleStore.registerSender(this.#send(name));\n\n // Store the storage instance\n this.#stores[name] = scheduleStore;\n };\n\n if (name.includes(\"schedule\")) {\n // Establish the store for each capability\n for (const { name, registerScheduleStore, hasSchedule } of capabilities) {\n if (hasSchedule === true) {\n // Register the scheduleStore with the capability\n setStorageInstance(registerScheduleStore, name);\n }\n }\n } else {\n // Establish the store for each capability\n for (const { name, registerStore } of capabilities) {\n setStorageInstance(registerStore, name);\n }\n }\n\n setTimeout(\n () =>\n K8s(Store)\n .InNamespace(namespace)\n .Get(this.#name)\n .then(async (store: Store) => await this.#migrateAndSetupWatch(store))\n .catch(this.#createStoreResource),\n Math.random() * 3000, // Add a jitter to the Store creation to avoid collisions\n );\n }\n\n #setupWatch = () => {\n const watcher = K8s(Store, { name: this.#name, namespace }).Watch(this.#receive);\n watcher.start().catch(e => Log.error(e, \"Error starting Pepr store watch\"));\n };\n\n #migrateAndSetupWatch = async (store: Store) => {\n Log.debug(redactedStore(store), \"Pepr Store migration\");\n const data: DataStore = store.data || {};\n let storeCache: Record<string, Operation> = {};\n\n for (const name of Object.keys(this.#stores)) {\n // Get the prefix offset for the keys\n const offset = `${name}-`.length;\n\n // Loop over each key in the store\n for (const key of Object.keys(data)) {\n // Match on the capability name as a prefix for non v2 keys\n if (startsWith(name, key) && !startsWith(`${name}-v2`, key)) {\n // populate migrate cache\n storeCache = fillStoreCache(storeCache, name, \"remove\", {\n key: [key.slice(offset)],\n value: data[key],\n });\n storeCache = fillStoreCache(storeCache, name, \"add\", {\n key: [key.slice(offset)],\n value: data[key],\n version: \"v2\",\n });\n }\n }\n }\n storeCache = await sendUpdatesAndFlushCache(storeCache, namespace, this.#name);\n this.#setupWatch();\n };\n\n #receive = (store: Store) => {\n Log.debug(redactedStore(store), \"Pepr Store update\");\n\n // Wrap the update in a debounced function\n const debounced = () => {\n // Base64 decode the data\n const data: DataStore = store.data || {};\n\n // Loop over each stored capability\n for (const name of Object.keys(this.#stores)) {\n // Get the prefix offset for the keys\n const offset = `${name}-`.length;\n\n // Get any keys that match the capability name prefix\n const filtered: DataStore = {};\n\n // Loop over each key in the secret\n for (const key of Object.keys(data)) {\n // Match on the capability name as a prefix\n if (startsWith(name, key)) {\n // Strip the prefix and store the value\n filtered[key.slice(offset)] = data[key];\n }\n }\n\n // Send the data to the receiver callback\n this.#stores[name].receive(filtered);\n }\n\n // Call the onReady callback if this is the first time the secret has been read\n if (this.#onReady) {\n this.#onReady();\n this.#onReady = undefined;\n }\n };\n\n // Debounce the update to 1 second to avoid multiple rapid calls\n clearTimeout(this.#sendDebounce);\n this.#sendDebounce = setTimeout(debounced, this.#onReady ? 0 : debounceBackoff);\n };\n\n #send = (capabilityName: string) => {\n let storeCache: Record<string, Operation> = {};\n\n // Create a sender function for the capability to add/remove data from the store\n const sender: DataSender = async (op: DataOp, key: string[], value?: string) => {\n storeCache = fillStoreCache(storeCache, capabilityName, op, { key, value });\n };\n\n // Send any cached updates every debounceBackoff milliseconds\n setInterval(() => {\n if (Object.keys(storeCache).length > 0) {\n Log.debug(redactedPatch(storeCache), \"Sending updates to Pepr store\");\n void sendUpdatesAndFlushCache(storeCache, namespace, this.#name);\n }\n }, debounceBackoff);\n\n return sender;\n };\n\n #createStoreResource = async (e: unknown) => {\n Log.info(`Pepr store not found, creating...`);\n Log.debug(e);\n\n try {\n await K8s(Store).Apply({\n metadata: {\n name: this.#name,\n namespace,\n },\n data: {\n // JSON Patch will die if the data is empty, so we need to add a placeholder\n __pepr_do_not_delete__: \"k-thx-bye\",\n },\n });\n\n // Now that the resource exists, setup the watch\n this.#setupWatch();\n } catch (err) {\n Log.error(err, \"Failed to create Pepr store\");\n }\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { GenericKind, RegisterKind } from \"kubernetes-fluent-client\";\n\n/**\n * PeprStore for internal use by Pepr. This is used to store arbitrary data in the cluster.\n */\nexport class Store extends GenericKind {\n declare data: {\n [key: string]: string;\n };\n}\n\nexport const peprStoreGVK = {\n kind: \"PeprStore\",\n version: \"v1\",\n group: \"pepr.dev\",\n};\n\nRegisterKind(Store, peprStoreGVK);\n\nexport interface MutateResponse {\n /** UID is an identifier for the individual request/response. This must be copied over from the corresponding AdmissionRequest. */\n uid: string;\n\n /** Allowed indicates whether or not the admission request was permitted. */\n allowed: boolean;\n\n /** Result contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\". */\n result?: string;\n\n /** The patch body. Currently we only support \"JSONPatch\" which implements RFC 6902. */\n patch?: string;\n\n /** The type of Patch. Currently we only allow \"JSONPatch\". */\n patchType?: \"JSONPatch\";\n\n /**\n * AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted).\n *\n * See https://kubernetes.io/docs/reference/labels-annotations-taints/audit-annotations/ for more information\n */\n auditAnnotations?: {\n [key: string]: string;\n };\n\n /** warnings is a list of warning messages to return to the requesting API client. */\n warnings?: string[];\n}\n\nexport interface ValidateResponse extends MutateResponse {\n /** Status contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\". */\n status?: {\n /** A machine-readable description of why this operation is in the\n \"Failure\" status. If this value is empty there is no information available. */\n code: number;\n\n /** A human-readable description of the status of this operation. */\n message: string;\n };\n}\n\nexport type WebhookIgnore = {\n /**\n * List of Kubernetes namespaces to always ignore.\n * Any resources in these namespaces will be ignored by Pepr.\n *\n * Note: `kube-system` and `pepr-system` are always ignored.\n */\n namespaces?: string[];\n};\n", "import { DataOp } from \"../storage\";\nimport Log from \"../logger\";\nimport { K8s } from \"kubernetes-fluent-client\";\nimport { Store } from \"../k8s\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { Operation } from \"fast-json-patch\";\n\nexport const sendUpdatesAndFlushCache = async (cache: Record<string, Operation>, namespace: string, name: string) => {\n const indexes = Object.keys(cache);\n const payload = Object.values(cache);\n\n try {\n if (payload.length > 0) {\n await K8s(Store, { namespace, name }).Patch(payload); // Send patch to cluster\n Object.keys(cache).forEach(key => delete cache[key]);\n }\n } catch (err) {\n Log.error(err, \"Pepr store update failure\");\n\n if (err.status === StatusCodes.UNPROCESSABLE_ENTITY) {\n Object.keys(cache).forEach(key => delete cache[key]);\n } else {\n indexes.forEach(index => {\n cache[index] = payload[Number(index)]; // On failure to update, re-add the operations to the cache to be retried\n });\n }\n }\n return cache;\n};\n\ntype CacheItem = {\n key: string[];\n value?: string;\n version?: string;\n};\n\nexport const fillStoreCache = (\n cache: Record<string, Operation>,\n capabilityName: string,\n op: DataOp,\n cacheItem: CacheItem,\n): Record<string, Operation> => {\n const path = [`/data/${capabilityName}`, cacheItem.version, cacheItem.key] // adjust the path, see ADR-0008\n .filter(str => str !== \"\" && str !== undefined)\n .join(\"-\");\n if (op === \"add\") {\n const value = cacheItem.value || \"\";\n const cacheIdx = [op, path, value].join(\":\");\n\n // Add the operation to the cache\n cache[cacheIdx] = { op, path, value };\n } else if (op === \"remove\") {\n if (cacheItem.key.length < 1) {\n throw new Error(`Key is required for REMOVE operation`);\n }\n const cacheIndex = [op, path].join(\":\");\n // Add the operation to the cache\n cache[cacheIndex] = { op, path };\n } else {\n throw new Error(`Unsupported operation: ${op}`);\n }\n return cache;\n};\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { K8s, KubernetesObject, WatchCfg, WatchEvent } from \"kubernetes-fluent-client\";\nimport { WatchPhase } from \"kubernetes-fluent-client/dist/fluent/types\";\nimport { Capability } from \"./capability\";\nimport { filterNoMatchReason } from \"./helpers\";\nimport { removeFinalizer } from \"./finalizer\";\nimport Log from \"./logger\";\nimport { Queue } from \"./queue\";\nimport { Binding } from \"./types\";\nimport { Event } from \"./enums\";\nimport { metricsCollector } from \"./metrics\";\n\n// stores Queue instances\nconst queues: Record<string, Queue<KubernetesObject>> = {};\n\n/**\n * Get the key for an entry in the queues\n *\n * @param obj The object to derive a key from\n * @returns The key to a Queue in the list of queues\n */\nexport function queueKey(obj: KubernetesObject) {\n const options = [\"kind\", \"kindNs\", \"kindNsName\", \"global\"];\n const d3fault = \"kind\";\n\n let strat = process.env.PEPR_RECONCILE_STRATEGY || d3fault;\n strat = options.includes(strat) ? strat : d3fault;\n\n const ns = obj.metadata?.namespace ?? \"cluster-scoped\";\n const kind = obj.kind ?? \"UnknownKind\";\n const name = obj.metadata?.name ?? \"Unnamed\";\n\n const lookup: Record<string, string> = {\n kind: `${kind}`,\n kindNs: `${kind}/${ns}`,\n kindNsName: `${kind}/${ns}/${name}`,\n global: \"global\",\n };\n return lookup[strat];\n}\n\nexport function getOrCreateQueue(obj: KubernetesObject) {\n const key = queueKey(obj);\n if (!queues[key]) {\n queues[key] = new Queue<KubernetesObject>(key);\n }\n return queues[key];\n}\n\n// Watch configuration\nconst watchCfg: WatchCfg = {\n resyncFailureMax: process.env.PEPR_RESYNC_FAILURE_MAX ? parseInt(process.env.PEPR_RESYNC_FAILURE_MAX, 10) : 5,\n resyncDelaySec: process.env.PEPR_RESYNC_DELAY_SECONDS ? parseInt(process.env.PEPR_RESYNC_DELAY_SECONDS, 10) : 5,\n lastSeenLimitSeconds: process.env.PEPR_LAST_SEEN_LIMIT_SECONDS\n ? parseInt(process.env.PEPR_LAST_SEEN_LIMIT_SECONDS, 10)\n : 300,\n relistIntervalSec: process.env.PEPR_RELIST_INTERVAL_SECONDS\n ? parseInt(process.env.PEPR_RELIST_INTERVAL_SECONDS, 10)\n : 600,\n};\n\n// Map the event to the watch phase\nconst eventToPhaseMap = {\n [Event.Create]: [WatchPhase.Added],\n [Event.Update]: [WatchPhase.Modified],\n [Event.CreateOrUpdate]: [WatchPhase.Added, WatchPhase.Modified],\n [Event.Delete]: [WatchPhase.Deleted],\n [Event.Any]: [WatchPhase.Added, WatchPhase.Modified, WatchPhase.Deleted],\n};\n\n/**\n * Entrypoint for setting up watches for all capabilities\n *\n * @param capabilities The capabilities to load watches for\n */\nexport function setupWatch(capabilities: Capability[], ignoredNamespaces?: string[]) {\n capabilities.map(capability =>\n capability.bindings\n .filter(binding => binding.isWatch)\n .forEach(bindingElement => runBinding(bindingElement, capability.namespaces, ignoredNamespaces)),\n );\n}\n\n/**\n * Setup a watch for a binding\n *\n * @param binding the binding to watch\n * @param capabilityNamespaces list of namespaces to filter on\n */\nasync function runBinding(binding: Binding, capabilityNamespaces: string[], ignoredNamespaces?: string[]) {\n // Get the phases to match, fallback to any\n const phaseMatch: WatchPhase[] = eventToPhaseMap[binding.event] || eventToPhaseMap[Event.Any];\n\n // The watch callback is run when an object is received or dequeued\n Log.debug({ watchCfg }, \"Effective WatchConfig\");\n\n const watchCallback = async (kubernetesObject: KubernetesObject, phase: WatchPhase) => {\n // First, filter the object based on the phase\n if (phaseMatch.includes(phase)) {\n try {\n // Then, check if the object matches the filter\n const filterMatch = filterNoMatchReason(binding, kubernetesObject, capabilityNamespaces, ignoredNamespaces);\n if (filterMatch !== \"\") {\n Log.debug(filterMatch);\n return;\n }\n if (binding.isFinalize) {\n await handleFinalizerRemoval(kubernetesObject);\n } else {\n await binding.watchCallback?.(kubernetesObject, phase);\n }\n } catch (e) {\n // Errors in the watch callback should not crash the controller\n Log.error(e, \"Error executing watch callback\");\n }\n }\n };\n\n const handleFinalizerRemoval = async (kubernetesObject: KubernetesObject) => {\n if (!kubernetesObject.metadata?.deletionTimestamp) {\n return;\n }\n let shouldRemoveFinalizer: boolean | void | undefined = true;\n try {\n shouldRemoveFinalizer = await binding.finalizeCallback?.(kubernetesObject);\n\n // if not opt'ed out of / if in error state, remove pepr finalizer\n } finally {\n const peprFinal = \"pepr.dev/finalizer\";\n const meta = kubernetesObject.metadata!;\n const resource = `${meta.namespace || \"ClusterScoped\"}/${meta.name}`;\n\n // [ true, void, undefined ] SHOULD remove finalizer\n // [ false ] should NOT remove finalizer\n shouldRemoveFinalizer === false\n ? Log.debug({ obj: kubernetesObject }, `Skipping removal of finalizer '${peprFinal}' from '${resource}'`)\n : await removeFinalizer(binding, kubernetesObject);\n }\n };\n\n // Setup the resource watch\n const watcher = K8s(binding.model, binding.filters).Watch(async (obj, phase) => {\n Log.debug(obj, `Watch event ${phase} received`);\n\n if (binding.isQueue) {\n const queue = getOrCreateQueue(obj);\n await queue.enqueue(obj, phase, watchCallback);\n } else {\n await watchCallback(obj, phase);\n }\n }, watchCfg);\n\n // If failure continues, log and exit\n watcher.events.on(WatchEvent.GIVE_UP, err => {\n Log.error(err, \"Watch failed after 5 attempts, giving up\");\n process.exit(1);\n });\n\n watcher.events.on(WatchEvent.CONNECT, url => logEvent(WatchEvent.CONNECT, url));\n\n watcher.events.on(WatchEvent.DATA_ERROR, err => logEvent(WatchEvent.DATA_ERROR, err.message));\n watcher.events.on(WatchEvent.RECONNECT, retryCount =>\n logEvent(WatchEvent.RECONNECT, `Reconnecting after ${retryCount} attempt${retryCount === 1 ? \"\" : \"s\"}`),\n );\n watcher.events.on(WatchEvent.RECONNECT_PENDING, () => logEvent(WatchEvent.RECONNECT_PENDING));\n watcher.events.on(WatchEvent.GIVE_UP, err => logEvent(WatchEvent.GIVE_UP, err.message));\n watcher.events.on(WatchEvent.ABORT, err => logEvent(WatchEvent.ABORT, err.message));\n watcher.events.on(WatchEvent.OLD_RESOURCE_VERSION, err => logEvent(WatchEvent.OLD_RESOURCE_VERSION, err));\n watcher.events.on(WatchEvent.NETWORK_ERROR, err => logEvent(WatchEvent.NETWORK_ERROR, err.message));\n watcher.events.on(WatchEvent.LIST_ERROR, err => logEvent(WatchEvent.LIST_ERROR, err.message));\n watcher.events.on(WatchEvent.LIST, list => logEvent(WatchEvent.LIST, JSON.stringify(list, undefined, 2)));\n watcher.events.on(WatchEvent.CACHE_MISS, windowName => {\n metricsCollector.incCacheMiss(windowName);\n });\n\n watcher.events.on(WatchEvent.INIT_CACHE_MISS, windowName => {\n metricsCollector.initCacheMissWindow(windowName);\n });\n\n watcher.events.on(WatchEvent.INC_RESYNC_FAILURE_COUNT, retryCount => {\n metricsCollector.incRetryCount(retryCount);\n });\n\n // Start the watch\n try {\n await watcher.start();\n } catch (err) {\n Log.error(err, \"Error starting watch\");\n process.exit(1);\n }\n}\n\nexport function logEvent(event: WatchEvent, message: string = \"\", obj?: KubernetesObject) {\n const logMessage = `Watch event ${event} received${message ? `. ${message}.` : \".\"}`;\n if (obj) {\n Log.debug(obj, logMessage);\n } else {\n Log.debug(logMessage);\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { promises as fs } from \"fs\";\nimport { K8s, KubernetesObject, kind } from \"kubernetes-fluent-client\";\nimport Log from \"./logger\";\nimport { Binding, CapabilityExport } from \"./types\";\nimport { sanitizeResourceName } from \"../sdk/sdk\";\nimport {\n carriedAnnotations,\n carriedLabels,\n carriedName,\n carriedNamespace,\n carriesIgnoredNamespace,\n definedAnnotations,\n definedLabels,\n definedName,\n definedNameRegex,\n definedNamespaces,\n definedNamespaceRegexes,\n misboundNamespace,\n mismatchedAnnotations,\n mismatchedDeletionTimestamp,\n mismatchedLabels,\n mismatchedName,\n mismatchedNameRegex,\n mismatchedNamespace,\n mismatchedNamespaceRegex,\n missingCarriableNamespace,\n unbindableNamespaces,\n uncarryableNamespace,\n} from \"./filter/adjudicators\";\n\nexport function matchesRegex(pattern: string, testString: string): boolean {\n // edge-case\n if (!pattern) {\n return false;\n }\n\n const regex = new RegExp(pattern);\n return regex.test(testString);\n}\n\nexport class ValidationError extends Error {}\n\nexport function validateCapabilityNames(capabilities: CapabilityExport[] | undefined): void {\n if (capabilities && capabilities.length > 0) {\n for (let i = 0; i < capabilities.length; i++) {\n if (capabilities[i].name !== sanitizeResourceName(capabilities[i].name)) {\n throw new ValidationError(`Capability name is not a valid Kubernetes resource name: ${capabilities[i].name}`);\n }\n }\n }\n}\n\nexport function validateHash(expectedHash: string): void {\n // Require the hash to be a valid SHA-256 hash (64 characters, hexadecimal)\n const sha256Regex = /^[a-f0-9]{64}$/i;\n if (!expectedHash || !sha256Regex.test(expectedHash)) {\n Log.error(`Invalid hash. Expected a valid SHA-256 hash, got ${expectedHash}`);\n throw new ValidationError(\"Invalid hash\");\n }\n}\n\nexport type RBACMap = {\n [key: string]: {\n verbs: string[];\n plural: string;\n };\n};\n\n/**\n * Decide to run callback after the event comes back from API Server\n **/\nexport function filterNoMatchReason(\n binding: Partial<Binding>,\n obj: Partial<KubernetesObject>,\n capabilityNamespaces: string[],\n ignoredNamespaces?: string[],\n): string {\n const prefix = \"Ignoring Watch Callback:\";\n\n // prettier-ignore\n return (\n mismatchedDeletionTimestamp(binding, obj) ?\n `${prefix} Binding defines deletionTimestamp but Object does not carry it.` :\n\n mismatchedName(binding, obj) ?\n `${prefix} Binding defines name '${definedName(binding)}' but Object carries '${carriedName(obj)}'.` :\n\n misboundNamespace(binding) ?\n `${prefix} Cannot use namespace filter on a namespace object.` :\n\n mismatchedLabels(binding, obj) ?\n (\n `${prefix} Binding defines labels '${JSON.stringify(definedLabels(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedLabels(obj))}'.`\n ) :\n\n mismatchedAnnotations(binding, obj) ?\n (\n `${prefix} Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedAnnotations(obj))}'.`\n ) :\n\n uncarryableNamespace(capabilityNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n unbindableNamespaces(capabilityNamespaces, binding) ?\n (\n `${prefix} Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n mismatchedNamespace(binding, obj) ?\n (\n `${prefix} Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedNamespaceRegex(binding, obj) ?\n (\n `${prefix} Binding defines namespace regexes ` +\n `'${JSON.stringify(definedNamespaceRegexes(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedNameRegex(binding, obj) ?\n (\n `${prefix} Binding defines name regex '${definedNameRegex(binding)}' ` +\n `but Object carries '${carriedName(obj)}'.`\n ) :\n\n carriesIgnoredNamespace(ignoredNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.`\n ) :\n\n missingCarriableNamespace(capabilityNamespaces, obj) ? \n (\n `${prefix} Object does not carry a namespace ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n \"\"\n );\n}\n\nexport function addVerbIfNotExists(verbs: string[], verb: string) {\n if (!verbs.includes(verb)) {\n verbs.push(verb);\n }\n}\n\nexport function createRBACMap(capabilities: CapabilityExport[]): RBACMap {\n return capabilities.reduce((acc: RBACMap, capability: CapabilityExport) => {\n capability.bindings.forEach(binding => {\n const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;\n\n acc[\"pepr.dev/v1/peprstore\"] = {\n verbs: [\"create\", \"get\", \"patch\", \"watch\"],\n plural: \"peprstores\",\n };\n\n acc[\"apiextensions.k8s.io/v1/customresourcedefinition\"] = {\n verbs: [\"patch\", \"create\"],\n plural: \"customresourcedefinitions\",\n };\n\n if (!acc[key] && binding.isWatch) {\n acc[key] = {\n verbs: [\"watch\"],\n plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`,\n };\n }\n\n // Add finalizer rbac\n if (binding.isFinalize) {\n acc[key] = {\n verbs: [\"patch\"],\n plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`,\n };\n }\n });\n\n return acc;\n }, {});\n}\n\nexport async function createDirectoryIfNotExists(path: string) {\n try {\n await fs.access(path);\n } catch (error) {\n if (error.code === \"ENOENT\") {\n await fs.mkdir(path, { recursive: true });\n } else {\n throw error;\n }\n }\n}\n\nexport function hasEveryOverlap<T>(array1: T[], array2: T[]): boolean {\n if (!Array.isArray(array1) || !Array.isArray(array2)) {\n return false;\n }\n\n return array1.every(element => array2.includes(element));\n}\n\nexport function hasAnyOverlap<T>(array1: T[], array2: T[]): boolean {\n if (!Array.isArray(array1) || !Array.isArray(array2)) {\n return false;\n }\n\n return array1.some(element => array2.includes(element));\n}\n\nexport function ignoredNamespaceConflict(ignoreNamespaces: string[], bindingNamespaces: string[]) {\n return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);\n}\n\nexport function bindingAndCapabilityNSConflict(bindingNamespaces: string[], capabilityNamespaces: string[]) {\n if (!capabilityNamespaces) {\n return false;\n }\n return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);\n}\n\nexport function generateWatchNamespaceError(\n ignoredNamespaces: string[],\n bindingNamespaces: string[],\n capabilityNamespaces: string[],\n) {\n let err = \"\";\n\n // check if binding uses an ignored namespace\n if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {\n err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(\n \", \",\n )}] bindingNamespaces: [${bindingNamespaces.join(\", \")}].`;\n }\n\n // ensure filter namespaces are part of capability namespaces\n if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {\n err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(\n \", \",\n )}] capabilityNamespaces: [${capabilityNamespaces.join(\", \")}].`;\n }\n\n // add a space if there is a period in the middle of the string\n return err.replace(/\\.([^ ])/g, \". $1\");\n}\n\n// namespaceComplianceValidator ensures that capability bindinds respect ignored and capability namespaces\nexport function namespaceComplianceValidator(capability: CapabilityExport, ignoredNamespaces?: string[]) {\n const { namespaces: capabilityNamespaces, bindings, name } = capability;\n const bindingNamespaces = bindings.flatMap((binding: Binding) => binding.filters.namespaces);\n const bindingRegexNamespaces = bindings.flatMap((binding: Binding) => binding.filters.regexNamespaces || []);\n\n const namespaceError = generateWatchNamespaceError(\n ignoredNamespaces ? ignoredNamespaces : [],\n bindingNamespaces,\n capabilityNamespaces ? capabilityNamespaces : [],\n );\n if (namespaceError !== \"\") {\n throw new Error(\n `Error in ${name} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`,\n );\n }\n\n // Ensure that each regexNamespace matches a capabilityNamespace\n\n if (\n bindingRegexNamespaces &&\n bindingRegexNamespaces.length > 0 &&\n capabilityNamespaces &&\n capabilityNamespaces.length > 0\n ) {\n for (const regexNamespace of bindingRegexNamespaces) {\n let matches = false;\n matches =\n regexNamespace !== \"\" &&\n capabilityNamespaces.some(capabilityNamespace => matchesRegex(regexNamespace, capabilityNamespace));\n if (!matches) {\n throw new Error(\n `Ignoring Watch Callback: Object namespace does not match any capability namespace with regex ${regexNamespace}.`,\n );\n }\n }\n }\n // ensure regexNamespaces do not match ignored ns\n if (\n bindingRegexNamespaces &&\n bindingRegexNamespaces.length > 0 &&\n ignoredNamespaces &&\n ignoredNamespaces.length > 0\n ) {\n for (const regexNamespace of bindingRegexNamespaces) {\n const matchedNS = ignoredNamespaces.find(ignoredNS => matchesRegex(regexNamespace, ignoredNS));\n if (matchedNS) {\n throw new Error(\n `Ignoring Watch Callback: Regex namespace: ${regexNamespace}, is an ignored namespace: ${matchedNS}.`,\n );\n }\n }\n }\n}\n\n// check to see if all replicas are ready for all deployments in the pepr-system namespace\n// returns true if all deployments are ready, false otherwise\nexport async function checkDeploymentStatus(namespace: string) {\n const deployments = await K8s(kind.Deployment).InNamespace(namespace).Get();\n let status = false;\n let readyCount = 0;\n\n for (const deployment of deployments.items) {\n const readyReplicas = deployment.status?.readyReplicas ? deployment.status?.readyReplicas : 0;\n if (deployment.status?.readyReplicas !== deployment.spec?.replicas) {\n Log.info(\n `Waiting for deployment ${deployment.metadata?.name} rollout to finish: ${readyReplicas} of ${deployment.spec?.replicas} replicas are available`,\n );\n } else {\n Log.info(\n `Deployment ${deployment.metadata?.name} rolled out: ${readyReplicas} of ${deployment.spec?.replicas} replicas are available`,\n );\n readyCount++;\n }\n }\n if (readyCount === deployments.items.length) {\n status = true;\n }\n return status;\n}\n\n// wait for all deployments in the pepr-system namespace to be ready\nexport async function namespaceDeploymentsReady(namespace: string = \"pepr-system\") {\n Log.info(`Checking ${namespace} deployments status...`);\n let ready = false;\n while (!ready) {\n ready = await checkDeploymentStatus(namespace);\n if (ready) {\n return ready;\n }\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n Log.info(`All ${namespace} deployments are ready`);\n}\n\n// check if secret is over the size limit\nexport function secretOverLimit(str: string): boolean {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(str);\n const sizeInBytes = encoded.length;\n const oneMiBInBytes = 1048576;\n return sizeInBytes > oneMiBInBytes;\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport const parseTimeout = (value: string, previous: unknown): number => {\n const parsedValue = parseInt(value, 10);\n const floatValue = parseFloat(value);\n if (isNaN(parsedValue)) {\n throw new Error(\"Not a number.\");\n } else if (parsedValue !== floatValue) {\n throw new Error(\"Value must be an integer.\");\n } else if (parsedValue < 1 || parsedValue > 30) {\n throw new Error(\"Number must be between 1 and 30.\");\n }\n return parsedValue;\n};\n\n// Remove leading whitespace while keeping format of file\nexport function dedent(file: string) {\n // Check if the first line is empty and remove it\n const lines = file.split(\"\\n\");\n if (lines[0].trim() === \"\") {\n lines.shift(); // Remove the first line if it's empty\n file = lines.join(\"\\n\"); // Rejoin the remaining lines back into a single string\n }\n\n const match = file.match(/^[ \\t]*(?=\\S)/gm);\n const indent = match && Math.min(...match.map(el => el.length));\n if (indent && indent > 0) {\n const re = new RegExp(`^[ \\\\t]{${indent}}`, \"gm\");\n return file.replace(re, \"\");\n }\n return file;\n}\n\nexport function replaceString(str: string, stringA: string, stringB: string) {\n // eslint-disable-next-line no-useless-escape\n const escapedStringA = stringA.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n const regExp = new RegExp(escapedStringA, \"g\");\n return str.replace(regExp, stringB);\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { PeprValidateRequest } from \"../lib/validate-request\";\nimport { PeprMutateRequest } from \"../lib/mutate-request\";\nimport { V1OwnerReference } from \"@kubernetes/client-node\";\nimport { GenericKind } from \"kubernetes-fluent-client\";\nimport { K8s, kind } from \"kubernetes-fluent-client\";\nimport Log from \"../lib/logger\";\n\n/**\n * Returns all containers in a pod\n * @param request the request/pod to get the containers from\n * @param containerType the type of container to get\n * @returns the list of containers in the pod\n */\nexport function containers(\n request: PeprValidateRequest<kind.Pod> | PeprMutateRequest<kind.Pod>,\n containerType?: \"containers\" | \"initContainers\" | \"ephemeralContainers\",\n) {\n const containers = request.Raw.spec?.containers || [];\n const initContainers = request.Raw.spec?.initContainers || [];\n const ephemeralContainers = request.Raw.spec?.ephemeralContainers || [];\n\n if (containerType === \"containers\") {\n return containers;\n }\n if (containerType === \"initContainers\") {\n return initContainers;\n }\n if (containerType === \"ephemeralContainers\") {\n return ephemeralContainers;\n }\n return [...containers, ...initContainers, ...ephemeralContainers];\n}\n\n/**\n * Write a K8s event for a CRD\n *\n * @param cr The custom resource to write the event for\n * @param event The event to write, should contain a human-readable message for the event\n * @param eventType The type of event to write, for example \"Warning\"\n * @param eventReason The reason for the event, for example \"ReconciliationFailed\"\n * @param reportingComponent The component that is reporting the event, for example \"uds.dev/operator\"\n * @param reportingInstance The instance of the component that is reporting the event, for example process.env.HOSTNAME\n */\nexport async function writeEvent(\n cr: GenericKind,\n event: Partial<kind.CoreEvent>,\n eventType: string,\n eventReason: string,\n reportingComponent: string,\n reportingInstance: string,\n) {\n Log.debug(cr.metadata, `Writing event: ${event.message}`);\n\n await K8s(kind.CoreEvent).Create({\n type: eventType,\n reason: eventReason,\n ...event,\n // Fixed values\n metadata: {\n namespace: cr.metadata!.namespace,\n generateName: cr.metadata!.name,\n },\n involvedObject: {\n apiVersion: cr.apiVersion,\n kind: cr.kind,\n name: cr.metadata!.name,\n namespace: cr.metadata!.namespace,\n uid: cr.metadata!.uid,\n },\n firstTimestamp: new Date(),\n reportingComponent: reportingComponent,\n reportingInstance: reportingInstance,\n });\n}\n\n/**\n * Get the owner reference for a custom resource\n * @param customResource the custom resource to get the owner reference for\n * @param blockOwnerDeletion if true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed.\n * @param controller if true, this reference points to the managing controller.\n * @returns the owner reference array for the custom resource\n */\nexport function getOwnerRefFrom(\n customResource: GenericKind,\n blockOwnerDeletion?: boolean,\n controller?: boolean,\n): V1OwnerReference[] {\n const { apiVersion, kind, metadata } = customResource;\n const { name, uid } = metadata!;\n\n return [\n {\n apiVersion: apiVersion!,\n kind: kind!,\n uid: uid!,\n name: name!,\n ...(blockOwnerDeletion !== undefined && { blockOwnerDeletion }),\n ...(controller !== undefined && { controller }),\n },\n ];\n}\n\n/**\n * Sanitize a resource name to make it a valid Kubernetes resource name.\n *\n * @param name the name of the resource to sanitize\n * @returns the sanitized resource name\n */\nexport function sanitizeResourceName(name: string) {\n return (\n name\n // The name must be lowercase\n .toLowerCase()\n // Replace sequences of non-alphanumeric characters with a single '-'\n .replace(/[^a-z0-9]+/g, \"-\")\n // Truncate the name to 250 characters\n .slice(0, 250)\n // Remove leading and trailing non-letter characters\n .replace(/^[^a-z]+|[^a-z]+$/g, \"\")\n );\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { K8s, KubernetesObject, RegisterKind } from \"kubernetes-fluent-client\";\nimport Log from \"./logger\";\nimport { Binding, DeepPartial } from \"./types\";\nimport { Operation } from \"./enums\";\nimport { PeprMutateRequest } from \"./mutate-request\";\n\nexport function addFinalizer<K extends KubernetesObject>(request: PeprMutateRequest<K>) {\n // if a DELETE is being processed, don't add a finalizer\n if (request.Request.operation === Operation.DELETE) {\n return;\n }\n\n // if an UPDATE is being processed and it HAS a deletionTimestamp, the\n // resource is going through a pre-delete flow so don't (re-)add a finalizer\n if (request.Request.operation === Operation.UPDATE && request.Raw.metadata?.deletionTimestamp) {\n return;\n }\n\n const peprFinal = \"pepr.dev/finalizer\";\n const finalizers = request.Raw.metadata?.finalizers || [];\n if (!finalizers.includes(peprFinal)) {\n finalizers.push(peprFinal);\n }\n\n request.Merge({ metadata: { finalizers } } as DeepPartial<K>);\n}\n\nexport async function removeFinalizer(binding: Binding, obj: KubernetesObject) {\n const peprFinal = \"pepr.dev/finalizer\";\n const meta = obj.metadata!;\n const resource = `${meta.namespace || \"ClusterScoped\"}/${meta.name}`;\n\n Log.debug({ obj }, `Removing finalizer '${peprFinal}' from '${resource}'`);\n\n // ensure request model is registerd with KFC (for non-built in CRD's, etc.)\n const { model, kind } = binding;\n try {\n RegisterKind(model, kind);\n } catch (e) {\n const expected = e.message === `GVK ${model.name} already registered`;\n if (!expected) {\n Log.error({ model, kind, error: e }, `Error registering \"${kind}\" during finalization.`);\n return;\n }\n }\n\n // remove pepr finalizers\n const finalizers = meta.finalizers?.filter(f => f !== peprFinal) || [];\n\n // JSON Patch - replace a key\n // https://datatracker.ietf.org/doc/html/rfc6902/#section-4.3\n obj = await K8s(model, meta).Patch([\n {\n op: \"replace\",\n path: `/metadata/finalizers`,\n value: finalizers,\n },\n ]);\n Log.debug({ obj }, `Removed finalizer '${peprFinal}' from '${resource}'`);\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { KubernetesObject } from \"@kubernetes/client-node\";\nimport { WatchPhase } from \"kubernetes-fluent-client/dist/fluent/types\";\nimport { randomBytes } from \"node:crypto\";\nimport Log from \"./logger\";\n\ntype WatchCallback = (obj: KubernetesObject, phase: WatchPhase) => Promise<void>;\n\ntype QueueItem<K extends KubernetesObject> = {\n item: K;\n phase: WatchPhase;\n callback: WatchCallback;\n resolve: (value: void | PromiseLike<void>) => void;\n reject: (reason?: string) => void;\n};\n\n/**\n * Queue is a FIFO queue for reconciling\n */\nexport class Queue<K extends KubernetesObject> {\n #name: string;\n #uid: string;\n #queue: QueueItem<K>[] = [];\n #pendingPromise = false;\n\n constructor(name: string) {\n this.#name = name;\n this.#uid = `${Date.now()}-${randomBytes(2).toString(\"hex\")}`;\n }\n\n label() {\n return { name: this.#name, uid: this.#uid };\n }\n\n stats() {\n return {\n queue: this.label(),\n stats: {\n length: this.#queue.length,\n },\n };\n }\n\n /**\n * Enqueue adds an item to the queue and returns a promise that resolves when the item is\n * reconciled.\n *\n * @param item The object to reconcile\n * @param type The watch phase requested for reconcile\n * @param reconcile The callback to enqueue for reconcile\n * @returns A promise that resolves when the object is reconciled\n */\n enqueue(item: K, phase: WatchPhase, reconcile: WatchCallback) {\n const note = {\n queue: this.label(),\n item: {\n name: item.metadata?.name,\n namespace: item.metadata?.namespace,\n resourceVersion: item.metadata?.resourceVersion,\n },\n };\n Log.debug(note, \"Enqueueing\");\n return new Promise<void>((resolve, reject) => {\n this.#queue.push({ item, phase, callback: reconcile, resolve, reject });\n Log.debug(this.stats(), \"Queue stats - push\");\n return this.#dequeue();\n });\n }\n\n /**\n * Dequeue reconciles the next item in the queue\n *\n * @returns A promise that resolves when the webapp is reconciled\n */\n async #dequeue() {\n // If there is a pending promise, do nothing\n if (this.#pendingPromise) {\n Log.debug(\"Pending promise, not dequeuing\");\n return false;\n }\n\n // Take the next element from the queue\n const element = this.#queue.shift();\n\n // If there is no element, do nothing\n if (!element) {\n Log.debug(\"No element, not dequeuing\");\n return false;\n }\n\n try {\n // Set the pending promise flag to avoid concurrent reconciliations\n this.#pendingPromise = true;\n\n // Reconcile the element\n const note = {\n queue: this.label(),\n item: {\n name: element.item.metadata?.name,\n namespace: element.item.metadata?.namespace,\n resourceVersion: element.item.metadata?.resourceVersion,\n },\n };\n Log.debug(note, \"Reconciling\");\n await element.callback(element.item, element.phase);\n Log.debug(note, \"Reconciled\");\n\n element.resolve();\n } catch (e) {\n Log.debug(`Error reconciling ${element.item.metadata!.name}`, { error: e });\n element.reject(e);\n } finally {\n Log.debug(this.stats(), \"Queue stats - shift\");\n\n // Reset the pending promise flag\n Log.debug(\"Resetting pending promise and dequeuing\");\n this.#pendingPromise = false;\n\n // After the element is reconciled, dequeue the next element\n await this.#dequeue();\n }\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { clone } from \"ramda\";\nimport pointer from \"json-pointer\";\nexport type DataOp = \"add\" | \"remove\";\nexport type DataStore = Record<string, string>;\nexport type DataSender = (op: DataOp, keys: string[], value?: string) => void;\nexport type DataReceiver = (data: DataStore) => void;\nexport type Unsubscribe = () => void;\n\nconst MAX_WAIT_TIME = 15000;\nconst STORE_VERSION_PREFIX = \"v2\";\n\nexport function v2StoreKey(key: string) {\n return `${STORE_VERSION_PREFIX}-${pointer.escape(key)}`;\n}\n\nexport function v2UnescapedStoreKey(key: string) {\n return `${STORE_VERSION_PREFIX}-${key}`;\n}\n\nexport function stripV2Prefix(key: string) {\n return key.replace(/^v2-/, \"\");\n}\nexport interface PeprStore {\n /**\n * Returns the current value associated with the given key, or null if the given key does not exist.\n */\n getItem(key: string): string | null;\n /**\n * Removes all key/value pairs, if there are any.\n */\n clear(): void;\n /**\n * Removes the key/value pair with the given key, if a key/value pair with the given key exists.\n */\n removeItem(key: string): void;\n /**\n * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.\n */\n setItem(key: string, value: string): void;\n\n /**\n * Subscribe to changes in the store. This API behaves similarly to the [Svelte Store API](https://vercel.com/docs/beginner-sveltekit/svelte-stores#using-the-store).\n *\n * @param listener - The callback to be invoked when the store changes.\n * @returns A function to unsubscribe from the listener.\n */\n subscribe(listener: DataReceiver): Unsubscribe;\n\n /**\n * Register a function to be called when the store is ready.\n */\n onReady(callback: DataReceiver): void;\n\n /**\n * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.\n * Resolves when the key/value show up in the store.\n */\n setItemAndWait(key: string, value: string): Promise<void>;\n\n /**\n * Remove the value of the key.\n * Resolves when the key does not show up in the store.\n */\n removeItemAndWait(key: string): Promise<void>;\n}\n\n/**\n * A key-value data store that can be used to persist data that should be shared across Pepr controllers and capabilities.\n *\n * The API is similar to the [Storage API](https://developer.mozilla.org/docs/Web/API/Storage)\n */\n\nexport class Storage implements PeprStore {\n #store: DataStore = {};\n #send!: DataSender;\n #subscribers: Record<number, DataReceiver> = {};\n #subscriberId = 0;\n #readyHandlers: DataReceiver[] = [];\n\n registerSender = (send: DataSender) => {\n this.#send = send;\n };\n\n receive = (data: DataStore) => {\n this.#store = data || {};\n\n this.#onReady();\n\n // Notify all subscribers\n for (const idx in this.#subscribers) {\n // Send a unique clone of the store to each subscriber\n this.#subscribers[idx](clone(this.#store));\n }\n };\n\n getItem = (key: string) => {\n const result = this.#store[v2UnescapedStoreKey(key)] || null;\n if (result !== null && typeof result !== \"function\" && typeof result !== \"object\") {\n return result;\n }\n return null;\n };\n\n clear = () => {\n Object.keys(this.#store).length > 0 &&\n this.#dispatchUpdate(\n \"remove\",\n Object.keys(this.#store).map(key => pointer.escape(key)),\n );\n };\n\n removeItem = (key: string) => {\n this.#dispatchUpdate(\"remove\", [v2StoreKey(key)]);\n };\n\n setItem = (key: string, value: string) => {\n this.#dispatchUpdate(\"add\", [v2StoreKey(key)], value);\n };\n\n /**\n * Creates a promise and subscribes to the store, the promise resolves when\n * the key and value are seen in the store.\n *\n * @param key - The key to add into the store\n * @param value - The value of the key\n * @returns\n */\n setItemAndWait = (key: string, value: string) => {\n this.#dispatchUpdate(\"add\", [v2StoreKey(key)], value);\n\n return new Promise<void>((resolve, reject) => {\n const unsubscribe = this.subscribe(data => {\n if (data[`${v2UnescapedStoreKey(key)}`] === value) {\n unsubscribe();\n resolve();\n }\n });\n\n // If promise has not resolved before MAX_WAIT_TIME reject\n setTimeout(() => {\n unsubscribe();\n return reject();\n }, MAX_WAIT_TIME);\n });\n };\n\n /**\n * Creates a promise and subscribes to the store, the promise resolves when\n * the key is removed from the store.\n *\n * @param key - The key to add into the store\n * @returns\n */\n removeItemAndWait = (key: string) => {\n this.#dispatchUpdate(\"remove\", [v2StoreKey(key)]);\n return new Promise<void>((resolve, reject) => {\n const unsubscribe = this.subscribe(data => {\n if (!Object.hasOwn(data, `${v2UnescapedStoreKey(key)}`)) {\n unsubscribe();\n resolve();\n }\n });\n\n // If promise has not resolved before MAX_WAIT_TIME reject\n setTimeout(() => {\n unsubscribe();\n return reject();\n }, MAX_WAIT_TIME);\n });\n };\n\n subscribe = (subscriber: DataReceiver) => {\n const idx = this.#subscriberId++;\n this.#subscribers[idx] = subscriber;\n return () => this.unsubscribe(idx);\n };\n\n onReady = (callback: DataReceiver) => {\n this.#readyHandlers.push(callback);\n };\n\n /**\n * Remove a subscriber from the list of subscribers.\n * @param idx - The index of the subscriber to remove.\n */\n unsubscribe = (idx: number) => {\n delete this.#subscribers[idx];\n };\n\n #onReady = () => {\n // Notify all ready handlers with a clone of the store\n for (const handler of this.#readyHandlers) {\n handler(clone(this.#store));\n }\n\n // Make this a noop so that it can't be called again\n this.#onReady = () => {};\n };\n\n /**\n * Dispatch an update to the store and notify all subscribers.\n * @param op - The type of operation to perform.\n * @param keys - The keys to update.\n * @param [value] - The new value.\n */\n #dispatchUpdate = (op: DataOp, keys: string[], value?: string) => {\n this.#send(op, keys, value);\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { PeprStore } from \"./storage\";\n\nexport type Unit = \"seconds\" | \"second\" | \"minute\" | \"minutes\" | \"hours\" | \"hour\";\n\nexport interface Schedule {\n /**\n * * The name of the store\n */\n name: string;\n /**\n * The value associated with a unit of time\n */\n every: number;\n /**\n * The unit of time\n */\n unit: Unit;\n /**\n * The code to run\n */\n run: () => void;\n /**\n * The start time of the schedule\n */\n startTime?: Date | undefined;\n\n /**\n * The number of times the schedule has run\n */\n completions?: number | undefined;\n /**\n * Tje intervalID to clear the interval\n */\n intervalID?: NodeJS.Timeout;\n}\n\nexport class OnSchedule implements Schedule {\n intervalId: NodeJS.Timeout | null = null;\n store: PeprStore | undefined;\n name!: string;\n completions?: number | undefined;\n every: number;\n unit: Unit;\n run!: () => void;\n startTime?: Date | undefined;\n duration: number | undefined;\n lastTimestamp: Date | undefined;\n\n constructor(schedule: Schedule) {\n this.name = schedule.name;\n this.run = schedule.run;\n this.every = schedule.every;\n this.unit = schedule.unit;\n this.startTime = schedule?.startTime;\n this.completions = schedule?.completions;\n }\n setStore(store: PeprStore) {\n this.store = store;\n this.startInterval();\n }\n startInterval() {\n this.checkStore();\n this.getDuration();\n this.setupInterval();\n }\n /**\n * Checks the store for this schedule and sets the values if it exists\n * @returns\n */\n checkStore() {\n const result = this.store && this.store.getItem(this.name);\n if (result) {\n const storedSchedule = JSON.parse(result);\n this.completions = storedSchedule?.completions;\n this.startTime = storedSchedule?.startTime;\n this.lastTimestamp = storedSchedule?.lastTimestamp;\n }\n }\n\n /**\n * Saves the schedule to the store\n * @returns\n */\n saveToStore() {\n const schedule = {\n completions: this.completions,\n startTime: this.startTime,\n lastTimestamp: new Date(),\n name: this.name,\n };\n this.store && this.store.setItem(this.name, JSON.stringify(schedule));\n }\n\n /**\n * Gets the durations in milliseconds\n */\n getDuration() {\n switch (this.unit) {\n case \"seconds\":\n if (this.every < 10) throw new Error(\"10 Seconds in the smallest interval allowed\");\n this.duration = 1000 * this.every;\n break;\n case \"minutes\":\n case \"minute\":\n this.duration = 1000 * 60 * this.every;\n break;\n case \"hours\":\n case \"hour\":\n this.duration = 1000 * 60 * 60 * this.every;\n break;\n default:\n throw new Error(\"Invalid time unit\");\n }\n }\n\n /**\n * Sets up the interval\n */\n setupInterval() {\n const now = new Date();\n let delay: number | undefined;\n\n if (this.lastTimestamp && this.startTime) {\n this.startTime = undefined;\n }\n\n if (this.startTime) {\n delay = this.startTime.getTime() - now.getTime();\n } else if (this.lastTimestamp && this.duration) {\n const lastTimestamp = new Date(this.lastTimestamp);\n delay = this.duration - (now.getTime() - lastTimestamp.getTime());\n }\n\n if (delay === undefined || delay <= 0) {\n this.start();\n } else {\n setTimeout(() => {\n this.start();\n }, delay);\n }\n }\n\n /**\n * Starts the interval\n */\n start() {\n this.intervalId = setInterval(() => {\n if (this.completions === 0) {\n this.stop();\n return;\n } else {\n this.run();\n\n if (this.completions && this.completions !== 0) {\n this.completions -= 1;\n }\n this.saveToStore();\n }\n }, this.duration);\n }\n\n /**\n * Stops the interval\n */\n stop() {\n if (this.intervalId) {\n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,GAAG,aAAa,UAAU,cAAc;AAAA,IACnD;AAEA,aAAS,wBAA0C;AACjD,qBAAI,MAAM,8BAA8B;AACxC,cAAQ,QAAQ,oBAAoB;AACpC,aAAO;AAAA,IACT;AAEA,aAAS,cAAc,WAAqC;AAC1D,qBAAI,MAAM,yBAAyB,SAAS,IAAI,MAAM;AACtD,cAAQ,QAAQ,YAAY,UAAU;AACtC,aAAO;AAAA,IACT;AAEA,aAAS,SAAS,MAAgC;AAChD,qBAAI,MAAM,mBAAmB,IAAI,IAAI,MAAM;AAC3C,cAAQ,QAAQ,OAAO;AACvB,aAAO;AAAA,IACT;AAEA,aAAS,UAAU,KAAa,QAAQ,IAAsB;AAC5D,qBAAI,MAAM,oBAAoB,GAAG,IAAI,KAAK,IAAI,MAAM;AACpD,cAAQ,QAAQ,OAAO,GAAG,IAAI;AAC9B,aAAO;AAAA,IACT;AAEA,aAAS,eAAe,KAAa,QAAQ,IAAsB;AACjE,qBAAI,MAAM,yBAAyB,GAAG,IAAI,KAAK,IAAI,MAAM;AACzD,cAAQ,QAAQ,YAAY,GAAG,IAAI;AACnC,aAAO;AAAA,IACT;AAEA,aAAS,MAAM,OAAe;AAC5B,qBAAI,MAAM,uBAAuB,KAAK,IAAI,MAAM;AAChD,cAAQ,QAAQ;AAChB,aAAO;AAAA,IACT;AAEA,aAAS,UAAU,OAAc;AAC/B,cAAQ,QAAQ;AAChB,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,oBAAoB,MAAM,+CAA8B;AAAA,MACxD,WAAW,MAAM,+BAAsB;AAAA,MACvC,WAAW,MAAM,+BAAsB;AAAA,MACvC,WAAW,MAAM,+BAAsB;AAAA,IACzC;AAAA,EACF;AACF;",
6
- "names": ["a", "import_kubernetes_fluent_client", "import_kubernetes_fluent_client", "import_ramda", "import_ramda", "promClient", "kind", "import_ramda", "jsonPatch", "e", "import_ramda", "import_kubernetes_fluent_client", "import_ramda", "import_kubernetes_fluent_client", "namespace", "name", "express", "fs", "https", "namespace", "res", "import_kubernetes_fluent_client", "import_kubernetes_fluent_client", "import_kubernetes_fluent_client", "containers", "kind", "import_kubernetes_fluent_client", "kind", "kind", "import_ramda", "pointer", "pointer", "kind"]
3
+ "sources": ["../src/lib.ts", "../src/lib/capability.ts", "../src/lib/telemetry/logger.ts", "../src/lib/module.ts", "../src/lib/controller/index.ts", "../src/lib/telemetry/metrics.ts", "../src/lib/mutate-processor.ts", "../src/lib/errors.ts", "../src/lib/filter/adjudicators/adjudicators.ts", "../src/lib/filter/filter.ts", "../src/lib/mutate-request.ts", "../src/lib/utils.ts", "../src/lib/validate-request.ts", "../src/lib/validate-processor.ts", "../src/lib/controller/store.ts", "../src/lib/k8s.ts", "../src/lib/controller/storeCache.ts", "../src/lib/controller/index.util.ts", "../src/lib/watch-processor.ts", "../src/sdk/sdk.ts", "../src/lib/helpers.ts", "../src/lib/finalizer.ts", "../src/lib/queue.ts", "../src/lib/storage.ts", "../src/lib/schedule.ts"],
4
+ "sourcesContent": ["import { K8s, RegisterKind, kind as a, fetch, fetchStatus, kind } from \"kubernetes-fluent-client\";\nimport * as R from \"ramda\";\n\nimport { Capability } from \"./lib/capability\";\nimport Log from \"./lib/telemetry/logger\";\nimport { PeprModule } from \"./lib/module\";\nimport { PeprMutateRequest } from \"./lib/mutate-request\";\nimport * as PeprUtils from \"./lib/utils\";\nimport { PeprValidateRequest } from \"./lib/validate-request\";\nimport * as sdk from \"./sdk/sdk\";\n\nexport {\n Capability,\n K8s,\n Log,\n PeprModule,\n PeprMutateRequest,\n PeprUtils,\n PeprValidateRequest,\n R,\n RegisterKind,\n a,\n fetch,\n fetchStatus,\n kind,\n sdk,\n};\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { GenericClass, GroupVersionKind, modelToGroupVersionKind } from \"kubernetes-fluent-client\";\nimport { pickBy } from \"ramda\";\nimport Log from \"./telemetry/logger\";\nimport { isBuildMode, isDevMode, isWatchMode } from \"./module\";\nimport { PeprStore, Storage } from \"./storage\";\nimport { OnSchedule, Schedule } from \"./schedule\";\nimport { Event } from \"./enums\";\nimport {\n Binding,\n BindingFilter,\n BindingWithName,\n CapabilityCfg,\n CapabilityExport,\n MutateAction,\n MutateActionChain,\n ValidateAction,\n ValidateActionChain,\n WatchLogAction,\n FinalizeAction,\n FinalizeActionChain,\n WhenSelector,\n} from \"./types\";\nimport { addFinalizer } from \"./finalizer\";\n\nconst registerAdmission = isBuildMode() || !isWatchMode();\nconst registerWatch = isBuildMode() || isWatchMode() || isDevMode();\n\n/**\n * A capability is a unit of functionality that can be registered with the Pepr runtime.\n */\nexport class Capability implements CapabilityExport {\n #name: string;\n #description: string;\n #namespaces?: string[] | undefined;\n #bindings: Binding[] = [];\n #store = new Storage();\n #scheduleStore = new Storage();\n #registered = false;\n #scheduleRegistered = false;\n hasSchedule: boolean;\n\n /**\n * Run code on a schedule with the capability.\n *\n * @param schedule The schedule to run the code on\n * @returns\n */\n OnSchedule: (schedule: Schedule) => void = (schedule: Schedule) => {\n const { name, every, unit, run, startTime, completions } = schedule;\n this.hasSchedule = true;\n\n if (process.env.PEPR_WATCH_MODE === \"true\" || process.env.PEPR_MODE === \"dev\") {\n // Only create/watch schedule store if necessary\n\n // Create a new schedule\n const newSchedule: Schedule = {\n name,\n every,\n unit,\n run,\n startTime,\n completions,\n };\n\n this.#scheduleStore.onReady(() => {\n new OnSchedule(newSchedule).setStore(this.#scheduleStore);\n });\n }\n };\n\n public getScheduleStore() {\n return this.#scheduleStore;\n }\n\n /**\n * Store is a key-value data store that can be used to persist data that should be shared\n * between requests. Each capability has its own store, and the data is persisted in Kubernetes\n * in the `pepr-system` namespace.\n *\n * Note: You should only access the store from within an action.\n */\n Store: PeprStore = {\n clear: this.#store.clear,\n getItem: this.#store.getItem,\n removeItem: this.#store.removeItem,\n removeItemAndWait: this.#store.removeItemAndWait,\n setItem: this.#store.setItem,\n subscribe: this.#store.subscribe,\n onReady: this.#store.onReady,\n setItemAndWait: this.#store.setItemAndWait,\n };\n\n /**\n * ScheduleStore is a key-value data store used to persist schedule data that should be shared\n * between intervals. Each Schedule shares store, and the data is persisted in Kubernetes\n * in the `pepr-system` namespace.\n *\n * Note: There is no direct access to schedule store\n */\n ScheduleStore: PeprStore = {\n clear: this.#scheduleStore.clear,\n getItem: this.#scheduleStore.getItem,\n removeItemAndWait: this.#scheduleStore.removeItemAndWait,\n removeItem: this.#scheduleStore.removeItem,\n setItemAndWait: this.#scheduleStore.setItemAndWait,\n setItem: this.#scheduleStore.setItem,\n subscribe: this.#scheduleStore.subscribe,\n onReady: this.#scheduleStore.onReady,\n };\n\n get bindings() {\n return this.#bindings;\n }\n\n get name() {\n return this.#name;\n }\n\n get description() {\n return this.#description;\n }\n\n get namespaces() {\n return this.#namespaces || [];\n }\n\n constructor(cfg: CapabilityCfg) {\n this.#name = cfg.name;\n this.#description = cfg.description;\n this.#namespaces = cfg.namespaces;\n this.hasSchedule = false;\n\n Log.info(`Capability ${this.#name} registered`);\n Log.debug(cfg);\n }\n\n /**\n * Register the store with the capability. This is called automatically by the Pepr controller.\n */\n registerScheduleStore = (): Storage => {\n Log.info(`Registering schedule store for ${this.#name}`);\n\n if (this.#scheduleRegistered) {\n throw new Error(`Schedule store already registered for ${this.#name}`);\n }\n\n this.#scheduleRegistered = true;\n\n // Pass back any ready callback to the controller\n return this.#scheduleStore;\n };\n\n /**\n * Register the store with the capability. This is called automatically by the Pepr controller.\n *\n * @param store\n */\n registerStore = (): Storage => {\n Log.info(`Registering store for ${this.#name}`);\n\n if (this.#registered) {\n throw new Error(`Store already registered for ${this.#name}`);\n }\n\n this.#registered = true;\n\n // Pass back any ready callback to the controller\n return this.#store;\n };\n\n /**\n * The When method is used to register a action to be executed when a Kubernetes resource is\n * processed by Pepr. The action will be executed if the resource matches the specified kind and any\n * filters that are applied.\n *\n * @param model the KubernetesObject model to match\n * @param kind if using a custom KubernetesObject not available in `a.*`, specify the GroupVersionKind\n * @returns\n */\n When = <T extends GenericClass>(model: T, kind?: GroupVersionKind): WhenSelector<T> => {\n const matchedKind = modelToGroupVersionKind(model.name);\n\n // If the kind is not specified and the model is not a KubernetesObject, throw an error\n if (!matchedKind && !kind) {\n throw new Error(`Kind not specified for ${model.name}`);\n }\n\n const binding: Binding = {\n model,\n // If the kind is not specified, use the matched kind from the model\n kind: kind || matchedKind,\n event: Event.ANY,\n filters: {\n name: \"\",\n namespaces: [],\n regexNamespaces: [],\n regexName: \"\",\n labels: {},\n annotations: {},\n deletionTimestamp: false,\n },\n };\n\n const bindings = this.#bindings;\n const prefix = `${this.#name}: ${model.name}`;\n const commonChain = { WithLabel, WithAnnotation, WithDeletionTimestamp, Mutate, Validate, Watch, Reconcile, Alias };\n const isNotEmpty = (value: object) => Object.keys(value).length > 0;\n const log = (message: string, cbString: string) => {\n const filteredObj = pickBy(isNotEmpty, binding.filters);\n\n Log.info(`${message} configured for ${binding.event}`, prefix);\n Log.info(filteredObj, prefix);\n Log.debug(cbString, prefix);\n };\n\n function Validate(validateCallback: ValidateAction<T>): ValidateActionChain<T> {\n if (registerAdmission) {\n log(\"Validate Action\", validateCallback.toString());\n\n // Create the child logger\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" });\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isValidate: true,\n validateCallback: async (req, logger = aliasLogger) => {\n Log.info(`Executing validate action with alias: ${binding.alias || \"no alias provided\"}`);\n return await validateCallback(req, logger);\n },\n });\n }\n\n return { Watch, Reconcile };\n }\n\n function Mutate(mutateCallback: MutateAction<T>): MutateActionChain<T> {\n if (registerAdmission) {\n log(\"Mutate Action\", mutateCallback.toString());\n\n // Create the child logger\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" });\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isMutate: true,\n mutateCallback: async (req, logger = aliasLogger) => {\n Log.info(`Executing mutation action with alias: ${binding.alias || \"no alias provided\"}`);\n await mutateCallback(req, logger);\n },\n });\n }\n\n // Now only allow adding actions to the same binding\n return { Watch, Validate, Reconcile };\n }\n\n function Watch(watchCallback: WatchLogAction<T>): FinalizeActionChain<T> {\n if (registerWatch) {\n log(\"Watch Action\", watchCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isWatch: true,\n watchCallback: async (update, phase, logger = aliasLogger) => {\n Log.info(`Executing watch action with alias: ${binding.alias || \"no alias provided\"}`);\n await watchCallback(update, phase, logger);\n },\n });\n }\n return { Finalize };\n }\n\n function Reconcile(reconcileCallback: WatchLogAction<T>): FinalizeActionChain<T> {\n if (registerWatch) {\n log(\"Reconcile Action\", reconcileCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Push the binding to the list of bindings for this capability as a new BindingAction\n // with the callback function to preserve\n bindings.push({\n ...binding,\n isWatch: true,\n isQueue: true,\n watchCallback: async (update, phase, logger = aliasLogger) => {\n Log.info(`Executing reconcile action with alias: ${binding.alias || \"no alias provided\"}`);\n await reconcileCallback(update, phase, logger);\n },\n });\n }\n return { Finalize };\n }\n\n function Finalize(finalizeCallback: FinalizeAction<T>): void {\n log(\"Finalize Action\", finalizeCallback.toString());\n\n // Create the child logger and cast it to the expected type\n const aliasLogger = Log.child({ alias: binding.alias || \"no alias provided\" }) as typeof Log;\n\n // Add binding to inject Pepr finalizer during admission (Mutate)\n if (registerAdmission) {\n const mutateBinding = {\n ...binding,\n isMutate: true,\n isFinalize: true,\n event: Event.ANY,\n mutateCallback: addFinalizer,\n };\n bindings.push(mutateBinding);\n }\n\n // Add binding to process finalizer callback / remove Pepr finalizer (Watch)\n if (registerWatch) {\n const watchBinding = {\n ...binding,\n isWatch: true,\n isFinalize: true,\n event: Event.UPDATE,\n finalizeCallback: async (update: InstanceType<T>, logger = aliasLogger) => {\n Log.info(`Executing finalize action with alias: ${binding.alias || \"no alias provided\"}`);\n return await finalizeCallback(update, logger);\n },\n };\n bindings.push(watchBinding);\n }\n }\n\n function InNamespace(...namespaces: string[]): BindingWithName<T> {\n Log.debug(`Add namespaces filter ${namespaces}`, prefix);\n binding.filters.namespaces.push(...namespaces);\n return { ...commonChain, WithName, WithNameRegex };\n }\n\n function InNamespaceRegex(...namespaces: RegExp[]): BindingWithName<T> {\n Log.debug(`Add regex namespaces filter ${namespaces}`, prefix);\n binding.filters.regexNamespaces.push(...namespaces.map(regex => regex.source));\n return { ...commonChain, WithName, WithNameRegex };\n }\n\n function WithDeletionTimestamp(): BindingFilter<T> {\n Log.debug(\"Add deletionTimestamp filter\");\n binding.filters.deletionTimestamp = true;\n return commonChain;\n }\n\n function WithNameRegex(regexName: RegExp): BindingFilter<T> {\n Log.debug(`Add regex name filter ${regexName}`, prefix);\n binding.filters.regexName = regexName.source;\n return commonChain;\n }\n\n function WithName(name: string): BindingFilter<T> {\n Log.debug(`Add name filter ${name}`, prefix);\n binding.filters.name = name;\n return commonChain;\n }\n\n function WithLabel(key: string, value = \"\"): BindingFilter<T> {\n Log.debug(`Add label filter ${key}=${value}`, prefix);\n binding.filters.labels[key] = value;\n return commonChain;\n }\n\n function WithAnnotation(key: string, value = \"\"): BindingFilter<T> {\n Log.debug(`Add annotation filter ${key}=${value}`, prefix);\n binding.filters.annotations[key] = value;\n return commonChain;\n }\n\n function Alias(alias: string) {\n Log.debug(`Adding prefix alias ${alias}`, prefix);\n binding.alias = alias;\n return commonChain;\n }\n\n function bindEvent(event: Event) {\n binding.event = event;\n return {\n ...commonChain,\n InNamespace,\n InNamespaceRegex,\n WithName,\n WithNameRegex,\n WithDeletionTimestamp,\n Alias,\n };\n }\n\n return {\n IsCreatedOrUpdated: () => bindEvent(Event.CREATE_OR_UPDATE),\n IsCreated: () => bindEvent(Event.CREATE),\n IsUpdated: () => bindEvent(Event.UPDATE),\n IsDeleted: () => bindEvent(Event.DELETE),\n };\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Operation } from \"fast-json-patch\";\nimport { pino, stdTimeFunctions } from \"pino\";\nimport { Store } from \"../k8s\";\n\nconst isPrettyLog = process.env.PEPR_PRETTY_LOGS === \"true\";\nconst redactedValue = \"**redacted**\";\n\nconst pretty = {\n target: \"pino-pretty\",\n options: {\n colorize: true,\n },\n};\n\nconst transport = isPrettyLog ? pretty : undefined;\n// epochTime is the pino default\nconst pinoTimeFunction =\n process.env.PINO_TIME_STAMP === \"iso\" ? () => stdTimeFunctions.isoTime() : () => stdTimeFunctions.epochTime();\nconst Log = pino({\n transport,\n timestamp: pinoTimeFunction,\n});\n\nif (process.env.LOG_LEVEL) {\n Log.level = process.env.LOG_LEVEL;\n}\n\nexport function redactedStore(store: Store): Store {\n const redacted = process.env.PEPR_STORE_REDACT_VALUES === \"true\";\n return {\n ...store,\n data: Object.keys(store.data).reduce((acc: Record<string, string>, key: string) => {\n acc[key] = redacted ? redactedValue : store.data[key];\n return acc;\n }, {}),\n };\n}\n\nexport function redactedPatch(patch: Record<string, Operation> = {}): Record<string, Operation> {\n const redacted = process.env.PEPR_STORE_REDACT_VALUES === \"true\";\n\n if (!redacted) {\n return patch;\n }\n\n const redactedCache: Record<string, Operation> = {};\n\n Object.entries(patch).forEach(([key, operation]) => {\n const isRedacted = key.includes(\":\");\n const targetKey = isRedacted ? `${key.substring(0, key.lastIndexOf(\":\"))}:**redacted**` : key;\n\n const redactedOperation = isRedacted\n ? {\n ...operation,\n ...(Object.hasOwn(operation, \"value\") ? { value: redactedValue } : {}),\n }\n : operation;\n\n redactedCache[targetKey] = redactedOperation;\n });\n\n return redactedCache;\n}\n\nexport default Log;\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { clone } from \"ramda\";\nimport { Capability } from \"./capability\";\nimport { Controller } from \"./controller\";\nimport { ValidateError } from \"./errors\";\nimport { MutateResponse, ValidateResponse, WebhookIgnore } from \"./k8s\";\nimport { CapabilityExport, AdmissionRequest } from \"./types\";\nimport { setupWatch } from \"./watch-processor\";\nimport { Log } from \"../lib\";\nimport { V1PolicyRule as PolicyRule } from \"@kubernetes/client-node\";\n\n/** Custom Labels Type for package.json */\nexport interface CustomLabels {\n namespace?: Record<string, string>;\n}\n/** Global configuration for the Pepr runtime. */\nexport type ModuleConfig = {\n /** The Pepr version this module uses */\n peprVersion?: string;\n /** The user-defined version of the module */\n appVersion?: string;\n /** A unique identifier for this Pepr module. This is automatically generated by Pepr. */\n uuid: string;\n /** A description of the Pepr module and what it does. */\n description?: string;\n /** The webhookTimeout */\n webhookTimeout?: number;\n /** Reject K8s resource AdmissionRequests on error. */\n onError?: string;\n /** Configure global exclusions that will never be processed by Pepr. */\n alwaysIgnore: WebhookIgnore;\n /** Define the log level for the in-cluster controllers */\n logLevel?: string;\n /** Propagate env variables to in-cluster controllers */\n env?: Record<string, string>;\n /** Custom Labels for Kubernetes Objects */\n customLabels?: CustomLabels;\n /** Custom RBAC rules */\n rbac?: PolicyRule[];\n /** The RBAC mode; if \"scoped\", generates scoped rules, otherwise uses wildcard rules. */\n rbacMode?: string;\n};\n\nexport type PackageJSON = {\n description: string;\n pepr: ModuleConfig;\n};\n\nexport type PeprModuleOptions = {\n deferStart?: boolean;\n\n /** A user-defined callback to pre-process or intercept a Pepr request from K8s immediately before it is processed */\n beforeHook?: (req: AdmissionRequest) => void;\n\n /** A user-defined callback to post-process or intercept a Pepr response just before it is returned to K8s */\n afterHook?: (res: MutateResponse | ValidateResponse) => void;\n};\n\n// Track if this is a watch mode controller\nexport const isWatchMode = () => process.env.PEPR_WATCH_MODE === \"true\";\n\n// Track if Pepr is running in build mode\nexport const isBuildMode = () => process.env.PEPR_MODE === \"build\";\n\nexport const isDevMode = () => process.env.PEPR_MODE === \"dev\";\n\nexport class PeprModule {\n #controller!: Controller;\n\n /**\n * Create a new Pepr runtime\n *\n * @param config The configuration for the Pepr runtime\n * @param capabilities The capabilities to be loaded into the Pepr runtime\n * @param opts Options for the Pepr runtime\n */\n constructor({ description, pepr }: PackageJSON, capabilities: Capability[] = [], opts: PeprModuleOptions = {}) {\n const config: ModuleConfig = clone(pepr);\n config.description = description;\n\n // Need to validate at runtime since TS gets sad about parsing the package.json\n ValidateError(config.onError);\n\n // Handle build mode\n if (isBuildMode()) {\n // Fail if process.send is not defined\n if (!process.send) {\n throw new Error(\"process.send is not defined\");\n }\n\n const exportedCapabilities: CapabilityExport[] = [];\n\n // Send capability map to parent process\n for (const capability of capabilities) {\n // Convert the capability to a capability config\n exportedCapabilities.push({\n name: capability.name,\n description: capability.description,\n namespaces: capability.namespaces,\n bindings: capability.bindings,\n hasSchedule: capability.hasSchedule,\n });\n }\n\n // Send the capabilities back to the parent process\n process.send(exportedCapabilities);\n\n return;\n }\n\n this.#controller = new Controller(config, capabilities, opts.beforeHook, opts.afterHook, () => {\n // Wait for the controller to be ready before setting up watches\n if (isWatchMode() || isDevMode()) {\n try {\n setupWatch(capabilities, pepr?.alwaysIgnore?.namespaces);\n } catch (e) {\n Log.error(e, \"Error setting up watch\");\n process.exit(1);\n }\n }\n });\n\n // Stop processing if deferStart is set to true\n if (opts.deferStart) {\n return;\n }\n\n this.start();\n }\n\n /**\n * Start the Pepr runtime manually.\n * Normally this is called automatically when the Pepr module is instantiated, but can be called manually if `deferStart` is set to `true` in the constructor.\n *\n * @param port\n */\n start = (port = 3000) => {\n this.#controller.startServer(port);\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport express, { NextFunction } from \"express\";\nimport fs from \"fs\";\nimport https from \"https\";\n\nimport { Capability } from \"../capability\";\nimport { MutateResponse, ValidateResponse } from \"../k8s\";\nimport Log from \"../telemetry/logger\";\nimport { metricsCollector, MetricsCollector } from \"../telemetry/metrics\";\nimport { ModuleConfig, isWatchMode } from \"../module\";\nimport { mutateProcessor } from \"../mutate-processor\";\nimport { validateProcessor } from \"../validate-processor\";\nimport { StoreController } from \"./store\";\nimport { AdmissionRequest } from \"../types\";\nimport { karForMutate, karForValidate, KubeAdmissionReview } from \"./index.util\";\n\nif (!process.env.PEPR_NODE_WARNINGS) {\n process.removeAllListeners(\"warning\");\n}\n\nexport class Controller {\n // Track whether the server is running\n #running = false;\n\n // Metrics collector\n #metricsCollector = metricsCollector;\n\n // The token used to authenticate requests\n #token = \"\";\n\n // The express app instance\n readonly #app = express();\n\n // Initialized with the constructor\n readonly #config: ModuleConfig;\n readonly #capabilities: Capability[];\n readonly #beforeHook?: (req: AdmissionRequest) => void;\n readonly #afterHook?: (res: MutateResponse | ValidateResponse) => void;\n\n constructor(\n config: ModuleConfig,\n capabilities: Capability[],\n beforeHook?: (req: AdmissionRequest) => void,\n afterHook?: (res: MutateResponse | ValidateResponse) => void,\n onReady?: () => void,\n ) {\n this.#config = config;\n this.#capabilities = capabilities;\n\n // Initialize the Pepr store for each capability\n new StoreController(capabilities, `pepr-${config.uuid}-store`, () => {\n this.#bindEndpoints();\n onReady && onReady();\n Log.info(\"\u2705 Controller startup complete\");\n // Initialize the schedule store for each capability\n new StoreController(capabilities, `pepr-${config.uuid}-schedule`, () => {\n Log.info(\"\u2705 Scheduling processed\");\n });\n });\n\n // Middleware for logging requests\n this.#app.use(Controller.#logger);\n\n // Middleware for parsing JSON, limit to 2mb vs 100K for K8s compatibility\n this.#app.use(express.json({ limit: \"2mb\" }));\n\n if (beforeHook) {\n Log.info(`Using beforeHook: ${beforeHook}`);\n this.#beforeHook = beforeHook;\n }\n\n if (afterHook) {\n Log.info(`Using afterHook: ${afterHook}`);\n this.#afterHook = afterHook;\n }\n }\n\n /** Start the webhook server */\n startServer = (port: number) => {\n if (this.#running) {\n throw new Error(\"Cannot start Pepr module: Pepr module was not instantiated with deferStart=true\");\n }\n\n // Load SSL certificate and key\n const options = {\n key: fs.readFileSync(process.env.SSL_KEY_PATH || \"/etc/certs/tls.key\"),\n cert: fs.readFileSync(process.env.SSL_CERT_PATH || \"/etc/certs/tls.crt\"),\n };\n\n // Get the API token if not in watch mode\n if (!isWatchMode()) {\n // Get the API token from the environment variable or the mounted secret\n this.#token = process.env.PEPR_API_TOKEN || fs.readFileSync(\"/app/api-token/value\").toString().trim();\n Log.info(`Using API token: ${this.#token}`);\n\n if (!this.#token) {\n throw new Error(\"API token not found\");\n }\n }\n\n // Create HTTPS server\n const server = https.createServer(options, this.#app).listen(port);\n\n // Handle server listening event\n server.on(\"listening\", () => {\n Log.info(`Server listening on port ${port}`);\n // Track that the server is running\n this.#running = true;\n });\n\n // Handle EADDRINUSE errors\n server.on(\"error\", (e: { code: string }) => {\n if (e.code === \"EADDRINUSE\") {\n Log.info(\n `Address in use, retrying in 2 seconds. If this persists, ensure ${port} is not in use, e.g. \"lsof -i :${port}\"`,\n );\n setTimeout(() => {\n server.close();\n server.listen(port);\n }, 2000);\n }\n });\n\n // Listen for the SIGTERM signal and gracefully close the server\n process.on(\"SIGTERM\", () => {\n Log.info(\"Received SIGTERM, closing server\");\n server.close(() => {\n Log.info(\"Server closed\");\n process.exit(0);\n });\n });\n };\n\n #bindEndpoints = () => {\n // Health check endpoint\n this.#app.get(\"/healthz\", Controller.#healthz);\n\n // Metrics endpoint\n this.#app.get(\"/metrics\", this.#metrics);\n\n if (isWatchMode()) {\n return;\n }\n\n // Require auth for webhook endpoints\n this.#app.use([\"/mutate/:token\", \"/validate/:token\"], this.#validateToken);\n\n // Mutate endpoint\n this.#app.post(\"/mutate/:token\", this.#admissionReq(\"Mutate\"));\n\n // Validate endpoint\n this.#app.post(\"/validate/:token\", this.#admissionReq(\"Validate\"));\n };\n\n /**\n * Validate the token in the request path\n *\n * @param req The incoming request\n * @param res The outgoing response\n * @param next The next middleware function\n * @returns\n */\n #validateToken = (req: express.Request, res: express.Response, next: NextFunction) => {\n // Validate the token\n const { token } = req.params;\n if (token !== this.#token) {\n const err = `Unauthorized: invalid token '${token.replace(/[^\\w]/g, \"_\")}'`;\n Log.info(err);\n res.status(401).send(err);\n this.#metricsCollector.alert();\n return;\n }\n\n // Token is valid, continue\n next();\n };\n\n /**\n * Metrics endpoint handler\n *\n * @param req the incoming request\n * @param res the outgoing response\n */\n #metrics = async (req: express.Request, res: express.Response) => {\n try {\n // https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md#basic-info\n res.set(\"Content-Type\", \"text/plain; version=0.0.4\");\n res.send(await this.#metricsCollector.getMetrics());\n } catch (err) {\n Log.error(err, `Error getting metrics`);\n res.status(500).send(\"Internal Server Error\");\n }\n };\n\n /**\n * Admission request handler for both mutate and validate requests\n *\n * @param admissionKind the type of admission request\n * @returns the request handler\n */\n #admissionReq = (admissionKind: \"Mutate\" | \"Validate\") => {\n // Create the admission request handler\n return async (req: express.Request, res: express.Response) => {\n // Start the metrics timer\n const startTime = MetricsCollector.observeStart();\n\n try {\n // Get the request from the body or create an empty request\n const request: AdmissionRequest = req.body?.request || ({} as AdmissionRequest);\n\n const { name, namespace, gvk } = {\n name: request?.name ? `/${request.name}` : \"\",\n namespace: request?.namespace || \"\",\n gvk: request?.kind || { group: \"\", version: \"\", kind: \"\" },\n };\n\n const reqMetadata = { uid: request.uid, namespace, name };\n Log.info({ ...reqMetadata, gvk, operation: request.operation, admissionKind }, \"Incoming request\");\n Log.debug({ ...reqMetadata, request }, \"Incoming request body\");\n\n // Run the before hook if it exists\n this.#beforeHook && this.#beforeHook(request || {});\n\n // Process the request\n const response: MutateResponse | ValidateResponse[] =\n admissionKind === \"Mutate\"\n ? await mutateProcessor(this.#config, this.#capabilities, request, reqMetadata)\n : await validateProcessor(this.#config, this.#capabilities, request, reqMetadata);\n\n // Run the after hook if it exists\n [response].flat().map(res => {\n this.#afterHook && this.#afterHook(res);\n Log.info({ ...reqMetadata, res }, \"Check response\");\n });\n\n const kar: KubeAdmissionReview =\n admissionKind === \"Mutate\"\n ? karForMutate(response as MutateResponse)\n : karForValidate(request, response as ValidateResponse[]);\n\n Log.debug({ ...reqMetadata, kubeAdmissionResponse: kar.response }, \"Outgoing response\");\n res.send(kar);\n\n this.#metricsCollector.observeEnd(startTime, admissionKind);\n } catch (err) {\n Log.error(err, `Error processing ${admissionKind} request`);\n res.status(500).send(\"Internal Server Error\");\n this.#metricsCollector.error();\n }\n };\n };\n\n /**\n * Middleware for logging requests\n *\n * @param req the incoming request\n * @param res the outgoing response\n * @param next the next middleware function\n */\n static #logger(req: express.Request, res: express.Response, next: express.NextFunction) {\n const startTime = Date.now();\n\n res.on(\"finish\", () => {\n const excludedRoutes = [\"/healthz\", \"/metrics\"];\n if (excludedRoutes.includes(req.originalUrl)) {\n return;\n }\n\n const elapsedTime = Date.now() - startTime;\n const message = {\n uid: req.body?.request?.uid,\n method: req.method,\n url: req.originalUrl,\n status: res.statusCode,\n duration: `${elapsedTime} ms`,\n };\n\n Log.info(message);\n });\n\n next();\n }\n /**\n * Health check endpoint handler\n *\n * @param req the incoming request\n * @param res the outgoing response\n */\n static #healthz(req: express.Request, res: express.Response) {\n try {\n res.send(\"OK\");\n } catch (err) {\n Log.error(err, `Error processing health check`);\n res.status(500).send(\"Internal Server Error\");\n }\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\n/* eslint-disable class-methods-use-this */\n\nimport { performance } from \"perf_hooks\";\nimport promClient, { Counter, Registry, Gauge, Summary } from \"prom-client\";\nimport Log from \"./logger\";\n\nconst loggingPrefix = \"MetricsCollector\";\n\ntype MetricsCollectorInstance = InstanceType<typeof MetricsCollector>;\ninterface MetricNames {\n errors: string;\n alerts: string;\n mutate: string;\n validate: string;\n cacheMiss: string;\n resyncFailureCount: string;\n}\n\ninterface MetricArgs {\n name: string;\n help: string;\n registers: Registry[];\n labelNames?: string[];\n}\n\n/**\n * MetricsCollector class handles metrics collection using prom-client and performance hooks.\n */\nexport class MetricsCollector {\n #registry: Registry;\n #counters: Map<string, Counter<string>> = new Map();\n #gauges: Map<string, Gauge<string>> = new Map();\n #summaries: Map<string, Summary<string>> = new Map();\n #prefix: string;\n #cacheMissWindows: Map<string, number> = new Map();\n\n #metricNames: MetricNames = {\n errors: \"errors\",\n alerts: \"alerts\",\n mutate: \"mutate\",\n validate: \"validate\",\n cacheMiss: \"cache_miss\",\n resyncFailureCount: \"resync_failure_count\",\n };\n\n /**\n * Creates a MetricsCollector instance with prefixed metrics.\n * @param [prefix='pepr'] - The prefix for the metric names.\n */\n constructor(prefix = \"pepr\") {\n this.#registry = new Registry();\n this.#prefix = prefix;\n this.addCounter(this.#metricNames.errors, \"Mutation/Validate errors encountered\");\n this.addCounter(this.#metricNames.alerts, \"Mutation/Validate bad api token received\");\n this.addSummary(this.#metricNames.mutate, \"Mutation operation summary\");\n this.addSummary(this.#metricNames.validate, \"Validation operation summary\");\n this.addGauge(this.#metricNames.cacheMiss, \"Number of cache misses per window\", [\"window\"]);\n this.addGauge(this.#metricNames.resyncFailureCount, \"Number of failures per resync operation\", [\"count\"]);\n }\n\n #getMetricName = (name: string): string => `${this.#prefix}_${name}`;\n\n #addMetric = <T extends Counter<string> | Gauge<string> | Summary<string>>(\n collection: Map<string, T>,\n MetricType: new (args: MetricArgs) => T,\n name: string,\n help: string,\n labelNames?: string[],\n ): void => {\n if (collection.has(this.#getMetricName(name))) {\n Log.debug(`Metric for ${name} already exists`, loggingPrefix);\n return;\n }\n\n const metric = new MetricType({\n name: this.#getMetricName(name),\n help,\n registers: [this.#registry],\n labelNames,\n });\n\n collection.set(this.#getMetricName(name), metric);\n };\n\n addCounter = (name: string, help: string): void => {\n this.#addMetric(this.#counters, promClient.Counter, name, help, []);\n };\n\n addSummary = (name: string, help: string): void => {\n this.#addMetric(this.#summaries, promClient.Summary, name, help, []);\n };\n\n addGauge = (name: string, help: string, labelNames?: string[]): void => {\n this.#addMetric(this.#gauges, promClient.Gauge, name, help, labelNames);\n };\n\n incCounter = (name: string): void => {\n this.#counters.get(this.#getMetricName(name))?.inc();\n };\n\n incGauge = (name: string, labels?: Record<string, string>, value: number = 1): void => {\n this.#gauges.get(this.#getMetricName(name))?.inc(labels || {}, value);\n };\n\n /**\n * Increments the error counter.\n */\n error = (): void => this.incCounter(this.#metricNames.errors);\n\n /**\n * Increments the alerts counter.\n */\n alert = (): void => this.incCounter(this.#metricNames.alerts);\n\n /**\n * Observes the duration since the provided start time and updates the summary.\n * @param startTime - The start time.\n * @param name - The metrics summary to increment.\n */\n observeEnd = (startTime: number, name: string = this.#metricNames.mutate): void => {\n this.#summaries.get(this.#getMetricName(name))?.observe(performance.now() - startTime);\n };\n\n /**\n * Fetches the current metrics from the registry.\n * @returns The metrics.\n */\n getMetrics = (): Promise<string> => this.#registry.metrics();\n\n /**\n * Returns the current timestamp from performance.now() method. Useful for start timing an operation.\n * @returns The timestamp.\n */\n static observeStart(): number {\n return performance.now();\n }\n\n /**\n * Increments the cache miss gauge for a given label.\n * @param label - The label for the cache miss.\n */\n incCacheMiss = (window: string): void => {\n this.incGauge(this.#metricNames.cacheMiss, { window });\n };\n\n /**\n * Increments the retry count gauge.\n * @param count - The count to increment by.\n */\n incRetryCount = (count: string): void => {\n this.incGauge(this.#metricNames.resyncFailureCount, { count });\n };\n\n /**\n * Initializes the cache miss gauge for a given label.\n * @param label - The label for the cache miss.\n */\n initCacheMissWindow = (window: string): void => {\n this.#rollCacheMissWindows();\n this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.set({ window }, 0);\n this.#cacheMissWindows.set(window, 0);\n };\n\n /**\n * Manages the size of the cache miss gauge map.\n */\n #rollCacheMissWindows = (): void => {\n const maxCacheMissWindows = process.env.PEPR_MAX_CACHE_MISS_WINDOWS\n ? parseInt(process.env.PEPR_MAX_CACHE_MISS_WINDOWS, 10)\n : undefined;\n\n if (maxCacheMissWindows !== undefined && this.#cacheMissWindows.size >= maxCacheMissWindows) {\n const firstKey = this.#cacheMissWindows.keys().next().value;\n if (firstKey !== undefined) {\n this.#cacheMissWindows.delete(firstKey);\n }\n this.#gauges.get(this.#getMetricName(this.#metricNames.cacheMiss))?.remove({ window: firstKey });\n }\n };\n}\n\nexport const metricsCollector: MetricsCollectorInstance = new MetricsCollector(\"pepr\");\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport jsonPatch from \"fast-json-patch\";\nimport { kind } from \"kubernetes-fluent-client\";\n\nimport { Capability } from \"./capability\";\nimport { Errors } from \"./errors\";\nimport { shouldSkipRequest } from \"./filter/filter\";\nimport { MutateResponse } from \"./k8s\";\nimport { AdmissionRequest } from \"./types\";\nimport Log from \"./telemetry/logger\";\nimport { ModuleConfig } from \"./module\";\nimport { PeprMutateRequest } from \"./mutate-request\";\nimport { base64Encode, convertFromBase64Map, convertToBase64Map } from \"./utils\";\n\nexport async function mutateProcessor(\n config: ModuleConfig,\n capabilities: Capability[],\n req: AdmissionRequest,\n reqMetadata: Record<string, string>,\n): Promise<MutateResponse> {\n const wrapped = new PeprMutateRequest(req);\n const response: MutateResponse = {\n uid: req.uid,\n warnings: [],\n allowed: false,\n };\n\n // Track whether any capability matched the request\n let matchedAction = false;\n\n // Track data fields that should be skipped during decoding\n let skipDecode: string[] = [];\n\n // If the resource is a secret, decode the data\n const isSecret = req.kind.version === \"v1\" && req.kind.kind === \"Secret\";\n if (isSecret) {\n skipDecode = convertFromBase64Map(wrapped.Raw as unknown as kind.Secret);\n }\n\n Log.info(reqMetadata, `Processing request`);\n\n for (const { name, bindings, namespaces } of capabilities) {\n const actionMetadata = { ...reqMetadata, name };\n for (const action of bindings) {\n // Skip this action if it's not a mutate action\n if (!action.mutateCallback) {\n continue;\n }\n\n // Continue to the next action without doing anything if this one should be skipped\n const shouldSkip = shouldSkipRequest(action, req, namespaces, config?.alwaysIgnore?.namespaces);\n if (shouldSkip !== \"\") {\n Log.debug(shouldSkip);\n continue;\n }\n\n const label = action.mutateCallback.name;\n Log.info(actionMetadata, `Processing mutation action (${label})`);\n matchedAction = true;\n\n // Add annotations to the request to indicate that the capability started processing\n // this will allow tracking of failed mutations that were permitted to continue\n const updateStatus = (status: string) => {\n // Only update the status if the request is a CREATE or UPDATE (we don't use CONNECT)\n if (req.operation === \"DELETE\") {\n return;\n }\n\n const identifier = `${config.uuid}.pepr.dev/${name}`;\n wrapped.Raw.metadata = wrapped.Raw.metadata || {};\n wrapped.Raw.metadata.annotations = wrapped.Raw.metadata.annotations || {};\n wrapped.Raw.metadata.annotations[identifier] = status;\n };\n\n updateStatus(\"started\");\n\n try {\n // Run the action\n await action.mutateCallback(wrapped);\n\n // Log on success\n Log.info(actionMetadata, `Mutation action succeeded (${label})`);\n\n // Add annotations to the request to indicate that the capability succeeded\n updateStatus(\"succeeded\");\n } catch (e) {\n updateStatus(\"warning\");\n response.warnings = response.warnings || [];\n\n const errorMessage = logMutateErrorMessage(e);\n\n // Log on failure\n Log.error(actionMetadata, `Action failed: ${errorMessage}`);\n response.warnings.push(`Action failed: ${errorMessage}`);\n\n switch (config.onError) {\n case Errors.reject:\n Log.error(actionMetadata, `Action failed: ${errorMessage}`);\n response.result = \"Pepr module configured to reject on error\";\n return response;\n\n case Errors.audit:\n response.auditAnnotations = response.auditAnnotations || {};\n response.auditAnnotations[Date.now()] = `Action failed: ${errorMessage}`;\n break;\n }\n }\n }\n }\n\n // If we've made it this far, the request is allowed\n response.allowed = true;\n\n // If no capability matched the request, exit early\n if (!matchedAction) {\n Log.info(reqMetadata, `No matching actions found`);\n return response;\n }\n\n // delete operations can't be mutate, just return before the transformation\n if (req.operation === \"DELETE\") {\n return response;\n }\n\n const transformed = wrapped.Raw;\n\n // Post-process the Secret requests to convert it back to the original format\n if (isSecret) {\n convertToBase64Map(transformed as unknown as kind.Secret, skipDecode);\n }\n\n // Compare the original request to the modified request to get the patches\n const patches = jsonPatch.compare(req.object, transformed);\n\n // Only add the patch if there are patches to apply\n if (patches.length > 0) {\n response.patchType = \"JSONPatch\";\n // Webhook must be base64-encoded\n // https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#response\n response.patch = base64Encode(JSON.stringify(patches));\n }\n\n // Remove the warnings array if it's empty\n if (response.warnings && response.warnings.length < 1) {\n delete response.warnings;\n }\n\n Log.debug({ ...reqMetadata, patches }, `Patches generated`);\n\n return response;\n}\n\nconst logMutateErrorMessage = (e: Error): string => {\n try {\n if (e.message && e.message !== \"[object Object]\") {\n return e.message;\n } else {\n throw new Error(\"An error occurred in the mutate action.\");\n }\n } catch (e) {\n return \"An error occurred with the mutate action.\";\n }\n};\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nexport const Errors = {\n audit: \"audit\",\n ignore: \"ignore\",\n reject: \"reject\",\n};\n\nexport const ErrorList = Object.values(Errors);\n\n/**\n * Validate the error or throw an error\n * @param error\n */\nexport function ValidateError(error = \"\") {\n if (!ErrorList.includes(error)) {\n throw new Error(`Invalid error: ${error}. Must be one of: ${ErrorList.join(\", \")}`);\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Event, Operation } from \"../../enums\";\nimport { AdmissionRequest, Binding } from \"../../types\";\nimport {\n __,\n allPass,\n any,\n anyPass,\n complement,\n curry,\n defaultTo,\n difference,\n equals,\n gt,\n length,\n not,\n nthArg,\n pipe,\n} from \"ramda\";\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\n\n/*\n Naming scheme:\n - AdmissionRequest - \"declares\" / \"neglects\"\n - KubernetesObject - \"carries\" / \"missing\"\n - Binding - \"defines\" / \"ignores\"\n*/\n\n/*\n AdmissionRequest collectors\n*/\nexport const declaredOperation = pipe(\n (request: AdmissionRequest<KubernetesObject>): Operation => request?.operation,\n defaultTo(\"\"),\n);\nexport const declaredGroup = pipe(\n (request: AdmissionRequest<KubernetesObject>): string => request?.kind?.group,\n defaultTo(\"\"),\n);\nexport const declaredVersion = pipe(\n (request: AdmissionRequest<KubernetesObject>): string | undefined => request?.kind?.version,\n defaultTo(\"\"),\n);\nexport const declaredKind = pipe(\n (request: AdmissionRequest<KubernetesObject>): string => request?.kind?.kind,\n defaultTo(\"\"),\n);\nexport const declaredUid = pipe((request: AdmissionRequest<KubernetesObject>): string => request?.uid, defaultTo(\"\"));\n\n/*\n KubernetesObject collectors\n*/\nexport const carriesDeletionTimestamp = pipe(\n kubernetesObject => !!kubernetesObject.metadata?.deletionTimestamp,\n defaultTo(false),\n);\nexport const missingDeletionTimestamp = complement(carriesDeletionTimestamp);\n\nexport const carriedKind = pipe(\n (kubernetesObject: KubernetesObject): string | undefined => kubernetesObject?.kind,\n defaultTo(\"not set\"),\n);\nexport const carriedVersion = pipe(\n (kubernetesObject: KubernetesObject): string | undefined => kubernetesObject?.metadata?.resourceVersion,\n defaultTo(\"not set\"),\n);\nexport const carriedName = pipe(\n (kubernetesObject: KubernetesObject): string | undefined => kubernetesObject?.metadata?.name,\n defaultTo(\"\"),\n);\nexport const carriesName = pipe(carriedName, equals(\"\"), not);\nexport const missingName = complement(carriesName);\n\nexport const carriedNamespace = pipe(\n (kubernetesObject: KubernetesObject): string | undefined => kubernetesObject?.metadata?.namespace,\n defaultTo(\"\"),\n);\nexport const carriesNamespace = pipe(carriedNamespace, equals(\"\"), not);\n\nexport const carriedAnnotations = pipe(\n (kubernetesObject: KubernetesObject): { [key: string]: string } | undefined =>\n kubernetesObject?.metadata?.annotations,\n defaultTo({}),\n);\nexport const carriesAnnotations = pipe(carriedAnnotations, equals({}), not);\n\nexport const carriedLabels = pipe(\n (kubernetesObject: KubernetesObject): { [key: string]: string } | undefined => kubernetesObject?.metadata?.labels,\n defaultTo({}),\n);\nexport const carriesLabels = pipe(carriedLabels, equals({}), not);\n\n/*\n Binding collectors\n*/\n\nexport const definesDeletionTimestamp = pipe(\n (binding: Binding): boolean => binding?.filters?.deletionTimestamp ?? false,\n defaultTo(false),\n);\nexport const ignoresDeletionTimestamp = complement(definesDeletionTimestamp);\n\nexport const definedName = pipe((binding: Binding): string => {\n return binding.filters.name;\n}, defaultTo(\"\"));\nexport const definesName = pipe(definedName, equals(\"\"), not);\nexport const ignoresName = complement(definesName);\n\nexport const definedNameRegex = pipe(\n (binding: Partial<Binding>): string | undefined => binding.filters?.regexName,\n defaultTo(\"\"),\n);\nexport const definesNameRegex = pipe(definedNameRegex, equals(\"\"), not);\n\nexport const definedNamespaces = pipe(binding => binding?.filters?.namespaces, defaultTo([]));\nexport const definesNamespaces = pipe(definedNamespaces, equals([]), not);\n\nexport const definedNamespaceRegexes = pipe(binding => binding?.filters?.regexNamespaces, defaultTo([]));\nexport const definesNamespaceRegexes = pipe(definedNamespaceRegexes, equals([]), not);\n\nexport const definedAnnotations = pipe((binding: Partial<Binding>) => binding?.filters?.annotations, defaultTo({}));\nexport const definesAnnotations = pipe(definedAnnotations, equals({}), not);\n\nexport const definedLabels = pipe((binding: Partial<Binding>) => binding?.filters?.labels, defaultTo({}));\nexport const definesLabels = pipe(definedLabels, equals({}), not);\n\nexport const definedEvent = (binding: Binding): Event => {\n return binding.event;\n};\n\nexport const definesDelete = pipe(definedEvent, equals(Event.DELETE));\n\nexport const definedGroup = pipe((binding): string => binding?.kind?.group, defaultTo(\"\"));\nexport const definesGroup = pipe(definedGroup, equals(\"\"), not);\n\nexport const definedVersion = pipe(\n (binding: Partial<Binding>): string | undefined => binding?.kind?.version,\n defaultTo(\"\"),\n);\nexport const definesVersion = pipe(definedVersion, equals(\"\"), not);\n\nexport const definedKind = pipe((binding): string => binding?.kind?.kind, defaultTo(\"\"));\nexport const definesKind = pipe(definedKind, equals(\"\"), not);\n\nexport const definedCategory = (binding: Partial<Binding>) => {\n // Ordering matters, finalize is a \"watch\"\n // prettier-ignore\n return binding.isFinalize ? \"Finalize\" :\n binding.isWatch ? \"Watch\" :\n binding.isMutate ? \"Mutate\" :\n binding.isValidate ? \"Validate\" :\n \"\";\n};\n\nexport const definedCallback = (binding: Partial<Binding>) => {\n // Ordering matters, finalize is a \"watch\"\n // prettier-ignore\n return binding.isFinalize ? binding.finalizeCallback :\n binding.isWatch ? binding.watchCallback :\n binding.isMutate ? binding.mutateCallback :\n binding.isValidate ? binding.validateCallback :\n null;\n};\nexport const definedCallbackName = pipe(definedCallback, defaultTo({ name: \"\" }), callback => callback.name);\n\n/*\n post-collection comparitors\n*/\nexport const mismatchedDeletionTimestamp = allPass([\n pipe(nthArg(0), definesDeletionTimestamp),\n pipe(nthArg(1), missingDeletionTimestamp),\n]);\n\nexport const mismatchedName = allPass([\n pipe(nthArg(0), definesName),\n pipe((binding, kubernetesObject) => definedName(binding) !== carriedName(kubernetesObject)),\n]);\n\nexport const mismatchedNameRegex = allPass([\n pipe(nthArg(0), definesNameRegex),\n pipe((binding, kubernetesObject) => new RegExp(definedNameRegex(binding)).test(carriedName(kubernetesObject)), not),\n]);\n\nexport const bindsToKind = curry(\n allPass([pipe(nthArg(0), definedKind, equals(\"\"), not), pipe((binding, kind) => definedKind(binding) === kind)]),\n);\nexport const bindsToNamespace = curry(pipe(bindsToKind(__, \"Namespace\")));\nexport const misboundNamespace = allPass([bindsToNamespace, definesNamespaces]);\n\nexport const mismatchedNamespace = allPass([\n pipe(nthArg(0), definesNamespaces),\n pipe((binding, kubernetesObject) => definedNamespaces(binding).includes(carriedNamespace(kubernetesObject)), not),\n]);\n\nexport const mismatchedNamespaceRegex = allPass([\n pipe(nthArg(0), definesNamespaceRegexes),\n pipe((binding, kubernetesObject) =>\n pipe(\n any((regEx: string) => new RegExp(regEx).test(carriedNamespace(kubernetesObject))),\n not,\n )(definedNamespaceRegexes(binding)),\n ),\n]);\n\nexport const metasMismatch = pipe(\n (defined, carried) => {\n const result = { defined, carried, unalike: {} };\n\n result.unalike = Object.entries(result.defined)\n .map(([key, value]) => {\n const keyMissing = !Object.hasOwn(result.carried, key);\n const noValue = !value;\n const valMissing = !result.carried[key];\n const valDiffers = result.carried[key] !== result.defined[key];\n\n // prettier-ignore\n return (\n keyMissing ? { [key]: value } :\n noValue ? {} :\n valMissing ? { [key]: value } :\n valDiffers ? { [key]: value } :\n {}\n )\n })\n .reduce((acc, cur) => ({ ...acc, ...cur }), {});\n\n return result.unalike;\n },\n unalike => Object.keys(unalike).length > 0,\n);\n\nexport const mismatchedAnnotations = allPass([\n pipe(nthArg(0), definesAnnotations),\n pipe((binding, kubernetesObject) => metasMismatch(definedAnnotations(binding), carriedAnnotations(kubernetesObject))),\n]);\n\nexport const mismatchedLabels = allPass([\n pipe(nthArg(0), definesLabels),\n pipe((binding, kubernetesObject) => metasMismatch(definedLabels(binding), carriedLabels(kubernetesObject))),\n]);\n\nexport const uncarryableNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), carriesNamespace),\n pipe((namespaceSelector, kubernetesObject) => namespaceSelector.includes(carriedNamespace(kubernetesObject)), not),\n]);\n\nexport const missingCarriableNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe((namespaceSelector: string[], kubernetesObject: KubernetesObject): boolean =>\n kubernetesObject.kind === \"Namespace\"\n ? !namespaceSelector.includes(kubernetesObject.metadata!.name!)\n : !carriesNamespace(kubernetesObject),\n ),\n]);\n\nexport const carriesIgnoredNamespace = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), carriesNamespace),\n pipe((namespaceSelector, kubernetesObject) => namespaceSelector.includes(carriedNamespace(kubernetesObject))),\n]);\n\nexport const unbindableNamespaces = allPass([\n pipe(nthArg(0), length, gt(__, 0)),\n pipe(nthArg(1), definesNamespaces),\n pipe(\n (namespaceSelector, binding) => difference(definedNamespaces(binding), namespaceSelector),\n length,\n equals(0),\n not,\n ),\n]);\n\nexport const misboundDeleteWithDeletionTimestamp = allPass([definesDelete, definesDeletionTimestamp]);\n\nexport const operationMatchesEvent = anyPass([\n pipe(nthArg(1), equals(Event.ANY)),\n pipe((operation: Operation, event: Event): boolean => operation.valueOf() === event.valueOf()),\n pipe((operation: Operation, event: Event): boolean => (operation ? event.includes(operation) : false)),\n]);\n\nexport const mismatchedEvent = pipe(\n (binding: Binding, request: AdmissionRequest): boolean =>\n operationMatchesEvent(declaredOperation(request), definedEvent(binding)),\n not,\n);\n\nexport const mismatchedGroup = allPass([\n pipe(nthArg(0), definesGroup),\n pipe((binding, request) => definedGroup(binding) !== declaredGroup(request)),\n]);\n\nexport const mismatchedVersion = allPass([\n pipe(nthArg(0), definesVersion),\n pipe((binding, request) => definedVersion(binding) !== declaredVersion(request)),\n]);\n\nexport const mismatchedKind = allPass([\n pipe(nthArg(0), definesKind),\n pipe((binding, request) => definedKind(binding) !== declaredKind(request)),\n]);\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { AdmissionRequest, Binding } from \"../types\";\nimport { Operation } from \"../enums\";\nimport {\n carriesIgnoredNamespace,\n carriedName,\n definedEvent,\n declaredOperation,\n definedName,\n definedGroup,\n declaredGroup,\n definedVersion,\n declaredVersion,\n definedKind,\n declaredKind,\n definedNamespaces,\n carriedNamespace,\n definedLabels,\n carriedLabels,\n definedAnnotations,\n carriedAnnotations,\n definedNamespaceRegexes,\n definedNameRegex,\n misboundDeleteWithDeletionTimestamp,\n mismatchedDeletionTimestamp,\n mismatchedAnnotations,\n mismatchedLabels,\n mismatchedName,\n mismatchedNameRegex,\n mismatchedNamespace,\n mismatchedNamespaceRegex,\n mismatchedEvent,\n mismatchedGroup,\n mismatchedVersion,\n mismatchedKind,\n missingCarriableNamespace,\n unbindableNamespaces,\n uncarryableNamespace,\n} from \"./adjudicators/adjudicators\";\n\n/**\n * shouldSkipRequest determines if a request should be skipped based on the binding filters.\n *\n * @param binding the action binding\n * @param req the incoming request\n * @returns\n */\nexport function shouldSkipRequest(\n binding: Binding,\n req: AdmissionRequest,\n capabilityNamespaces: string[],\n ignoredNamespaces?: string[],\n): string {\n const prefix = \"Ignoring Admission Callback:\";\n const obj = (req.operation === Operation.DELETE ? req.oldObject : req.object)!;\n\n // prettier-ignore\n return (\n misboundDeleteWithDeletionTimestamp(binding) ?\n `${prefix} Cannot use deletionTimestamp filter on a DELETE operation.` :\n\n mismatchedDeletionTimestamp(binding, obj) ?\n `${prefix} Binding defines deletionTimestamp but Object does not carry it.` :\n\n mismatchedEvent(binding, req) ?\n (\n `${prefix} Binding defines event '${definedEvent(binding)}' but ` +\n `Request declares '${declaredOperation(req)}'.`\n ) :\n\n mismatchedName(binding, obj) ?\n `${prefix} Binding defines name '${definedName(binding)}' but Object carries '${carriedName(obj)}'.` :\n\n mismatchedGroup(binding, req) ?\n (\n `${prefix} Binding defines group '${definedGroup(binding)}' but ` +\n `Request declares '${declaredGroup(req)}'.`\n ) :\n\n mismatchedVersion(binding, req) ?\n (\n `${prefix} Binding defines version '${definedVersion(binding)}' but ` +\n `Request declares '${declaredVersion(req)}'.`\n ) :\n\n mismatchedKind(binding, req) ?\n (\n `${prefix} Binding defines kind '${definedKind(binding)}' but ` +\n `Request declares '${declaredKind(req)}'.`\n ) :\n\n unbindableNamespaces(capabilityNamespaces, binding) ?\n (\n `${prefix} Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n uncarryableNamespace(capabilityNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n mismatchedNamespace(binding, obj) ?\n (\n `${prefix} Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedLabels(binding, obj) ?\n (\n `${prefix} Binding defines labels '${JSON.stringify(definedLabels(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedLabels(obj))}'.`\n ) :\n\n mismatchedAnnotations(binding, obj) ?\n (\n `${prefix} Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedAnnotations(obj))}'.`\n ) :\n\n mismatchedNamespaceRegex(binding, obj) ?\n (\n `${prefix} Binding defines namespace regexes ` +\n `'${JSON.stringify(definedNamespaceRegexes(binding))}' ` +\n `but Object carries '${carriedNamespace(obj)}'.`\n ) :\n\n mismatchedNameRegex(binding, obj) ?\n (\n `${prefix} Binding defines name regex '${definedNameRegex(binding)}' ` +\n `but Object carries '${carriedName(obj)}'.`\n ) :\n\n carriesIgnoredNamespace(ignoredNamespaces, obj) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(obj)}' ` +\n `but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.`\n ) :\n\n missingCarriableNamespace(capabilityNamespaces, obj) ? \n (\n `${prefix} Object does not carry a namespace ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n \"\"\n );\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { AdmissionRequest, DeepPartial } from \"./types\";\nimport { Operation } from \"./enums\";\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\nimport { clone, mergeDeepRight } from \"ramda\";\n\n// PeprMutateRequest class for mutation request handling\nexport class PeprMutateRequest<T extends KubernetesObject> {\n Raw: T;\n #input: AdmissionRequest<T>;\n\n get PermitSideEffects() {\n return !this.#input.dryRun;\n }\n\n get IsDryRun() {\n return this.#input.dryRun;\n }\n\n get OldResource() {\n return this.#input.oldObject;\n }\n\n get Request() {\n return this.#input;\n }\n\n constructor(input: AdmissionRequest<T>) {\n this.#input = input;\n // If this is a DELETE operation, use the oldObject instead\n if (input.operation.toUpperCase() === Operation.DELETE) {\n this.Raw = clone(input.oldObject as T);\n } else {\n // Otherwise, use the incoming object\n this.Raw = clone(input.object);\n }\n\n if (!this.Raw) {\n throw new Error(\"Unable to load the request object into PeprRequest.Raw\");\n }\n }\n\n Merge = (obj: DeepPartial<T>) => {\n this.Raw = mergeDeepRight(this.Raw, obj) as unknown as T;\n };\n\n SetLabel = (key: string, value: string) => {\n const ref = this.Raw;\n ref.metadata = ref.metadata ?? {};\n ref.metadata.labels = ref.metadata.labels ?? {};\n ref.metadata.labels[key] = value;\n return this;\n };\n\n SetAnnotation = (key: string, value: string) => {\n const ref = this.Raw;\n ref.metadata = ref.metadata ?? {};\n ref.metadata.annotations = ref.metadata.annotations ?? {};\n ref.metadata.annotations[key] = value;\n return this;\n };\n\n RemoveLabel = (key: string) => {\n if (this.Raw.metadata?.labels?.[key]) {\n delete this.Raw.metadata.labels[key];\n }\n return this;\n };\n\n RemoveAnnotation = (key: string) => {\n if (this.Raw.metadata?.annotations?.[key]) {\n delete this.Raw.metadata.annotations[key];\n }\n return this;\n };\n\n HasLabel = (key: string) => {\n return this.Raw.metadata?.labels?.[key] !== undefined;\n };\n\n HasAnnotation = (key: string) => {\n return this.Raw.metadata?.annotations?.[key] !== undefined;\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport Log from \"./telemetry/logger\";\n\n/** Test if a string is ascii or not */\nexport const isAscii = /^[\\s\\x20-\\x7E]*$/;\n\n/**\n * Encode all ascii values in a map to base64\n * @param obj The object to encode\n * @param skip A list of keys to skip encoding\n */\nexport function convertToBase64Map(obj: { data?: Record<string, string> }, skip: string[]) {\n obj.data = obj.data ?? {};\n for (const key in obj.data) {\n const value = obj.data[key];\n // Only encode ascii values\n obj.data[key] = skip.includes(key) ? value : base64Encode(value);\n }\n}\n\n/**\n * Decode all ascii values in a map from base64 to utf-8\n * @param obj The object to decode\n * @returns A list of keys that were skipped\n */\nexport function convertFromBase64Map(obj: { data?: Record<string, string> }) {\n const skip: string[] = [];\n\n obj.data = obj.data ?? {};\n for (const key in obj.data) {\n if (obj.data[key] === undefined) {\n obj.data[key] = \"\";\n } else {\n const decoded = base64Decode(obj.data[key]);\n if (isAscii.test(decoded)) {\n // Only decode ascii values\n obj.data[key] = decoded;\n } else {\n skip.push(key);\n }\n }\n }\n Log.debug(`Non-ascii data detected in keys: ${skip}, skipping automatic base64 decoding`);\n return skip;\n}\n\n/** Decode a base64 string */\nexport function base64Decode(data: string) {\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/** Encode a string to base64 */\nexport function base64Encode(data: string) {\n return Buffer.from(data).toString(\"base64\");\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\n/* eslint-disable class-methods-use-this */\n\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\n\nimport { clone } from \"ramda\";\nimport { AdmissionRequest } from \"./types\";\nimport { ValidateActionResponse } from \"./types\";\nimport { Operation } from \"./enums\";\n\n/**\n * The RequestWrapper class provides methods to modify Kubernetes objects in the context\n * of a mutating webhook request.\n */\nexport class PeprValidateRequest<T extends KubernetesObject> {\n Raw: T;\n\n #input: AdmissionRequest<T>;\n\n /**\n * Provides access to the old resource in the request if available.\n * @returns The old Kubernetes resource object or null if not available.\n */\n get OldResource() {\n return this.#input.oldObject;\n }\n\n /**\n * Provides access to the request object.\n * @returns The request object containing the Kubernetes resource.\n */\n get Request() {\n return this.#input;\n }\n\n /**\n * Creates a new instance of the Action class.\n * @param input - The request object containing the Kubernetes resource to modify.\n */\n constructor(input: AdmissionRequest<T>) {\n this.#input = input;\n\n // If this is a DELETE operation, use the oldObject instead\n if (input.operation.toUpperCase() === Operation.DELETE) {\n this.Raw = clone(input.oldObject as T);\n } else {\n // Otherwise, use the incoming object\n this.Raw = clone(input.object);\n }\n\n if (!this.Raw) {\n throw new Error(\"unable to load the request object into PeprRequest.Raw\");\n }\n }\n\n /**\n * Check if a label exists on the Kubernetes resource.\n *\n * @param key the label key to check\n * @returns\n */\n HasLabel = (key: string) => {\n return this.Raw.metadata?.labels?.[key] !== undefined;\n };\n\n /**\n * Check if an annotation exists on the Kubernetes resource.\n *\n * @param key the annotation key to check\n * @returns\n */\n HasAnnotation = (key: string) => {\n return this.Raw.metadata?.annotations?.[key] !== undefined;\n };\n\n /**\n * Create a validation response that allows the request.\n *\n * @returns The validation response.\n */\n Approve = (): ValidateActionResponse => {\n return {\n allowed: true,\n };\n };\n\n /**\n * Create a validation response that denies the request.\n *\n * @param statusMessage Optional status message to return to the user.\n * @param statusCode Optional status code to return to the user.\n * @returns The validation response.\n */\n Deny = (statusMessage?: string, statusCode?: number): ValidateActionResponse => {\n return {\n allowed: false,\n statusCode,\n statusMessage,\n };\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { kind } from \"kubernetes-fluent-client\";\n\nimport { Capability } from \"./capability\";\nimport { shouldSkipRequest } from \"./filter/filter\";\nimport { ValidateResponse } from \"./k8s\";\nimport { AdmissionRequest } from \"./types\";\nimport Log from \"./telemetry/logger\";\nimport { convertFromBase64Map } from \"./utils\";\nimport { PeprValidateRequest } from \"./validate-request\";\nimport { ModuleConfig } from \"./module\";\n\nexport async function validateProcessor(\n config: ModuleConfig,\n capabilities: Capability[],\n req: AdmissionRequest,\n reqMetadata: Record<string, string>,\n): Promise<ValidateResponse[]> {\n const wrapped = new PeprValidateRequest(req);\n const response: ValidateResponse[] = [];\n\n // If the resource is a secret, decode the data\n const isSecret = req.kind.version === \"v1\" && req.kind.kind === \"Secret\";\n if (isSecret) {\n convertFromBase64Map(wrapped.Raw as unknown as kind.Secret);\n }\n\n Log.info(reqMetadata, `Processing validation request`);\n\n for (const { name, bindings, namespaces } of capabilities) {\n const actionMetadata = { ...reqMetadata, name };\n\n for (const action of bindings) {\n // Skip this action if it's not a validation action\n if (!action.validateCallback) {\n continue;\n }\n\n const localResponse: ValidateResponse = {\n uid: req.uid,\n allowed: true, // Assume it's allowed until a validation check fails\n };\n\n // Continue to the next action without doing anything if this one should be skipped\n const shouldSkip = shouldSkipRequest(action, req, namespaces, config?.alwaysIgnore?.namespaces);\n if (shouldSkip !== \"\") {\n Log.debug(shouldSkip);\n continue;\n }\n\n const label = action.validateCallback.name;\n Log.info(actionMetadata, `Processing validation action (${label})`);\n\n try {\n // Run the validation callback, if it fails set allowed to false\n const resp = await action.validateCallback(wrapped);\n localResponse.allowed = resp.allowed;\n\n // If the validation callback returned a status code or message, set it in the Response\n if (resp.statusCode || resp.statusMessage) {\n localResponse.status = {\n code: resp.statusCode || 400,\n message: resp.statusMessage || `Validation failed for ${name}`,\n };\n }\n\n Log.info(actionMetadata, `Validation action complete (${label}): ${resp.allowed ? \"allowed\" : \"denied\"}`);\n } catch (e) {\n // If any validation throws an error, note the failure in the Response\n Log.error(actionMetadata, `Action failed: ${JSON.stringify(e)}`);\n localResponse.allowed = false;\n localResponse.status = {\n code: 500,\n message: `Action failed with error: ${JSON.stringify(e)}`,\n };\n return [localResponse];\n }\n response.push(localResponse);\n }\n }\n\n return response;\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { Operation } from \"fast-json-patch\";\nimport { K8s } from \"kubernetes-fluent-client\";\nimport { startsWith } from \"ramda\";\n\nimport { Capability } from \"../capability\";\nimport { Store } from \"../k8s\";\nimport Log, { redactedPatch, redactedStore } from \"../telemetry/logger\";\nimport { DataOp, DataSender, DataStore, Storage } from \"../storage\";\nimport { fillStoreCache, sendUpdatesAndFlushCache } from \"./storeCache\";\n\nconst namespace = \"pepr-system\";\nexport const debounceBackoff = 1000;\n\nexport class StoreController {\n #name: string;\n #stores: Record<string, Storage> = {};\n #sendDebounce: NodeJS.Timeout | undefined;\n #onReady?: () => void;\n\n constructor(capabilities: Capability[], name: string, onReady?: () => void) {\n this.#onReady = onReady;\n\n this.#name = name;\n\n const setStorageInstance = (registrationFunction: () => Storage, name: string) => {\n const scheduleStore = registrationFunction();\n\n // Bind the store sender to the capability\n scheduleStore.registerSender(this.#send(name));\n\n // Store the storage instance\n this.#stores[name] = scheduleStore;\n };\n\n if (name.includes(\"schedule\")) {\n // Establish the store for each capability\n for (const { name, registerScheduleStore, hasSchedule } of capabilities) {\n if (hasSchedule === true) {\n // Register the scheduleStore with the capability\n setStorageInstance(registerScheduleStore, name);\n }\n }\n } else {\n // Establish the store for each capability\n for (const { name, registerStore } of capabilities) {\n setStorageInstance(registerStore, name);\n }\n }\n\n setTimeout(\n () =>\n K8s(Store)\n .InNamespace(namespace)\n .Get(this.#name)\n .then(async (store: Store) => await this.#migrateAndSetupWatch(store))\n .catch(this.#createStoreResource),\n Math.random() * 3000, // Add a jitter to the Store creation to avoid collisions\n );\n }\n\n #setupWatch = () => {\n const watcher = K8s(Store, { name: this.#name, namespace }).Watch(this.#receive);\n watcher.start().catch(e => Log.error(e, \"Error starting Pepr store watch\"));\n };\n\n #migrateAndSetupWatch = async (store: Store) => {\n Log.debug(redactedStore(store), \"Pepr Store migration\");\n const data: DataStore = store.data || {};\n let storeCache: Record<string, Operation> = {};\n\n for (const name of Object.keys(this.#stores)) {\n // Get the prefix offset for the keys\n const offset = `${name}-`.length;\n\n // Loop over each key in the store\n for (const key of Object.keys(data)) {\n // Match on the capability name as a prefix for non v2 keys\n if (startsWith(name, key) && !startsWith(`${name}-v2`, key)) {\n // populate migrate cache\n storeCache = fillStoreCache(storeCache, name, \"remove\", {\n key: [key.slice(offset)],\n value: data[key],\n });\n storeCache = fillStoreCache(storeCache, name, \"add\", {\n key: [key.slice(offset)],\n value: data[key],\n version: \"v2\",\n });\n }\n }\n }\n storeCache = await sendUpdatesAndFlushCache(storeCache, namespace, this.#name);\n this.#setupWatch();\n };\n\n #receive = (store: Store) => {\n Log.debug(redactedStore(store), \"Pepr Store update\");\n\n // Wrap the update in a debounced function\n const debounced = () => {\n // Base64 decode the data\n const data: DataStore = store.data || {};\n\n // Loop over each stored capability\n for (const name of Object.keys(this.#stores)) {\n // Get the prefix offset for the keys\n const offset = `${name}-`.length;\n\n // Get any keys that match the capability name prefix\n const filtered: DataStore = {};\n\n // Loop over each key in the secret\n for (const key of Object.keys(data)) {\n // Match on the capability name as a prefix\n if (startsWith(name, key)) {\n // Strip the prefix and store the value\n filtered[key.slice(offset)] = data[key];\n }\n }\n\n // Send the data to the receiver callback\n this.#stores[name].receive(filtered);\n }\n\n // Call the onReady callback if this is the first time the secret has been read\n if (this.#onReady) {\n this.#onReady();\n this.#onReady = undefined;\n }\n };\n\n // Debounce the update to 1 second to avoid multiple rapid calls\n clearTimeout(this.#sendDebounce);\n this.#sendDebounce = setTimeout(debounced, this.#onReady ? 0 : debounceBackoff);\n };\n\n #send = (capabilityName: string) => {\n let storeCache: Record<string, Operation> = {};\n\n // Create a sender function for the capability to add/remove data from the store\n const sender: DataSender = async (op: DataOp, key: string[], value?: string) => {\n storeCache = fillStoreCache(storeCache, capabilityName, op, { key, value });\n };\n\n // Send any cached updates every debounceBackoff milliseconds\n setInterval(() => {\n if (Object.keys(storeCache).length > 0) {\n Log.debug(redactedPatch(storeCache), \"Sending updates to Pepr store\");\n void sendUpdatesAndFlushCache(storeCache, namespace, this.#name);\n }\n }, debounceBackoff);\n\n return sender;\n };\n\n #createStoreResource = async (e: unknown) => {\n Log.info(`Pepr store not found, creating...`);\n Log.debug(e);\n\n try {\n await K8s(Store).Apply({\n metadata: {\n name: this.#name,\n namespace,\n },\n data: {\n // JSON Patch will die if the data is empty, so we need to add a placeholder\n __pepr_do_not_delete__: \"k-thx-bye\",\n },\n });\n\n // Now that the resource exists, setup the watch\n this.#setupWatch();\n } catch (err) {\n Log.error(err, \"Failed to create Pepr store\");\n }\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { GenericKind, RegisterKind } from \"kubernetes-fluent-client\";\n\n/**\n * PeprStore for internal use by Pepr. This is used to store arbitrary data in the cluster.\n */\nexport class Store extends GenericKind {\n declare data: {\n [key: string]: string;\n };\n}\n\nexport const peprStoreGVK = {\n kind: \"PeprStore\",\n version: \"v1\",\n group: \"pepr.dev\",\n};\n\nRegisterKind(Store, peprStoreGVK);\n\nexport interface MutateResponse {\n /** UID is an identifier for the individual request/response. This must be copied over from the corresponding AdmissionRequest. */\n uid: string;\n\n /** Allowed indicates whether or not the admission request was permitted. */\n allowed: boolean;\n\n /** Result contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\". */\n result?: string;\n\n /** The patch body. Currently we only support \"JSONPatch\" which implements RFC 6902. */\n patch?: string;\n\n /** The type of Patch. Currently we only allow \"JSONPatch\". */\n patchType?: \"JSONPatch\";\n\n /**\n * AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted).\n *\n * See https://kubernetes.io/docs/reference/labels-annotations-taints/audit-annotations/ for more information\n */\n auditAnnotations?: {\n [key: string]: string;\n };\n\n /** warnings is a list of warning messages to return to the requesting API client. */\n warnings?: string[];\n}\n\nexport interface ValidateResponse extends MutateResponse {\n /** Status contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\". */\n status?: {\n /** A machine-readable description of why this operation is in the\n \"Failure\" status. If this value is empty there is no information available. */\n code: number;\n\n /** A human-readable description of the status of this operation. */\n message: string;\n };\n}\n\nexport type WebhookIgnore = {\n /**\n * List of Kubernetes namespaces to always ignore.\n * Any resources in these namespaces will be ignored by Pepr.\n *\n * Note: `kube-system` and `pepr-system` are always ignored.\n */\n namespaces?: string[];\n};\n", "import { DataOp } from \"../storage\";\nimport Log from \"../telemetry/logger\";\nimport { K8s } from \"kubernetes-fluent-client\";\nimport { Store } from \"../k8s\";\nimport { StatusCodes } from \"http-status-codes\";\nimport { Operation } from \"fast-json-patch\";\n\nexport const sendUpdatesAndFlushCache = async (cache: Record<string, Operation>, namespace: string, name: string) => {\n const indexes = Object.keys(cache);\n const payload = Object.values(cache);\n\n try {\n if (payload.length > 0) {\n await K8s(Store, { namespace, name }).Patch(payload); // Send patch to cluster\n Object.keys(cache).forEach(key => delete cache[key]);\n }\n } catch (err) {\n Log.error(err, \"Pepr store update failure\");\n\n if (err.status === StatusCodes.UNPROCESSABLE_ENTITY) {\n Object.keys(cache).forEach(key => delete cache[key]);\n } else {\n indexes.forEach(index => {\n cache[index] = payload[Number(index)]; // On failure to update, re-add the operations to the cache to be retried\n });\n }\n }\n return cache;\n};\n\ntype CacheItem = {\n key: string[];\n value?: string;\n version?: string;\n};\n\nexport const fillStoreCache = (\n cache: Record<string, Operation>,\n capabilityName: string,\n op: DataOp,\n cacheItem: CacheItem,\n): Record<string, Operation> => {\n const path = [`/data/${capabilityName}`, cacheItem.version, cacheItem.key] // adjust the path, see ADR-0008\n .filter(str => str !== \"\" && str !== undefined)\n .join(\"-\");\n if (op === \"add\") {\n const value = cacheItem.value || \"\";\n const cacheIdx = [op, path, value].join(\":\");\n\n // Add the operation to the cache\n cache[cacheIdx] = { op, path, value };\n } else if (op === \"remove\") {\n if (cacheItem.key.length < 1) {\n throw new Error(`Key is required for REMOVE operation`);\n }\n const cacheIndex = [op, path].join(\":\");\n // Add the operation to the cache\n cache[cacheIndex] = { op, path };\n } else {\n throw new Error(`Unsupported operation: ${op}`);\n }\n return cache;\n};\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { MutateResponse, ValidateResponse } from \"../k8s\";\nimport { ResponseItem, AdmissionRequest } from \"../types\";\n\nexport interface KubeAdmissionReview {\n apiVersion: string;\n kind: string;\n response: ValidateResponse[] | MutateResponse | ResponseItem;\n}\n\nexport function karForMutate(mr: MutateResponse): KubeAdmissionReview {\n return {\n apiVersion: \"admission.k8s.io/v1\",\n kind: \"AdmissionReview\",\n response: mr,\n };\n}\n\nexport function karForValidate(ar: AdmissionRequest, vr: ValidateResponse[]): KubeAdmissionReview {\n const isAllowed = vr.filter(r => !r.allowed).length === 0;\n\n const resp: ValidateResponse =\n vr.length === 0\n ? {\n uid: ar.uid,\n allowed: true,\n status: { code: 200, message: \"no in-scope validations -- allowed!\" },\n }\n : {\n uid: vr[0].uid,\n allowed: isAllowed,\n status: {\n code: isAllowed ? 200 : 422,\n message: vr\n .filter(rl => !rl.allowed)\n .map(curr => curr.status?.message)\n .join(\"; \"),\n },\n };\n return {\n apiVersion: \"admission.k8s.io/v1\",\n kind: \"AdmissionReview\",\n response: resp,\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { K8s, KubernetesObject, WatchCfg, WatchEvent } from \"kubernetes-fluent-client\";\nimport { WatchPhase } from \"kubernetes-fluent-client/dist/fluent/types\";\nimport { Capability } from \"./capability\";\nimport { filterNoMatchReason } from \"./helpers\";\nimport { removeFinalizer } from \"./finalizer\";\nimport Log from \"./telemetry/logger\";\nimport { Queue } from \"./queue\";\nimport { Binding } from \"./types\";\nimport { Event } from \"./enums\";\nimport { metricsCollector } from \"./telemetry/metrics\";\n\n// stores Queue instances\nconst queues: Record<string, Queue<KubernetesObject>> = {};\n\n/**\n * Get the key for an entry in the queues\n *\n * @param obj The object to derive a key from\n * @returns The key to a Queue in the list of queues\n */\nexport function queueKey(obj: KubernetesObject) {\n const options = [\"kind\", \"kindNs\", \"kindNsName\", \"global\"];\n const d3fault = \"kind\";\n\n let strat = process.env.PEPR_RECONCILE_STRATEGY || d3fault;\n strat = options.includes(strat) ? strat : d3fault;\n\n const ns = obj.metadata?.namespace ?? \"cluster-scoped\";\n const kind = obj.kind ?? \"UnknownKind\";\n const name = obj.metadata?.name ?? \"Unnamed\";\n\n const lookup: Record<string, string> = {\n kind: `${kind}`,\n kindNs: `${kind}/${ns}`,\n kindNsName: `${kind}/${ns}/${name}`,\n global: \"global\",\n };\n return lookup[strat];\n}\n\nexport function getOrCreateQueue(obj: KubernetesObject) {\n const key = queueKey(obj);\n if (!queues[key]) {\n queues[key] = new Queue<KubernetesObject>(key);\n }\n return queues[key];\n}\n\n// Watch configuration\nconst watchCfg: WatchCfg = {\n resyncFailureMax: process.env.PEPR_RESYNC_FAILURE_MAX ? parseInt(process.env.PEPR_RESYNC_FAILURE_MAX, 10) : 5,\n resyncDelaySec: process.env.PEPR_RESYNC_DELAY_SECONDS ? parseInt(process.env.PEPR_RESYNC_DELAY_SECONDS, 10) : 5,\n lastSeenLimitSeconds: process.env.PEPR_LAST_SEEN_LIMIT_SECONDS\n ? parseInt(process.env.PEPR_LAST_SEEN_LIMIT_SECONDS, 10)\n : 300,\n relistIntervalSec: process.env.PEPR_RELIST_INTERVAL_SECONDS\n ? parseInt(process.env.PEPR_RELIST_INTERVAL_SECONDS, 10)\n : 600,\n};\n\n// Map the event to the watch phase\nconst eventToPhaseMap = {\n [Event.CREATE]: [WatchPhase.Added],\n [Event.UPDATE]: [WatchPhase.Modified],\n [Event.CREATE_OR_UPDATE]: [WatchPhase.Added, WatchPhase.Modified],\n [Event.DELETE]: [WatchPhase.Deleted],\n [Event.ANY]: [WatchPhase.Added, WatchPhase.Modified, WatchPhase.Deleted],\n};\n\n/**\n * Entrypoint for setting up watches for all capabilities\n *\n * @param capabilities The capabilities to load watches for\n */\nexport function setupWatch(capabilities: Capability[], ignoredNamespaces?: string[]) {\n capabilities.map(capability =>\n capability.bindings\n .filter(binding => binding.isWatch)\n .forEach(bindingElement => runBinding(bindingElement, capability.namespaces, ignoredNamespaces)),\n );\n}\n\n/**\n * Setup a watch for a binding\n *\n * @param binding the binding to watch\n * @param capabilityNamespaces list of namespaces to filter on\n */\nasync function runBinding(binding: Binding, capabilityNamespaces: string[], ignoredNamespaces?: string[]) {\n // Get the phases to match, fallback to any\n const phaseMatch: WatchPhase[] = eventToPhaseMap[binding.event] || eventToPhaseMap[Event.ANY];\n\n // The watch callback is run when an object is received or dequeued\n Log.debug({ watchCfg }, \"Effective WatchConfig\");\n\n const watchCallback = async (kubernetesObject: KubernetesObject, phase: WatchPhase) => {\n // First, filter the object based on the phase\n if (phaseMatch.includes(phase)) {\n try {\n // Then, check if the object matches the filter\n const filterMatch = filterNoMatchReason(binding, kubernetesObject, capabilityNamespaces, ignoredNamespaces);\n if (filterMatch !== \"\") {\n Log.debug(filterMatch);\n return;\n }\n if (binding.isFinalize) {\n await handleFinalizerRemoval(kubernetesObject);\n } else {\n await binding.watchCallback?.(kubernetesObject, phase);\n }\n } catch (e) {\n // Errors in the watch callback should not crash the controller\n Log.error(e, \"Error executing watch callback\");\n }\n }\n };\n\n const handleFinalizerRemoval = async (kubernetesObject: KubernetesObject) => {\n if (!kubernetesObject.metadata?.deletionTimestamp) {\n return;\n }\n let shouldRemoveFinalizer: boolean | void | undefined = true;\n try {\n shouldRemoveFinalizer = await binding.finalizeCallback?.(kubernetesObject);\n\n // if not opt'ed out of / if in error state, remove pepr finalizer\n } finally {\n const peprFinal = \"pepr.dev/finalizer\";\n const meta = kubernetesObject.metadata!;\n const resource = `${meta.namespace || \"ClusterScoped\"}/${meta.name}`;\n\n // [ true, void, undefined ] SHOULD remove finalizer\n // [ false ] should NOT remove finalizer\n shouldRemoveFinalizer === false\n ? Log.debug({ obj: kubernetesObject }, `Skipping removal of finalizer '${peprFinal}' from '${resource}'`)\n : await removeFinalizer(binding, kubernetesObject);\n }\n };\n\n // Setup the resource watch\n const watcher = K8s(binding.model, binding.filters).Watch(async (obj, phase) => {\n Log.debug(obj, `Watch event ${phase} received`);\n\n if (binding.isQueue) {\n const queue = getOrCreateQueue(obj);\n await queue.enqueue(obj, phase, watchCallback);\n } else {\n await watchCallback(obj, phase);\n }\n }, watchCfg);\n\n // If failure continues, log and exit\n watcher.events.on(WatchEvent.GIVE_UP, err => {\n Log.error(err, \"Watch failed after 5 attempts, giving up\");\n process.exit(1);\n });\n\n watcher.events.on(WatchEvent.CONNECT, url => logEvent(WatchEvent.CONNECT, url));\n\n watcher.events.on(WatchEvent.DATA_ERROR, err => logEvent(WatchEvent.DATA_ERROR, err.message));\n watcher.events.on(WatchEvent.RECONNECT, retryCount =>\n logEvent(WatchEvent.RECONNECT, `Reconnecting after ${retryCount} attempt${retryCount === 1 ? \"\" : \"s\"}`),\n );\n watcher.events.on(WatchEvent.RECONNECT_PENDING, () => logEvent(WatchEvent.RECONNECT_PENDING));\n watcher.events.on(WatchEvent.GIVE_UP, err => logEvent(WatchEvent.GIVE_UP, err.message));\n watcher.events.on(WatchEvent.ABORT, err => logEvent(WatchEvent.ABORT, err.message));\n watcher.events.on(WatchEvent.OLD_RESOURCE_VERSION, err => logEvent(WatchEvent.OLD_RESOURCE_VERSION, err));\n watcher.events.on(WatchEvent.NETWORK_ERROR, err => logEvent(WatchEvent.NETWORK_ERROR, err.message));\n watcher.events.on(WatchEvent.LIST_ERROR, err => logEvent(WatchEvent.LIST_ERROR, err.message));\n watcher.events.on(WatchEvent.LIST, list => logEvent(WatchEvent.LIST, JSON.stringify(list, undefined, 2)));\n watcher.events.on(WatchEvent.CACHE_MISS, windowName => {\n metricsCollector.incCacheMiss(windowName);\n });\n\n watcher.events.on(WatchEvent.INIT_CACHE_MISS, windowName => {\n metricsCollector.initCacheMissWindow(windowName);\n });\n\n watcher.events.on(WatchEvent.INC_RESYNC_FAILURE_COUNT, retryCount => {\n metricsCollector.incRetryCount(retryCount);\n });\n\n // Start the watch\n try {\n await watcher.start();\n } catch (err) {\n Log.error(err, \"Error starting watch\");\n process.exit(1);\n }\n}\n\nexport function logEvent(event: WatchEvent, message: string = \"\", obj?: KubernetesObject) {\n const logMessage = `Watch event ${event} received${message ? `. ${message}.` : \".\"}`;\n if (obj) {\n Log.debug(obj, logMessage);\n } else {\n Log.debug(logMessage);\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { PeprValidateRequest } from \"../lib/validate-request\";\nimport { PeprMutateRequest } from \"../lib/mutate-request\";\nimport { V1OwnerReference, V1Container } from \"@kubernetes/client-node\";\nimport { GenericKind, K8s, kind } from \"kubernetes-fluent-client\";\n\n/**\n * Returns all containers in a pod\n * @param request the request/pod to get the containers from\n * @param containerType the type of container to get\n * @returns the list of containers in the pod\n */\nexport function containers(\n request: PeprValidateRequest<kind.Pod> | PeprMutateRequest<kind.Pod>,\n containerType?: \"containers\" | \"initContainers\" | \"ephemeralContainers\",\n): V1Container[] {\n const containers = request.Raw.spec?.containers || [];\n const initContainers = request.Raw.spec?.initContainers || [];\n const ephemeralContainers = request.Raw.spec?.ephemeralContainers || [];\n\n if (containerType === \"containers\") {\n return containers;\n }\n if (containerType === \"initContainers\") {\n return initContainers;\n }\n if (containerType === \"ephemeralContainers\") {\n return ephemeralContainers;\n }\n return [...containers, ...initContainers, ...ephemeralContainers];\n}\n\n/**\n * Write a K8s event for a CRD\n *\n * @param cr The custom resource to write the event for\n * @param event The event to write, should contain a human-readable message for the event\n * @param eventType The type of event to write, for example \"Warning\"\n * @param eventReason The reason for the event, for example \"ReconciliationFailed\"\n * @param reportingComponent The component that is reporting the event, for example \"uds.dev/operator\"\n * @param reportingInstance The instance of the component that is reporting the event, for example process.env.HOSTNAME\n */\n\nexport async function writeEvent(\n cr: GenericKind,\n event: Partial<kind.CoreEvent>,\n eventType: string,\n eventReason: string,\n reportingComponent: string,\n reportingInstance: string,\n): Promise<void> {\n await K8s(kind.CoreEvent).Create({\n type: eventType,\n reason: eventReason,\n ...event,\n // Fixed values\n metadata: {\n namespace: cr.metadata!.namespace,\n generateName: cr.metadata!.name,\n },\n involvedObject: {\n apiVersion: cr.apiVersion,\n kind: cr.kind,\n name: cr.metadata!.name,\n namespace: cr.metadata!.namespace,\n uid: cr.metadata!.uid,\n },\n firstTimestamp: new Date(),\n reportingComponent: reportingComponent,\n reportingInstance: reportingInstance,\n });\n}\n\n/**\n * Get the owner reference for a custom resource\n * @param customResource the custom resource to get the owner reference for\n * @param blockOwnerDeletion if true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed.\n * @param controller if true, this reference points to the managing controller.\n * @returns the owner reference array for the custom resource\n */\nexport function getOwnerRefFrom(\n customResource: GenericKind,\n blockOwnerDeletion?: boolean,\n controller?: boolean,\n): V1OwnerReference[] {\n const { apiVersion, kind, metadata } = customResource;\n const { name, uid } = metadata!;\n\n return [\n {\n apiVersion: apiVersion!,\n kind: kind!,\n uid: uid!,\n name: name!,\n ...(blockOwnerDeletion !== undefined && { blockOwnerDeletion }),\n ...(controller !== undefined && { controller }),\n },\n ];\n}\n\n/**\n * Sanitize a resource name to make it a valid Kubernetes resource name.\n *\n * @param name the name of the resource to sanitize\n * @returns the sanitized resource name\n */\nexport function sanitizeResourceName(name: string): string {\n return (\n name\n // The name must be lowercase\n .toLowerCase()\n // Replace sequences of non-alphanumeric characters with a single '-'\n .replace(/[^a-z0-9]+/g, \"-\")\n // Truncate the name to 250 characters\n .slice(0, 250)\n // Remove leading and trailing non-letter characters\n .replace(/^[^a-z]+|[^a-z]+$/g, \"\")\n );\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { KubernetesObject } from \"kubernetes-fluent-client\";\nimport Log from \"./telemetry/logger\";\nimport { Binding, CapabilityExport } from \"./types\";\nimport { sanitizeResourceName } from \"../sdk/sdk\";\nimport {\n carriedAnnotations,\n carriedLabels,\n carriedName,\n carriedNamespace,\n carriesIgnoredNamespace,\n definedAnnotations,\n definedLabels,\n definedName,\n definedNameRegex,\n definedNamespaces,\n definedNamespaceRegexes,\n misboundNamespace,\n mismatchedAnnotations,\n mismatchedDeletionTimestamp,\n mismatchedLabels,\n mismatchedName,\n mismatchedNameRegex,\n mismatchedNamespace,\n mismatchedNamespaceRegex,\n missingCarriableNamespace,\n unbindableNamespaces,\n uncarryableNamespace,\n} from \"./filter/adjudicators/adjudicators\";\n\nexport function matchesRegex(pattern: string, testString: string): boolean {\n return new RegExp(pattern).test(testString);\n}\n\nexport class ValidationError extends Error {}\n\nexport function validateCapabilityNames(capabilities: CapabilityExport[] | undefined): void {\n if (capabilities && capabilities.length > 0) {\n for (let i = 0; i < capabilities.length; i++) {\n if (capabilities[i].name !== sanitizeResourceName(capabilities[i].name)) {\n throw new ValidationError(`Capability name is not a valid Kubernetes resource name: ${capabilities[i].name}`);\n }\n }\n }\n}\n\nexport function validateHash(expectedHash: string): void {\n // Require the hash to be a valid SHA-256 hash (64 characters, hexadecimal)\n const sha256Regex = /^[a-f0-9]{64}$/i;\n if (!expectedHash || !sha256Regex.test(expectedHash)) {\n Log.error(`Invalid hash. Expected a valid SHA-256 hash, got ${expectedHash}`);\n throw new ValidationError(\"Invalid hash\");\n }\n}\n\nexport type RBACMap = {\n [key: string]: {\n verbs: string[];\n plural: string;\n };\n};\n\n/**\n * Decide to run callback after the event comes back from API Server\n **/\nexport function filterNoMatchReason(\n binding: Binding,\n kubernetesObject: Partial<KubernetesObject>,\n capabilityNamespaces: string[],\n ignoredNamespaces?: string[],\n): string {\n const prefix = \"Ignoring Watch Callback:\";\n\n // prettier-ignore\n return (\n mismatchedDeletionTimestamp(binding, kubernetesObject) ?\n `${prefix} Binding defines deletionTimestamp but Object does not carry it.` :\n\n mismatchedName(binding, kubernetesObject) ?\n `${prefix} Binding defines name '${definedName(binding)}' but Object carries '${carriedName(kubernetesObject)}'.` :\n\n misboundNamespace(binding) ?\n `${prefix} Cannot use namespace filter on a namespace object.` :\n\n mismatchedLabels(binding, kubernetesObject) ?\n (\n `${prefix} Binding defines labels '${JSON.stringify(definedLabels(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedLabels(kubernetesObject))}'.`\n ) :\n\n mismatchedAnnotations(binding, kubernetesObject) ?\n (\n `${prefix} Binding defines annotations '${JSON.stringify(definedAnnotations(binding))}' ` +\n `but Object carries '${JSON.stringify(carriedAnnotations(kubernetesObject))}'.`\n ) :\n\n uncarryableNamespace(capabilityNamespaces, kubernetesObject) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(kubernetesObject)}' ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n unbindableNamespaces(capabilityNamespaces, binding) ?\n (\n `${prefix} Binding defines namespaces ${JSON.stringify(definedNamespaces(binding))} ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n mismatchedNamespace(binding, kubernetesObject) ?\n (\n `${prefix} Binding defines namespaces '${JSON.stringify(definedNamespaces(binding))}' ` +\n `but Object carries '${carriedNamespace(kubernetesObject)}'.`\n ) :\n\n mismatchedNamespaceRegex(binding, kubernetesObject) ?\n (\n `${prefix} Binding defines namespace regexes ` +\n `'${JSON.stringify(definedNamespaceRegexes(binding))}' ` +\n `but Object carries '${carriedNamespace(kubernetesObject)}'.`\n ) :\n\n mismatchedNameRegex(binding, kubernetesObject) ?\n (\n `${prefix} Binding defines name regex '${definedNameRegex(binding)}' ` +\n `but Object carries '${carriedName(kubernetesObject)}'.`\n ) :\n\n carriesIgnoredNamespace(ignoredNamespaces, kubernetesObject) ?\n (\n `${prefix} Object carries namespace '${carriedNamespace(kubernetesObject)}' ` +\n `but ignored namespaces include '${JSON.stringify(ignoredNamespaces)}'.`\n ) :\n\n missingCarriableNamespace(capabilityNamespaces, kubernetesObject) ? \n (\n `${prefix} Object does not carry a namespace ` +\n `but namespaces allowed by Capability are '${JSON.stringify(capabilityNamespaces)}'.`\n ) :\n\n \"\"\n );\n}\n\nexport function addVerbIfNotExists(verbs: string[], verb: string) {\n if (!verbs.includes(verb)) {\n verbs.push(verb);\n }\n}\n\nexport function createRBACMap(capabilities: CapabilityExport[]): RBACMap {\n return capabilities.reduce((acc: RBACMap, capability: CapabilityExport) => {\n capability.bindings.forEach(binding => {\n const key = `${binding.kind.group}/${binding.kind.version}/${binding.kind.kind}`;\n\n acc[\"pepr.dev/v1/peprstore\"] = {\n verbs: [\"create\", \"get\", \"patch\", \"watch\"],\n plural: \"peprstores\",\n };\n\n acc[\"apiextensions.k8s.io/v1/customresourcedefinition\"] = {\n verbs: [\"patch\", \"create\"],\n plural: \"customresourcedefinitions\",\n };\n\n if (!acc[key] && binding.isWatch) {\n acc[key] = {\n verbs: [\"watch\"],\n plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`,\n };\n }\n\n // Add finalizer rbac\n if (binding.isFinalize) {\n acc[key] = {\n verbs: [\"patch\"],\n plural: binding.kind.plural || `${binding.kind.kind.toLowerCase()}s`,\n };\n }\n });\n\n return acc;\n }, {});\n}\n\nexport function hasEveryOverlap<T>(array1: T[], array2: T[]): boolean {\n if (!Array.isArray(array1) || !Array.isArray(array2)) {\n return false;\n }\n\n return array1.every(element => array2.includes(element));\n}\n\nexport function hasAnyOverlap<T>(array1: T[], array2: T[]): boolean {\n if (!Array.isArray(array1) || !Array.isArray(array2)) {\n return false;\n }\n\n return array1.some(element => array2.includes(element));\n}\n\nexport function ignoredNamespaceConflict(ignoreNamespaces: string[], bindingNamespaces: string[]) {\n return hasAnyOverlap(bindingNamespaces, ignoreNamespaces);\n}\n\nexport function bindingAndCapabilityNSConflict(bindingNamespaces: string[], capabilityNamespaces: string[]) {\n if (!capabilityNamespaces) {\n return false;\n }\n return capabilityNamespaces.length !== 0 && !hasEveryOverlap(bindingNamespaces, capabilityNamespaces);\n}\n\nexport function generateWatchNamespaceError(\n ignoredNamespaces: string[],\n bindingNamespaces: string[],\n capabilityNamespaces: string[],\n) {\n let err = \"\";\n\n // check if binding uses an ignored namespace\n if (ignoredNamespaceConflict(ignoredNamespaces, bindingNamespaces)) {\n err += `Binding uses a Pepr ignored namespace: ignoredNamespaces: [${ignoredNamespaces.join(\n \", \",\n )}] bindingNamespaces: [${bindingNamespaces.join(\", \")}].`;\n }\n\n // ensure filter namespaces are part of capability namespaces\n if (bindingAndCapabilityNSConflict(bindingNamespaces, capabilityNamespaces)) {\n err += `Binding uses namespace not governed by capability: bindingNamespaces: [${bindingNamespaces.join(\n \", \",\n )}] capabilityNamespaces: [${capabilityNamespaces.join(\", \")}].`;\n }\n\n // add a space if there is a period in the middle of the string\n return err.replace(/\\.([^ ])/g, \". $1\");\n}\n\n// namespaceComplianceValidator ensures that capability bindings respect ignored and capability namespaces\nexport function namespaceComplianceValidator(capability: CapabilityExport, ignoredNamespaces?: string[]) {\n const { namespaces: capabilityNamespaces, bindings, name } = capability;\n const bindingNamespaces: string[] = bindings.flatMap((binding: Binding) => binding.filters.namespaces);\n const bindingRegexNamespaces: string[] = bindings.flatMap(\n (binding: Binding) => binding.filters.regexNamespaces || [],\n );\n\n const namespaceError = generateWatchNamespaceError(\n ignoredNamespaces ? ignoredNamespaces : [],\n bindingNamespaces,\n capabilityNamespaces ? capabilityNamespaces : [],\n );\n if (namespaceError !== \"\") {\n throw new Error(\n `Error in ${name} capability. A binding violates namespace rules. Please check ignoredNamespaces and capability namespaces: ${namespaceError}`,\n );\n }\n\n // Ensure that each regexNamespace matches a capabilityNamespace\n\n if (\n bindingRegexNamespaces &&\n bindingRegexNamespaces.length > 0 &&\n capabilityNamespaces &&\n capabilityNamespaces.length > 0\n ) {\n for (const regexNamespace of bindingRegexNamespaces) {\n let matches = false;\n matches =\n regexNamespace !== \"\" &&\n capabilityNamespaces.some(capabilityNamespace => matchesRegex(regexNamespace, capabilityNamespace));\n if (!matches) {\n throw new Error(\n `Ignoring Watch Callback: Object namespace does not match any capability namespace with regex ${regexNamespace}.`,\n );\n }\n }\n }\n // ensure regexNamespaces do not match ignored ns\n if (\n bindingRegexNamespaces &&\n bindingRegexNamespaces.length > 0 &&\n ignoredNamespaces &&\n ignoredNamespaces.length > 0\n ) {\n for (const regexNamespace of bindingRegexNamespaces) {\n const matchedNS = ignoredNamespaces.find(ignoredNS => matchesRegex(regexNamespace, ignoredNS));\n if (matchedNS) {\n throw new Error(\n `Ignoring Watch Callback: Regex namespace: ${regexNamespace}, is an ignored namespace: ${matchedNS}.`,\n );\n }\n }\n }\n}\n\n// check if secret is over the size limit\nexport function secretOverLimit(str: string): boolean {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(str);\n const sizeInBytes = encoded.length;\n const oneMiBInBytes = 1048576;\n return sizeInBytes > oneMiBInBytes;\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\nexport const parseTimeout = (value: string, previous: unknown): number => {\n const parsedValue = parseInt(value, 10);\n const floatValue = parseFloat(value);\n if (isNaN(parsedValue)) {\n throw new Error(\"Not a number.\");\n } else if (parsedValue !== floatValue) {\n throw new Error(\"Value must be an integer.\");\n } else if (parsedValue < 1 || parsedValue > 30) {\n throw new Error(\"Number must be between 1 and 30.\");\n }\n return parsedValue;\n};\n\n// Remove leading whitespace while keeping format of file\nexport function dedent(file: string): string {\n // Check if the first line is empty and remove it\n const lines = file.split(\"\\n\");\n if (lines[0].trim() === \"\") {\n lines.shift(); // Remove the first line if it's empty\n file = lines.join(\"\\n\"); // Rejoin the remaining lines back into a single string\n }\n\n const match = file.match(/^[ \\t]*(?=\\S)/gm);\n const indent = match && Math.min(...match.map(el => el.length));\n if (indent && indent > 0) {\n const re = new RegExp(`^[ \\\\t]{${indent}}`, \"gm\");\n return file.replace(re, \"\");\n }\n return file;\n}\n\nexport function replaceString(str: string, stringA: string, stringB: string): string {\n // eslint-disable-next-line no-useless-escape\n const escapedStringA = stringA.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n const regExp = new RegExp(escapedStringA, \"g\");\n return str.replace(regExp, stringB);\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { K8s, KubernetesObject, RegisterKind } from \"kubernetes-fluent-client\";\nimport Log from \"./telemetry/logger\";\nimport { Binding, DeepPartial } from \"./types\";\nimport { Operation } from \"./enums\";\nimport { PeprMutateRequest } from \"./mutate-request\";\n\nexport function addFinalizer<K extends KubernetesObject>(request: PeprMutateRequest<K>) {\n // if a DELETE is being processed, don't add a finalizer\n if (request.Request.operation === Operation.DELETE) {\n return;\n }\n\n // if an UPDATE is being processed and it HAS a deletionTimestamp, the\n // resource is going through a pre-delete flow so don't (re-)add a finalizer\n if (request.Request.operation === Operation.UPDATE && request.Raw.metadata?.deletionTimestamp) {\n return;\n }\n\n const peprFinal = \"pepr.dev/finalizer\";\n const finalizers = request.Raw.metadata?.finalizers || [];\n if (!finalizers.includes(peprFinal)) {\n finalizers.push(peprFinal);\n }\n\n request.Merge({ metadata: { finalizers } } as DeepPartial<K>);\n}\n\nexport async function removeFinalizer(binding: Binding, obj: KubernetesObject) {\n const peprFinal = \"pepr.dev/finalizer\";\n const meta = obj.metadata!;\n const resource = `${meta.namespace || \"ClusterScoped\"}/${meta.name}`;\n\n Log.debug({ obj }, `Removing finalizer '${peprFinal}' from '${resource}'`);\n\n // ensure request model is registerd with KFC (for non-built in CRD's, etc.)\n const { model, kind } = binding;\n try {\n RegisterKind(model, kind);\n } catch (e) {\n const expected = e.message === `GVK ${model.name} already registered`;\n if (!expected) {\n Log.error({ model, kind, error: e }, `Error registering \"${kind}\" during finalization.`);\n return;\n }\n }\n\n // remove pepr finalizers\n const finalizers = meta.finalizers?.filter(f => f !== peprFinal) || [];\n\n // JSON Patch - replace a key\n // https://datatracker.ietf.org/doc/html/rfc6902/#section-4.3\n obj = await K8s(model, meta).Patch([\n {\n op: \"replace\",\n path: `/metadata/finalizers`,\n value: finalizers,\n },\n ]);\n Log.debug({ obj }, `Removed finalizer '${peprFinal}' from '${resource}'`);\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\nimport { KubernetesObject } from \"@kubernetes/client-node\";\nimport { WatchPhase } from \"kubernetes-fluent-client/dist/fluent/types\";\nimport { randomBytes } from \"node:crypto\";\nimport Log from \"./telemetry/logger\";\n\ntype WatchCallback = (obj: KubernetesObject, phase: WatchPhase) => Promise<void>;\n\ntype QueueItem<K extends KubernetesObject> = {\n item: K;\n phase: WatchPhase;\n callback: WatchCallback;\n resolve: (value: void | PromiseLike<void>) => void;\n reject: (reason?: string) => void;\n};\n\n/**\n * Queue is a FIFO queue for reconciling\n */\nexport class Queue<K extends KubernetesObject> {\n #name: string;\n #uid: string;\n #queue: QueueItem<K>[] = [];\n #pendingPromise = false;\n\n constructor(name: string) {\n this.#name = name;\n this.#uid = `${Date.now()}-${randomBytes(2).toString(\"hex\")}`;\n }\n\n label() {\n return { name: this.#name, uid: this.#uid };\n }\n\n stats() {\n return {\n queue: this.label(),\n stats: {\n length: this.#queue.length,\n },\n };\n }\n\n /**\n * Enqueue adds an item to the queue and returns a promise that resolves when the item is\n * reconciled.\n *\n * @param item The object to reconcile\n * @param type The watch phase requested for reconcile\n * @param reconcile The callback to enqueue for reconcile\n * @returns A promise that resolves when the object is reconciled\n */\n enqueue(item: K, phase: WatchPhase, reconcile: WatchCallback) {\n const note = {\n queue: this.label(),\n item: {\n name: item.metadata?.name,\n namespace: item.metadata?.namespace,\n resourceVersion: item.metadata?.resourceVersion,\n },\n };\n Log.debug(note, \"Enqueueing\");\n return new Promise<void>((resolve, reject) => {\n this.#queue.push({ item, phase, callback: reconcile, resolve, reject });\n Log.debug(this.stats(), \"Queue stats - push\");\n return this.#dequeue();\n });\n }\n\n /**\n * Dequeue reconciles the next item in the queue\n *\n * @returns A promise that resolves when the webapp is reconciled\n */\n async #dequeue() {\n // If there is a pending promise, do nothing\n if (this.#pendingPromise) {\n Log.debug(\"Pending promise, not dequeuing\");\n return false;\n }\n\n // Take the next element from the queue\n const element = this.#queue.shift();\n\n // If there is no element, do nothing\n if (!element) {\n Log.debug(\"No element, not dequeuing\");\n return false;\n }\n\n try {\n // Set the pending promise flag to avoid concurrent reconciliations\n this.#pendingPromise = true;\n\n // Reconcile the element\n const note = {\n queue: this.label(),\n item: {\n name: element.item.metadata?.name,\n namespace: element.item.metadata?.namespace,\n resourceVersion: element.item.metadata?.resourceVersion,\n },\n };\n Log.debug(note, \"Reconciling\");\n await element.callback(element.item, element.phase);\n Log.debug(note, \"Reconciled\");\n\n element.resolve();\n } catch (e) {\n Log.debug(`Error reconciling ${element.item.metadata!.name}`, { error: e });\n element.reject(e);\n } finally {\n Log.debug(this.stats(), \"Queue stats - shift\");\n\n // Reset the pending promise flag\n Log.debug(\"Resetting pending promise and dequeuing\");\n this.#pendingPromise = false;\n\n // After the element is reconciled, dequeue the next element\n await this.#dequeue();\n }\n }\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { clone } from \"ramda\";\nimport pointer from \"json-pointer\";\nexport type DataOp = \"add\" | \"remove\";\nexport type DataStore = Record<string, string>;\nexport type DataSender = (op: DataOp, keys: string[], value?: string) => void;\nexport type DataReceiver = (data: DataStore) => void;\nexport type Unsubscribe = () => void;\n\nconst MAX_WAIT_TIME = 15000;\nconst STORE_VERSION_PREFIX = \"v2\";\n\nexport function v2StoreKey(key: string): string {\n return `${STORE_VERSION_PREFIX}-${pointer.escape(key)}`;\n}\n\nexport function v2UnescapedStoreKey(key: string): string {\n return `${STORE_VERSION_PREFIX}-${key}`;\n}\n\nexport function stripV2Prefix(key: string): string {\n return key.replace(/^v2-/, \"\");\n}\nexport interface PeprStore {\n /**\n * Returns the current value associated with the given key, or null if the given key does not exist.\n */\n getItem(key: string): string | null;\n /**\n * Removes all key/value pairs, if there are any.\n */\n clear(): void;\n /**\n * Removes the key/value pair with the given key, if a key/value pair with the given key exists.\n */\n removeItem(key: string): void;\n /**\n * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.\n */\n setItem(key: string, value: string): void;\n\n /**\n * Subscribe to changes in the store. This API behaves similarly to the [Svelte Store API](https://vercel.com/docs/beginner-sveltekit/svelte-stores#using-the-store).\n *\n * @param listener - The callback to be invoked when the store changes.\n * @returns A function to unsubscribe from the listener.\n */\n subscribe(listener: DataReceiver): Unsubscribe;\n\n /**\n * Register a function to be called when the store is ready.\n */\n onReady(callback: DataReceiver): void;\n\n /**\n * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.\n * Resolves when the key/value show up in the store.\n */\n setItemAndWait(key: string, value: string): Promise<void>;\n\n /**\n * Remove the value of the key.\n * Resolves when the key does not show up in the store.\n */\n removeItemAndWait(key: string): Promise<void>;\n}\n\n/**\n * A key-value data store that can be used to persist data that should be shared across Pepr controllers and capabilities.\n *\n * The API is similar to the [Storage API](https://developer.mozilla.org/docs/Web/API/Storage)\n */\n\nexport class Storage implements PeprStore {\n #store: DataStore = {};\n #send!: DataSender;\n #subscribers: Record<number, DataReceiver> = {};\n #subscriberId = 0;\n #readyHandlers: DataReceiver[] = [];\n\n registerSender = (send: DataSender): void => {\n this.#send = send;\n };\n\n receive = (data: DataStore): void => {\n this.#store = data || {};\n\n this.#onReady();\n\n // Notify all subscribers\n for (const idx in this.#subscribers) {\n // Send a unique clone of the store to each subscriber\n this.#subscribers[idx](clone(this.#store));\n }\n };\n\n getItem = (key: string): string | null => {\n const result = this.#store[v2UnescapedStoreKey(key)] || null;\n if (result !== null && typeof result !== \"function\" && typeof result !== \"object\") {\n return result;\n }\n return null;\n };\n\n clear = (): void => {\n Object.keys(this.#store).length > 0 &&\n this.#dispatchUpdate(\n \"remove\",\n Object.keys(this.#store).map(key => pointer.escape(key)),\n );\n };\n\n removeItem = (key: string): void => {\n this.#dispatchUpdate(\"remove\", [v2StoreKey(key)]);\n };\n\n setItem = (key: string, value: string): void => {\n this.#dispatchUpdate(\"add\", [v2StoreKey(key)], value);\n };\n\n /**\n * Creates a promise and subscribes to the store, the promise resolves when\n * the key and value are seen in the store.\n *\n * @param key - The key to add into the store\n * @param value - The value of the key\n * @returns\n */\n setItemAndWait = (key: string, value: string): Promise<void> => {\n this.#dispatchUpdate(\"add\", [v2StoreKey(key)], value);\n\n return new Promise<void>((resolve, reject) => {\n const unsubscribe = this.subscribe(data => {\n if (data[`${v2UnescapedStoreKey(key)}`] === value) {\n unsubscribe();\n resolve();\n }\n });\n\n // If promise has not resolved before MAX_WAIT_TIME reject\n setTimeout(() => {\n unsubscribe();\n return reject();\n }, MAX_WAIT_TIME);\n });\n };\n\n /**\n * Creates a promise and subscribes to the store, the promise resolves when\n * the key is removed from the store.\n *\n * @param key - The key to add into the store\n * @returns\n */\n removeItemAndWait = (key: string): Promise<void> => {\n this.#dispatchUpdate(\"remove\", [v2StoreKey(key)]);\n return new Promise<void>((resolve, reject) => {\n const unsubscribe = this.subscribe(data => {\n if (!Object.hasOwn(data, `${v2UnescapedStoreKey(key)}`)) {\n unsubscribe();\n resolve();\n }\n });\n\n // If promise has not resolved before MAX_WAIT_TIME reject\n setTimeout(() => {\n unsubscribe();\n return reject();\n }, MAX_WAIT_TIME);\n });\n };\n\n subscribe = (subscriber: DataReceiver): (() => void) => {\n const idx = this.#subscriberId++;\n this.#subscribers[idx] = subscriber;\n return () => this.unsubscribe(idx);\n };\n\n onReady = (callback: DataReceiver): void => {\n this.#readyHandlers.push(callback);\n };\n\n /**\n * Remove a subscriber from the list of subscribers.\n * @param idx - The index of the subscriber to remove.\n */\n unsubscribe = (idx: number): void => {\n delete this.#subscribers[idx];\n };\n\n #onReady = (): void => {\n // Notify all ready handlers with a clone of the store\n for (const handler of this.#readyHandlers) {\n handler(clone(this.#store));\n }\n\n // Make this a noop so that it can't be called again\n this.#onReady = (): void => {};\n };\n\n /**\n * Dispatch an update to the store and notify all subscribers.\n * @param op - The type of operation to perform.\n * @param keys - The keys to update.\n * @param [value] - The new value.\n */\n #dispatchUpdate = (op: DataOp, keys: string[], value?: string): void => {\n this.#send(op, keys, value);\n };\n}\n", "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2023-Present The Pepr Authors\n\nimport { PeprStore } from \"./storage\";\n\nexport type Unit = \"seconds\" | \"second\" | \"minute\" | \"minutes\" | \"hours\" | \"hour\";\n\nexport interface Schedule {\n /**\n * * The name of the store\n */\n name: string;\n /**\n * The value associated with a unit of time\n */\n every: number;\n /**\n * The unit of time\n */\n unit: Unit;\n /**\n * The code to run\n */\n run: () => void;\n /**\n * The start time of the schedule\n */\n startTime?: Date | undefined;\n\n /**\n * The number of times the schedule has run\n */\n completions?: number | undefined;\n /**\n * Tje intervalID to clear the interval\n */\n intervalID?: NodeJS.Timeout;\n}\n\nexport class OnSchedule implements Schedule {\n intervalId: NodeJS.Timeout | null = null;\n store: PeprStore | undefined;\n name!: string;\n completions?: number | undefined;\n every: number;\n unit: Unit;\n run!: () => void;\n startTime?: Date | undefined;\n duration: number | undefined;\n lastTimestamp: Date | undefined;\n\n constructor(schedule: Schedule) {\n this.name = schedule.name;\n this.run = schedule.run;\n this.every = schedule.every;\n this.unit = schedule.unit;\n this.startTime = schedule?.startTime;\n this.completions = schedule?.completions;\n }\n setStore(store: PeprStore): void {\n this.store = store;\n this.startInterval();\n }\n startInterval(): void {\n this.checkStore();\n this.getDuration();\n this.setupInterval();\n }\n /**\n * Checks the store for this schedule and sets the values if it exists\n * @returns\n */\n checkStore(): void {\n const result = this.store && this.store.getItem(this.name);\n if (result) {\n const storedSchedule = JSON.parse(result);\n this.completions = storedSchedule?.completions;\n this.startTime = storedSchedule?.startTime;\n this.lastTimestamp = storedSchedule?.lastTimestamp;\n }\n }\n\n /**\n * Saves the schedule to the store\n * @returns\n */\n saveToStore(): void {\n const schedule = {\n completions: this.completions,\n startTime: this.startTime,\n lastTimestamp: new Date(),\n name: this.name,\n };\n this.store && this.store.setItem(this.name, JSON.stringify(schedule));\n }\n\n /**\n * Gets the durations in milliseconds\n */\n getDuration(): void {\n switch (this.unit) {\n case \"seconds\":\n if (this.every < 10) throw new Error(\"10 Seconds in the smallest interval allowed\");\n this.duration = 1000 * this.every;\n break;\n case \"minutes\":\n case \"minute\":\n this.duration = 1000 * 60 * this.every;\n break;\n case \"hours\":\n case \"hour\":\n this.duration = 1000 * 60 * 60 * this.every;\n break;\n default:\n throw new Error(\"Invalid time unit\");\n }\n }\n\n /**\n * Sets up the interval\n */\n setupInterval(): void {\n const now = new Date();\n let delay: number | undefined;\n\n if (this.lastTimestamp && this.startTime) {\n this.startTime = undefined;\n }\n\n if (this.startTime) {\n delay = this.startTime.getTime() - now.getTime();\n } else if (this.lastTimestamp && this.duration) {\n const lastTimestamp = new Date(this.lastTimestamp);\n delay = this.duration - (now.getTime() - lastTimestamp.getTime());\n }\n\n if (delay === undefined || delay <= 0) {\n this.start();\n } else {\n setTimeout(() => {\n this.start();\n }, delay);\n }\n }\n\n /**\n * Starts the interval\n */\n start(): void {\n this.intervalId = setInterval(() => {\n if (this.completions === 0) {\n this.stop();\n return;\n } else {\n this.run();\n\n if (this.completions && this.completions !== 0) {\n this.completions -= 1;\n }\n this.saveToStore();\n }\n }, this.duration);\n }\n\n /**\n * Stops the interval\n */\n stop(): void {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n this.store && this.store.removeItem(this.name);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4CAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAC,mCAAuE;AACvE,QAAmB;;;ACEnB,IAAAC,mCAAwE;AACxE,IAAAC,gBAAuB;;;ACAvB,kBAAuC;AAGvC,IAAM,cAAc,QAAQ,IAAI,qBAAqB;AACrD,IAAM,gBAAgB;AAEtB,IAAM,SAAS;AAAA,EACb,QAAQ;AAAA,EACR,SAAS;AAAA,IACP,UAAU;AAAA,EACZ;AACF;AAEA,IAAM,YAAY,cAAc,SAAS;AAEzC,IAAM,mBACJ,QAAQ,IAAI,oBAAoB,QAAQ,MAAM,6BAAiB,QAAQ,IAAI,MAAM,6BAAiB,UAAU;AAC9G,IAAM,UAAM,kBAAK;AAAA,EACf;AAAA,EACA,WAAW;AACb,CAAC;AAED,IAAI,QAAQ,IAAI,WAAW;AACzB,MAAI,QAAQ,QAAQ,IAAI;AAC1B;AAEO,SAAS,cAAc,OAAqB;AACjD,QAAM,WAAW,QAAQ,IAAI,6BAA6B;AAC1D,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,OAAO,KAAK,MAAM,IAAI,EAAE,OAAO,CAAC,KAA6B,QAAgB;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AAS,MAAM,OAAe;AAC5B,qBAAI,MAAM,uBAAuB,KAAK,IAAI,MAAM;AAChD,cAAQ,QAAQ;AAChB,aAAO;AAAA,IACT;AAEA,aAAS,UAAU,OAAc;AAC/B,cAAQ,QAAQ;AAChB,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,oBAAoB,MAAM,iDAAgC;AAAA,MAC1D,WAAW,MAAM,+BAAsB;AAAA,MACvC,WAAW,MAAM,+BAAsB;AAAA,MACvC,WAAW,MAAM,+BAAsB;AAAA,IACzC;AAAA,EACF;AACF;",
6
+ "names": ["a", "import_kubernetes_fluent_client", "import_kubernetes_fluent_client", "import_ramda", "import_ramda", "promClient", "kind", "import_ramda", "jsonPatch", "e", "import_ramda", "import_kubernetes_fluent_client", "import_ramda", "import_kubernetes_fluent_client", "namespace", "name", "express", "fs", "https", "namespace", "res", "import_kubernetes_fluent_client", "import_kubernetes_fluent_client", "containers", "kind", "import_kubernetes_fluent_client", "kind", "kind", "import_ramda", "pointer", "pointer", "kind"]
7
7
  }