Debian Codegraph @

pkg/authentication/request/bearertoken/bearertoken.go

raw
1 /*
2 Copyright 2014 The Kubernetes 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 bearertoken
18
19 import (
20 "errors"
21 "net/http"
22 "strings"
23
24 "k8s.io/apiserver/pkg/authentication/authenticator"
25 "k8s.io/apiserver/pkg/warning"
26 )
27
28 const (
29 invalidTokenWithSpaceWarning = "the provided Authorization header contains extra space before the bearer token, and is ignored"
30 )
31
32 type Authenticator struct {
33 auth authenticator.Token
34 }
35
36 func New(auth authenticator.Token) *Authenticator {
37 return &Authenticator{auth}
38 }
39
40 var invalidToken = errors.New("invalid bearer token")
41
42 func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
43 auth := strings.TrimSpace(req.Header.Get("Authorization"))
44 if auth == "" {
45 return nil, false, nil
46 }
47 parts := strings.SplitN(auth, " ", 3)
48 if len(parts) < 2 || strings.ToLower(parts[0]) != "bearer" {
49 return nil, false, nil
50 }
51
52 token := parts[1]
53
54 // Empty bearer tokens aren't valid
55 if len(token) == 0 {
56 // The space before the token case
57 if len(parts) == 3 {
58 warning.AddWarning(req.Context(), "", invalidTokenWithSpaceWarning)
59 }
60 return nil, false, nil
61 }
62
63 resp, ok, err := a.auth.AuthenticateToken(req.Context(), token)
64 // if we authenticated successfully, go ahead and remove the bearer token so that no one
65 // is ever tempted to use it inside of the API server
66 if ok {
67 req.Header.Del("Authorization")
68 }
69
70 // If the token authenticator didn't error, provide a default error
71 if !ok && err == nil {
72 err = invalidToken
73 }
74
75 return resp, ok, err
76 }