k8s.io/apiserver@v0.31.1/pkg/authentication/request/anonymous/anonymous.go (about)

     1  /*
     2  Copyright 2016 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 anonymous
    18  
    19  import (
    20  	"net/http"
    21  
    22  	"k8s.io/apiserver/pkg/apis/apiserver"
    23  	"k8s.io/apiserver/pkg/authentication/authenticator"
    24  	"k8s.io/apiserver/pkg/authentication/user"
    25  )
    26  
    27  const (
    28  	anonymousUser        = user.Anonymous
    29  	unauthenticatedGroup = user.AllUnauthenticated
    30  )
    31  
    32  type Authenticator struct {
    33  	allowedPaths map[string]bool
    34  }
    35  
    36  func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
    37  	if len(a.allowedPaths) > 0 && !a.allowedPaths[req.URL.Path] {
    38  		return nil, false, nil
    39  	}
    40  
    41  	auds, _ := authenticator.AudiencesFrom(req.Context())
    42  	return &authenticator.Response{
    43  		User: &user.DefaultInfo{
    44  			Name:   anonymousUser,
    45  			Groups: []string{unauthenticatedGroup},
    46  		},
    47  		Audiences: auds,
    48  	}, true, nil
    49  }
    50  
    51  // NewAuthenticator returns a new anonymous authenticator.
    52  // When conditions is empty all requests are authenticated as anonymous.
    53  // When conditions are non-empty only those requests that match the at-least one
    54  // condition are authenticated as anonymous.
    55  func NewAuthenticator(conditions []apiserver.AnonymousAuthCondition) authenticator.Request {
    56  	allowedPaths := make(map[string]bool)
    57  	for _, c := range conditions {
    58  		allowedPaths[c.Path] = true
    59  	}
    60  
    61  	return &Authenticator{allowedPaths: allowedPaths}
    62  }