This repository has been archived by the owner on Mar 15, 2020. It is now read-only.
/
relengapi.go
93 lines (79 loc) · 2.1 KB
/
relengapi.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/taskcluster/httpbackoff"
)
const ScopePrefix = "docker-worker:relengapi-proxy:"
func scopesToPerms(scopes []string) []string {
var perms []string
for _, scope := range scopes {
if strings.HasPrefix(scope, ScopePrefix) {
perm := scope[len(ScopePrefix):]
if len(perm) != 0 {
perms = append(perms, perm)
}
}
}
return perms
}
type relengapiTokenJson struct {
Typ string `json:"typ"`
Id int `json:"id,omitempty"`
NotBefore *time.Time `json:"not_before,omitempty"`
Expires *time.Time `json:"expires,omitempty"`
Metadata interface{} `json:"metadata,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Permissions []string `json:"permissions,omitempty"`
Description string `json:"description,omitempty"`
User string `json:"user,omitempty"`
Token string `json:"token,omitempty"`
}
func getTmpToken(url string, issuingToken string, expires time.Time, perms []string) (tok string, err error) {
request := relengapiTokenJson{
Typ: "tmp",
Expires: &expires,
Permissions: perms,
Metadata: map[string]interface{}{},
}
reqbody, err := json.Marshal(request)
if err != nil {
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqbody))
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", issuingToken))
resp, _, err := httpbackoff.ClientDo(client, req)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = errors.New(fmt.Sprintf(
"Got '%s' while trying to get new tmp token:\n%s",
resp.Status, string(body)))
return
}
var responseBody interface{}
err = json.Unmarshal(body, &responseBody)
if err != nil {
return
}
result := responseBody.(map[string]interface{})["result"]
tok = result.(map[string]interface{})["token"].(string)
return
}