-
Notifications
You must be signed in to change notification settings - Fork 7
/
enterprise.go
105 lines (90 loc) · 2.49 KB
/
enterprise.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
package config
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/dgrijalva/jwt-go"
log "github.com/sirupsen/logrus"
)
func initEnterprise() {
token, err := generateJWTToken()
if err != nil {
log.Fatalf("Unable to generate JWT token: %s", err)
os.Exit(1)
}
defaultConfig.DCOSVariant = DCOSVariant{"enterprise"}
defaultConfig.ExtraHeaders["Authorization"] = fmt.Sprintf("token=%s", token)
}
func generateJWTToken() (string, error) {
securityConfig := struct {
UID string `json:"uid"`
PrivateKey string `json:"private_key"`
LoginEndpoint string `json:"login_endpoint"`
JWTToken string
SecretJSONPath string
}{
SecretJSONPath: "/run/dcos/etc/signal-service/service_account.json",
}
// Load the secret file if it exists
secretJSON, loadErr := ioutil.ReadFile(securityConfig.SecretJSONPath)
if loadErr != nil {
log.Warn("Service account not detected, continuing with out secure requests.")
return "", nil
}
if jsonErr := json.Unmarshal(secretJSON, &securityConfig); jsonErr != nil {
return "", jsonErr
}
if securityConfig.UID == "" || securityConfig.PrivateKey == "" || securityConfig.LoginEndpoint == "" {
return "", errors.New("UID, private key or login endpoint can not be empty.")
}
log.Debug("Generating JWT token...")
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{
"uid": securityConfig.UID,
"exp": time.Now().Add(time.Hour).Unix(),
})
tokenStr, err := token.SignedString([]byte(securityConfig.PrivateKey))
if err != nil {
return "", err
}
client := http.Client{
Timeout: time.Duration(5 * time.Second),
}
authReq := struct {
UID string `json:"uid"`
Token string `json:"token,omitempty"`
}{
UID: securityConfig.UID,
Token: tokenStr,
}
b, err := json.Marshal(authReq)
if err != nil {
return "", err
}
authBody := bytes.NewBuffer(b)
req, err := http.NewRequest("POST", securityConfig.LoginEndpoint, authBody)
if err != nil {
return "", err
}
req.Header.Add("Content-type", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to auth with Bouncer, status code: %d", resp.StatusCode)
}
var authResp struct {
Token string `json:"token"`
}
if err = json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return "", err
}
log.Debugf("Successfully retrieved JWT token: %s", authResp.Token)
return authResp.Token, nil
}