forked from arbourd/concourse-slack-alert-resource
/
client.go
251 lines (213 loc) · 5.52 KB
/
client.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
package concourse
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
"github.com/Masterminds/semver/v3"
"golang.org/x/oauth2"
)
// A Client is a Concourse API connection.
type Client struct {
atcurl *url.URL
team string
conn *http.Client
}
// Info is version information from the Concourse API.
type Info struct {
ATCVersion string `json:"version"`
WorkerVersion string `json:"worker_version"`
}
// A Token is a legacy Concourse access token.
type Token struct {
Type string `json:"type"`
Value string `json:"value"`
}
// NewClient returns an authorized Client (if private) for the Concourse API.
func NewClient(atcurl, team, username, password string) (*Client, error) {
u, err := url.Parse(atcurl)
if err != nil {
return nil, err
}
// This cookie jar implementation never returns an error.
jar, _ := cookiejar.New(nil)
c := &Client{
atcurl: u,
team: team,
conn: &http.Client{Jar: jar},
}
// Return Client early if authorization is not needed.
if username == "" && password == "" {
return c, nil
}
info, err := c.info()
if err != nil {
return nil, err
}
legacy, err := semver.NewConstraint("< 4.0.0")
if err != nil {
return nil, err
}
v, err := semver.NewVersion(info.ATCVersion)
if err != nil {
return nil, err
}
multiCookie, err := semver.NewConstraint("5.5 - 6.4")
if err != nil {
return nil, err
}
oldsky, err := semver.NewConstraint("< 6.1.0")
if err != nil {
return nil, err
}
// Check if target Concourse is less than '4.0.0'.
if legacy.Check(v) {
url := fmt.Sprintf("%s/api/v1/teams/%s/auth/token", c.atcurl, c.team)
err = c.loginLegacy(url, username, password)
return c, err
}
url := fmt.Sprintf("%s/sky/issuer/token", c.atcurl)
// Support 4.x and 5.x skymarshall calls
if oldsky.Check(v) {
url = fmt.Sprintf("%s/sky/token", c.atcurl)
}
token, err := c.login(url, username, password)
if err != nil {
return nil, err
}
// Check if the version supports single cookie access tokens.
// Single cookie is used between versions 4.0.0 - 5.5.0 and 6.5.0 or greater.
if !multiCookie.Check(v) {
err = c.singleCookie(token.TokenType, token.AccessToken)
return c, err
}
// Check if the version is less than '6.1.0'.
if oldsky.Check(v) {
err = c.splitToken(token.TokenType, token.AccessToken)
return c, err
}
idToken, ok := token.Extra("id_token").(string)
if !ok {
return c, errors.New("invalid id_token")
}
err = c.splitToken(token.TokenType, idToken)
return c, err
}
// info queries Concourse for its version information.
func (c *Client) info() (Info, error) {
u := fmt.Sprintf("%s/api/v1/info", c.atcurl)
var info Info
r, err := c.conn.Get(u)
if err != nil {
return info, err
}
if r.StatusCode != 200 {
return info, fmt.Errorf("could not get info from Concourse: status code %d", r.StatusCode)
}
json.NewDecoder(r.Body).Decode(&info)
return info, nil
}
// singleCookie add the token as a single cookie.
func (c *Client) singleCookie(tokenType, tokenValue string) error {
c.conn.Jar.SetCookies(
c.atcurl,
[]*http.Cookie{{
Name: "skymarshal_auth",
Value: fmt.Sprintf("%s %s", tokenType, tokenValue),
}},
)
return nil
}
// splitToken splits the token across multiple cookies.
func (c *Client) splitToken(tokenType, tokenValue string) error {
const NumCookies = 15
const authCookieName = "skymarshal_auth"
const maxCookieSize = 4000
tokenStr := fmt.Sprintf("%s %s", tokenType, tokenValue)
for i := 0; i < NumCookies; i++ {
if len(tokenStr) > maxCookieSize {
c.conn.Jar.SetCookies(
c.atcurl,
[]*http.Cookie{{
Name: authCookieName + strconv.Itoa(i),
Value: tokenStr[:maxCookieSize],
}},
)
tokenStr = tokenStr[maxCookieSize:]
} else {
}
c.conn.Jar.SetCookies(
c.atcurl,
[]*http.Cookie{{
Name: authCookieName + strconv.Itoa(i),
Value: tokenStr,
}},
)
break
}
return nil
}
// login gets an access token from Concourse.
func (c *Client) login(url, username, password string) (*oauth2.Token, error) {
config := oauth2.Config{
ClientID: "fly",
ClientSecret: "Zmx5",
Endpoint: oauth2.Endpoint{TokenURL: url},
Scopes: []string{"openid", "profile", "email", "federated:id", "groups"},
}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, c.conn)
t, err := config.PasswordCredentialsToken(ctx, username, password)
return t, err
}
// loginLegacy gets a legacy access token from Concourse.
func (c *Client) loginLegacy(url, username, password string) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.SetBasicAuth(username, password)
r, err := c.conn.Do(req)
if err != nil {
return err
}
if r.StatusCode != 200 {
return fmt.Errorf("could not log into Concourse: status code %d", r.StatusCode)
}
var t Token
json.NewDecoder(r.Body).Decode(&t)
c.conn.Jar.SetCookies(
c.atcurl,
[]*http.Cookie{{
Name: "skymarshal_auth",
Value: fmt.Sprintf("%s %s", t.Type, t.Value),
}},
)
return nil
}
// JobBuild finds and returns a Build from the Concourse API by its
// pipeline name, job name and build name.
func (c *Client) JobBuild(pipeline, job, name, instanceVars string) (*Build, error) {
u := fmt.Sprintf(
"%s/api/v1/teams/%s/pipelines/%s/jobs/%s/builds/%s%s",
c.atcurl,
c.team,
pipeline,
job,
name,
instanceVars,
)
r, err := c.conn.Get(u)
if err != nil {
return nil, err
}
if r.StatusCode != 200 {
return nil, fmt.Errorf("unexpected status code: %d", r.StatusCode)
}
var build *Build
json.NewDecoder(r.Body).Decode(&build)
return build, nil
}