-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtask_agent.go
More file actions
168 lines (150 loc) · 4.47 KB
/
task_agent.go
File metadata and controls
168 lines (150 loc) · 4.47 KB
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
package protocol
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/golang-jwt/jwt"
"github.com/google/uuid"
)
const (
// JWT token expiration time
jwtExpiration = 5 * time.Minute
// Error message prefix for authorization failures
authFailurePrefix = "Failed to Authorize: "
)
type TaskAgentPublicKey struct {
Exponent string
Modulus string
}
type TaskAgentAuthorization struct {
AuthorizationURL string `json:",omitempty"`
ClientID string `json:",omitempty"`
PublicKey TaskAgentPublicKey
}
type AgentLabel struct {
ID int
Name string
Type string
}
type PropertyValue struct {
Type string `json:"$type"`
Value interface{} `json:"$value"`
}
func (v *PropertyValue) UnmarshalJSON(data []byte) error {
var b bool
if json.Unmarshal(data, &b) == nil {
v.Type = "System.Boolean"
v.Value = b
return nil
}
var raw string
if json.Unmarshal(data, &raw) == nil {
v.Type = "System.String"
v.Value = raw
return nil
}
type PropertyValueRaw PropertyValue
// Best Effort, drop errors
_ = json.Unmarshal(data, (*PropertyValueRaw)(v))
return nil
}
type PropertiesCollection map[string]PropertyValue
func (c *PropertiesCollection) Lookup(name, ty string) (interface{}, bool) {
for k, v := range *c {
if strings.EqualFold(k, name) && strings.EqualFold(v.Type, ty) {
return v.Value, true
}
}
return nil, false
}
func (c *PropertiesCollection) LookupBool(name string) (value, ok bool) {
if v, ok := c.Lookup(name, "System.Boolean"); ok && v != nil {
b, isBool := v.(bool)
return b, isBool
}
return false, false
}
func (c *PropertiesCollection) LookupString(name string) (string, bool) {
if v, ok := c.Lookup(name, "System.String"); ok && v != nil {
b, isString := v.(string)
return b, isString
}
return "", false
}
type TaskAgent struct {
Authorization TaskAgentAuthorization
Labels []AgentLabel
MaxParallelism int
ID int64
Name string
Version string
OSDescription string
Enabled *bool `json:",omitempty"`
ProvisioningState string
AccessPoint string `json:",omitempty"`
CreatedOn string
Ephemeral bool `json:",omitempty"`
DisableUpdate bool `json:",omitempty"`
Properties PropertiesCollection
}
type TaskAgents struct {
Count int64
Value []TaskAgent
}
func (taskAgent *TaskAgent) Authorize(c *http.Client, key interface{}) (*VssOAuthTokenResponse, error) {
tokenresp := &VssOAuthTokenResponse{}
now := time.Now().UTC().Add(-30 * time.Second)
var method jwt.SigningMethod = jwt.SigningMethodRS256
requireFipsCryptography, hasRequireFipsCryptography := taskAgent.Properties.LookupBool("RequireFipsCryptography")
serverV2URL, _ := taskAgent.Properties.LookupString("ServerUrlV2")
if requireFipsCryptography && hasRequireFipsCryptography || serverV2URL != "" {
method = jwt.SigningMethodPS256
}
token2 := jwt.NewWithClaims(method, jwt.StandardClaims{
Subject: taskAgent.Authorization.ClientID,
Issuer: taskAgent.Authorization.ClientID,
Id: uuid.New().String(),
Audience: taskAgent.Authorization.AuthorizationURL,
NotBefore: now.Unix(),
IssuedAt: now.Unix(),
ExpiresAt: now.Add(jwtExpiration).Unix(),
})
stkn, err := token2.SignedString(key)
if err != nil {
return nil, err
}
data := url.Values{}
data.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
data.Set("client_assertion", stkn)
data.Set("grant_type", "client_credentials")
//nolint:noctx // Legacy function without context - would break API compatibility
poolsreq, err := http.NewRequest(http.MethodPost, taskAgent.Authorization.AuthorizationURL, bytes.NewBufferString(data.Encode()))
if err != nil {
return nil, errors.New(authFailurePrefix + err.Error())
}
poolsreq.Header["Content-Type"] = []string{"application/x-www-form-urlencoded; charset=utf-8"}
poolsreq.Header["Accept"] = []string{"application/json"}
poolsresp, err := c.Do(poolsreq)
if err != nil {
return nil, errors.New(authFailurePrefix + err.Error())
}
defer func() {
_ = poolsresp.Body.Close() // Ignore close error
}()
if poolsresp.StatusCode != http.StatusOK {
responseBytes, _ := io.ReadAll(poolsresp.Body)
return nil, errors.New("Failed to Authorize, service responded with code " + fmt.Sprint(poolsresp.StatusCode) +
": " + string(responseBytes))
}
dec := json.NewDecoder(poolsresp.Body)
if err := dec.Decode(tokenresp); err != nil {
return nil, err
}
return tokenresp, nil
}