forked from d2iq-archive/mesos-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iam.go
88 lines (77 loc) · 2.06 KB
/
iam.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
package iam
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/mesosphere/mesos-dns/errorutil"
"github.com/mesosphere/mesos-dns/httpcli"
)
// Register registers a DoerFactory for IAM (JWT-based) authentication
func Register() {
httpcli.Register(httpcli.AuthIAM, httpcli.DoerFactory(func(cm httpcli.ConfigMap, c *http.Client) (doer httpcli.Doer) {
obj := cm.FindOrPanic(httpcli.AuthIAM)
config, ok := obj.(Config)
if !ok {
panic(fmt.Errorf("expected Config instead of %#+v", obj))
}
validate(config)
if c != nil {
doer = Doer(c, config)
}
return
}))
}
func validate(c Config) {
if c.ID == "" || c.PrivateKey == "" || c.LoginEndpoint == "" {
panic(ErrInvalidConfiguration)
}
}
// Doer wraps an HTTP transactor given an IAM configuration
func Doer(client *http.Client, config Config) httpcli.Doer {
return httpcli.DoerFunc(func(req *http.Request) (*http.Response, error) {
// TODO if we still have a valid token, try using it first
token := jwt.New(jwt.SigningMethodRS256)
token.Claims["uid"] = config.ID
token.Claims["exp"] = time.Now().Add(time.Hour).Unix()
// SignedString will treat secret as PEM-encoded key
tokenStr, err := token.SignedString([]byte(config.PrivateKey))
if err != nil {
return nil, err
}
authReq := struct {
UID string `json:"uid"`
Token string `json:"token,omitempty"`
}{
UID: config.ID,
Token: tokenStr,
}
b, err := json.Marshal(authReq)
if err != nil {
return nil, err
}
authBody := bytes.NewBuffer(b)
resp, err := client.Post(config.LoginEndpoint, "application/json", authBody)
if err != nil {
return nil, err
}
defer errorutil.Ignore(resp.Body.Close)
if resp.StatusCode != 200 {
return nil, httpcli.ErrAuthFailed
}
var authResp struct {
Token string `json:"token"`
}
err = json.NewDecoder(resp.Body).Decode(&authResp)
if err != nil {
return nil, err
}
if req.Header == nil {
req.Header = make(http.Header)
}
req.Header.Set("Authorization", "token="+authResp.Token)
return client.Do(req)
})
}