-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-resources.yaml
578 lines (524 loc) · 21.1 KB
/
aws-resources.yaml
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
AWSTemplateFormatVersion: '2010-09-09'
Description: Q Business using Identity Federation with Cognito Stack
Resources:
UserPool:
Type: "AWS::Cognito::UserPool"
Properties:
UserPoolName: !Sub "${AWS::StackName}-user-pool"
UsernameConfiguration:
CaseSensitive: true
AutoVerifiedAttributes:
- email
MfaConfiguration: "OFF"
UserPoolAddOns:
AdvancedSecurityMode: "AUDIT"
LambdaConfig:
PreTokenGenerationConfig:
LambdaArn: !GetAtt LambdaTriggerFunction.Arn
LambdaVersion: "V2_0"
AdminCreateUserConfig:
AllowAdminCreateUserOnly: true
Schema:
- Name: email
AttributeDataType: String
Mutable: false
Required: true
UserPoolDomain:
Type: "AWS::Cognito::UserPoolDomain"
Properties:
UserPoolId: !Ref UserPool
Domain: !Join
- ""
- - !Select [0, !Split ["-", !Select [2, !Split ["/", !Ref "AWS::StackId"]]]]
- !Select [1, !Split ["-", !Select [2, !Split ["/", !Ref "AWS::StackId"]]]]
- !Select [2, !Split ["-", !Select [2, !Split ["/", !Ref "AWS::StackId"]]]]
UserPoolClient:
Type: "AWS::Cognito::UserPoolClient"
Properties:
ClientName: !Sub "${AWS::StackName}-client"
UserPoolId: !Ref UserPool
GenerateSecret: true
IdentityPool:
Type: "AWS::Cognito::IdentityPool"
Properties:
IdentityPoolName: !Sub "${AWS::StackName}-identity-pool"
AllowClassicFlow: true
AllowUnauthenticatedIdentities: false
CognitoIdentityProviders:
- ClientId: !Ref UserPoolClient
ProviderName: !GetAtt UserPool.ProviderName
IdentityPoolRoleMapping:
Type: "AWS::Cognito::IdentityPoolRoleAttachment"
Properties:
IdentityPoolId: !Ref IdentityPool
Roles:
authenticated: !GetAtt CognitoAuthorizedRole.Arn
IdentityPoolPrincipalTag:
Type: "AWS::Cognito::IdentityPoolPrincipalTag"
Properties:
IdentityPoolId: !Ref IdentityPool
IdentityProviderName: !Select [1, !Split ["oidc-provider/", !GetAtt IDPOIDCProvider.Arn]]
PrincipalTags:
Email: "email"
UseDefaults: false
IDPOIDCProvider:
Type: 'AWS::IAM::OIDCProvider'
Properties:
Url: !Select [0, !Split ["/.well-known/jwks.json", !GetAtt UserPool.ProviderURL]]
ClientIdList:
- !GetAtt UserPoolClient.ClientId
CognitoAuthorizedRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Federated: "cognito-identity.amazonaws.com"
Action:
- "sts:AssumeRoleWithWebIdentity"
- "sts:TagSession"
Condition:
StringEquals:
"cognito-identity.amazonaws.com:aud": !Ref IdentityPool
"ForAnyValue:StringLike":
"cognito-identity.amazonaws.com:amr": authenticated
Policies:
- PolicyName: "CognitoAuthorizedPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "cognito-identity:GetCredentialsForIdentity"
Resource: "*"
LambdaTriggerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: AppendToLogsPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
LambdaInvokePermission:
Type: 'AWS::Lambda::Permission'
Properties:
FunctionName: !GetAtt LambdaTriggerFunction.Arn
Action: 'lambda:InvokeFunction'
Principal: cognito-idp.amazonaws.com
SourceArn: !GetAtt UserPool.Arn
LambdaTriggerFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt LambdaTriggerRole.Arn
Code:
ZipFile: |
def handler(event, context):
email = event['request']['userAttributes']['email']
sub = event['request']['userAttributes']['sub']
# Create the JSON object
tags_object = {
"principal_tags": {
"Email": [email]
}
}
claims = {}
claims["https://aws.amazon.com/tags"] = tags_object
event['response'] = {
"claimsAndScopeOverrideDetails": {
"idTokenGeneration": {
"claimsToAddOrOverride": claims
}
}
}
return event
QBusinessApplication:
Type: 'AWS::QBusiness::Application'
Properties:
DisplayName: !Sub "${AWS::StackName}-qbusiness-app"
IdentityType: "AWS_IAM_IDP_OIDC"
IamIdentityProviderArn: !GetAtt IDPOIDCProvider.Arn
ClientIdsForOIDC:
- !GetAtt UserPoolClient.ClientId
AutoSubscriptionConfiguration:
AutoSubscribe: "ENABLED"
DefaultSubscriptionType: "Q_BUSINESS"
QBusinessRetriever:
Type: 'AWS::QBusiness::Retriever'
Properties:
ApplicationId: !GetAtt QBusinessApplication.ApplicationId
DisplayName: !Sub "${AWS::StackName}-qbusiness-retriever"
Type: "NATIVE_INDEX"
Configuration:
NativeIndexConfiguration:
IndexId: !GetAtt QBusinessIndex.IndexId
QBusinessIndex:
Type: 'AWS::QBusiness::Index'
Properties:
ApplicationId: !GetAtt QBusinessApplication.ApplicationId
DisplayName: !Sub "${AWS::StackName}-qbusiness-index"
Type: "ENTERPRISE"
QBusinessWebExperience:
Type: 'AWS::QBusiness::WebExperience'
Properties:
ApplicationId: !GetAtt QBusinessApplication.ApplicationId
RoleArn: !GetAtt QBusinessWebExperienceRole.Arn
IdentityProviderConfiguration:
OpenIDConnectConfiguration:
SecretsArn : !GetAtt QBusinessOIDCClientSecret.Id
SecretsRole : !GetAtt QBusinessSecretsRole.Arn
QBusinessWebExperienceRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Federated: !GetAtt IDPOIDCProvider.Arn
Action:
- "sts:AssumeRoleWithWebIdentity"
- Effect: "Allow"
Principal:
Federated: !GetAtt IDPOIDCProvider.Arn
Action:
- "sts:TagSession"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AdministratorAccess"
QBusinessSecretsRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "application.qbusiness.amazonaws.com"
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AdministratorAccess"
QBusinessOIDCClientSecret:
Type: 'AWS::SecretsManager::Secret'
Properties:
Name: !Sub "${AWS::StackName}-client-secret"
SecretString: !Sub '{"client_secret": "dummyvalue"}'
UpdateOIDCDetailsCustom:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt UpdateOIDCDetailsLambdaFunction.Arn
UpdateOIDCDetailsLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: UpdateOIDCDetailsLambdaPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- cognito-idp:DescribeUserPoolClient
- cognito-idp:UpdateUserPoolClient
- secretsmanager:PutSecretValue
- secretsmanager:GetSecretValue
Resource: "*"
UpdateOIDCDetailsLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Description: Update OIDC callback URL and client secret
Handler: index.handler
Runtime: python3.12
Role: !GetAtt 'UpdateOIDCDetailsLambdaRole.Arn'
Timeout: 10
Environment:
Variables:
userPoolId: !GetAtt UserPool.UserPoolId
userPoolClientId: !GetAtt UserPoolClient.ClientId
callbackUrl: !Sub "${QBusinessWebExperience.DefaultEndpoint}authorization-code/callback"
secretArn: !GetAtt QBusinessOIDCClientSecret.Id
Code:
ZipFile: |
from __future__ import print_function
import os
import json
import boto3
import urllib3
SUCCESS = 'SUCCESS'
FAILED = 'FAILED'
http = urllib3.PoolManager()
def handler(event, context):
print('handler() received event: ' + json.dumps(event))
status = FAILED
data = {}
try:
if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
update_oidc_details()
status = SUCCESS
elif event['RequestType'] == 'Delete':
print('deletion of CloudFormation stack has no impact on updating OIDC details')
status = SUCCESS
except Exception as e:
print('handler error: ' + str(e))
status = FAILED
send(event, context, status, data)
return
def update_oidc_details():
userPoolId = os.environ.get('userPoolId')
userPoolClientId = os.environ.get('userPoolClientId')
callbackUrl = os.environ.get('callbackUrl')
secretArn = os.environ.get('secretArn')
cognito_client = boto3.client('cognito-idp')
secrets_manager = boto3.client('secretsmanager')
response = cognito_client.describe_user_pool_client(
UserPoolId=userPoolId,
ClientId=userPoolClientId
)
client_secret = response['UserPoolClient'].get('ClientSecret')
secrets_manager.put_secret_value(
SecretId=secretArn,
SecretString=json.dumps({'client_secret': client_secret})
)
print("Secret updated successfully in Secrets Manager")
update_params = {
'UserPoolId': userPoolId,
'ClientId': userPoolClientId,
'PreventUserExistenceErrors': 'ENABLED',
'AllowedOAuthFlowsUserPoolClient': True,
'AllowedOAuthFlows': ['code'],
'AllowedOAuthScopes': ['email', 'openid'],
'SupportedIdentityProviders': ['COGNITO'],
'ExplicitAuthFlows': ['ALLOW_REFRESH_TOKEN_AUTH', 'ALLOW_USER_SRP_AUTH', 'ALLOW_USER_PASSWORD_AUTH'],
'CallbackURLs': [callbackUrl]
}
cognito_client.update_user_pool_client(**update_params)
print("Callback URL updated successfully")
return
def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=None):
responseUrl = event['ResponseURL']
print('responseUrl: ' + responseUrl)
responseBody = {
'Status' : responseStatus,
'Reason' : reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name),
'PhysicalResourceId' : physicalResourceId or context.log_stream_name,
'StackId' : event['StackId'],
'RequestId' : event['RequestId'],
'LogicalResourceId' : event['LogicalResourceId'],
'NoEcho' : noEcho,
'Data' : responseData
}
json_responseBody = json.dumps(responseBody)
print("Response body:")
print(json_responseBody)
headers = {
'content-type' : '',
'content-length' : str(len(json_responseBody))
}
try:
response = http.request('PUT', responseUrl, headers=headers, body=json_responseBody)
print("Status code:", response.status)
except Exception as e:
print("send(..) failed executing http.request(..):", e)
ChatPromptingCredentials:
Type: 'AWS::SecretsManager::Secret'
Properties:
Name: !Sub "${AWS::StackName}-chat-user"
SecretString: !Sub '{"username": "dummyvalue", "password": "dummyvalue"}'
ChatPromptingFunction:
Type: AWS::Lambda::Function
DependsOn: UpdateOIDCDetailsCustom
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt ChatPromptingRole.Arn
Timeout: 10
Environment:
Variables:
COGNITO_DOMAIN: !Sub "${UserPoolDomain}.auth.${AWS::Region}.amazoncognito.com"
COGNITO_CLIENT_ID: !GetAtt UserPoolClient.ClientId
COGNITO_CLIENT_SECRET: !Join
- ''
- - '{{resolve:secretsmanager:'
- !Ref QBusinessOIDCClientSecret
- ':SecretString:client_secret}}'
COGNITO_IDENTITY_POOL_ID: !Ref IdentityPool
COGNITO_USER_POOL_ID: !GetAtt UserPool.UserPoolId
QBUSINESS_APPLICATION_ID: !GetAtt QBusinessApplication.ApplicationId
QBUSINESS_WEB_EXPERIENCE_ROLE: !GetAtt QBusinessWebExperienceRole.Arn
CHAT_PROMPTING_CREDENTIALS_ID: !GetAtt ChatPromptingCredentials.Id
Code:
ZipFile: |
import os
import json
import hmac
import base64
import hashlib
import boto3
from botocore.exceptions import ClientError
# Set up your Cognito OIDC details
cognito_domain = os.environ['COGNITO_DOMAIN']
cognito_client_id = os.environ['COGNITO_CLIENT_ID']
cognito_client_secret = os.environ['COGNITO_CLIENT_SECRET']
cognito_identity_pool_id = os.environ['COGNITO_IDENTITY_POOL_ID']
cognito_user_pool_id = os.environ['COGNITO_USER_POOL_ID']
qbusiness_application_id = os.environ['QBUSINESS_APPLICATION_ID']
qbusiness_web_experience_role = os.environ['QBUSINESS_WEB_EXPERIENCE_ROLE']
user_credentials_id = os.environ['CHAT_PROMPTING_CREDENTIALS_ID']
# Extract region from the Cognito domain
cognito_region = cognito_domain.split('.')[2]
def handler(event, context):
print("Starting lambda handler")
try:
print("Attempting to get secret")
username, password = get_secret()
print(f"Secret retrieved successfully for username: {username}")
print("Attempting to get Cognito credentials")
credentials = get_cognito_credentials(username, password)
print("Cognito credentials retrieved successfully")
print("Attempting to call Q Business ChatSync")
response = call_qbusiness_chat_sync(credentials)
print("Q Business ChatSync returned successfully: " + response)
print("Preparing successful response")
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Authentication & Prompting successful',
'response': response
})
}
except Exception as e:
print(f"Error in lambda_handler: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps({
'error': str(e)
})
}
def get_secret():
session = boto3.session.Session()
client = session.client(service_name='secretsmanager')
try:
get_secret_value_response = client.get_secret_value(SecretId=user_credentials_id)
except ClientError as e:
raise Exception(f"Failed to retrieve secret: {str(e)}")
else:
if 'SecretString' in get_secret_value_response:
secret = json.loads(get_secret_value_response['SecretString'])
return secret['username'], secret['password']
else:
raise Exception("Secret is not a string")
def get_cognito_credentials(username, password):
print("Starting get_cognito_credentials")
cognito_idp_client = boto3.client('cognito-idp')
cognito_identity_client = boto3.client('cognito-identity')
sts_client = boto3.client('sts')
# Calculate SECRET_HASH
message = username + cognito_client_id
dig = hmac.new(cognito_client_secret.encode('utf-8'),
msg=message.encode('utf-8'),
digestmod=hashlib.sha256).digest()
secret_hash = base64.b64encode(dig).decode()
try:
# Authenticate with Cognito User Pool
auth_response = cognito_idp_client.initiate_auth(
ClientId=cognito_client_id,
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': username,
'PASSWORD': password,
'SECRET_HASH': secret_hash
}
)
id_token = auth_response['AuthenticationResult']['IdToken']
# Get Identity ID
get_id_response = cognito_identity_client.get_id(
IdentityPoolId=cognito_identity_pool_id,
Logins={
f'cognito-idp.{cognito_region}.amazonaws.com/{cognito_user_pool_id}': id_token
}
)
identity_id = get_id_response['IdentityId']
# AssumeRoleWithWebIdentity
assumed_role_response = sts_client.assume_role_with_web_identity(
RoleArn=qbusiness_web_experience_role,
RoleSessionName="WebExperienceSession",
WebIdentityToken=id_token
)
print("Cognito tokens and credentials retrieved successfully")
return assumed_role_response['Credentials']
except Exception as e:
print(f"Error getting Cognito tokens and credentials: {str(e)}")
raise
def call_qbusiness_chat_sync(credentials):
print("Starting call_qbusiness_chat_sync")
qbusiness_client = boto3.client('qbusiness',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken'])
try:
chat_sync_response = qbusiness_client.chat_sync(applicationId=qbusiness_application_id,
userMessage='What is AWS?')
print("response:" + str(chat_sync_response))
return chat_sync_response['systemMessage']
except ClientError as e:
print(f"Error calling Q Business ChatSync: {str(e)}")
raise Exception(f"Failed to call Q Business ChatSync: {str(e)}")
ChatPromptingRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: TestPromptingPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- secretsmanager:GetSecretValue
- cognito-idp:InitiateAuth
- cognito-idp:AdminInitiateAuth
- cognito-idp:AdminGetUser
- cognito-identity:GetId
- cognito-identity:GetCredentialsForIdentity
- qbusiness:ChatSync
Resource: '*'