pepr 0.1.25 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/module.ts DELETED
@@ -1,57 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
-
4
- import R from "ramda";
5
- import { Capability } from "./capability";
6
- import { GroupVersionKind, Request, Response } from "./k8s";
7
- import logger from "./logger";
8
- import { processor } from "./processor";
9
- import { ModuleConfig } from "./types";
10
-
11
- const alwaysIgnore = {
12
- namespaces: ["kube-system", "pepr-system"],
13
- labels: [{ "pepr.dev": "ignore" }],
14
- };
15
-
16
- export type PackageJSON = {
17
- description: string;
18
- pepr: ModuleConfig;
19
- };
20
-
21
- export class PeprModule {
22
- private _config: ModuleConfig;
23
- private _state: Capability[] = [];
24
- private _kinds: GroupVersionKind[] = [];
25
-
26
- get kinds(): GroupVersionKind[] {
27
- return this._kinds;
28
- }
29
-
30
- get UUID(): string {
31
- return this._config.uuid;
32
- }
33
-
34
- /**
35
- * Create a new Pepr runtime
36
- *
37
- * @param config The configuration for the Pepr runtime
38
- */
39
- constructor({ description, pepr }: PackageJSON) {
40
- pepr.description = description;
41
- this._config = R.mergeDeepWith(R.concat, pepr, alwaysIgnore);
42
- }
43
-
44
- Register = (capability: Capability) => {
45
- logger.info(`Registering capability ${capability.name}`);
46
-
47
- // Add the kinds to the list of kinds (ignoring duplicates for now)
48
- this._kinds = capability.bindings.map(({ kind }) => kind);
49
-
50
- // Add the capability to the state
51
- this._state.push(capability);
52
- };
53
-
54
- ProcessRequest = (req: Request): Response => {
55
- return processor(this._config, this._state, req);
56
- };
57
- }
@@ -1,83 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
-
4
- import { compare } from "fast-json-patch";
5
- import { Capability } from "./capability";
6
- import { shouldSkipRequest } from "./filter";
7
- import { Request, Response } from "./k8s/types";
8
- import logger from "./logger";
9
- import { RequestWrapper } from "./request";
10
- import { ModuleConfig } from "./types";
11
-
12
- export function processor(config: ModuleConfig, capabilities: Capability[], req: Request): Response {
13
- const wrapped = new RequestWrapper(req);
14
- const response: Response = {
15
- uid: req.uid,
16
- patchType: "JSONPatch",
17
- warnings: [],
18
- allowed: false,
19
- };
20
-
21
- logger.info(`Processing '${req.uid}' for '${req.kind.kind}' '${req.name}'`);
22
-
23
- for (const { name, bindings } of capabilities) {
24
- const prefix = `${req.uid} ${req.name}: ${name}`;
25
- logger.info(`Processing capability ${name}`, prefix);
26
-
27
- for (const action of bindings) {
28
- // Continue to the next action without doing anything if this one should be skipped
29
- if (shouldSkipRequest(action, req)) {
30
- continue;
31
- }
32
-
33
- logger.info(`Processing matched action ${action.kind.kind}`, prefix);
34
-
35
- // Add annotations to the request to indicate that the capability started processing
36
- // this will allow tracking of failed mutations that were permitted to continue
37
- const { metadata } = wrapped.Raw;
38
- const identifier = `pepr.dev/${config.uuid}/${name}`;
39
- metadata.annotations = metadata.annotations || {};
40
- metadata.annotations[identifier] = "started";
41
-
42
- try {
43
- // Run the action
44
- action.callback(wrapped);
45
-
46
- // Add annotations to the request to indicate that the capability succeeded
47
- metadata.annotations[identifier] = "succeeded";
48
- } catch (e) {
49
- response.warnings.push(`Action failed: ${e}`);
50
-
51
- // If errors are not allowed, note the failure in the Reponse
52
- if (config.onError) {
53
- logger.error(`Action failed: ${e}`, prefix);
54
- response.result = "Pepr module configured to reject on error";
55
- return response;
56
- } else {
57
- logger.warn(`Action failed: ${e}`, prefix);
58
- metadata.annotations[identifier] = "warning";
59
- }
60
- }
61
- }
62
- }
63
-
64
- // If we've made it this far, the request is allowed
65
- response.allowed = true;
66
-
67
- // Compare the original request to the modified request to get the patches
68
- const patches = compare(req.object, wrapped.Raw);
69
-
70
- // Only add the patch if there are patches to apply
71
- if (patches.length > 0) {
72
- response.patch = JSON.stringify(patches);
73
- }
74
-
75
- // Remove the warnings array if it's empty
76
- if (response.warnings.length < 1) {
77
- delete response.warnings;
78
- }
79
-
80
- logger.debug(patches);
81
-
82
- return response;
83
- }
@@ -1,140 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
-
4
- import * as R from "ramda";
5
- import { KubernetesObject, Request } from "./k8s";
6
- import { DeepPartial } from "./types";
7
-
8
- /**
9
- * The RequestWrapper class provides methods to modify Kubernetes objects in the context
10
- * of a mutating webhook request.
11
- */
12
- export class RequestWrapper<T extends KubernetesObject> {
13
- private _input: Request<T>;
14
-
15
- public Raw: T;
16
-
17
- get PermitSideEffects() {
18
- return !this._input.dryRun;
19
- }
20
-
21
- /**
22
- * Indicates whether the request is a dry run.
23
- * @returns true if the request is a dry run, false otherwise.
24
- */
25
- get IsDryRun() {
26
- return this._input.dryRun;
27
- }
28
-
29
- /**
30
- * Provides access to the old resource in the request if available.
31
- * @returns The old Kubernetes resource object or null if not available.
32
- */
33
- get OldResource() {
34
- return this._input.oldObject;
35
- }
36
-
37
- /**
38
- * Provides access to the request object.
39
- * @returns The request object containing the Kubernetes resource.
40
- */
41
- get Request() {
42
- return this._input;
43
- }
44
-
45
- /**
46
- * Creates a new instance of the Action class.
47
- * @param input - The request object containing the Kubernetes resource to modify.
48
- */
49
- constructor(input: Request<T>) {
50
- // Deep clone the object to prevent mutation of the original object
51
- this.Raw = R.clone(input.object);
52
- // Store the input
53
- this._input = input;
54
- }
55
-
56
- /**
57
- * Deep merges the provided object with the current resource.
58
- *
59
- * @param obj - The object to merge with the current resource.
60
- */
61
- Merge(obj: DeepPartial<T>) {
62
- this.Raw = R.mergeDeepRight(this.Raw, obj) as T;
63
- }
64
-
65
- /**
66
- * Updates a label on the Kubernetes resource.
67
- * @param key - The key of the label to update.
68
- * @param value - The value of the label.
69
- * @returns The current Action instance for method chaining.
70
- */
71
- SetLabel(key: string, value: string) {
72
- const ref = this.Raw;
73
-
74
- ref.metadata = ref.metadata ?? {};
75
- ref.metadata.labels = ref.metadata.labels ?? {};
76
- ref.metadata.labels[key] = value;
77
-
78
- return this;
79
- }
80
-
81
- /**
82
- * Updates an annotation on the Kubernetes resource.
83
- * @param key - The key of the annotation to update.
84
- * @param value - The value of the annotation.
85
- * @returns The current Action instance for method chaining.
86
- */
87
- SetAnnotation(key: string, value: string) {
88
- const ref = this.Raw;
89
-
90
- ref.metadata = ref.metadata ?? {};
91
- ref.metadata.annotations = ref.metadata.annotations ?? {};
92
- ref.metadata.annotations[key] = value;
93
-
94
- return this;
95
- }
96
-
97
- /**
98
- * Removes a label from the Kubernetes resource.
99
- * @param key - The key of the label to remove.
100
- * @returns The current Action instance for method chaining.
101
- */
102
- RemoveLabel(key: string) {
103
- if (this.Raw.metadata?.labels?.[key]) {
104
- delete this.Raw.metadata.labels[key];
105
- }
106
- return this;
107
- }
108
-
109
- /**
110
- * Removes an annotation from the Kubernetes resource.
111
- * @param key - The key of the annotation to remove.
112
- * @returns The current Action instance for method chaining.
113
- */
114
- RemoveAnnotation(key: string) {
115
- if (this.Raw.metadata?.annotations?.[key]) {
116
- delete this.Raw.metadata.annotations[key];
117
- }
118
- return this;
119
- }
120
-
121
- /**
122
- * Check if a label exists on the Kubernetes resource.
123
- *
124
- * @param key the label key to check
125
- * @returns
126
- */
127
- HasLabel(key: string) {
128
- return this.Raw?.metadata?.labels?.[key] !== undefined;
129
- }
130
-
131
- /**
132
- * Check if an annotation exists on the Kubernetes resource.
133
- *
134
- * @param key the annotation key to check
135
- * @returns
136
- */
137
- HasAnnotation(key: string) {
138
- return this.Raw?.metadata?.annotations?.[key] !== undefined;
139
- }
140
- }
package/src/lib/types.ts DELETED
@@ -1,211 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
- // SPDX-FileCopyrightText: 2023-Present The Pepr Authors
3
-
4
- import { GroupVersionKind, KubernetesObject, WebhookIgnore } from "./k8s";
5
- import { RequestWrapper } from "./request";
6
-
7
- /**
8
- * The behavior of this module when an error occurs.
9
- */
10
- export enum ErrorBehavior {
11
- ignore = "ignore",
12
- audit = "audit",
13
- reject = "reject",
14
- }
15
-
16
- /**
17
- * The phase of the Kubernetes admission webhook that the capability is registered for.
18
- *
19
- * Currently only `mutate` is supported.
20
- */
21
- export enum HookPhase {
22
- mutate = "mutate",
23
- valdiate = "validate",
24
- }
25
-
26
- /**
27
- * Recursively make all properties in T optional.
28
- */
29
- export type DeepPartial<T> = {
30
- [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
31
- };
32
-
33
- /**
34
- * The type of Kubernetes mutating webhook event ethat the capability action is registered for.
35
- */
36
-
37
- export enum Event {
38
- Create = "create",
39
- Update = "update",
40
- Delete = "delete",
41
- CreateOrUpdate = "createOrUpdate",
42
- }
43
-
44
- export interface CapabilityCfg {
45
- /**
46
- * The name of the capability. This should be unique.
47
- */
48
- name: string;
49
- /**
50
- * A description of the capability and what it does.
51
- */
52
- description: string;
53
- /**
54
- * List of namespaces that this capability applies to, if empty, applies to all namespaces (cluster-wide).
55
- * This does not supersede the `alwaysIgnore` global configuration.
56
- */
57
- namespaces?: string[];
58
-
59
- /**
60
- * FUTURE USE.
61
- *
62
- * Declare if this capability should be used for mutation or validation. Currently this is not used
63
- * and everything is considered a mutation.
64
- */
65
- mutateOrValidate?: HookPhase;
66
- }
67
-
68
- export type ModuleSigning = {
69
- /**
70
- * Specifies the signing policy.
71
- * "requireAuthorizedKey" - only authorized keys are accepted.
72
- * "requireAnyKey" - any key is accepted, as long as it's valid.
73
- * "none" - no signing required.
74
- */
75
- signingPolicy?: "requireAuthorizedKey" | "requireAnyKey" | "none";
76
- /**
77
- * List of authorized keys for the "requireAuthorizedKey" policy.
78
- * These keys are allowed to sign Pepr capabilities.
79
- */
80
- authorizedKeys?: string[];
81
- };
82
-
83
- /** Global configuration for the Pepr runtime. */
84
- export type ModuleConfig = {
85
- /** The user-defined name for the module */
86
- name: string;
87
- /** The version of Pepr that the module was originally generated with */
88
- version: string;
89
- /** A unique identifier for this Pepr module. This is automatically generated by Pepr. */
90
- uuid: string;
91
- /** A description of the Pepr module and what it does. */
92
- description?: string;
93
- /** Reject K8s resource AdmissionRequests on error. */
94
- onError: ErrorBehavior | string;
95
- /** Configure global exclusions that will never be processed by Pepr. */
96
- alwaysIgnore: WebhookIgnore;
97
- /**
98
- * FUTURE USE.
99
- *
100
- * Configure the signing policy for Pepr capabilities.
101
- * This setting determines the requirements for signing keys in Pepr.
102
- */
103
- signing?: ModuleSigning;
104
- };
105
-
106
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
107
- export type GenericClass = abstract new () => any;
108
-
109
- export type WhenSelector<T extends GenericClass> = {
110
- /** Register a capability action to be executed when a Kubernetes resource is created or updated. */
111
- IsCreatedOrUpdated: () => BindingAll<T>;
112
- /** Register a capability action to be executed when a Kubernetes resource is created. */
113
- IsCreated: () => BindingAll<T>;
114
- /** Register a capability action to be executed when a Kubernetes resource is updated. */
115
- IsUpdated: () => BindingAll<T>;
116
- /** Register a capability action to be executed when a Kubernetes resource is deleted. */
117
- IsDeleted: () => BindingAll<T>;
118
- };
119
-
120
- export type Binding = {
121
- event?: Event;
122
- readonly kind: GroupVersionKind;
123
- readonly filters: {
124
- name: string;
125
- namespaces: string[];
126
- labels: Record<string, string>;
127
- annotations: Record<string, string>;
128
- };
129
- readonly callback: CapabilityAction<GenericClass, InstanceType<GenericClass>>;
130
- };
131
-
132
- export type BindingFilter<T extends GenericClass> = BindToActionOrSet<T> & {
133
- /**
134
- * Only apply the capability action if the resource has the specified label. If no value is specified, the label must exist.
135
- * Note multiple calls to this method will result in an AND condition. e.g.
136
- *
137
- * ```ts
138
- * When(a.Deployment)
139
- * .IsCreated()
140
- * .WithLabel("foo", "bar")
141
- * .WithLabel("baz", "qux")
142
- * .Then(...)
143
- * ```
144
- *
145
- * Will only apply the capability action if the resource has both the `foo=bar` and `baz=qux` labels.
146
- *
147
- * @param key
148
- * @param value
149
- */
150
- WithLabel: (key: string, value?: string) => BindingFilter<T>;
151
- /**
152
- * Only apply the capability action if the resource has the specified annotation. If no value is specified, the annotation must exist.
153
- * Note multiple calls to this method will result in an AND condition. e.g.
154
- *
155
- * ```ts
156
- * When(a.Deployment)
157
- * .IsCreated()
158
- * .WithAnnotation("foo", "bar")
159
- * .WithAnnotation("baz", "qux")
160
- * .Then(...)
161
- * ```
162
- *
163
- * Will only apply the capability action if the resource has both the `foo=bar` and `baz=qux` annotations.
164
- *
165
- * @param key
166
- * @param value
167
- */
168
- WithAnnotation: (key: string, value?: string) => BindingFilter<T>;
169
- };
170
-
171
- export type BindingWithName<T extends GenericClass> = BindingFilter<T> & {
172
- /** Only apply the capability action if the resource name matches the specified name. */
173
- WithName: (name: string) => BindingFilter<T>;
174
- };
175
-
176
- export type BindingAll<T extends GenericClass> = BindingWithName<T> & {
177
- /** Only apply the cabability action if the resource is in one of the specified namespaces.*/
178
- InNamespace: (...namespaces: string[]) => BindingFilter<T>;
179
- };
180
-
181
- export type BindToAction<T extends GenericClass> = {
182
- /**
183
- * Create a new capability action with the specified callback function and previously specified
184
- * filters.
185
- * @param action The capability action to be executed when the Kubernetes resource is processed by the AdmissionController.
186
- */
187
- Then: (action: CapabilityAction<T, InstanceType<T>>) => BindToAction<T>;
188
- };
189
-
190
- export type BindToActionOrSet<T extends GenericClass> = BindToAction<T> & {
191
- /**
192
- * Merge the specified updates into the resource, this can only be used once per binding.
193
- * Note this is just a convenience method for `request.Merge(values)`.
194
- *
195
- * Example change the `minReadySeconds` to 3 of a deployment when it is created:
196
- *
197
- * ```ts
198
- * When(a.Deployment)
199
- * .IsCreated()
200
- * .ThenSet({ spec: { minReadySeconds: 3 } });
201
- * ```
202
- *
203
- * @param merge
204
- * @returns
205
- */
206
- ThenSet: (val: DeepPartial<InstanceType<T>>) => BindToAction<T>;
207
- };
208
-
209
- export type CapabilityAction<T extends GenericClass, K extends KubernetesObject = InstanceType<T>> = (
210
- req: RequestWrapper<K>
211
- ) => void;