-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathVraNgRestClient.ts
More file actions
237 lines (199 loc) · 7.9 KB
/
VraNgRestClient.ts
File metadata and controls
237 lines (199 loc) · 7.9 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
/*!
* Copyright 2018-2020 VMware, Inc.
* SPDX-License-Identifier: MIT
*/
import * as request from "request-promise-native"
import { VraNgAuth } from "./auth"
import { VraAuthType } from "../types"
import { Blueprint, Deployment, PagedResult, Project, Token } from "./vra-model"
const VMWARE_CLOUD_API = "api.mgmt.cloud.vmware.com"
const VMWARE_CLOUD_CSP = "console.cloud.vmware.com"
export interface TokenPair {
accessToken?: string // undefined when expired
refreshToken?: string
}
export class AuthGrant implements TokenPair {
constructor(
public readonly type: VraAuthType,
public readonly refreshToken?: string,
public readonly clientId?: string,
public readonly clientSecret?: string,
public readonly username?: string,
public readonly password?: string,
public readonly orgId?: string
) {
// empty
}
static RefreshToken(refreshToken: string) {
return new AuthGrant("refresh_token", refreshToken)
}
static Password(username: string, password: string, orgId?: string) {
return new AuthGrant("password", undefined, undefined, undefined, username, password, orgId)
}
// static ClientCredentials(clientId: string, clientSecret: string) {
// return new AuthGrant("client_credentials", undefined, clientId, clientSecret)
// }
}
export interface VraIdentityIO {
write(host: string, token: Token): Promise<void>
read(host: string): Promise<TokenPair | undefined>
}
export class VraNgRestClient {
constructor(private host: string, private port: number, private identity: VraIdentityIO) {
if (host === VMWARE_CLOUD_CSP) {
// CSP is only for identity operations, switch to management api
this.host = VMWARE_CLOUD_API
}
if (host === "cloud.vmware.com" || host === "mgmt.cloud.vmware.com" || host === "www.mgmt.cloud.vmware.com") {
this.host = VMWARE_CLOUD_API
}
if (!port || port <= 0) {
this.port = 443
}
}
private async send<T = any>(
method: "GET" | "POST" | "PUT" | "DELETE",
route: string,
options?: Partial<request.OptionsWithUrl>,
skipAuth: boolean = false
): Promise<T> {
const url = route.indexOf("://") > 0 ? route : `https://${this.host}:${this.port}/${route.replace(/^\//, "")}`
const auth = skipAuth ? undefined : { ...(await this.getAuth()) }
return request({
headers: {
Accept: "application/json"
},
json: true,
simple: true, // reject non-2xx
resolveWithFullResponse: false,
rejectUnauthorized: false,
...options,
method,
url,
auth
})
}
private async getAuth(): Promise<Record<string, unknown>> {
const token = await this.identity.read(this.host)
if (!token) {
return Promise.reject("Missing vRA authentication configuration")
}
if (token.accessToken) {
return new VraNgAuth(token.accessToken).toRequestJson()
}
if (!token.refreshToken) {
return Promise.reject("Missing refresh token for an expired access token")
}
const tokenResponse: Token = await this.login(AuthGrant.RefreshToken(token.refreshToken))
return new VraNgAuth(tokenResponse.access_token).toRequestJson()
}
private async isOnPrem(baseUrl: string): Promise<boolean> {
try {
const deployment = (await this.send("GET", `${baseUrl}/automation-ui/config.json`, undefined, true))
.deployment
return deployment == "onprem"
} catch {
return false
}
}
private async unwrapPages<A>(payload: PagedResult<A>, uri: string): Promise<A[]> {
if (!payload.pageable.paged || payload.numberOfElements <= payload.totalElements) {
return payload.content
}
if (!uri.endsWith("/")) {
uri += "/"
}
const result: A[] = []
result.push(...payload.content)
while (payload.pageable.pageNumber < payload.totalPages) {
const nextPage = payload.pageable.pageNumber + 1
const skipElements = nextPage * payload.pageable.pageSize
payload = await this.send("GET", `${uri}?$skip=${skipElements}`)
result.push(...payload.content)
}
return result
}
async login(grant: AuthGrant): Promise<Token> {
const baseUrl =
this.host === VMWARE_CLOUD_API ? `https://${VMWARE_CLOUD_CSP}` : `https://${this.host}:${this.port}`
let uri: string
const options: any = {}
const isOnPrem = this.isOnPrem(baseUrl)
switch (grant.type) {
case "refresh_token": {
uri = `${baseUrl}/csp/gateway/am/api/auth/api-tokens/authorize?refresh_token=${grant.refreshToken}`
break
}
case "password": {
if (isOnPrem) {
uri = `${baseUrl}/csp/gateway/am/api/login?access_token`
options.body = {
username: grant.username,
password: grant.password,
domain: grant.orgId || undefined
}
} else {
uri = `${baseUrl}/am/api/auth/authorize`
options.form = {
username: grant.username,
password: grant.password,
orgId: grant.orgId || undefined
}
}
break
}
default: {
throw new Error(`Unsupported authentication type: ${grant.type}`)
}
}
const tokenResponse: Token = await this.send("POST", uri, options, true)
await this.identity.write(this.host, tokenResponse)
return tokenResponse
}
async getLoggedInUser(): Promise<any> {
const baseUrl = this.host === VMWARE_CLOUD_API ? `https://${VMWARE_CLOUD_CSP}` : ""
const uri = `${baseUrl}/csp/gateway/am/api/loggedin/user`
return this.send("GET", uri)
}
// -----------------------------------------------------------
// Blueprint related APIs ------------------------------------
// -----------------------------------------------------------
async getBlueprintById(id: string): Promise<Blueprint> {
return this.send("GET", `/blueprint/api/blueprints/${id}`)
}
async getBlueprintByName(name: string): Promise<Blueprint | undefined> {
const blueprints: PagedResult<Blueprint> = await this.send("GET", `/blueprint/api/blueprints?name=${name}`)
return (await this.unwrapPages(blueprints, ""))[0]
}
async getBlueprints(): Promise<Blueprint[]> {
const blueprints: PagedResult<Blueprint> = await this.send("GET", "/blueprint/api/blueprints")
return this.unwrapPages(blueprints, "/blueprint/api/blueprints")
}
async createBlueprint(body: {
name: string
projectId: string
content: string
description: string
}): Promise<any> {
return this.send("POST", "/blueprint/api/blueprints", { body })
}
async updateBlueprint(
id: string,
body: { name: string; projectId: string; content: string; description: string }
): Promise<void> {
return this.send("PUT", `/blueprint/api/blueprints/${id}`, { body })
}
async deployBlueprint(body: {
deploymentName: string
projectId: string
blueprintId?: string
content?: string
inputs?: Record<string, unknown>
}): Promise<Deployment> {
return this.send("POST", "/blueprint/api/blueprint-requests", { body })
}
async getProjects(): Promise<Project[]> {
const projects: { content: Project[] } = await this.send("GET", "/iaas/api/projects")
return projects.content
}
}