Troubleshooting problems with permissions when using the AWS IAM assumeRole function with session

Within my aws-cdk application, I am working on setting up a lambda function to assume a specific role and obtain credentials through aws-sts. These credentials need to include a tenant_id tag.

AWS CDK Code:

Role to be assumed:

const pdfUserRole = new Role(this, "PDFTenantUserRole", {
  assumedBy: new ServicePrincipal("lambda.amazonaws.com").withSessionTags(),
  description: "Role assumed by the pdf service for a user",
});

pdfUserRole.addToPolicy(
  new PolicyStatement({
    actions: ["sts:TagSession"],
    resources: ["*"],
  })
);

Lambda Function definition:

this.pdfGeneratorFunction = new LambdaFunctionTypescript(
  this,
  "Handler",
  {
    tracing: Tracing.PASS_THROUGH,
    entry: getFilePath(import.meta.url, "pdf-generator-function.ts"),
    memorySize: 1536,
    layers: [],
    initialPolicy: [
      new PolicyStatement({
        resources: [pdfUserRole.roleArn],
        actions: ["sts:AssumeRole", "sts:TagSession"],
      }),
    ],
  }
);

This role is supposed to be assumed by the lambda function in the handler code:

const sts = new STSClient({});

const getCredentials = async (tenantId: string) => {
  return sts.send(
    new AssumeRoleCommand({
      RoleArn: userRoleArn,
      RoleSessionName: "PDFGenerator_" + tenantId,
      TransitiveTagKeys: ["tenant_id"],
      Tags: [
        {
          Key: "tenant_id",
          Value: tenantId,
        },
      ],
    })
  );
};

The lambda function is associated with a service role that contains an inline definition from the handler.

I am facing an issue where my lambda function cannot call the AssumeRole:

User: arn:aws:sts::<AWSAccountId>:assumed-role/PDFGeneratorHandlerServiceRole/PDFGeneratorHandler is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::<AWSAccountId>:role/PDFGeneratorPDFTenantUserRole

I suspect there might be a principal issue since it seems like it is calling as the service role instead of the lambda. I have already tried adding a trust relationship between the function and the role without success.

Update: The credentials generated by the lambda function are intended to be used within a virtual browser, not by the lambda itself.

Update 2: You can find an example link here: https://github.com/aws-samples/multi-tenant-database-isolation-patterns/blob/2000b9ff4630d181421a8761ffea3f7a9039eacf/patterns/3-pool-compute-db-per-tenant-iam-auth/silo-compute-iam.ts#29

Answer №1

It's important to differentiate between the IAM role of the lambda function and the code within the function itself. The role must have a trust relationship allowing lambda to assume it, as lambda fetches credentials before running your code. Without this role and proper trust relationship, your function will not work.

On the other hand, your code uses the credentials obtained by lambda service when attempting to assume any other roles. This means that subsequent actions with these credentials are independent of the lambda service's principal.


If your function's role only permits lambda to assume it, any attempt to perform an assume role call from within your function will fail. There is no need to manually perform this call since your function already possesses valid credentials for the role. If further role assumptions are necessary, those roles should trust the actual role your lambda runs with, not the lambda service itself.

To establish a trust relationship on the role to be assumed by the lambda function's service role, you can use the following configuration:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<AWSAccountId>:role/PDFGeneratorHandlerServiceRole"
            },
            "Action": [
                "sts:AssumeRole",
                "sts:TagSession"
            ]
        }
    ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Is there a possible method to retrieve the Spot-Fleet-Request identification using a CloudFormation Template?

I'm facing a challenge in creating a unified template that includes the following components: 1. AWS::EC2::SpotFleet resource 2. 2 AWS::ApplicationAutoScaling::ScalingPolicy resources (for scale up and scale down) Initially, my template only had th ...

Utilize rest parameters for destructuring操作

I am attempting to destructure a React context using rest parameters within a custom hook. Let's say I have an array of enums and I only want to return the ones passed into the hook. Here is my interface for the context type enum ConfigItem { Some ...

Having trouble understanding how to receive a response from an AJAX request

Here is the code that I am having an issue with: render() { var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php'; urlstr = urlstr + "?division=sdsdfdsf"; urlst ...

Utilizing movingMarker from leaflet-moving-marker in Angular: A Step-by-Step Guide

I am currently working on incorporating the leaflet-moving-marker plugin but encountering some errors in the process. import {movingMarker} from 'leaflet-moving-marker' var myMovingMarker = L.movingMarker([[48.8567, 2.3508],[50.45, 30.523 ...

Numerous attributes housed within a single element

In my project, I have set up a Store using Angular and NgRx 13. Within my SharedModule, I define components including selectors which load content into the store to prevent redundant API calls. https://i.stack.imgur.com/sr3nl.png This approach is impleme ...

I'm sorry, we couldn't locate the module: Unable to find the path '../types/index'

After spending an hour attempting to troubleshoot this issue, I am still unable to find a solution. I have stored index.d.ts in the types folder. The content of the types file is as follows: export interface tag { created_at: string id: nu ...

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

how to navigate to a different page programmatically upon selecting an option in the side menu

ionic start mySideMenu sidemenu --v2 After creating a sidemenu using the code above, I implemented some login-logout functionality by storing user details in a localStorage variable named "userDetails". When clicking on the logout option from the sideme ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

What role does NPM play in the deployment of a Node.js App with AWS Beanstalk?

I'm interested in the workflow of an AWS Beanstalk deployment, particularly regarding the installation of packages. I assume that npm is used during the process to install packages on the server(s). However, I am curious to know if AWS Beanstalk utili ...

Encountering an error when setting up a React-TypeScript ContextAPI

I am currently attempting to understand and replicate the functionality of a specific package found at: https://github.com/AlexSegen/react-shopping-cart Working within a React-Typescript project, I have encountered challenges when creating the ProductCont ...

The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests. Below is the nginx configuration located within the sites-enabled directory ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

Working with Angular: Managing an Array of Objects

After retrieving an array of objects using the code snippet below: this.serviceOne.getRemoteData().subscribe( data => this.MyArray.push(data) ); I encounter issues when trying to iterate through the array using the code snippet bel ...