Skip to content

Commit ee791fc

Browse files
committed
Filter extra keys containing kcp.io on per-workspace authentication
Signed-off-by: Nelo-T. Wallus <[email protected]> Signed-off-by: Nelo-T. Wallus <[email protected]>
1 parent 896e5e9 commit ee791fc

File tree

8 files changed

+219
-11
lines changed

8 files changed

+219
-11
lines changed

docs/content/concepts/authentication/workspace.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ This feature has some small limitations that users should keep in mind:
4747
* Even when the feature is disabled on all shards and all front-proxies, the API (CRDs) are always available in kcp. Admins might uses RBAC or webhooks to prevent creating `WorkspaceAuthenticationConfiguration` objects if needed.
4848
* It is not possible to authenticate users with a username starting with with `system:` through per-workspace authentication.
4949
* It is not possible to assign groups starting with `system:` to users authenticated via per-workspace authentication, e.g. via claim mappings.
50+
* It is not possible to set keys containing `kcp.io` through the extra mappings in the authentication configuration.
5051

5152
## Example
5253

pkg/authentication/extra.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
Copyright 2025 The KCP Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package authentication
18+
19+
import (
20+
"net/http"
21+
"slices"
22+
"strings"
23+
24+
"k8s.io/apiserver/pkg/authentication/authenticator"
25+
"k8s.io/apiserver/pkg/authentication/user"
26+
)
27+
28+
// ExtraFilter is a filter that filters out extra fields that are not
29+
// allowed.
30+
type ExtraFilter struct {
31+
Authenticator authenticator.Request
32+
33+
// AllowExtraKeys is a list of exact keys to allow through.
34+
// It takes precedence over DropExtraKeyContains.
35+
AllowExtraKeys []string
36+
// DropExtraKeyContains is a list of strings that will cause an extra
37+
// key/value pair to be dropped if the key contains any of them.
38+
DropExtraKeyContains []string
39+
}
40+
41+
var _ authenticator.Request = &ExtraFilter{}
42+
43+
func (a *ExtraFilter) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
44+
resp, ok, err := a.Authenticator.AuthenticateRequest(req)
45+
if resp == nil || resp.User == nil {
46+
return resp, ok, err
47+
}
48+
49+
info := user.DefaultInfo{
50+
Name: resp.User.GetName(),
51+
UID: resp.User.GetUID(),
52+
Groups: resp.User.GetGroups(),
53+
Extra: map[string][]string{},
54+
}
55+
for k, v := range resp.User.GetExtra() {
56+
if slices.Contains(a.AllowExtraKeys, k) {
57+
info.Extra[k] = v
58+
continue
59+
}
60+
if containsAny(k, a.DropExtraKeyContains...) {
61+
continue
62+
}
63+
info.Extra[k] = v
64+
}
65+
resp.User = &info
66+
67+
return resp, ok, err
68+
}
69+
70+
func containsAny(s string, substrs ...string) bool {
71+
for _, substr := range substrs {
72+
if strings.Contains(s, substr) {
73+
return true
74+
}
75+
}
76+
return false
77+
}

