-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
81 lines (75 loc) · 2.25 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"encoding/json"
authentication "k8s.io/api/authentication/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"log"
"net/http"
"os"
)
func authenticationResponse(w http.ResponseWriter, trs *authentication.TokenReviewStatus) {
tr := authentication.TokenReview{
TypeMeta: metav1.TypeMeta{
APIVersion: "authentication.k8s.io/v1beta1",
Kind: "TokenReview"},
Status: *trs,
}
json.NewEncoder(w).Encode(tr)
}
func authenticate(w http.ResponseWriter, r *http.Request, config *Settings) {
decoder := json.NewDecoder(r.Body)
var tr authentication.TokenReview
err := decoder.Decode(&tr)
if err != nil {
log.Println("[Error]", err.Error())
w.WriteHeader(http.StatusBadRequest)
authenticationResponse(w, &authentication.TokenReviewStatus{Authenticated: false, Error: "Bad Request"})
return
}
// Main verificatoin step
err, user, groups := verifyToken(tr.Spec.Token, config.Credentials)
if err != nil {
log.Println("[Error]", err.Error())
w.WriteHeader(http.StatusUnauthorized)
// Not responding with error because that could leak information.
authenticationResponse(w, &authentication.TokenReviewStatus{Authenticated: false,
Error: "Access not granted"})
return
}
log.Printf("[Success] login as %s", user)
w.WriteHeader(http.StatusOK)
trs := authentication.TokenReviewStatus{
Authenticated: true,
User: authentication.UserInfo{
Username: user,
UID: user,
Groups: groups,
},
}
json.NewEncoder(w).Encode(authentication.TokenReview{
Status: trs,
})
}
func assertFileExists(path string) {
_, err := os.Stat(path)
if os.IsNotExist(err) {
log.Printf("File '%v' does not exist.\n", path)
os.Exit(1)
}
}
func runServer(config *Settings) *http.Server {
srv := &http.Server{Addr: config.ListenAddress}
http.HandleFunc("/authenticate", func(w http.ResponseWriter, r *http.Request) {
authenticate(w, r, config)
})
if config.SSL {
assertFileExists(config.SSLKeyPath)
assertFileExists(config.SSLCrtPath)
log.Printf("Starting HTTPS server on address: %v", srv.Addr)
go func() { log.Fatal(srv.ListenAndServeTLS(config.SSLCrtPath, config.SSLKeyPath)) }()
} else {
log.Printf("Starting HTTP server on address: %v", srv.Addr)
go func() { log.Fatal(srv.ListenAndServe()) }()
}
return srv
}