#AWS - Quicksight(SSO) user management.
Tags: aws
Published: 2022-07-17 19:21:45

## Scenario:

- Consider that our AWS Quicksight account is configured with SSO for visualizing product metrics and you want to manage the Quicksight users.

## Requirement:

- User activity monitoring, including last login, resource usage, dashboard popularity, etc…

## Issue:
- Currently, in QuickSight there is no feature that allows you to see the activity of your users' metrics directly.
QuickSight users are charged monthly, even if the user does not sign in to the account.
You can expect a full month's charge, even if a user is removed before the end of the month.

## Why?

- To keep track of user activity and identify inactive users.
- To notify inactive users to remind them.
- Delete the user automatically if the user has not been active for n days.
- Make improvements to the dashboards with the lowest visits.
- To decommission the dashboards that are less popular.

## Solution:

- Everything is an API call when it comes to AWS.
- Each activity will be logged in to Cloudtrail.
- We can use Amazon CloudTrail logs to gather information on user/dashboard activity
.

**Quicksight Account Access:**

- When the user login to AWS if the user account is not available in Quicksight the same will be created.
- Once the user account is created based on the role and permissions provided, the user can access Quicksight resources such as Dashboards, Analysis, DataSets, etc…
- CloudTrail records actions taken by a user, role, or an AWS service in Amazon QuickSight.
- CloudTrail will log the following events for Quicksight:

> **Data source** create/update/delete
> **Data set** create/update/delete
> **Analysis** create/access/update/delete
> **Dashboard** create/access/update/delete, etc…