pkg/authentication/extra_test.go

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*
2+
Copyright 2025 The KCP Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package authentication
18+
19+
import (
20+
"net/http"
21+
"testing"
22+
23+
"github.com/stretchr/testify/require"
24+
)
25+
26+
func TestExtraFilter(t *testing.T) {
27+
t.Parallel()
28+
for _, tc := range []struct {
29+
name string
30+
allowExtraKeys []string
31+
dropExtraKeyContains []string
32+
requestedExtra map[string][]string
33+
wantExtra map[string][]string
34+
}{
35+
{
36+
name: "no extra",
37+
wantExtra: map[string][]string{},
38+
},
39+
{
40+
name: "pass all",
41+
42+
requestedExtra: map[string][]string{
43+
"foo": {"bar"},
44+
"foobar": {"baz"},
45+
"barfoo": {"baz2"},
46+
},
47+
wantExtra: map[string][]string{
48+
"foo": {"bar"},
49+
"foobar": {"baz"},
50+
"barfoo": {"baz2"},
51+
},
52+
},
53+
{
54+
name: "drop contains",
55+
56+
dropExtraKeyContains: []string{"bar"},
57+
requestedExtra: map[string][]string{
58+
"foo": {"bar"},
59+
"foobar": {"baz"},
60+
"barfoo": {"baz2"},
61+
},
62+
wantExtra: map[string][]string{
63+
"foo": {"bar"},
64+
},
65+
},
66+
{
67+
name: "allow takes precedence over drop contains",
68+
69+
allowExtraKeys: []string{"barfoo"},
70+
dropExtraKeyContains: []string{"bar"},
71+
requestedExtra: map[string][]string{
72+
"foo": {"bar"},
73+
"foobar": {"baz"},
74+
"barfoo": {"baz2"},
75+
},
76+
wantExtra: map[string][]string{
77+
"foo": {"bar"},
78+
"barfoo": {"baz2"},
79+
},
80+
},
81+
} {
82+
t.Run(tc.name, func(t *testing.T) {
83+
t.Parallel()
84+
filter := &ExtraFilter{
85+
Authenticator: &requestAuthenticator{extra: tc.requestedExtra},
86+
AllowExtraKeys: tc.allowExtraKeys,
87+
DropExtraKeyContains: tc.dropExtraKeyContains,
88+
}
89+
res, gotAuthenticated, err := filter.AuthenticateRequest(&http.Request{})
90+
require.NoError(t, err)
91+
require.True(t, gotAuthenticated)
92+
require.Equal(t, tc.wantExtra, res.User.GetExtra())
93+
})
94+
}
95+
}

