Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/cmd/headlamp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1986,7 +1986,7 @@ func TestCacheMiddleware_AuthErrorResponse(t *testing.T) {
ctx := context.Background()

expectedResponse := `{"kind":"Status","apiVersion":"v1","metadata":{"resourceVersion":""},` +
`"message":"resource is forbidden: User \"system:serviceaccount:default:test\" cannot get resource ` +
`"message":"resource is forbidden: User \"system:serviceaccount:default:test\" cannot list resource ` +
`\"resource\" in API group \"\" at the cluster scope","reason":"Forbidden","details":{"kind":"resource"},` +
`"code":403}`

Expand Down
139 changes: 118 additions & 21 deletions backend/pkg/k8cache/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ import (
// it becomes eligible for eviction.
const clientsetTTL = 10 * time.Minute

const unknownVerb = "unknown"

// janitorInterval is how often the background goroutine sweeps the
// cache for expired entries.
const janitorInterval = 5 * time.Minute
Expand Down Expand Up @@ -263,33 +265,131 @@ func GetClientSet(k *kubeconfig.Context, token string) (*kubernetes.Clientset, e
return cs, err
}

// GetKindAndVerb extracts the Kubernetes resource kind and intended verb (e.g., get, watch)
// from the incoming HTTP request.
func GetKindAndVerb(r *http.Request) (string, string) {
apiPath, ok := mux.Vars(r)["api"]
if !ok || apiPath == "" {
return "", "unknown"
type apiResourceRequest struct {
group string
version string
namespace string
resource string
name string
subresource string
}

func isNamespaceSubresource(subresource string) bool {
return subresource == "status" || subresource == "finalize"
}

func parseAPIResourceRequest(apiPath string) (apiResourceRequest, bool) {
parts := strings.Split(strings.Trim(apiPath, "/"), "/")
if len(parts) < 3 {
return apiResourceRequest{}, false
}

parts := strings.Split(apiPath, "/")
last := parts[len(parts)-1]
request := apiResourceRequest{}
resourceIndex := 0

var kubeVerb string
switch parts[0] {
case apiPathSegment:
request.version = parts[1]
resourceIndex = 2
case apisPathSegment:
if len(parts) < 4 {
return apiResourceRequest{}, false
}

request.group = parts[1]
request.version = parts[2]
resourceIndex = 3
default:
return apiResourceRequest{}, false
}
Comment thread
harrshita123 marked this conversation as resolved.

if parts[resourceIndex] == namespacePathSegment &&
len(parts) == resourceIndex+3 &&
isNamespaceSubresource(parts[resourceIndex+2]) {
request.resource = namespacePathSegment
request.name = parts[resourceIndex+1]
request.subresource = parts[resourceIndex+2]

return request, true
}

if parts[resourceIndex] == namespacePathSegment && len(parts) > resourceIndex+2 {
request.namespace = parts[resourceIndex+1]
resourceIndex += 2
Comment thread
harrshita123 marked this conversation as resolved.
}

request.resource = parts[resourceIndex]
if len(parts) > resourceIndex+1 {
request.name = parts[resourceIndex+1]
}

if len(parts) > resourceIndex+2 {
request.subresource = parts[resourceIndex+2]
}

return request, true
}

func getKubeVerb(r *http.Request, request apiResourceRequest) string {
isWatch, _ := strconv.ParseBool(r.URL.Query().Get("watch"))

switch r.Method {
case "GET":
if isWatch {
kubeVerb = "watch"
} else {
kubeVerb = "get"
return "watch"
}

if request.name == "" {
return "list"
}

return "get"
default:
kubeVerb = "unknown"
return unknownVerb
}
}

// GetKindAndVerb extracts the Kubernetes resource kind and intended verb (e.g., get, watch)
// from the incoming HTTP request.
func GetKindAndVerb(r *http.Request) (string, string) {
apiPath, ok := mux.Vars(r)["api"]
if !ok || apiPath == "" {
return "", unknownVerb
}

request, ok := parseAPIResourceRequest(apiPath)
if !ok {
return "", unknownVerb
}

return last, kubeVerb
return request.resource, getKubeVerb(r, request)
}

func getResourceAttributes(r *http.Request) (*authorizationv1.ResourceAttributes, error) {
apiPath, ok := mux.Vars(r)["api"]
if !ok || apiPath == "" {
return nil, fmt.Errorf("could not determine resource or verb from request")
}

request, ok := parseAPIResourceRequest(apiPath)
if !ok {
return nil, fmt.Errorf("could not determine resource or verb from request")
}

kubeVerb := getKubeVerb(r, request)
if request.resource == "" || kubeVerb == "" {
return nil, fmt.Errorf("could not determine resource or verb from request")
}

return &authorizationv1.ResourceAttributes{
Group: request.group,
Version: request.version,
Resource: request.resource,
Subresource: request.subresource,
Namespace: request.namespace,
Name: request.name,
Verb: kubeVerb,
}, nil
}

// IsAllowed checks the user's permission to access the resource.
Expand All @@ -307,17 +407,14 @@ func IsAllowed(
return false, err
}

last, kubeVerb := GetKindAndVerb(r)
if last == "" || kubeVerb == "" {
return false, fmt.Errorf("could not determine resource or verb from request")
resourceAttributes, err := getResourceAttributes(r)
if err != nil {
return false, err
}

review := &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Resource: last,
Verb: kubeVerb,
},
ResourceAttributes: resourceAttributes,
},
}

Expand Down
145 changes: 145 additions & 0 deletions backend/pkg/k8cache/authorization_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// Copyright 2025 The Kubernetes Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package k8cache

import (
"context"
"net/http"
"net/http/httptest"
"testing"

"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)

type resourceAttributesTestCase struct {
name string
urlPath string
apiPath string
expectedGroup string
expectedVersion string
expectedNamespace string
expectedResource string
expectedName string
expectedSubresource string
expectedVerb string
}

func TestGetResourceAttributesForNamedResource(t *testing.T) {
tests := []resourceAttributesTestCase{
{
name: "named namespaced core resource",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default/pods/nginx",
apiPath: "api/v1/namespaces/default/pods/nginx",
expectedVersion: "v1",
expectedNamespace: "default",
expectedResource: "pods",
expectedName: "nginx",
expectedVerb: "get",
},
{
name: "named resource with subresource",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default/pods/nginx/log",
apiPath: "api/v1/namespaces/default/pods/nginx/log",
expectedVersion: "v1",
expectedNamespace: "default",
expectedResource: "pods",
expectedName: "nginx",
expectedSubresource: "log",
expectedVerb: "get",
},
{
name: "named namespaced API group resource",
urlPath: "/clusters/named-resource-test/apis/apps/v1/namespaces/default/deployments/frontend",
apiPath: "apis/apps/v1/namespaces/default/deployments/frontend",
expectedGroup: "apps",
expectedVersion: "v1",
expectedNamespace: "default",
expectedResource: "deployments",
expectedName: "frontend",
expectedVerb: "get",
},
{
name: "namespaced collection",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default/pods",
apiPath: "api/v1/namespaces/default/pods",
expectedVersion: "v1",
expectedNamespace: "default",
expectedResource: "pods",
expectedVerb: "list",
},
Comment thread
harrshita123 marked this conversation as resolved.
}

runResourceAttributesTests(t, tests)
}

func TestGetResourceAttributesForNamespaceResource(t *testing.T) {
tests := []resourceAttributesTestCase{
{
name: "named namespace",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default",
apiPath: "api/v1/namespaces/default",
expectedVersion: "v1",
expectedResource: "namespaces",
expectedName: "default",
expectedVerb: "get",
},
{
name: "namespace status subresource",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default/status",
apiPath: "api/v1/namespaces/default/status",
expectedVersion: "v1",
expectedResource: "namespaces",
expectedName: "default",
expectedSubresource: "status",
expectedVerb: "get",
},
{
name: "namespace finalize subresource",
urlPath: "/clusters/named-resource-test/api/v1/namespaces/default/finalize",
apiPath: "api/v1/namespaces/default/finalize",
expectedVersion: "v1",
expectedResource: "namespaces",
expectedName: "default",
expectedSubresource: "finalize",
expectedVerb: "get",
},
}

runResourceAttributesTests(t, tests)
}

func runResourceAttributesTests(t *testing.T, tests []resourceAttributesTestCase) {
t.Helper()

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, tc.urlPath, nil)
req = mux.SetURLVars(req, map[string]string{
"api": tc.apiPath,
})

attributes, err := getResourceAttributes(req)
assert.NoError(t, err)

assert.Equal(t, tc.expectedGroup, attributes.Group)
assert.Equal(t, tc.expectedVersion, attributes.Version)
assert.Equal(t, tc.expectedNamespace, attributes.Namespace)
assert.Equal(t, tc.expectedResource, attributes.Resource)
assert.Equal(t, tc.expectedName, attributes.Name)
assert.Equal(t, tc.expectedSubresource, attributes.Subresource)
assert.Equal(t, tc.expectedVerb, attributes.Verb)
})
}
}
Loading
Loading