-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathenvironment-accessor.ts
353 lines (318 loc) · 10.1 KB
/
environment-accessor.ts
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { createLogger, ErrorWithCause, first } from '@sap-cloud-sdk/util';
import * as xsenv from '@sap/xsenv';
import { audiences, DecodedJWT, decodeJwt } from './jwt';
import {
DestinationServiceCredentials,
Service,
ServiceCredentials,
XsuaaServiceCredentials
} from './environment-accessor-types';
import { ClientCredentials } from './xsuaa-service-types';
const logger = createLogger({
package: 'core',
messageContext: 'environment-accessor'
});
/**
* Basic Credentials Getter from Destination service credentials needed for JWT generator.
*
* @returns Basic credentials.
*/
export function getDestinationBasicCredentials(): BasicCredentials {
const destinationCredentials = getDestinationServiceCredentials();
const basicCredentials: BasicCredentials = {
clientid: destinationCredentials.clientid
? destinationCredentials.clientid
: null,
clientsecret: destinationCredentials.clientsecret
? destinationCredentials.clientsecret
: null
};
return basicCredentials;
}
/**
* First 'destination' credentials getter.
*
* @returns The 'destination' credentials object or null if it does not exist.
*/
export function getDestinationServiceCredentials(): any {
return first(getDestinationServiceCredentialsList());
}
/**
* Destination credentials getter.
*
* @returns A list of 'credentials' objects in 'destination' service.
*/
export function getDestinationServiceCredentialsList(): DestinationServiceCredentials[] {
return getServiceList('destination').map(
s => s.credentials as DestinationServiceCredentials
);
}
/**
* Credentials list getter for a given service.
*
* @param service - Service name
* @returns Fetched credentials objects of existing service in 'VCAP_SERVICES'.
*/
export function getServiceCredentialsList(service: string): any[] {
const credentials: any[] = [];
getServiceList(service).forEach(entry => {
if ('credentials' in entry) {
credentials.push(entry['credentials']);
} else {
logger.warn(
`Skipping a service in ${service}. Object has no 'credentials'.`
);
}
});
return credentials;
}
/**
* Services getter for a given service.
*
* @param service - Service name.
* @returns List of service bindings of the given type. Returns an empty array if no service binding exists for the given type.
*/
export function getServiceList(service: string): Service[] {
return xsenv.filterServices({ label: service }); // TODO: how do we allow propagating custom secret paths for k8s?
}
/**
* Returns the first found instance for the given service type.
*
* @param service - The service type.
* @returns The first found service.
*/
export function getService(service: string): Service | undefined {
const services = xsenv.filterServices({ label: service }) as Service[];
if (!services.length) {
logger.warn(
`No services of type ${service} found! This might cause errors in other parts of the application.`
);
return undefined;
}
if (services.length > 1) {
logger.warn(
`Found more than one service instance for service type ${service}. Found: ${services
.map(s => s.name)
.join(', ')}. Selecting the first one.`
);
}
return services[0];
}
/**
* Get destination service if one is present.
*
* @returns Destination service
* @throws Error in case no destination service is found in the VCAP variables
*/
export function getDestinationService() {
const destinationService = getService('destination');
if (!destinationService) {
throw Error('No binding to a destination service found.');
}
return destinationService;
}
/**
* 'VCAP_SERVICES' Getter from environment variables.
* This function returns the VCAP_SERVICES as object or null if it is not defined (i.e. no services are bound to the application).
*
* @returns 'VCAP_SERVICES' found in environment variables or null if not defined. The key denotes the name ov the service and the value is the definition.
*/
export function getVcapService(): Record<string, any> | null {
const env = getEnvironmentVariable('VCAP_SERVICES');
let vcapServices: Record<string, any>;
if (!env) {
logger.warn("Environment variable 'VCAP_SERVICES' is not defined.");
return null;
}
try {
vcapServices = JSON.parse(env);
} catch (error) {
throw new ErrorWithCause(
"Failed to parse environment variable 'VCAP_SERVICES'.",
error
);
}
if (!Object.keys(vcapServices).length) {
throw new Error(
"Environment variable 'VCAP_SERVICES' is defined but empty. This should not happen."
);
}
return vcapServices;
}
/**
* Environment variables accessor.
*
* @param name - Environment variable name.
* @returns Env variable value if defined.
* null: If not defined.
*/
export function getEnvironmentVariable(
name: string
): string | undefined | null {
if (process.env[name]) {
return process.env[name];
}
logger.info('Environment variable ' + name + ' is not defined.');
return null;
}
/**
* Destination URI getter
* NOTICE: If there exist more than one destination/uri, the function
* returns the first entry.
*
* @returns The first existing uri in destination or null if not found.
*/
export function getDestinationServiceUri(): string | null {
const destinationServiceCredentials = getDestinationServiceCredentialsList();
const uris: string[] = [];
for (const credential of destinationServiceCredentials) {
if ('uri' in credential) {
uris.push(credential['uri']);
} else {
logger.info(
"Skipping credentials in 'destination'. 'uri' property not defined"
);
}
}
return uris[0] || null;
}
/**
* Takes a decoded JWT and uses the client_id and audience claims to determine the XSUAA service instance
* that issued the JWT. Returns the credentials if a match is found, otherwise throws an error.
* If no decoded JWT is specified, then returns the first existing XSUAA credential service plan "application".
*
* @param token - Either an encoded or decoded JWT.
* @returns The credentials for a match, otherwise null.
*/
export function getXsuaaServiceCredentials(
token?: DecodedJWT | string
): XsuaaServiceCredentials {
if (typeof token === 'string') {
return getXsuaaServiceCredentials(decodeJwt(token)); // Decode without verifying
}
return selectXsuaaInstance(token);
}
/**
* Takes a string that represents the service type and resolves it by calling [[getService]].
* If the parameter is already an instance of [[Service]], it is returned directly.
*
* Throws an error when no service can be found for the given type.
*
* @param service - A string representing the service type or a [[Service]] instance.
* @returns A [[Service]] instance.
*/
export function resolveService(service: string | Service): Service {
if (typeof service === 'string') {
const serviceInstance = getService(service);
if (!serviceInstance) {
throw Error(
`Unable to get access token for "${service}" service! No service instance of type "${service}" found.`
);
}
return serviceInstance;
}
return service;
}
/**
* Extracts the credentials of a service into an instance of [[ClientCredentials]].
*
* @param serviceCreds - The credentials of a service as read from VCAP_SERVICES.
* @returns A [[ClientCredentials]] instance.
*/
export function extractClientCredentials(
serviceCreds: ServiceCredentials
): ClientCredentials {
return {
username: serviceCreds.clientid,
password: serviceCreds.clientsecret
};
}
function selectXsuaaInstance(token?: DecodedJWT): XsuaaServiceCredentials {
const xsuaaInstances = getServiceList('xsuaa');
if (!xsuaaInstances.length) {
throw Error(
'No binding to an XSUAA service instance found. Please make sure to bind an instance of the XSUAA service to your application!'
);
}
const strategies = [matchingClientId, matchingAudience, takeFirstAndWarn];
const selected = applyStrategiesInOrder(strategies, xsuaaInstances, token);
if (selected.length === 0) {
throw Error('No XSUAA instances are found from the given JWT.');
}
if (selected.length > 1) {
logger.warn(
`Multiple XSUAA instances could be matched to the given JWT! Choosing the first one (xsappname: ${
first(selected)!.credentials.xsappname
}).`
);
}
return first(selected)!.credentials;
}
function applyStrategiesInOrder(
selectionStrategies: SelectionStrategyFn[],
xsuaaInstances: Record<string, any>[],
token?: DecodedJWT
): Record<string, any>[] {
return selectionStrategies.reduce(
(result, strategy) =>
result.length ? result : strategy(xsuaaInstances, token),
[]
);
}
type SelectionStrategyFn = (
xsuaaInstances: Record<string, any>[],
token?: DecodedJWT
) => Record<string, any>[];
function matchingClientId(
xsuaaInstances: Record<string, any>[],
token?: DecodedJWT
): Record<string, any>[] {
if (!token) {
return [];
}
return xsuaaInstances.filter(
xsuaa => xsuaa.credentials.clientid === token.client_id
);
}
function matchingAudience(
xsuaaInstances: Record<string, any>[],
token?: DecodedJWT
): Record<string, any>[] {
if (!token) {
return [];
}
return xsuaaInstances.filter(xsuaa =>
audiences(token).has(xsuaa.credentials.xsappname)
);
}
function takeFirstAndWarn(
xsuaaInstances: Record<string, any>[],
token?: DecodedJWT
): Record<string, any>[] {
logger.warn(
`Unable to match a specific XSUAA service instance to the given JWT. The following XSUAA instances are bound: ${xsuaaInstances.map(
x => x.credentials.xsappname
)}. The following one will be selected: ${
xsuaaInstances[0].credentials.xsappname
}. This might produce errors in other parts of the system!`
);
return xsuaaInstances.slice(0, 1);
}
interface BasicCredentials {
clientid: string;
clientsecret: string;
}
/**
* @deprecated Since v1.5.0. Use directly exported functions instead
*/
export const EnvironmentAccessor = {
getDestinationBasicCredentials,
getDestinationServiceCredentials,
getDestinationServiceCredentialsList,
getServiceCredentialsList,
getServiceList,
getVcapService,
getEnvironmentVariable,
getDestinationServiceUri,
getXsuaaServiceCredentials
};