Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New serverless pattern - okta-eventbridge-lambda #2573

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions eventbridge-partner-sources/1-okta/cdk-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Okta Amazon EventBridge Partner Integration to AWS Lambda

This pattern demonstrates how to use the Okta Amazon EventBridge integration and AWS Lambda to process events from Okta. This pattern is leveraging the Okta Amazon EventBridge integration to send Okta System Log events from the customer's Okta account to their AWS account, via an Amazon EventBridge Partner event bus. Once the Okta events are in the customer's account, an Amazon EventBridge rule routes unusual location user login events to a downstream Lambda function. In production cases, the Lambda function could transform the event, send it to a downstream application, archive it in a warehouse service, or send a notification email to a customer using SES. Amazon CloudWatch Log Groups are provisioned for debugging and auditing. This pattern deploys two EventBridge rules, one Lambda function, and two CloudWatch Log Groups.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/okta-eventbridge-lambda

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS CDK CLI](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) (AWS CDK) installed
* [Create an Okta Organization](https://www.okta.com/okta-advantage/?utm_source=google&utm_campaign=amer_mult_usa_all_wf-all_dg-ao_a-wf_search_google_text_kw_workforce-OktaBrand-exact_utm2&utm_medium=cpc&utm_id=aNK4z0000004DlbGAE&utm_term=okta&utm_page={url}&utm_content=679261513163&gad_source=1&gclid=CjwKCAjwnK60BhA9EiwAmpHZwy2ms0vms2fFPJZr0aECIlwkSs6Qs3U03pzFghn_wajg7chitFT1cRoCRKwQAvD_BwE) if you do not already have one and log in.
* [Set up the Okta Amazon EventBridge integration](https://help.okta.com/en-us/content/topics/reports/log-streaming/add-aws-eb-log-stream.htm) if you have not already configured the integration.


## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```
cd eventbridge-partner-sources/1-okta/cdk-python
```
3. From the command line, use AWS CDK to deploy the AWS resources for the pattern as specified in the app.py file. A command-line argument is needed to deploy the CDK stack, "oktaEventBusName". This argument is the name of the **SaaS event bus** associated with your Okta [partner event source](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-saas.html).
```
cdk deploy --parameters oktaEventBusName=SAAS_EVENT_BUS_NAME_HERE
```

4. Note the outputs from the CDK deployment process. These contain the resource names and/or ARNs which are used for testing. This stack will output the name of the Lambda function deployed for testing to the CLI. See the example below.

```
Outputs:
OktaIntegrationStack.OktaProcessUserLoginUnusualLocationLambdaOutput = OktaIntegrationStack-OktaProcessUserLoginUnusualLocationLambd....
```

## How it works

This service interaction uses an existing Okta System integration in the customer's AWS account. If you do not have the Okta System integration set up in your AWS account, please set it up before deploying this pattern. View the [integration on Okta's site](https://help.okta.com/en-us/content/topics/reports/log-streaming/add-aws-eb-log-stream.htm).

This pattern demonstrates how to:
1. Write EventBridge rules that match Okta's event pattern
2. Send events from Okta's EventBridge integration to Amazon CloudWatch for logging and debugging
3. Transform Okta events using AWS Lambda and allows you to connect to other services going forward

See the below architecture diagram from the data flow of this pattern.

![Architecture Diagram](./img/readme-arch-diagram.png)

## Testing

### Test the AWS Lambda Function

The event.json file included in this pattern is a sample EventBridge event from Okta. This event can be used to test the Lambda function and EventBridge rules deployed by this pattern.

To test the Lambda function via the CLI, copy and paste the following command, replacing the variables in <> with your own values:
```
aws lambda invoke --function-name <OktaIntegrationStack-OktaProcessUserLoginUnusual-....> --payload file://event.json --cli-binary-format raw-in-base64-out response.json
```

You should receive a response that looks like:
```
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
```

The command creates a response.json file in your directory. If you open this file, you see the output of the Lambda function.

### Test the EventBridge Rule

Only Okta can publish events to the event bus. To test the EventBridge rules deployed by this pattern, follow these instructions:

1. Navigate to the Amazon EventBridge console. Select "Rules".

2. From the Event bus list, choose the SaaS event bus associated with your Okta partner event source.

3. From the Rules list, select the "OktaIntegrationStack-OktaSpecficEventsRule54D..."

![EventBridge Console](./img/EBconsole-rules.png)

4. Choose "Edit" to enter the rule editor. Click through to "Step 2. Build Event Pattern."

![EventBridge Console](./img/BuildEvent.png)

5. Scroll down to "Sample event - optional." Select "Enter my own," and delete the pre-populated event. Copy the contents of event.json into the event editor.

![EventBridge Console](./img/SampleEvent.png)

6. Scroll down to "Event pattern." Choose "Test Pattern."

![EventBridge Console](./img/TestEvent.png)

A successful test results in a "Sample event matched the event pattern." message. This means that the rule will successfully route incoming events to the AWS Lambda function.

![EventBridge Console](./img/TestEventSuccessful.png)


## Cleanup

1. Delete the stack
```bash
cdk destroy
```

----
Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
111 changes: 111 additions & 0 deletions eventbridge-partner-sources/1-okta/cdk-python/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
import os

import aws_cdk as cdk
from aws_cdk import (
Stack,
aws_s3 as s3,
aws_lambda as _lambda,
RemovalPolicy,
aws_events as events,
aws_events_targets as targets,
aws_iam as iam,
aws_logs as logs,
Duration,
CfnParameter,
CfnOutput
)

from constructs import Construct

class OktaIntegrationStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

# Stack inputs
OKTA_PARTNER_EVENT_BUS = CfnParameter(self, id="oktaEventBusName", type="String",
description="The name of event bus the Okta Partner EventSource is associated with.")

# Turn partner event bus from string to IEventBus object
partner_event_bus = events.EventBus.from_event_bus_name(scope=self, id='partner-event-bus', event_bus_name=OKTA_PARTNER_EVENT_BUS.value_as_string)

# CloudWatch Logs Group that stores all events sent by Okta for debugging or archive
log_group = logs.LogGroup(
self, "Okta-all-events",
retention=logs.RetentionDays.ONE_DAY,
removal_policy=RemovalPolicy.DESTROY
)

# CloudWatch Logs Group that stores specific login location events from Okta for debugging or archive
log_group_user_login_unusual_location_app = logs.LogGroup(
self, "Okta-user-login-unusual-location-events",
retention=logs.RetentionDays.ONE_DAY,
removal_policy=RemovalPolicy.DESTROY
)

lambda_role = iam.Role(scope=self, id='okta-cdk-lambda-role',
assumed_by=iam.ServicePrincipal('lambda.amazonaws.com'),
managed_policies=[
iam.ManagedPolicy.from_aws_managed_policy_name(
'service-role/AWSLambdaBasicExecutionRole')
]
)

# A Lambda function to consume and process specific events
okta_process_user_login_unusual_location_events_lambda = _lambda.Function(
self,
id='OktaProcessUserLoginUnusualLocation',
runtime=_lambda.Runtime.PYTHON_3_12,
code=_lambda.Code.from_asset('src'),
handler='OktaProcessUserLoginUnusualLocation.handler',
role=lambda_role,
timeout=Duration.seconds(15)
)

# EventBridge Okta all events rule
okta_all_events_rule = events.Rule(
self,
id="OktaAllEventsRule",
event_bus=partner_event_bus
)

# Add event pattern to rule
okta_all_events_rule.add_event_pattern(
source=events.Match.prefix('aws.partner/okta.com/evership/evershipsecuritylake'),
)

# CloudWatch Log Group as target for EventBridge Rule
okta_all_events_rule.add_target(targets.CloudWatchLogGroup(log_group))

# EventBridge Okta user unusual login location events
okta_user_access_admin_app_rule = events.Rule(
self,
id="OktaUnusualLoginEventsRule",
event_bus=partner_event_bus
)

# Add rule to the event bus for specific events
okta_user_access_admin_app_rule.add_event_pattern(
source=events.Match.prefix('aws.partner/okta.com/evership/evershipsecuritylake'),
detail_type=["SystemLog"],
detail={
"eventType": ["user.session.access_admin_app"]
}
)

# Lambda as target for EventBridge Rule
okta_user_access_admin_app_rule.add_target(targets.LambdaFunction(okta_process_user_login_unusual_location_events_lambda))

# CloudWatch Log Group as target for EventBridge Rule
okta_user_access_admin_app_rule.add_target(targets.CloudWatchLogGroup(log_group_user_login_unusual_location_app))

# Print the Lambda function name
CfnOutput(self, "OktaProcessUserLoginUnusualLocationLambdaOutput", value=okta_process_user_login_unusual_location_events_lambda.function_name)

app = cdk.App()
description = (
"Okta EventBridge Integration (uksb-1tthgi812) (tag:eventbridge-partner-sources-okta-cdk-python)"
)
OktaIntegrationStack(app, "OktaIntegrationStack", description=description)
app.synth()
25 changes: 25 additions & 0 deletions eventbridge-partner-sources/1-okta/cdk-python/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"python/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/core:stackRelativeExports": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:target-partitions": [
"aws"
]
}
}
109 changes: 109 additions & 0 deletions eventbridge-partner-sources/1-okta/cdk-python/event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
{
"version": "0",
"id": "4ab6d852-09e9-1036-fc04-2e22004b3c3f",
"detail-type": "SystemLog",
"source": "aws.partner/okta.com/evership/evershipsecuritylake",
"account": "999999999999",
"time": "2023-05-30T14:17:58Z",
"region": "us-east-1",
"resources": [],
"detail": {
"actor": {
"id": "00uttidj04jqI21bA1d6",
"type": "User",
"alternateId": "[email protected]",
"displayName": "A User",
"detailEntry": null
},
"client": {
"userAgent": {
"rawUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
"os": "Mac OS X",
"browser": "CHROME"
},
"zone": "null",
"device": "Computer",
"id": null,
"ipAddress": "127.0.0.1",
"geographicalContext": {
"city": "Fictionville",
"state": "Pennsylvania",
"country": "United States",
"postalCode": "19513",
"geolocation": {
"lat": 41.1286,
"lon": -73.4835
}
}
},
"device": null,
"authenticationContext": {
"authenticationProvider": null,
"credentialProvider": null,
"credentialType": null,
"issuer": null,
"interface": null,
"authenticationStep": 0,
"externalSessionId": "102BoThue9qT2uRBdaO_Z9msg"
},
"displayMessage": "User accessing Okta admin app",
"eventType": "user.session.access_admin_app",
"outcome": {
"result": "SUCCESS",
"reason": null
},
"published": "2023-05-30T14:17:58.126Z",
"securityContext": {
"asNumber": 6167,
"asOrg": "verizon",
"isp": "verizon",
"domain": "myvzw.com",
"isProxy": false
},
"severity": "INFO",
"debugContext": {
"debugData": {
"requestId": "ZHYFlX6QY0rHqq1oihP7CwAACSI",
"dtHash": "e463841eed07369aeb7ace43a41fcef75ccefa573ced0420039c16b0e3d7cc99",
"requestUri": "/admin/sso/callback",
"url": "/admin/sso/callback?code=******&state=vdC6CnQXeZqyxBJKBVmtej9wMnF4nM1r"
}
},
"legacyEventType": "app.admin.sso.login.success",
"transaction": {
"type": "WEB",
"id": "ZHYFlX6QY0rHqq1oihP7CwAACSI",
"detail": {}
},
"uuid": "c6ed294a-fef4-11ed-a5b1-bbb7c1de1a4b",
"version": "0",
"request": {
"ipChain": [
{
"ip": "127.0.0.1",
"geographicalContext": {
"city": "Fictionville",
"state": "Pennsylvania",
"country": "United States",
"postalCode": "19513",
"geolocation": {
"lat": 41.1286,
"lon": -73.4835
}
},
"version": "V4",
"source": null
}
]
},
"target": [
{
"id": "00uttidj04jqI21bA1d6",
"type": "AppUser",
"alternateId": "[email protected]",
"displayName": "A User",
"detailEntry": null
}
]
}
}
Loading