Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically retrieve the cluster audiences #49796

Merged
merged 6 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
48 changes: 35 additions & 13 deletions lib/kube/token/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ const (
// Kubernetes should support bound tokens on 1.20 and 1.21,
// but we can have an apiserver running 1.21 and kubelets running 1.19.
kubernetesBoundTokenSupportVersion = "1.22.0"
// kubernetesAudience is the Kubernetes default audience put on SA tokens if we don't specify one.
kubernetesAudience = "https://kubernetes.default.svc"
)

type ValidationResult struct {
Expand Down Expand Up @@ -85,35 +83,59 @@ func (c *ValidationResult) JoinAuditAttributes() (map[string]interface{}, error)
// Kubernetes TokenRequest API endpoint.
type TokenReviewValidator struct {
mu sync.Mutex
// client is protected by mu and should only be accessed via the getClient
// method.
client kubernetes.Interface
// client and clusterAudiences are protected by mu and should only be
// accessed via the getClient method.
client kubernetes.Interface
clusterAudiences []string
}

// getClient allows the lazy initialisation of the Kubernetes client
hugoShaka marked this conversation as resolved.
Show resolved Hide resolved
func (v *TokenReviewValidator) getClient() (kubernetes.Interface, error) {
func (v *TokenReviewValidator) getClient(ctx context.Context) (kubernetes.Interface, []string, error) {
v.mu.Lock()
defer v.mu.Unlock()
if v.client != nil {
return v.client, nil
if v.client != nil && v.clusterAudiences != nil {
hugoShaka marked this conversation as resolved.
Show resolved Hide resolved
return v.client, v.clusterAudiences, nil
}

config, err := rest.InClusterConfig()
if err != nil {
return nil, trace.WrapWithMessage(err, "failed to initialize in-cluster Kubernetes config")
return nil, nil, trace.WrapWithMessage(err, "failed to initialize in-cluster Kubernetes config")
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, trace.WrapWithMessage(err, "failed to initialize in-cluster Kubernetes client")
return nil, nil, trace.WrapWithMessage(err, "failed to initialize in-cluster Kubernetes client")
}

// We do a self-review to recover the default cluster audience
hugoShaka marked this conversation as resolved.
Show resolved Hide resolved
audiences, err := getTokenAudiences(ctx, client, config.BearerToken)
if err != nil {
return nil, nil, trace.Wrap(err, "doing a self-review")
}

v.client = client
return client, nil
v.clusterAudiences = audiences
return client, audiences, nil
}

func getTokenAudiences(ctx context.Context, client kubernetes.Interface, token string) ([]string, error) {
review := &v1.TokenReview{
Spec: v1.TokenReviewSpec{
Token: token,
},
}
options := metav1.CreateOptions{}

reviewResult, err := client.AuthenticationV1().TokenReviews().Create(ctx, review, options)
if err != nil {
return nil, trace.Wrap(err, "reviewing token and retrieving audience")
}

return reviewResult.Status.Audiences, nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The API docs for status.audiences mention

a TokenReview returns an empty status.audience field where status.authenticated is "true", the token is valid against the audience of the Kubernetes API server.

Can we be reasonably sure that all supported kube api servers will actually populate the field?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If Kubernetes doesn't guarantee that the audiences field is always defined, we should prioritize parsing the JWT token directly, as this ensures we know the field is set. My concern is that, since the documentation doesn't mandate it, there might have been a version in the past that didn't include the audiences field, or a future version might omit it. To safeguard against this, we should handle the token by unmarshaling it ourselves.

You can use jwt/v4 package for that

import "github.com/golang-jwt/jwt/v4"
...
p := jwt.NewParser()
	claims := &jwt.RegisteredClaims{}
	_, _, err := p.ParseUnverified(token, claims)
	if err != nil {
		panic(err.Error())
	}

	fmt.Println(claims.Audiences)
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(there is a (go-jose/v3/*jwt.JSONWebToken).UnsafeClaimsWithoutVerification method fyi)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed to parsing our own token without validating. The missing audience thing is for legacy Kubernetes tokens (which are in theory still supported, but we do reject them for kube >= 1.21).

So basically:

  • if there's an audience on our token we know this is a modern kube and can set the audience
  • if there are no audience on our token, this is an old kube and we do the review without specifying audience, as we were doing before

}

// Validate uses the Kubernetes TokenReview API to validate a token and return its UserInfo
func (v *TokenReviewValidator) Validate(ctx context.Context, token, clusterName string) (*ValidationResult, error) {
client, err := v.getClient()
client, audiences, err := v.getClient(ctx)
if err != nil {
return nil, trace.Wrap(err)
}
Expand All @@ -125,7 +147,7 @@ func (v *TokenReviewValidator) Validate(ctx context.Context, token, clusterName
// But people kept confusing it with JWKS and set the cluster name
// as the audience/. To avoid his common footgun we now allow tokens
// whose audience is the teleport cluster name.
Audiences: []string{kubernetesAudience, clusterName},
Audiences: append(audiences, clusterName),
hugoShaka marked this conversation as resolved.
Show resolved Hide resolved
},
}
options := metav1.CreateOptions{}
Expand Down
10 changes: 7 additions & 3 deletions lib/kube/token/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ import (
"github.com/gravitational/teleport/lib/cryptosuites"
)

const testClusterName = "teleport.example.com"
const (
testClusterName = "teleport.example.com"
testAudience = "test-audience"
)

var userGroups = []string{"system:serviceaccounts", "system:serviceaccounts:namespace", "system:authenticated"}

Expand All @@ -67,7 +70,7 @@ func tokenReviewMock(t *testing.T, reviewResult *v1.TokenReview) func(ctest.Acti
require.True(t, ok)

require.Equal(t, reviewResult.Spec.Token, reviewRequest.Spec.Token)
require.ElementsMatch(t, reviewRequest.Spec.Audiences, []string{kubernetesAudience, testClusterName})
require.ElementsMatch(t, reviewRequest.Spec.Audiences, []string{testAudience, testClusterName})
return true, reviewResult, nil
}
}
Expand Down Expand Up @@ -239,7 +242,8 @@ func TestIDTokenValidator_Validate(t *testing.T) {
client := newFakeClientset(tt.kubeVersion)
client.AddReactor("create", "tokenreviews", tokenReviewMock(t, tt.review))
v := TokenReviewValidator{
client: client,
client: client,
clusterAudiences: []string{testAudience},
}
result, err := v.Validate(context.Background(), tt.token, testClusterName)
if tt.expectedError != nil {
Expand Down
Loading