/
client.go
300 lines (271 loc) · 9.95 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright 2016 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package iam
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"golang.org/x/net/context/ctxhttp"
"golang.org/x/oauth2"
"google.golang.org/api/googleapi"
"github.com/TriggerMail/luci-go/common/logging"
)
const (
// OAuthScope is an OAuth scope required by IAM API.
OAuthScope = "https://www.googleapis.com/auth/iam"
// Token type for generated OAauth2 tokens
tokenType = "Bearer"
)
var (
// DefaultIamBaseURL resembles IAM's core API endpoint.
DefaultIamBaseURL = &url.URL{
Scheme: "https",
Host: "iam.googleapis.com",
}
// DefaultAccountCredentialsBaseURL resembles IAM's account credentials API endpoint.
DefaultAccountCredentialsBaseURL = &url.URL{
Scheme: "https",
Host: "iamcredentials.googleapis.com",
}
)
// ClaimSet contains information about the JWT signature including the
// permissions being requested (scopes), the target of the token, the issuer,
// the time the token was issued, and the lifetime of the token.
//
// See RFC 7515.
type ClaimSet struct {
Iss string `json:"iss"` // email address of the client_id of the application making the access token request
Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch)
Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch)
Typ string `json:"typ,omitempty"` // token type (Optional).
// Email for which the application is requesting delegated access (Optional).
Sub string `json:"sub,omitempty"`
}
// Client knows how to perform IAM API v1 calls.
type Client struct {
Client *http.Client // client to use to make calls
BasePath string // replaceable in tests, DefaultIamBaseURL / DefaultAccountCredentials by default.
}
// SignBlob signs a blob using a service account's system-managed key.
//
// The caller must have "roles/iam.serviceAccountActor" role in the service
// account's IAM policy and caller's OAuth token must have one of the scopes:
// * https://www.googleapis.com/auth/iam
// * https://www.googleapis.com/auth/cloud-platform
//
// Returns ID of the signing key and the signature on success.
//
// On API-level errors (e.g. insufficient permissions) returns *googleapi.Error.
func (cl *Client) SignBlob(c context.Context, serviceAccount string, blob []byte) (keyName string, signature []byte, err error) {
var request struct {
BytesToSign []byte `json:"bytesToSign"`
}
request.BytesToSign = blob
var response struct {
KeyID string `json:"keyId"`
Signature []byte `json:"signature"`
}
if err = cl.iamAPIRequest(c, "projects/-/serviceAccounts/"+serviceAccount, "signBlob", &request, &response); err != nil {
return "", nil, err
}
return response.KeyID, response.Signature, nil
}
// SignJWT signs a claim set using a service account's system-managed key.
//
// It injects the key ID into the JWT header before singing. As a result, JWTs
// produced by SignJWT are slightly faster to verify, because we know what
// public key to use exactly and don't need to enumerate all active keys.
//
// It also checks the expiration time and refuses to sign claim sets with
// 'exp' set to more than 1h from now. Otherwise it is similar to SignBlob.
//
// The caller must have "roles/iam.serviceAccountActor" role in the service
// account's IAM policy and caller's OAuth token must have one of the scopes:
// * https://www.googleapis.com/auth/iam
// * https://www.googleapis.com/auth/cloud-platform
//
// Returns ID of the signing key and the signed JWT on success.
//
// On API-level errors (e.g. insufficient permissions) returns *googleapi.Error.
func (cl *Client) SignJWT(c context.Context, serviceAccount string, cs *ClaimSet) (keyName, signedJwt string, err error) {
blob, err := json.Marshal(cs)
if err != nil {
return "", "", err
}
var request struct {
Payload string `json:"payload"`
}
request.Payload = string(blob) // yep, this is JSON inside JSON
var response struct {
KeyID string `json:"keyId"`
SignedJwt string `json:"signedJwt"`
}
if err = cl.iamAPIRequest(c, "projects/-/serviceAccounts/"+serviceAccount, "signJwt", &request, &response); err != nil {
return "", "", err
}
return response.KeyID, response.SignedJwt, nil
}
// GetIAMPolicy fetches an IAM policy of a resource.
//
// On non-success HTTP status codes returns googleapi.Error.
func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) {
response := &Policy{}
if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil {
return nil, err
}
return response, nil
}
// SetIAMPolicy replaces an IAM policy of a resource.
//
// Returns a new policy (with Etag field updated).
func (cl *Client) SetIAMPolicy(c context.Context, resource string, p Policy) (*Policy, error) {
var request struct {
Policy *Policy `json:"policy"`
}
request.Policy = &p
response := &Policy{}
if err := cl.iamAPIRequest(c, resource, "setIamPolicy", &request, response); err != nil {
return nil, err
}
return response, nil
}
// ModifyIAMPolicy reads IAM policy, calls callback to modify it, and then
// puts it back (if callback really changed it).
//
// Cast error to *googleapi.Error and compare http status to http.StatusConflict
// to detect update race conditions. It is usually safe to retry in case of
// a conflict.
func (cl *Client) ModifyIAMPolicy(c context.Context, resource string, cb func(*Policy) error) error {
policy, err := cl.GetIAMPolicy(c, resource)
if err != nil {
return err
}
// Make a copy to be mutated in the callback. Need to keep the original to
// be able to detect changes.
clone := policy.Clone()
if err := cb(&clone); err != nil {
return err
}
if clone.Equals(*policy) {
return nil
}
_, err = cl.SetIAMPolicy(c, resource, clone)
return err
}
// GenerateAccessToken creates a service account OAuth token using IAM's
// :generateAccessToken API.
//
// On non-success HTTP status codes returns googleapi.Error.
func (cl *Client) GenerateAccessToken(c context.Context, serviceAccount string, scopes []string, delegates []string, lifetime time.Duration) (*oauth2.Token, error) {
var body struct {
Delegates []string `json:"delegates"`
Scope []string `json:"scope"`
Lifetime string `json:"lifetime,omitempty"`
}
body.Scope = scopes
body.Delegates = delegates
// Default lifetime is 3600 seconds according to API documentation.
// Requesting longer lifetime will cause an API error which is
// forwarded to the caller.
if lifetime > 0 {
body.Lifetime = lifetime.String()
}
var resp struct {
AccessToken string `json:"accessToken"`
ExpireTime string `json:"expireTime"`
}
if err := cl.credentialsAPIRequest(c, fmt.Sprintf("projects/-/serviceAccounts/%s", url.QueryEscape(serviceAccount)), "generateAccessToken", &body, &resp); err != nil {
return nil, err
}
expires, err := time.Parse(time.RFC3339, resp.ExpireTime)
if err != nil {
err = fmt.Errorf("Unable to parse 'expireTime': %s", resp.ExpireTime)
logging.WithError(err).Errorf(c, "Bad token endpoint response, unable to parse expireTime")
return nil, err
}
return &oauth2.Token{
AccessToken: resp.AccessToken,
TokenType: tokenType,
Expiry: expires.UTC(),
}, nil
}
// iamAPIRequest performs HTTP POST to the core IAM API endpoint.
func (cl *Client) iamAPIRequest(c context.Context, resource, action string, body, resp interface{}) error {
if cl.BasePath != "" {
// We are in "testing"
base, err := url.Parse(cl.BasePath)
if err != nil {
return err
}
return cl.genericAPIRequest(c, base, resource, action, body, resp)
}
return cl.genericAPIRequest(c, DefaultIamBaseURL, resource, action, body, resp)
}
// credentialsAPIRequest performs HTTP POST to the IAM credentials API endpoint.
func (cl *Client) credentialsAPIRequest(c context.Context, resource, action string, body, resp interface{}) error {
if cl.BasePath != "" {
// We are in "testing"
base, err := url.Parse(cl.BasePath)
if err != nil {
return err
}
return cl.genericAPIRequest(c, base, resource, action, body, resp)
}
return cl.genericAPIRequest(c, DefaultAccountCredentialsBaseURL, resource, action, body, resp)
}
// genericAPIRequest performs HTTP POST to an IAM API endpoint.
func (cl *Client) genericAPIRequest(c context.Context, base *url.URL, resource, action string, body, resp interface{}) error {
query, err := url.Parse(fmt.Sprintf("v1/%s:%s?alt=json", resource, action))
if err != nil {
return err
}
endpoint := base.ResolveReference(query)
// Serialize the body.
var reader io.Reader
if body != nil {
blob, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(blob)
}
// Issue the request
req, err := http.NewRequest("POST", endpoint.String(), reader)
if err != nil {
return err
}
if reader != nil {
req.Header.Set("Content-Type", "application/json")
}
// Send and handle errors. This is roughly how google-api-go-client calls
// methods. CheckResponse returns *googleapi.Error.
logging.Debugf(c, "POST %s", endpoint)
res, err := ctxhttp.Do(c, cl.Client, req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
logging.WithError(err).Errorf(c, "POST %s failed", endpoint)
return err
}
return json.NewDecoder(res.Body).Decode(resp)
}