1 Commits

Author SHA1 Message Date
Ethan Pini
af0e2a11af kubectl: Fix current-context being written to wrong file
This is what happens when writing back a OIDC refresh token:

 - plugin/pkg/client/auth/oidc/oidc.go:282
   Calls `Persist` to save the new refresh token.

 - tools/clientcmd/config.go:372
   Calls `ModifyConfig` to save the config.

 - tools/clientcmd/config.go:167
   Calls `configAccess.GetLoadingPrecedence()` to get the files
   listed from the `KUBECONFIG` environment variable.

 - tools/clientcmd/loader.go:334
   If the `ConfigAccess` was a `ClientConfigLoadingRules`, it
   directly returns the `Precedence` slice from its `rules`
   field.

   THE PROBLEM:
     The slice can be modified by the caller, unintentionally
     changing the value of the `ClientConfigLoadingRules`'
     `Precedence` field.

 - tools/clientcmd/config.go:170
   Then proceeds to in-place sort the slice returned by the
   `ConfigAccess`. This is the same slice (by identity)
   as the `ClientConfigLoadingRules`' `Precedence` field,
   destroying its intended order.

 - tools/clientcmd/config.go:179
   Calls `configAccess.GetStartingConfig` to read the original
   config so it can be compared with the new config.

 - tools/clientcmd/loader.go:339
   Calls `NewNonInteractiveDeferredLoadingClientConfig` with
   itself as a parameter.

   CONSEQUENCE:
     At this point, its the `Precedence` has been
     unintentionally sorted. When it loads the
     config again, it gives precedence to whichever
     file comes first in ascending alphabetical order.

 - tools/clientcmd/config.go:192
   If the file returned by `GetStartingConfig` has a
   different `current-context` than the new config,
   it calls `writeCurrentContext` to update the first
   kubeconfig file in the `KUBECONFIG` environment
   variable.

 - tools/clientcmd/config.go:403
   Calls `configAccess.GetDefaultFilename` to find the
   destination kubeconfig file.

 - tools/clientcmd/loader.go:358
   Iterates through the kubeconfig files returned by
   `GetLoadingPreferences` to find the first file
   that exists.

   CONSEQUENCE:
     With the slice being sorted earlier, the files
     returned by this call of `GetLoadingPreferences`
     will be sorted alphabetically, rather than by
     their intended order.

Kubernetes-commit: ffa084f81129ea685b176a282921c4d54906c539
2025-04-14 15:19:04 -07:00