handlers.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 handlers
  14. import (
  15. "net/http"
  16. "strings"
  17. "github.com/golang/glog"
  18. "github.com/prometheus/client_golang/prometheus"
  19. "k8s.io/kubernetes/pkg/api"
  20. "k8s.io/kubernetes/pkg/auth/authenticator"
  21. )
  22. var (
  23. authenticatedUserCounter = prometheus.NewCounterVec(
  24. prometheus.CounterOpts{
  25. Name: "authenticated_user_requests",
  26. Help: "Counter of authenticated requests broken out by username.",
  27. },
  28. []string{"username"},
  29. )
  30. )
  31. func init() {
  32. prometheus.MustRegister(authenticatedUserCounter)
  33. }
  34. // NewRequestAuthenticator creates an http handler that tries to authenticate the given request as a user, and then
  35. // stores any such user found onto the provided context for the request. If authentication fails or returns an error
  36. // the failed handler is used. On success, handler is invoked to serve the request.
  37. func NewRequestAuthenticator(mapper api.RequestContextMapper, auth authenticator.Request, failed http.Handler, handler http.Handler) (http.Handler, error) {
  38. return api.NewRequestContextFilter(
  39. mapper,
  40. http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  41. user, ok, err := auth.AuthenticateRequest(req)
  42. if err != nil || !ok {
  43. if err != nil {
  44. glog.Errorf("Unable to authenticate the request due to an error: %v", err)
  45. }
  46. failed.ServeHTTP(w, req)
  47. return
  48. }
  49. if ctx, ok := mapper.Get(req); ok {
  50. mapper.Update(req, api.WithUser(ctx, user))
  51. }
  52. authenticatedUserCounter.WithLabelValues(compressUsername(user.GetName())).Inc()
  53. handler.ServeHTTP(w, req)
  54. }),
  55. )
  56. }
  57. func Unauthorized(supportsBasicAuth bool) http.HandlerFunc {
  58. if supportsBasicAuth {
  59. return unauthorizedBasicAuth
  60. }
  61. return unauthorized
  62. }
  63. // unauthorizedBasicAuth serves an unauthorized message to clients.
  64. func unauthorizedBasicAuth(w http.ResponseWriter, req *http.Request) {
  65. w.Header().Set("WWW-Authenticate", `Basic realm="kubernetes-master"`)
  66. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  67. }
  68. // unauthorized serves an unauthorized message to clients.
  69. func unauthorized(w http.ResponseWriter, req *http.Request) {
  70. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  71. }
  72. // compressUsername maps all possible usernames onto a small set of categories
  73. // of usernames. This is done both to limit the cardinality of the
  74. // authorized_user_requests metric, and to avoid pushing actual usernames in the
  75. // metric.
  76. func compressUsername(username string) string {
  77. switch {
  78. // Known internal identities.
  79. case username == "admin" ||
  80. username == "client" ||
  81. username == "kube_proxy" ||
  82. username == "kubelet" ||
  83. username == "system:serviceaccount:kube-system:default":
  84. return username
  85. // Probably an email address.
  86. case strings.Contains(username, "@"):
  87. return "email_id"
  88. // Anything else (custom service accounts, custom external identities, etc.)
  89. default:
  90. return "other"
  91. }
  92. }