kubewarden / cel-policy

A policy that can run CEL expressions
Apache License 2.0
3 stars 5 forks source link

Policy targeting a sub-resource fails #96

Open flavio opened 4 hours ago

flavio commented 4 hours ago

Is there an existing issue for this?

Current Behavior

I've created a CEL-based policy that targets a sub-resource. The policy fails at runtime with the following error message:

wrong object format: metadata not found in object

Expected Behavior

The policy is evaluated without failing

Steps To Reproduce

I've created the following policy:

apiVersion: policies.kubewarden.io/v1
kind: AdmissionPolicy
metadata:
  annotations:
  name: "block-kubectl-exec"
spec:
  module: ghcr.io/kubewarden/policies/cel-policy:v1.2.1
  settings:
    variables:
      - name: "replicas"
        expression: "object.spec.replicas"
    validations:
      - expression: "request.name == 'alpine'"
        message: "cannot connect to pods with label flavio set"
  rules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CONNECT"]
      resources: ["pods/exec", "pods/attach", "pods/portforward"]
  backgroundAudit: false

Then run the following command:

kubectl exec -ti alpine -- ash

This will fail with the following error:

Error from server: admission webhook "namespaced-default-block-kubectl-exec.kubewarden.admission" denied the request: wrong object format: metadata not found in object

The CEL code fails because the admission object is not the usual one:

{
  "kind": "AdmissionReview",
  "apiVersion": "admission.k8s.io/v1",
  "request": {
    "uid": "ab70f6b0-5d91-42df-96d4-747b2153e7df",
    "kind": {
      "group": "",
      "version": "v1",
      "kind": "PodExecOptions"
    },
    "resource": {
      "group": "",
      "version": "v1",
      "resource": "pods"
    },
    "subResource": "exec",
    "requestKind": {
      "group": "",
      "version": "v1",
      "kind": "PodExecOptions"
    },
    "requestResource": {
      "group": "",
      "version": "v1",
      "resource": "pods"
    },
    "requestSubResource": "exec",
    "name": "alpine",
    "namespace": "default",
    "operation": "CONNECT",
    "userInfo": {
      "groups": [
        "system:masters",
        "system:authenticated"
      ],
      "username": "minikube-user"
    },
    "object": {
      "apiVersion": "v1",
      "command": [
        "ash"
      ],
      "container": "main",
      "kind": "PodExecOptions",
      "stdin": true,
      "stdout": true,
      "tty": true
    },
    "dryRun": false
  }
}

Environment

Kubewarden 1.17, running the latest stable release of the CEL policy

Anything else?

No response