Merge pull request #2016 from erictune/whoami

Added /whoami and integration test for authorization.
pull/6/head
Clayton Coleman 2014-10-28 13:21:24 -04:00
commit 88cd3988f7
3 changed files with 177 additions and 7 deletions

48
pkg/master/handlers.go Normal file
View File

@ -0,0 +1,48 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package master
import (
"net/http"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/authenticator"
)
// handleWhoAmI returns the user-string which this request is authenticated as (if any).
// Useful for debugging authentication. Always returns HTTP status okay and a human
// readable (not intended as API) description of authentication state of request.
func handleWhoAmI(auth authenticator.Request) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
if auth == nil {
w.Write([]byte("NO AUTHENTICATION SUPPORT"))
return
}
userInfo, ok, err := auth.AuthenticateRequest(req)
if err != nil {
w.Write([]byte("ERROR WHILE AUTHENTICATING"))
return
}
if !ok {
w.Write([]byte("NOT AUTHENTICATED"))
return
}
w.Write([]byte("AUTHENTICATED AS " + userInfo.GetName()))
return
}
}

View File

@ -27,6 +27,7 @@ import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta1"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta2"
"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/authenticator"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/authenticator/bearertoken"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/authenticator/tokenfile"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/handlers"
@ -160,6 +161,16 @@ func (m *Master) init(c *Config) {
}
}
var userContexts = handlers.NewUserRequestContext()
var authenticator authenticator.Request
if len(c.TokenAuthFile) != 0 {
tokenAuthenticator, err := tokenfile.New(c.TokenAuthFile)
if err != nil {
glog.Fatalf("Unable to load the token authentication file '%s': %v", c.TokenAuthFile, err)
}
authenticator = bearertoken.New(tokenAuthenticator)
}
m.storage = map[string]apiserver.RESTStorage{
"pods": pod.NewREST(&pod.RESTConfig{
CloudProvider: c.Cloud,
@ -197,14 +208,11 @@ func (m *Master) init(c *Config) {
handler = apiserver.CORS(handler, allowedOriginRegexps, nil, nil, "true")
}
if len(c.TokenAuthFile) != 0 {
auth, err := tokenfile.New(c.TokenAuthFile)
if err != nil {
glog.Fatalf("Unable to load the token authentication file '%s': %v", c.TokenAuthFile, err)
}
userContexts := handlers.NewUserRequestContext()
handler = handlers.NewRequestAuthenticator(userContexts, bearertoken.New(auth), handlers.Unauthorized, handler)
if authenticator != nil {
handler = handlers.NewRequestAuthenticator(userContexts, authenticator, handlers.Unauthorized, handler)
}
m.mux.HandleFunc("/_whoami", handleWhoAmI(authenticator))
m.Handler = handler
}

View File

@ -0,0 +1,114 @@
// +build integration,!no-etcd
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package integration
// This file tests authentication and (soon) authorization of HTTP requests to a master object.
// It does not use the client in pkg/client/... because authentication and authorization needs
// to work for any client of the HTTP interface.
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/GoogleCloudPlatform/kubernetes/pkg/master"
)
func init() {
requireEtcd()
}
// TestWhoAmI passes a known Bearer Token to the master's /_whoami endpoint and checks that
// the master authenticates the user.
func TestWhoAmI(t *testing.T) {
deleteAllEtcdKeys()
// Write a token file.
json := `
abc123,alice,1
xyz987,bob,2
`
f, err := ioutil.TempFile("", "auth_integration_test")
f.Close()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(json), 0700); err != nil {
t.Fatalf("unexpected error writing tokenfile: %v", err)
}
// Set up a master
helper, err := master.NewEtcdHelper(newEtcdClient(), "v1beta1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
mux := http.NewServeMux()
master.New(&master.Config{
EtcdHelper: helper,
Mux: mux,
EnableLogsSupport: false,
EnableUISupport: false,
APIPrefix: "/api",
TokenAuthFile: f.Name(),
})
s := httptest.NewServer(mux)
defer s.Close()
// TODO: also test TLS, using e.g NewUnsafeTLSTransport() and NewClientCertTLSTransport() (see pkg/client/helper.go)
transport := http.DefaultTransport
testCases := []struct {
name string
token string
expected string
}{
{"Valid token", "abc123", "AUTHENTICATED AS alice"},
{"Unknown token", "456jkl", "NOT AUTHENTICATED"},
{"Empty token", "", "NOT AUTHENTICATED"},
}
for _, tc := range testCases {
req, err := http.NewRequest("GET", s.URL+"/_whoami", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tc.token))
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
actual := string(body)
if tc.expected != actual {
t.Errorf("case: %s expected: %v got: %v", tc.name, tc.expected, actual)
}
}
}