-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappstream-sc-service.js
285 lines (247 loc) · 10.1 KB
/
appstream-sc-service.js
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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
const crypto = require('crypto');
const _ = require('lodash');
const Service = require('@amzn/base-services-container/lib/service');
const ENABLE_PASSWORD_SHARE = false;
const settingKeys = {
enableAmiSharing: 'enableAmiSharing',
devopsRoleArn: 'devopsRoleArn',
devopsRoleExternalId: 'devopsRoleExternalId',
};
class AppStreamScService extends Service {
constructor() {
super();
this.dependency([
'auditWriterService',
'aws',
'awsAccountsService',
'environmentScKeypairService',
'environmentScService',
'indexesService',
]);
}
async init() {
await super.init();
}
async shareAppStreamImageWithAccount(requestContext, accountId, appStreamImageName) {
const appStream = await this.getAppStream();
const result = await appStream
.updateImagePermissions({
ImagePermissions: {
allowFleet: true,
allowImageBuilder: false,
},
Name: appStreamImageName,
SharedAccountId: accountId,
})
.promise();
// Write audit event
await this.audit(requestContext, { action: 'share-appstream-image-with-account', body: { accountId } });
return result;
}
async getStackAndFleet(requestContext, { environmentId, indexId }) {
const [environmentScService, awsAccountsService, indexesService] = await this.service([
'environmentScService',
'awsAccountsService',
'indexesService',
]);
// Find stack
const { awsAccountId } = await indexesService.mustFind(requestContext, { id: indexId });
const {
appStreamStackName: stackName,
accountId,
appStreamFleetName: fleetName,
} = await awsAccountsService.mustFind(requestContext, {
id: awsAccountId,
});
if (!stackName) {
throw this.boom.badRequest(`No AppStream stack is associated with the account ${accountId}`, true);
}
// Verify fleet is associated to appstream stack
const appStream = await environmentScService.getClientSdkWithEnvMgmtRole(
requestContext,
{ id: environmentId },
{ clientName: 'AppStream', options: { signatureVersion: 'v4' } },
);
const { Names: fleetNames } = await appStream.listAssociatedFleets({ StackName: stackName }).promise();
if (!_.includes(fleetNames, fleetName)) {
throw this.boom.badRequest(
`AppStream Fleet ${fleetName} is not associated with the AppStream stack ${stackName}`,
true,
);
}
return { stackName, fleetName };
}
generateSessionSuffix(environment) {
// Generate a unique session suffix for the environment as a 6 character alphanumeric string
// This is random looking but string but is deterministic so can be derived from the environment
return (new Date(environment.createdAt).getTime() % 36 ** 6).toString(36);
}
generateUserId(requestContext, environment) {
// UserId must match [\w+=,.@-]* with max length 32
// Don't let the username be too long (otherwise the user won't be able to open multiple sessions)
const uid = _.get(requestContext, 'principalIdentifier.uid');
// Append a unique session suffix to the user id, this user id is used for creating unique AppStream session
// appending suffix to make sure a unique session is created per environment per user
const sessionSuffix = this.generateSessionSuffix(environment);
return `${uid}-${sessionSuffix}`.replace(/[^\w+=,.@-]+/g, '').slice(0, 32);
}
async getStreamingUrl(requestContext, { environmentId, applicationId, sessionContext }) {
const environmentScService = await this.service('environmentScService');
const appStream = await environmentScService.getClientSdkWithEnvMgmtRole(
requestContext,
{ id: environmentId },
{ clientName: 'AppStream', options: { signatureVersion: 'v4' } },
);
const environment = await environmentScService.mustFind(requestContext, { id: environmentId });
const { stackName, fleetName } = await this.getStackAndFleet(requestContext, {
environmentId,
indexId: environment.indexId,
});
let result = {};
try {
result = await appStream
.createStreamingURL({
FleetName: fleetName,
StackName: stackName,
UserId: this.generateUserId(requestContext, environment),
ApplicationId: applicationId,
SessionContext: sessionContext,
})
.promise();
} catch (err) {
throw this.boom.badRequest('There was an error generating AppStream URL', true);
}
// Write audit event
await this.audit(requestContext, { action: 'appstream-firefox-app-url-requested', body: { environmentId } });
return result.StreamingURL;
}
async urlForRemoteDesktop(requestContext, { environmentId, instanceId }) {
const [environmentScService, environmentScKeypairService] = await this.service([
'environmentScService',
'environmentScKeypairService',
]);
const environment = await environmentScService.mustFind(requestContext, { id: environmentId });
const connectionScheme = environment.outputs.filter(output =>
output.OutputValue === 'customrdp' || output.OutputValue === 'rdp' ? output.OutputValue : undefined,
);
// Get stack and fleet
const { stackName, fleetName } = await this.getStackAndFleet(requestContext, {
environmentId,
indexId: environment.indexId,
});
// Generate AppStream URL
const appStream = await environmentScService.getClientSdkWithEnvMgmtRole(
requestContext,
{ id: environmentId },
{ clientName: 'AppStream', options: { signatureVersion: 'v4' } },
);
const ec2 = await environmentScService.getClientSdkWithEnvMgmtRole(
requestContext,
{ id: environmentId },
{ clientName: 'EC2', options: { apiVersion: '2016-11-15' } },
);
const data = await ec2.describeInstances({ InstanceIds: [instanceId] }).promise();
const instanceInfo = _.get(data, 'Reservations[0].Instances[0]');
const networkInterfaces = _.get(instanceInfo, 'NetworkInterfaces') || [];
const privateIp = _.get(networkInterfaces[0], 'PrivateIpAddress');
const userId = this.generateUserId(requestContext, environment);
this.log.info({ msg: `Creating AppStream URL`, appStreamSessionUid: userId });
let sessionContext;
if (connectionScheme && connectionScheme[0].OutputValue === 'rdp') {
sessionContext = `${privateIp},Administrator,rdp`;
if (ENABLE_PASSWORD_SHARE) {
const { PasswordData: passwordData } = await ec2.getPasswordData({ InstanceId: instanceId }).promise();
const { privateKey } = await environmentScKeypairService.mustFind(requestContext, environmentId);
const password = crypto
.privateDecrypt(
{ key: privateKey, padding: crypto.constants.RSA_PKCS1_PADDING },
Buffer.from(passwordData, 'base64'),
)
.toString('utf8');
// Write audit event
await this.audit(requestContext, {
action: 'env-windows-password-requested',
body: { id: environmentId, instanceId },
});
sessionContext = `${sessionContext},${password}`;
}
} else if (connectionScheme && connectionScheme[0].OutputValue === 'customrdp') {
sessionContext = `${privateIp},ec2-user,customrdp`;
sessionContext = ENABLE_PASSWORD_SHARE ? `${sessionContext},${instanceId}` : sessionContext;
} else {
sessionContext = privateIp;
}
let result = {};
try {
result = await appStream
.createStreamingURL({
FleetName: fleetName,
StackName: stackName,
UserId: userId,
ApplicationId: 'remmina-client',
SessionContext: sessionContext,
})
.promise();
} catch (err) {
throw this.boom.badRequest('There was an error generating AppStream URL', true);
}
// Write audit event
await this.audit(requestContext, { action: 'appstream-remote-desktop-app-url-requested', body: { environmentId } });
return result.StreamingURL;
}
async audit(requestContext, auditEvent) {
const auditWriterService = await this.service('auditWriterService');
// Calling "writeAndForget" instead of "write" to allow main call to continue without waiting for audit logging
// and not fail main call if audit writing fails for some reason
// If the main call also needs to fail in case writing to any audit destination fails then switch to "write" method as follows
// return auditWriterService.write(requestContext, auditEvent);
return auditWriterService.writeAndForget(requestContext, auditEvent);
}
async getAWS() {
const aws = await this.service('aws');
return aws;
}
async getAppStream() {
const aws = await this.getAWS();
const isAmiSharingEnabled = this.checkIfAmiSharingEnabled();
let appstreamClient;
// Get Devops account client if AMI sharing enabled.
if (isAmiSharingEnabled) {
this.log.info(`AMI Sharing enabled. Reading SDK using DevOps account role`);
const { roleArn, externalId } = this.getDevopsAccountDetails();
appstreamClient = await aws.getClientSdkForRole({
roleArn,
clientName: 'AppStream',
options: { apiVersion: '2016-12-01' },
externalId,
});
} else {
appstreamClient = await new aws.sdk.AppStream();
}
return appstreamClient;
}
getDevopsAccountDetails() {
return {
roleArn: this.settings.get(settingKeys.devopsRoleArn),
externalId: this.settings.get(settingKeys.devopsRoleExternalId),
};
}
checkIfAmiSharingEnabled() {
return this.settings.getBoolean(settingKeys.enableAmiSharing);
}
}
module.exports = AppStreamScService;