**Quicksight user activity monitoring process:**
- [Direct user activity monitoring](https://aws.amazon.com/blogs/big-data/building-an-administrative-console-in-amazon-quicksight-to-analyze-usage-metrics/)

- Once the SSO tool is integrated with Quicksight, users can use the tool to log in to Quicksight.
- Most of the tools use [SAML](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) (Security Assertion Markup Language 2.0) to federate users into AWS
- The only way to monitor the user activity out of the box is via Quicksight Manage Console only.
- By using the AWS API/CLI/SDK we can collect the required information from Cloudtrail.
- SSO will use the AWS [STS](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html) (Security Token Service) to request temporary, limited-privilege credentials for federated users.
- The federated user will be provisioned to perform the **sts:AssumeRoleWithSAML** action to access Quicksight resources.
- The SSO user login activity will be logged under {'Event' : 'AssumeRoleWithSAML'}
- Other activities will be logged under {'Event' : **['CreateUser', 'DeleteUser', 'UpdateUser', 'GetDashboard', 'GetAnalysis']**}
- By filtering the events based on the event name we can get the list of all activities from CloudTrail.
- From the CloudTrail log, we can get the user identity details such as event time, type, username, identity provider, etc…

## Code sample:

**[AWS CLI:](https://docs.aws.amazon.com/cli/latest/reference/cloudtrail/lookup-events.html)**
```
aws cloudtrail lookup-events - lookup-attributes AttributeKey=EventName,AttributeValue=GetDashboard
```

**[AWS API:](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html)**
```
{
   "EndTime": number,
   "EventCategory": "string",
   "LookupAttributes": [ 
      { 
         "AttributeKey": "string",
         "AttributeValue": "string"
      }
   ],
   "MaxResults": number,
   "NextToken": "string",
   "StartTime": number
}
```

**[Boto SDK:](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudtrail.html#CloudTrail.Client.lookup_events)**
```
response = client.lookup_events(
    LookupAttributes=[
        {
            'AttributeKey': 'EventId'|'EventName'|'ReadOnly'|'Username'|'ResourceType'|'ResourceName'|'EventSource'|'AccessKeyId',
            'AttributeValue': 'string'
        },
    ],
    StartTime=datetime(2015, 1, 1),
    EndTime=datetime(2015, 1, 1),
    EventCategory='insight',
    MaxResults=123,
    NextToken='string'
)
```

## Sample response:
```
{
    "userIdentity": {
        "type": "AssumedRole",
        "principalId": "<principal_id>: <user_name>",
        "arn": "arn:aws:sts:: <aws_account_id>:assumed-role/<IAM_role_ name>/<user_name>",
        "accountId": "<aws_account_id>",
        "sessionContext": {
            "sessionIssuer": {
                "type": "Role",
                "principalId": "<principal_id>",
                …
            }
        }
    },
    "eventTime": "2022-17-13T16:55:36Z",
    "eventSource": "quicksight.amazonaws.com",
    "eventName": "GetDashboard",
    "awsRegion": "us-east-1",
    "eventID": "65ae334b-4202-4961-9ac7-d5a9d44416e2",
    "readOnly": true,
    "eventType": "AwsServiceEvent",
    "serviceEventDetails": {
        "eventRequestDetails": {
            "dashboardId": "arn:aws:quicksight:us-east-1: <aws_account_id>:dashboard/<dashboard_id>"
        },
        "eventResponseDetails": {
            "dashboardDetails": {
                "dashboardName": "Product X",
                "dashboardId": "arn:aws:quicksight:us-east-1: <aws_account_id>:dashboard/<dashboard_id>",
                "analysisIdList": [
                    "arn:aws:quicksight:us-east-1: <aws_account_id>:analysis/<analysis_id>"
            }
        }
    }
}
```

**[Delete user:](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/quicksight.html#QuickSight.Client.delete_user)**
```
response = client.delete_user(
    UserName='string',
    AwsAccountId='string',
    Namespace='string'
)
```
**Here are a few things to keep in mind:**

- CloudTrail keeps the logs for 90 days only.
- QuickSight users are charged monthly, even if the user does not sign in to the account.
- You can expect an entire month's charge, even if a user is removed before the end of the month.
- QuickSight users are charged based on QuickSights Edition (Standard/Enterprise)
- QuickSight Readers are charged per reader session basis, and sessions are in 30-minute increments. Each session costs $0.30, per reader, up to a maximum of $5 per reader per month (month-to-month).
- If a Reader has a dashboard open, the timer will continue to run(in 30min increments), until the Reader closes or minimizes the dashboard window.
- If a Reader opens a dashboard and closes the dashboard before the 30min of the session expires, the timer will stop at 30min and will not continue to run.
- 10GB of SPICE capacity is provisioned to the QuickSight account for each user added, at no additional cost.
- Additional SPICE can be purchased at $0.38 per GB/month.

## Conclusion:
- Once the required data is available from CloudTrail we can store the data in S3 and use the same to manage the Quicksight account. We use a simple Lambda function that can automatically remove inactive users. We can also set up a trigger for the lambda function using Cloudwath (Cron job).

**FAQs:**
**Question:** If a user was added and deleted at any point of a month, the charge would be added for the days he was active right?
**Answer:**
- No, If the Author/Admin user is removed from the account, you are still billed for that user for the month (starting from the day they were listed as active). If the user was already listed on the account from day 1 of the month, you could expect the full monthly charge. If the user was only added to the account partway through the month (say, on the 10th day) then you will only receive a total charge that calculates up to the remaining days of the month, you will not be charged for the 10 days the user was not listed as active.

**Question:** When an ADMIN / AUTHOR is working on a Resource (Analysis / Dashboard etc….). Will that be charged in any way?
**Answer:**
- Users are charged per month, regardless of their sign-in activity, or use of resources on the account. It is a monthly charge.

**Question:** If a READER is active in a day the sessions will be charged if the Max $5 USD is not reached already, correct?
**Answer:**
- The user will be charged based on the time a dashboard is open. For example,
- A Reader opens a dashboard for 1hr, 2x 30min sessions. Considering each session is charged at $0.30 per 30min session, this particular Reader will be charged $0.60 ($0.30 x 2 (30min + 30min) = $0.60).
- If the Reader leaves the dashboard open and is visible at all times, for 16 hours, then the charge for that user will be $5 for that day. However, since there is a maximum charge of $5 per month, you will not see any further billing for that specific Reader.

**Question:** If a user is added on the 5th and deleted on the 6th will there be any charge?
**Answer:**
- Since users are charged monthly, you will be charged from the 5th until the last day of the same month, thereafter you will not be charged for the removed user. This is why user charges are displayed daily on the Billing Console.

**Question:** If we were to get a subscription for all our ADMIN / AUTHOR (8 Users) how much cost it will save?
**Answer:**
- For the Enterprise Edition of QuickSight, paying month-to-month, you will pay $192 for the 8 users ($24 per user/month * 8 users = $192)
- The Annual Subscription is $18 per user per month. This means you will pay $144 per month for the 8 users, saving you $48 monthly.

**References:**
- [Single Sign-On between Okta Universal Directory and AWS](https://aws.amazon.com/blogs/aws/single-sign-on-between-okta-universal-directory-and-aws/)
- [Federate amazon Quicksight access with okta](https://aws.amazon.com/blogs/big-data/federate-amazon-quicksight-access-with-okta/)
- [Building an administrative console in Amazon QuickSight to analyze usage metrics](https://aws.amazon.com/blogs/big-data/building-an-administrative-console-in-amazon-quicksight-to-analyze-usage-metrics/)
- [Logging Operations with AWS CloudTrail](https://docs.aws.amazon.com/quicksight/latest/user/logging-using-cloudtrail.html)
- [Manually Creating the Table for CloudTrail Logs in Athena](https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html)
- [Analyse Security, Compliance, and Operational Activity Using AWS CloudTrail and Amazon Athena](https://aws.amazon.com/blogs/big-data/aws-cloudtrail-and-amazon-athena-dive-deep-to-analyze-security-compliance-and-operational-activity/)
- [Amazon QuickSight Now Supports Audit Logging with AWS CloudTrail](https://aws.amazon.com/blogs/big-data/amazon-quicksight-now-supports-audit-logging-with-cloudtrail/)
- [Tracking Non-API Events by Using CloudTrail Logs](https://docs.aws.amazon.com/quicksight/latest/user/logging-non-api.html)
- [Querying AWS CloudTrail Logs - Understanding CloudTrail Logs and Athena Tables](https://docs.aws.amazon.com/athena/latest/ug/cloudtrail-logs.html#create-cloudtrail-table-understanding)