Watching for port forward events

Hi all,

Is it possible to listen to port-forward events in a cluster?

I tried to setup a simple watch that should print out any port-forward that gets created via kubectl, but this watch isn’t showing the port-forward I create.

Here’s how I set up the code :

Initialization/creation of client

await config.load_kube_config(config_file="~/.kube/config-auto")
configuration = client.Configuration().get_default_copy()
configuration.verify_ssl = False
my_client = client.ApiClient(configuration)
v1 = client.CoreV1Api(my_client)

The actual watch

while True:
        w = watch.Watch()
        stream = w.stream(
            v1.connect_get_namespaced_pod_portforward,
        )
        for event in stream:
            try:
                print(event)

I tried to watch the other port forward resources listed in the core api client:

v1.connect_get_namespaced_pod_portforward_with_http_info,
v1.connect_post_namespaced_pod_portforward,
v1.connect_post_namespaced_pod_portforward_with_http_info

But that didn’t help either.

Am I doing something wrong or is it just not possible to watch for port-forward events?

My idea was if I can watch for port-forward events, then I could create a validating web hook that verifies whether a port-forward is allowed or not.

Thanks!

Hi,
AFAIK k8s watch relies on a feature of etcd that allows to watch for specific objects and any changes related to these objects.
During port-forward kubectl sends a POST request ex: https://172.20.172.2:6443/api/v1/namespaces/default/pods/service1-64f47b454b-wm85q/portforward to enable port forwarding. I am pretty sure it does not remain in etcd.
If you want to control port-forwarding, one of the options I see is to create a ValidatingWebhookConfiguration that would catch all port-forwarding requests and forward AdmissionReview requests to your application that is going to make a decision.

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: "pod-policy.example.com"
webhooks:
- name: "pod-policy.example.com"
  rules:
  - apiGroups:   [""]
    apiVersions: ["v1"]
    operations:  ["CONNECT"]
    resources:   ["pods/portforward"]
    scope:       "*"

HTH

Ahh okay!

I was assuming that because I couldn’t watch for port-forward events, a web hook wouldn’t be able to intercept these events either.

Thanks for the explanation!