util.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package serviceaccount
  14. import (
  15. "k8s.io/api/core/v1"
  16. apiserverserviceaccount "k8s.io/apiserver/pkg/authentication/serviceaccount"
  17. "k8s.io/apiserver/pkg/authentication/user"
  18. )
  19. const (
  20. // PodNameKey is the key used in a user's "extra" to specify the pod name of
  21. // the authenticating request.
  22. PodNameKey = "authentication.kubernetes.io/pod-name"
  23. // PodUIDKey is the key used in a user's "extra" to specify the pod UID of
  24. // the authenticating request.
  25. PodUIDKey = "authentication.kubernetes.io/pod-uid"
  26. )
  27. // UserInfo returns a user.Info interface for the given namespace, service account name and UID
  28. func UserInfo(namespace, name, uid string) user.Info {
  29. return (&ServiceAccountInfo{
  30. Name: name,
  31. Namespace: namespace,
  32. UID: uid,
  33. }).UserInfo()
  34. }
  35. type ServiceAccountInfo struct {
  36. Name, Namespace, UID string
  37. PodName, PodUID string
  38. }
  39. func (sa *ServiceAccountInfo) UserInfo() user.Info {
  40. info := &user.DefaultInfo{
  41. Name: apiserverserviceaccount.MakeUsername(sa.Namespace, sa.Name),
  42. UID: sa.UID,
  43. Groups: apiserverserviceaccount.MakeGroupNames(sa.Namespace),
  44. }
  45. if sa.PodName != "" && sa.PodUID != "" {
  46. info.Extra = map[string][]string{
  47. PodNameKey: {sa.PodName},
  48. PodUIDKey: {sa.PodUID},
  49. }
  50. }
  51. return info
  52. }
  53. // IsServiceAccountToken returns true if the secret is a valid api token for the service account
  54. func IsServiceAccountToken(secret *v1.Secret, sa *v1.ServiceAccount) bool {
  55. if secret.Type != v1.SecretTypeServiceAccountToken {
  56. return false
  57. }
  58. name := secret.Annotations[v1.ServiceAccountNameKey]
  59. uid := secret.Annotations[v1.ServiceAccountUIDKey]
  60. if name != sa.Name {
  61. // Name must match
  62. return false
  63. }
  64. if len(uid) > 0 && uid != string(sa.UID) {
  65. // If UID is specified, it must match
  66. return false
  67. }
  68. return true
  69. }