<p>I have a HTTP server running in a pod in K8s environment. The server exposes 4 endpoints. Now what I want is to restict one of those 4 APIs if the user is using port-forwarding to access the endpoints on  localhost. Essentially, I dont anyone('kubeclt' user) to access a certain endpoint via port-forwarding.</p>
<p>I was thinking of implementing a middleware in code which would intercept and reject calls to that ndpoint based on the URL but that also blocks all the calls when someone directly <code>kubectl exec</code> into  the pods and directly use curl which I don't want. (<em>Can we figure out if the user has port-forwarded from inside the pod?</em>)</p>
<p>I was wondering if there is a way this could be done?
Any suggestions would be appriciated. Thanks!</p>

ray an
<p>Port forwarding control can be achieved by using on Kubernetes built-in RBAC(Role Based Access Control). You can give or revoke access for users to be able to use port-forwarding at first place.</p>
<p>Here is an example below, which grants such access and can be removed:</p>
<pre class="lang-yaml prettyprint-override"><code>---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: my-namespace
  name: port-forward-access
rules:
- apiGroups: [&quot;&quot;]
  resources: [&quot;pods/portforward&quot;]
  verbs: [&quot;create&quot;]
</code></pre>
<p>see: <a href="https://github.com/kubernetes/kubernetes/issues/110999" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/issues/110999</a></p>
<hr />
<blockquote>
<p>restrict one of those 4 APIs</p>
</blockquote>
<p>However, as you are asking to <em>restrict one of those 4 APIs</em>, I must say that this is the application which is exposing those endpoints, which should be configured on the application side to allow only partial traffic, say localhost only. I will recommend not to complicate things by trying to achieve that using Kubernetes.</p>
<p>One key thing to keep in mind that a pod is considered the smallest unit in the object model of Kubernetes. So complete what is operating inside and only expose what can be exposed.</p>
<p>Also, consider looking into service mesh or a sidecar container as the gateway to the actual application, if it cannot be achieved from within your said HTTP server.</p>
