-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
283 lines (244 loc) · 7.72 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"os"
"path"
"time"
nautilusapi "github.com/dimm0/k8s_portal/pkg/apis/optiputer.net/v1alpha1"
"k8s.io/api/core/v1"
"k8s.io/api/extensions/v1beta1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
oidc "github.com/coreos/go-oidc"
"github.com/gorilla/sessions"
"github.com/spf13/viper"
"golang.org/x/net/context"
"golang.org/x/oauth2"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var config oauth2.Config
var pubconfig oauth2.Config
var provider *oidc.Provider
var clientset *kubernetes.Clientset
var filestore *sessions.FilesystemStore
var crdclient *nautilusapi.CrdClient
func randStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func main() {
rand.Seed(time.Now().UnixNano())
ctx := context.Background()
viper.SetConfigName("config")
viper.AddConfigPath("config")
viper.SetDefault("cluster_name", "kubernetes")
viper.SetDefault("storage_path", "/")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %s", err))
}
os.Mkdir(path.Join(viper.GetString("storage_path"), "sessions"), 0777)
filestore = sessions.NewFilesystemStore(path.Join(viper.GetString("storage_path"), "sessions"), []byte(viper.GetString("session_auth_key")), []byte(viper.GetString("session_enc_key")))
filestore.Options.Domain = viper.GetString("cluster_url")
filestore.Options.Secure = true
filestore.Options.Path = "/"
filestore.Options.MaxAge = 86400 * 7
filestore.Options.HttpOnly = true
provider, err = oidc.NewProvider(ctx, viper.GetString("oidc_provider"))
if err != nil {
log.Fatal(err)
}
config = oauth2.Config{
ClientID: viper.GetString("client_id"),
ClientSecret: viper.GetString("client_secret"),
Endpoint: provider.Endpoint(),
RedirectURL: "https://" + viper.GetString("cluster_url") + "/callback",
Scopes: []string{oidc.ScopeOpenID, "profile", "email", "org.cilogon.userinfo"},
}
pubconfig = oauth2.Config{
ClientID: viper.GetString("pub_client_id"),
ClientSecret: viper.GetString("pub_client_secret"),
Endpoint: provider.Endpoint(),
RedirectURL: "https://" + viper.GetString("cluster_url") + "/callback",
Scopes: []string{oidc.ScopeOpenID},
}
k8sconfig, err := rest.InClusterConfig()
if err != nil {
log.Fatal("Failed to do inclusterconfig: " + err.Error())
return
}
clientset, err = kubernetes.NewForConfig(k8sconfig)
if err != nil {
log.Printf("Error creating client: %s", err.Error())
}
// Create a new clientset which include our CRD schema
crdcs, scheme, err := nautilusapi.NewClient(k8sconfig)
if err != nil {
log.Printf("Error creating CRD client: %s", err.Error())
}
// Create a CRD client interface
crdclient = nautilusapi.MakeCrdClient(crdcs, scheme, "default")
SetupSecurity()
http.Handle("/media/", http.StripPrefix("/media/", http.FileServer(http.Dir("/media"))))
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/media/favicon.ico")
})
http.HandleFunc("/", RootHandler)
http.HandleFunc("/namespaces", NamespacesHandler)
http.HandleFunc("/nodes", NodesHandler)
http.HandleFunc("/profile", ProfileHandler)
http.HandleFunc("/nsMeta", NsMetaHandler)
http.HandleFunc("/tests", TestsHandler)
http.HandleFunc("/authConfig", func(w http.ResponseWriter, r *http.Request) {
statesLock.Lock()
defer statesLock.Unlock()
newState := randStringBytes(36)
states[newState] = "config"
cleanStateTimer := time.NewTimer(time.Minute * 10)
go func() {
<-cleanStateTimer.C
statesLock.Lock()
defer statesLock.Unlock()
delete(states, newState)
}()
http.Redirect(w, r, pubconfig.AuthCodeURL(newState), http.StatusFound)
})
http.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
statesLock.Lock()
defer statesLock.Unlock()
newState := randStringBytes(36)
states[newState] = "auth"
cleanStateTimer := time.NewTimer(time.Minute * 10)
go func() {
<-cleanStateTimer.C
statesLock.Lock()
defer statesLock.Unlock()
delete(states, newState)
}()
http.Redirect(w, r, config.AuthCodeURL(newState), http.StatusFound)
})
http.HandleFunc("/getConfig", GetConfigHandler)
http.HandleFunc("/callback", AuthenticateHandler)
http.HandleFunc("/users", UsersHandler)
http.HandleFunc("/logout", LogoutHandler)
log.Printf("listening on http://%s/", "127.0.0.1")
go func() {
GetCrd()
}()
go func() {
WatchGpuPods()
}()
log.Fatal(http.ListenAndServe(":80", nil))
}
func SetupSecurity() error {
if _, err := clientset.Extensions().PodSecurityPolicies().Get("nautilususerpolicy", metav1.GetOptions{}); err != nil {
f := false
if _, err := clientset.Extensions().PodSecurityPolicies().Create(&v1beta1.PodSecurityPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "nautilususerpolicy",
},
//https://kubernetes.io/docs/concepts/policy/pod-security-policy
Spec: v1beta1.PodSecurityPolicySpec{
Privileged: false,
AllowPrivilegeEscalation: &f,
Volumes: []v1beta1.FSType{
v1beta1.ConfigMap,
v1beta1.EmptyDir,
// v1beta1.Projected,
v1beta1.Secret,
v1beta1.NFS,
v1beta1.DownwardAPI,
v1beta1.PersistentVolumeClaim,
v1beta1.GitRepo,
},
AllowedCapabilities: []v1.Capability{"NET_ADMIN"},
HostNetwork: false,
HostIPC: false,
HostPID: false,
HostPorts: []v1beta1.HostPortRange{
{
Min: 1024,
Max: 65536,
},
},
RunAsUser: v1beta1.RunAsUserStrategyOptions{
Rule: v1beta1.RunAsUserStrategyRunAsAny,
},
SELinux: v1beta1.SELinuxStrategyOptions{
Rule: v1beta1.SELinuxStrategyRunAsAny,
},
SupplementalGroups: v1beta1.SupplementalGroupsStrategyOptions{
Rule: v1beta1.SupplementalGroupsStrategyRunAsAny,
},
FSGroup: v1beta1.FSGroupStrategyOptions{
Rule: v1beta1.FSGroupStrategyRunAsAny,
},
ReadOnlyRootFilesystem: false,
},
}); err != nil {
log.Printf("Error creating PSP %s", err.Error())
return err
}
}
if _, err := clientset.Rbac().ClusterRoles().Get("psp:nautilus-user", metav1.GetOptions{}); err != nil {
if _, err := clientset.Rbac().ClusterRoles().Create(&rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "psp:nautilus-user",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"extensions"},
Verbs: []string{"use"},
Resources: []string{"podsecuritypolicies"},
ResourceNames: []string{"nautilususerpolicy"},
},
},
}); err != nil {
log.Printf("Error creating PSP role %s", err.Error())
return err
}
}
if _, err := clientset.Rbac().ClusterRoles().Get("nautilus-cluster-user", metav1.GetOptions{}); err != nil {
if _, err := clientset.Rbac().ClusterRoles().Create(&rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "nautilus-cluster-user",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{""},
Verbs: []string{"get", "list"},
Resources: []string{"nodes"},
},
},
}); err != nil {
log.Printf("Error creating cluster Nautilus admin role %s", err.Error())
return err
}
}
if _, err := clientset.Rbac().ClusterRoles().Get("nautilus-admin", metav1.GetOptions{}); err != nil {
if _, err := clientset.Rbac().ClusterRoles().Create(&rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: "nautilus-admin",
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{""},
Verbs: []string{"delete"},
Resources: []string{"namespaces"},
},
},
}); err != nil {
log.Printf("Error creating Nautilus admin role %s", err.Error())
return err
}
}
return nil
}