-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
343 lines (319 loc) · 9.62 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"bytes"
"crypto/tls"
"encoding/gob"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
type AuthResponse struct {
AccessToken string `json:"access_token"`
Expiry int `json:"expires_in"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Error string `json:"error"`
ErrorDesc string `json:"error_description"`
ClientID string `json:"client_id"`
}
type AuthServerResponse struct {
AuthServer struct {
URL string `json:"url"`
} `json:"auth-server"`
App struct {
Name string `json:"name"`
} `json:"app"`
}
var (
// key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
keyVal = os.Getenv("COOKIE_KEY")
key = []byte(keyVal)
store = sessions.NewCookieStore(key)
credhubServer = os.Getenv("CREDHUB_SERVER")
uiSslCert = os.Getenv("UI_SSL_CERT")
uiSslKey = os.Getenv("UI_SSL_KEY")
uiPort = os.Getenv("UI_PORT")
cookieName = os.Getenv("COOKIE_NAME")
clientID = os.Getenv("CLIENT_ID")
clientSecret = os.Getenv("CLIENT_SECRET")
uiUrl = os.Getenv("UI_URL") //used for callback url
customName = os.Getenv("DISPLAY_CUSTOM_NAME") // display a custom name on login page
)
type CredentialsData struct {
Credentials []struct {
VersionCreatedAt time.Time `json:"version_created_at"`
Name string `json:"name"`
} `json:"credentials"`
}
type CredentialPageData struct {
PageTitle string
Credentials []CredentialsData
UserName string
Flash Flash
}
func ListCredentials(w http.ResponseWriter, r *http.Request) {
//set the access token from session
session := GetSession(w, r, cookieName)
accessToken, _ := session.Values["access_token"].(string)
//api call to make
apiQuery := "/api/v1/data?name-like="
//if we get a search query, add it to the api_query
param1, ok := r.URL.Query()["search"]
if ok {
apiQuery = apiQuery + param1[0]
}
// call the credhub api to get all credentials
// set up netClient for use later
var netClient = &http.Client{
Timeout: time.Second * 10,
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //ignore cert for now FIX: add credhub and uaa certificate as environment variables on startup
req, _ := http.NewRequest("GET", credhubServer+apiQuery, bytes.NewBuffer([]byte("")))
req.Header.Add("authorization", "bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")
resp, reqErr := netClient.Do(req)
if reqErr != nil {
fmt.Println(reqErr)
http.Error(w, "Error", http.StatusBadRequest)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
credRespBytes := []byte(body)
credResp := CredentialsData{}
if credServErr := json.Unmarshal([]byte(credRespBytes), &credResp); credServErr != nil {
fmt.Println(credServErr)
}
flashsession := GetSession(w, r, "flash-cookie")
flashes := flashsession.Flashes()
var flash Flash
if len(flashes) > 0 {
flash = flashes[0].(Flash)
}
err := flashsession.Save(r, w)
if err != nil {
fmt.Println(err)
}
var p jwt.Parser
claims := jwt.MapClaims{}
_, _, _ = p.ParseUnverified(accessToken, claims)
userNameVal := ""
if val, ok := claims["user_name"]; ok {
userNameVal = val.(string)
} else {
userNameVal = claims["client_id"].(string)
}
data := CredentialPageData{
PageTitle: "List Credentials",
Credentials: []CredentialsData{
credResp,
},
UserName: userNameVal,
Flash: flash,
}
// use template
tmpl := template.Must(template.ParseFiles("templates/credentials.html", "templates/base.html"))
tmpl.ExecuteTemplate(w, "base", data)
}
func ReturnBlank(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "")
}
func RedirectHome(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func RedirectLogin(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
func FaviconHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "favicon.ico")
}
func GetSession(w http.ResponseWriter, r *http.Request, sessionCookie string) *sessions.Session {
session, err := store.Get(r, sessionCookie)
if err != nil {
fmt.Printf("session error")
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
return session
}
func AddFlash(w http.ResponseWriter, r *http.Request, flashMessage string, flashType template.JS) {
flashsession := GetSession(w, r, "flash-cookie")
flash := Flash{
Type: flashType,
Message: flashMessage,
Display: true,
}
flashsession.AddFlash(flash)
flashsession.Save(r, w)
}
func CheckError(w http.ResponseWriter, r *http.Request, responseBody []byte, defaultFlashMessage string, defaultFlashType template.JS) {
var rawJson map[string]interface{}
json.Unmarshal(responseBody, &rawJson)
for a, b := range rawJson {
if a == "error" {
AddFlash(w, r, b.(string), "danger")
return
}
}
AddFlash(w, r, defaultFlashMessage, defaultFlashType)
return
}
func ValidateToken(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
session := GetSession(w, req, cookieName)
accessToken, setbool := session.Values["access_token"].(string)
if setbool == true && accessToken == "" {
RedirectLogin(w, req)
//return
} else if setbool == false {
RedirectLogin(w, req)
} else {
var p jwt.Parser
token, _, _ := p.ParseUnverified(accessToken, &jwt.StandardClaims{})
if err := token.Claims.Valid(); err != nil {
//invalid
RedirectLogin(w, req)
//return
} else {
//valid
next(w, req)
//return
}
}
//RedirectLogin(w, r)
return
})
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func main() {
keyValVar := flag.String("cookie-key", "", "Must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)")
cookieNameVar := flag.String("cookie-name", "auth-cookie", "Name of the cookie to use (auth-cookie)")
credhubServerVar := flag.String("credhub-server", "", "URL of CredHub server to target (https://<ip-or-host>:<port>)")
uiSslCertVar := flag.String("ui-ssl-cert", "", "SSL certificate for the web frontend (server.crt)")
uiSslKeyVar := flag.String("ui-ssl-key", "", "SSL certificate key for the web frontend (server.key)")
uiPortVar := flag.String("ui-port", "", "Port to run the server on")
clientIDVar := flag.String("client-id", "", "Client ID that has credhub.read and credhub.write authorization")
clientSecretVar := flag.String("client-secret", "", "Secret for the Client ID")
uiUrlVar := flag.String("ui-url", "", "URL of this UI (https://<ip-or-host>:<port>)")
customNameVar := flag.String("custom-name", "", "a custom name to display on login page")
flag.Parse()
if len(os.Getenv("CREDHUB_SERVER")) == 0 {
if *credhubServerVar != "" {
credhubServer = *credhubServerVar
} else {
log.Fatalln("CREDHUB_SERVER not set")
}
}
if len(os.Getenv("COOKIE_NAME")) == 0 {
if *cookieNameVar != "" {
cookieName = *cookieNameVar
} else {
log.Fatalln("COOKIE_NAME not set")
}
}
if len(os.Getenv("COOKIE_KEY")) == 0 {
if *keyValVar != "" {
keyVal = *keyValVar
key = []byte(keyVal)
store = sessions.NewCookieStore(key)
} else {
log.Fatalln("COOKIE_KEY not set")
}
}
if len(os.Getenv("UI_SSL_CERT")) == 0 {
if *uiSslCertVar != "" {
uiSslCert = *uiSslCertVar
} else {
log.Fatalln("UI_SSL_CERT not set")
}
}
if len(os.Getenv("UI_SSL_KEY")) == 0 {
if *uiSslKeyVar != "" {
uiSslKey = *uiSslKeyVar
} else {
log.Fatalln("UI_SSL_KEY not set")
}
}
if len(os.Getenv("CLIENT_ID")) == 0 {
if *clientIDVar != "" {
clientID = *clientIDVar
} else {
log.Fatalln("CLIENT_ID not set")
}
}
if len(os.Getenv("CLIENT_SECRET")) == 0 {
if *clientSecretVar != "" {
clientSecret = *clientSecretVar
} else {
clientSecret = "" //allow empty secret?
//log.Fatalln("CLIENT_SECRET not set")
}
}
if len(os.Getenv("UI_URL")) == 0 {
if *uiUrlVar != "" {
uiUrl = *uiUrlVar
} else {
log.Fatalln("UI_URL not set")
}
}
if len(os.Getenv("UI_PORT")) == 0 {
if *uiPortVar != "" {
uiPort = *uiPortVar
} else {
log.Fatalln("UI_PORT not set")
}
}
if len(os.Getenv("DISPLAY_CUSTOM_NAME")) == 0 {
if *customNameVar != "" {
customName = *customNameVar
} else {
customName = "" //allow custom name
}
}
gob.Register(Flash{})
log.SetFlags(log.Ldate | log.Ltime)
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400,
HttpOnly: true,
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //ignore cert for now FIX: add credhub and uaa certificate as environment variables on startup
r := mux.NewRouter()
r.HandleFunc("/login", Login)
r.HandleFunc("/login/callback", LoginCallback)
r.HandleFunc("/logout", Logout)
r.HandleFunc("/get", ValidateToken(GetCredentials))
r.HandleFunc("/delete", ValidateToken(DeleteCredentials))
r.HandleFunc("/generate/{credtype}", ValidateToken(GenerateCredentials))
r.HandleFunc("/set/{credtype}", ValidateToken(SetCredentials))
r.HandleFunc("/edit", ValidateToken(EditCredentials))
r.HandleFunc("/favicon.ico", FaviconHandler)
r.HandleFunc("/", ValidateToken(ListCredentials))
err := http.ListenAndServeTLS(":"+uiPort, uiSslCert, uiSslKey, LogRequest(r))
if err != nil {
fmt.Println(err)
}
}
func LogRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}