pkg/authentication/groups_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,21 @@ import (
2929

3030
type requestAuthenticator struct {
3131
groups []string
32+
extra map[string][]string
3233
}
3334

3435
func (a *requestAuthenticator) AuthenticateRequest(*http.Request) (*authenticator.Response, bool, error) {
3536
return &authenticator.Response{
3637
User: &user.DefaultInfo{
3738
Name: "system:unsecured",
3839
Groups: a.groups,
40+
Extra: a.extra,
3941
},
4042
}, true, nil
4143
}
4244

4345
func TestGroupFilter(t *testing.T) {
46+
t.Parallel()
4447
for _, tc := range []struct {
4548
name string
4649
passOnGroups, dropGroups sets.Set[string]
@@ -114,6 +117,7 @@ func TestGroupFilter(t *testing.T) {
114117
},
115118
} {
116119
t.Run(tc.name, func(t *testing.T) {
120+
t.Parallel()
117121
filter := &GroupFilter{
118122
Authenticator: &requestAuthenticator{groups: tc.requestedGroups},
119123
PassOnGroups: tc.passOnGroups,

pkg/authentication/index.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,10 +239,14 @@ func (c *state) Lookup(wsType logicalcluster.Path) (authenticator.Request, bool)
239239

240240
// ensure that per-workspace auth cannot be used to become a system: user/group
241241
authenticator = ForbidSystemUsernames(authenticator)
242-
filtered := &GroupFilter{
242+
groupFiltered := &GroupFilter{
243243
Authenticator: authenticator,
244244
DropGroupPrefixes: []string{"system:"},
245245
}
246+
extraFiltered := &ExtraFilter{
247+
Authenticator: groupFiltered,
248+
DropExtraKeyContains: []string{"kcp.io"},
249+
}
246250

247-
return filtered, true
251+
return extraFiltered, true
248252
}

pkg/authentication/index_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ import (
3434
)
3535

3636
func TestCrossShardWorkspaceType(t *testing.T) {
37+
t.Parallel()
38+
3739
const (
3840
shardName = "shard-1"
3941
teamCluster = "logicalteamcluster"

test/e2e/authentication/workspace_test.go

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ func TestWorkspaceOIDC(t *testing.T) {
6565

6666
// setup a new workspace auth config that uses mockoidc's server, one for
6767
// each of our mockoidc servers
68-
authConfigA := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mockA, ca)
69-
authConfigB := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mockB, ca)
68+
authConfigA := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mockA, ca, nil)
69+
authConfigB := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mockB, ca, nil)
7070

7171
// use these configs in new WorkspaceTypes and create one extra workspace type that allows
7272
// both mockoidc issuers
@@ -268,7 +268,22 @@ func TestUserScope(t *testing.T) {
268268
require.NoError(t, err)
269269

270270
mock, ca := authfixtures.StartMockOIDC(t, server)
271-
authConfig := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mock, ca)
271+
authConfig := authfixtures.CreateWorkspaceOIDCAuthentication(t, ctx, kcpClusterClient, baseWsPath, mock, ca,
272+
[]tenancyv1alpha1.ExtraMapping{
273+
{
274+
Key: "authentication.kcp.io/scopes",
275+
ValueExpression: "['cluster:my-test-cluster']",
276+
},
277+
{
278+
Key: "kcp.io/test",
279+
ValueExpression: "'test-value'",
280+
},
281+
{
282+
Key: "other.example.com/test",
283+
ValueExpression: "'pass-value'",
284+
},
285+
},
286+
)
272287
wsType := authfixtures.CreateWorkspaceType(t, ctx, kcpClusterClient, baseWsPath, "with-oidc", authConfig)
273288

274289
// create a new workspace with our new type
@@ -280,6 +295,14 @@ func TestUserScope(t *testing.T) {
280295
userEmail = "[email protected]"
281296
userGroups = []string{"developers", "admins"}
282297
expectedGroups = []string{"system:authenticated"}
298+
expectedExtras = map[string]authenticationv1.ExtraValue{
299+
// authentication.kcp.io/scopes from the extra mapping has
300+
// been scrubbed and only the expected cluster:<id> is set
301+
"authentication.kcp.io/scopes": {"cluster:" + teamWs.Spec.Cluster},
302+
"authentication.kcp.io/cluster-name": {teamWs.Spec.Cluster},
303+
// kcp.io/test from the extra mapping should be scrubbed
304+
"other.example.com/test": {"pass-value"},
305+
}
283306
)
284307

285308
for _, group := range userGroups {
@@ -314,8 +337,7 @@ func TestUserScope(t *testing.T) {
314337
user := review.Status.UserInfo
315338
require.Equal(t, "oidc:"+userEmail, user.Username)
316339
require.Subset(t, user.Groups, expectedGroups)
317-
require.Equal(t, user.Extra["authentication.kcp.io/scopes"], authenticationv1.ExtraValue{"cluster:" + teamWs.Spec.Cluster})
318-
require.Equal(t, user.Extra["authentication.kcp.io/cluster-name"], authenticationv1.ExtraValue{teamWs.Spec.Cluster})
340+
require.Subset(t, user.Extra, expectedExtras)
319341
}
320342

321343
func TestForbiddenSystemAccess(t *testing.T) {

test/e2e/fixtures/authfixtures/mockoidc.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,18 +167,21 @@ func CreateOIDCToken(t *testing.T, mock *mockoidc.MockOIDC, subject, email strin
167167
return token
168168
}
169169

170-
func CreateWorkspaceOIDCAuthentication(t *testing.T, ctx context.Context, client kcpclientset.ClusterInterface, workspace logicalcluster.Path, mock *mockoidc.MockOIDC, ca *crypto.CA) string {
170+
func CreateWorkspaceOIDCAuthentication(t *testing.T, ctx context.Context, client kcpclientset.ClusterInterface, workspace logicalcluster.Path, mock *mockoidc.MockOIDC, ca *crypto.CA, extraMapping []tenancyv1alpha1.ExtraMapping) string {
171171
name := fmt.Sprintf("mockoidc-%d", rand.Int())
172172

173+
jwtAuth := MockJWTAuthenticator(t, mock, ca, "oidc:", "oidc:")
174+
if len(extraMapping) > 0 {
175+
jwtAuth.ClaimMappings.Extra = extraMapping
176+
}
177+
173178
// setup a new workspace auth config that uses mockoidc's server
174179
authConfig := &tenancyv1alpha1.WorkspaceAuthenticationConfiguration{
175180
ObjectMeta: metav1.ObjectMeta{
176181
Name: name,
177182
},
178183
Spec: tenancyv1alpha1.WorkspaceAuthenticationConfigurationSpec{
179-
JWT: []tenancyv1alpha1.JWTAuthenticator{
180-
MockJWTAuthenticator(t, mock, ca, "oidc:", "oidc:"),
181-
},
184+
JWT: []tenancyv1alpha1.JWTAuthenticator{jwtAuth},
182185
},
183186
}
184187

0 commit comments

Comments
 (0)