-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
75 lines (65 loc) · 2.66 KB
/
Copy pathlambda_function.py
File metadata and controls
75 lines (65 loc) · 2.66 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
import json
import boto3
import requests
from datetime import datetime, timezone
from google.oauth2 import service_account
from google.auth.transport.requests import Request
def lambda_handler(event, context):
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'POST,OPTIONS'
}
method = event.get('requestContext', {}).get('http', {}).get('method', '')
if method == 'OPTIONS':
return {'statusCode': 200, 'headers': headers, 'body': ''}
try:
body = json.loads(event.get('body', '{}'))
secrets = boto3.client('secretsmanager', region_name='us-east-1')
secret_value = secrets.get_secret_value(SecretId='gcp-service-account-key')
secret_dict = json.loads(secret_value['SecretString'])
gcp_creds = json.loads(secret_dict['gcp_credentials'])
credentials = service_account.Credentials.from_service_account_info(
gcp_creds,
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
credentials.refresh(Request())
timestamp = datetime.now(timezone.utc).isoformat()
blob_name = f'logs/{datetime.now(timezone.utc).strftime("%Y/%m/%d")}/{context.aws_request_id}.json'
log_entry = {
'timestamp': timestamp,
'source_cloud': 'aws',
'source_service': 'lambda',
'source_region': 'us-east-1',
'event_type': body.get('event_type', 'form_submission'),
'payload': body
}
bucket = 'cross-cloud-audit-logs-bj'
upload_url = f'https://storage.googleapis.com/upload/storage/v1/b/{bucket}/o'
response = requests.post(
upload_url,
params={'uploadType': 'media', 'name': blob_name},
headers={
'Authorization': f'Bearer {credentials.token}',
'Content-Type': 'application/json'
},
data=json.dumps(log_entry, indent=2)
)
if response.status_code not in (200, 201):
raise Exception(f'GCS upload failed: {response.status_code} {response.text}')
return {
'statusCode': 200,
'headers': headers,
'body': json.dumps({
'message': 'Audit log written successfully',
'log_path': f'gs://{bucket}/{blob_name}',
'written_from': 'AWS Lambda',
'destination': 'Google Cloud Storage'
})
}
except Exception as e:
return {
'statusCode': 500,
'headers': headers,
'body': json.dumps({'error': str(e)})
}