forked from oursky/kubernetes-github-authn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
202 lines (188 loc) · 5.06 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
authentication "k8s.io/client-go/pkg/apis/authentication/v1beta1"
)
func authenticationToken(r *http.Request) (oauth2.TokenSource, error) {
decoder := json.NewDecoder(r.Body)
var tr authentication.TokenReview
err := decoder.Decode(&tr)
if err != nil {
return nil, err
}
return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: tr.Spec.Token}), nil
}
func checkUser(client GithubService, ui *authentication.UserInfo) error {
user, _, err := client.UserGet("")
if err != nil {
return err
}
ui.Username = user.GetLogin()
ui.UID = fmt.Sprintf("%d", user.GetID())
return nil
}
func checkOrgs(client GithubService, ui *authentication.UserInfo) error {
requiredOrg := os.Getenv("REQUIRED_ORG")
matchesRequiredOrg := requiredOrg == ""
opt := &github.ListOrgMembershipsOptions{
ListOptions: github.ListOptions{PerPage: 100},
}
for {
memberships, resp, err := client.ListOrgMemberships(opt)
if resp.StatusCode == 403 {
// Token doesn't have permissions to query memberships.
return nil
}
if err != nil {
return err
}
for _, membership := range memberships {
ui.Groups = append(ui.Groups, "github:"+membership.Organization.GetLogin())
if membership.Organization.GetLogin() == requiredOrg {
matchesRequiredOrg = true
}
}
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
if !matchesRequiredOrg {
return fmt.Errorf("user %s is not a member of require organization %s", ui.Username, requiredOrg)
}
return nil
}
func checkTeams(client GithubService, ui *authentication.UserInfo) error {
opt := &github.ListOptions{PerPage: 100}
for {
teams, resp, err := client.ListUserTeams(opt)
if resp.StatusCode == 404 {
// Token doesn't have permissions to query teams. Not sure why this isn't a 403.
return nil
}
if err != nil {
return err
}
for _, team := range teams {
ui.Groups = append(ui.Groups, "github:"+team.Organization.GetLogin()+":"+team.GetSlug())
}
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return nil
}
func authenticate(r *http.Request) (*authentication.UserInfo, error) {
// Create the client to talk to GitHub.
ts, err := authenticationToken(r)
if err != nil {
return nil, err
}
client, err := newGithubClient(ts)
if err != nil {
return nil, err
}
// Run checks for authn and authz.
ui := &authentication.UserInfo{}
err = checkUser(client, ui)
if err != nil {
return nil, err
}
err = checkOrgs(client, ui)
if err != nil {
return nil, err
}
err = checkTeams(client, ui)
if err != nil {
return nil, err
}
return ui, nil
}
func authenticationHandler(w http.ResponseWriter, r *http.Request) {
ui, err := authenticate(r)
if err != nil {
log.Printf("[Error] %s", err.Error())
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]interface{}{
"apiVersion": "authentication.k8s.io/v1beta1",
"kind": "TokenReview",
"status": authentication.TokenReviewStatus{
Authenticated: false,
Error: err.Error(),
},
})
} else {
log.Printf("[Success] login as %s; groups %s", ui.Username, strings.Join(ui.Groups, ", "))
w.WriteHeader(http.StatusOK)
trs := authentication.TokenReviewStatus{
Authenticated: true,
User: *ui,
}
json.NewEncoder(w).Encode(map[string]interface{}{
"apiVersion": "authentication.k8s.io/v1beta1",
"kind": "TokenReview",
"status": trs,
})
}
}
const certPath = "/etc/ssl/webhook/tls.crt"
const keyPath = "/etc/ssl/webhook/tls.key"
var currentCert *tls.Certificate
var currentCertTime time.Time
func getCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
info, err := os.Stat(certPath)
if err != nil {
return nil, err
}
// If the cached cert is out of date, reload it.
fileTime := info.ModTime()
if fileTime.After(currentCertTime) {
log.Printf("[Cert] Reloading certificate from %s", certPath)
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
currentCert = &cert
currentCertTime = fileTime
} else {
log.Printf("[Cert] using cached certificate, file %v cache %v", fileTime, currentCertTime)
}
return currentCert, nil
}
func main() {
bindAddress := ":3000"
if port, ok := os.LookupEnv("PORT"); ok {
bindAddress = ":" + port
}
mux := http.NewServeMux()
mux.HandleFunc("/authenticate", authenticationHandler)
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
GetCertificate: getCertificate,
}
srv := &http.Server{
Addr: bindAddress,
Handler: mux,
TLSConfig: cfg,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
log.Fatal(srv.ListenAndServeTLS("", ""))
}