forked from aws/aws-toolkit-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclients.ts
More file actions
319 lines (277 loc) · 12.2 KB
/
clients.ts
File metadata and controls
319 lines (277 loc) · 12.2 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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import globals from '../../shared/extensionGlobals'
import {
AccountInfo,
GetRoleCredentialsRequest,
ListAccountRolesRequest,
ListAccountsRequest,
LogoutRequest,
RoleInfo,
SSO,
SSOServiceException,
} from '@aws-sdk/client-sso'
import {
AuthorizationPendingException,
CreateTokenRequest,
RegisterClientRequest,
SSOOIDC,
SSOOIDCClient,
StartDeviceAuthorizationRequest,
} from '@aws-sdk/client-sso-oidc'
import { AsyncCollection } from '../../shared/utilities/asyncCollection'
import { pageableToCollection, partialClone } from '../../shared/utilities/collectionUtils'
import { assertHasProps, isNonNullable, RequiredProps, selectFrom } from '../../shared/utilities/tsUtils'
import { getLogger } from '../../shared/logger/logger'
import { SsoAccessTokenProvider } from './ssoAccessTokenProvider'
import { AwsClientResponseError, isClientFault } from '../../shared/errors'
import { DevSettings } from '../../shared/settings'
import { HttpRequest, HttpResponse } from '@smithy/protocol-http'
import { StandardRetryStrategy, defaultRetryDecider } from '@smithy/middleware-retry'
import { AuthenticationFlow } from './model'
import { toSnakeCase } from '../../shared/utilities/textUtilities'
import { getUserAgent, withTelemetryContext } from '../../shared/telemetry/util'
import { oneSecond } from '../../shared/datetime'
import { telemetry } from '../../shared/telemetry/telemetry'
import { getTelemetryReason, getTelemetryReasonDesc, getHttpStatusCode } from '../../shared/errors'
export class OidcClient {
public constructor(
private readonly client: SSOOIDC,
private readonly clock: { Date: typeof Date }
) {}
public async registerClient(request: RegisterClientRequest, startUrl: string, flow?: AuthenticationFlow) {
const response = await this.client.registerClient(request)
assertHasProps(response, 'clientId', 'clientSecret', 'clientSecretExpiresAt')
return {
scopes: request.scopes,
clientId: response.clientId,
clientSecret: response.clientSecret,
expiresAt: new this.clock.Date(response.clientSecretExpiresAt * 1000),
startUrl,
...(flow ? { flow } : {}),
}
}
public async startDeviceAuthorization(request: StartDeviceAuthorizationRequest) {
const response = await this.client.startDeviceAuthorization(request)
assertHasProps(response, 'expiresIn', 'deviceCode', 'userCode', 'verificationUri')
return {
...selectFrom(response, 'deviceCode', 'userCode', 'verificationUri'),
expiresAt: new this.clock.Date(response.expiresIn * 1000 + this.clock.Date.now()),
interval: response.interval ? response.interval * 1000 : undefined,
}
}
public async authorize(request: {
responseType: string
clientId: string
redirectUri: string
scopes: string[]
state: string
codeChallenge: string
codeChallengeMethod: string
}) {
// aws sdk doesn't convert to url params until right before you make the request, so we have to do
// it manually ahead of time
const params = toSnakeCase(request)
const searchParams = new URLSearchParams(params).toString()
const region = await this.client.config.region()
return `https://oidc.${region}.amazonaws.com/authorize?${searchParams}`
}
public async createToken(request: CreateTokenRequest) {
const startTime = this.clock.Date.now()
const grantType = request.grantType
let response
try {
response = await this.client.createToken(request as CreateTokenRequest)
} catch (err) {
const statusCode = getHttpStatusCode(err)
telemetry.auth_ssoTokenOperation.emit({
result: 'Failed',
grantType: grantType ?? 'unknown',
duration: this.clock.Date.now() - startTime,
reason: getTelemetryReason(err),
reasonDesc: getTelemetryReasonDesc(err),
...(statusCode !== undefined ? { httpStatusCode: String(statusCode) } : {}),
})
getLogger().error(`sso-oidc: createToken failed (grantType=${grantType}): ${err}`)
const newError = AwsClientResponseError.instanceIf(err)
throw newError
}
assertHasProps(response, 'accessToken', 'expiresIn')
telemetry.auth_ssoTokenOperation.emit({
result: 'Succeeded',
grantType: grantType ?? 'unknown',
duration: this.clock.Date.now() - startTime,
})
getLogger().debug(
`sso-oidc: createToken succeeded (grantType=${grantType}, requestId=${response.$metadata.requestId})`
)
return {
...selectFrom(response, 'accessToken', 'refreshToken', 'tokenType'),
requestId: response.$metadata.requestId,
expiresAt: new this.clock.Date(response.expiresIn * 1000 + this.clock.Date.now()),
}
}
public static create(region: string) {
const client = new SSOOIDC({
region,
endpoint: DevSettings.instance.get('endpoints', {})['ssooidc'],
retryStrategy: new StandardRetryStrategy(
() => Promise.resolve(3), // Maximum number of retries
{ retryDecider: defaultRetryDecider }
),
customUserAgent: getUserAgent({ includePlatform: true, includeClientId: true }),
requestHandler: {
// This field may have a bug: https://github.com/aws/aws-sdk-js-v3/issues/6271
// If the bug is real but is fixed, then we can probably remove this field and just have no timeout by default
//
// Also, we bump this higher due to ticket V1761315147, so that SSO does not timeout
requestTimeout: oneSecond * 12,
},
})
addLoggingMiddleware(client)
return new this(client, globals.clock)
}
}
type OmittedProps = 'accessToken' | 'nextToken'
type ExtractOverload<T, U> = T extends {
(...args: infer P1): infer R1
(...args: infer P2): infer R2
(...args: infer P3): infer R3
}
? (this: U, ...args: P1) => R1
: never
// Removes all methods that use callbacks instead of promises
type PromisifyClient<T> = {
[P in keyof T]: T[P] extends (...args: any[]) => any ? ExtractOverload<T[P], PromisifyClient<T>> : T[P]
}
const ssoClientClassName = 'SsoClient'
export class SsoClient {
public get region() {
const region = this.client.config.region
return typeof region === 'string' ? (region as string) : undefined
}
public constructor(
private readonly client: PromisifyClient<SSO>,
private readonly provider: SsoAccessTokenProvider
) {}
@withTelemetryContext({ name: 'listAccounts', class: ssoClientClassName })
public listAccounts(
request: Omit<ListAccountsRequest, OmittedProps> = {}
): AsyncCollection<RequiredProps<AccountInfo, 'accountId'>[]> {
const requester = (request: Omit<ListAccountsRequest, 'accessToken'>) =>
this.call(this.client.listAccounts, request)
const collection = pageableToCollection(requester, request, 'nextToken', 'accountList')
return collection
.filter(isNonNullable)
.map((accounts) => accounts.map((a) => (assertHasProps(a, 'accountId'), a)))
}
@withTelemetryContext({ name: 'listAccountRoles', class: ssoClientClassName })
public listAccountRoles(
request: Omit<ListAccountRolesRequest, OmittedProps>
): AsyncCollection<Required<RoleInfo>[]> {
const requester = (request: Omit<ListAccountRolesRequest, 'accessToken'>) =>
this.call(this.client.listAccountRoles, request)
const collection = pageableToCollection(requester, request, 'nextToken', 'roleList')
return collection
.filter(isNonNullable)
.map((roles) => roles.map((r) => (assertHasProps(r, 'roleName', 'accountId'), r)))
}
@withTelemetryContext({ name: 'getRoleCredentials', class: ssoClientClassName })
public async getRoleCredentials(request: Omit<GetRoleCredentialsRequest, OmittedProps>) {
const response = await this.call(this.client.getRoleCredentials, request)
assertHasProps(response, 'roleCredentials')
assertHasProps(response.roleCredentials, 'accessKeyId', 'secretAccessKey')
const expiration = response.roleCredentials.expiration
return {
...response.roleCredentials,
expiration: expiration ? new globals.clock.Date(expiration) : undefined,
}
}
@withTelemetryContext({ name: 'logout', class: ssoClientClassName })
public async logout(request: Omit<LogoutRequest, OmittedProps> = {}) {
await this.call(this.client.logout, request)
}
private call<T extends { accessToken: string | undefined }, U>(
method: (this: typeof this.client, request: T) => Promise<U>,
request: Omit<T, 'accessToken'>
): Promise<U> {
const requester = async (req: T) => {
const token = await this.provider.getToken()
assertHasProps(token, 'accessToken')
try {
return await method.call(this.client, { ...req, accessToken: token.accessToken })
} catch (error) {
await this.handleError(error)
throw error
}
}
return requester(request as T)
}
@withTelemetryContext({ name: 'handleError', class: ssoClientClassName })
private async handleError(error: unknown): Promise<never> {
if (error instanceof SSOServiceException && isClientFault(error) && error.name !== 'ForbiddenException') {
getLogger().warn(`credentials (sso): invalidating stored token: ${error.message}`)
await this.provider.invalidate(`ssoClient:${error.name}`)
}
throw error
}
public static create(region: string, provider: SsoAccessTokenProvider) {
return new this(
new SSO({
region,
endpoint: DevSettings.instance.get('endpoints', {})['sso'],
customUserAgent: getUserAgent({ includePlatform: true, includeClientId: true }),
}),
provider
)
}
}
function addLoggingMiddleware(client: SSOOIDCClient) {
client.middlewareStack.add(
(next, context) => (args) => {
if (HttpRequest.isInstance(args.request)) {
const { hostname, path } = args.request
const input = partialClone(
// TODO: Fix
args.input as unknown as Record<string, unknown>,
3,
['clientSecret', 'accessToken', 'refreshToken'],
{ replacement: '[omitted]' }
)
getLogger().debug('API request (%s %s): %O', hostname, path, input)
}
return next(args)
},
{ step: 'finalizeRequest' }
)
client.middlewareStack.add(
(next, context) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args)
}
const { hostname, path } = args.request
const result = await next(args).catch((e) => {
if (e instanceof Error && !(e instanceof AuthorizationPendingException)) {
const err = { ...e }
delete err['stack']
getLogger().error('API response (%s %s): %O', hostname, path, err)
}
throw e
})
if (HttpResponse.isInstance(result.response)) {
const output = partialClone(
// TODO: Fix
result.output as unknown as Record<string, unknown>,
3,
['clientSecret', 'accessToken', 'refreshToken'],
{ replacement: '[omitted]' }
)
getLogger().debug('API response (%s %s): %O', hostname, path, output)
}
return result
},
{ step: 'deserialize' }
)
}