SkillSprout
Chapter 9 · Lesson 4
Advanced
5 min read

Multi-Tenant Data Access and Microservice Authentication

Overview

A multi-tenant application serves many customers from shared infrastructure. The biggest risk is tenant leakage, where customer A sees customer B's data. In a microservice system, services also need to authenticate each other so a compromised service cannot call everything.

Picture an apartment building. Every flat has its own key (tenant isolation) and the building's service doors (microservices) only open with a staff badge that says exactly which rooms you may enter.

On AWS you enforce isolation in the data layer and IAM, not only in application WHERE clauses, and you authenticate service calls with IAM/SigV4, JWTs or mutual TLS.

Key Concepts

  • Silo (account or stack per tenant), pool (shared tables with a tenant key) and bridge (mixed) are the main multi-tenant models.
  • DynamoDB fine-grained access control uses the condition key dynamodb:LeadingKeys to restrict a caller to items whose partition key starts with their tenant ID.
  • ABAC uses session tags and resource tags with conditions like aws:PrincipalTag/tenant to scale permissions without a role per tenant.
  • STS AssumeRole with session tags or Cognito identity pool role mapping produces tenant-scoped credentials at runtime.
  • Service-to-service authentication options: IAM (SigV4) with API Gateway or Lambda function URLs, JWT validated by the receiver, or mTLS.
  • Lambda authorizers can return a policy and context including the tenant ID for downstream functions.
  • Least privilege per service: each microservice has its own role and only the resources it owns.
  • Include the tenant ID in every key, log line, metric dimension and cache key.

Detailed Notes

Tenant models compared

ModelIsolationCostExample
SiloStrongest (account/stack per tenant)HighestRegulated enterprise customers
PoolLogical (tenant key + IAM conditions)LowestSelf-service SaaS
BridgeMixedMediumShared compute, separate databases

Enforcing isolation in DynamoDB

Design keys as TENANT#<id> for the partition key so every item belongs to a tenant. Then give the tenant-scoped credentials an IAM policy that only allows matching keys.

json
{
  "Effect": "Allow",
  "Action": ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:PutItem", "dynamodb:UpdateItem"],
  "Resource": "arn:aws:dynamodb:eu-west-1:111122223333:table/Orders",
  "Condition": {
    "ForAllValues:StringLike": {
      "dynamodb:LeadingKeys": ["TENANT#${aws:PrincipalTag/tenant}"]
    }
  }
}

The caller then assumes a role with a session tag carrying the tenant, taken from a verified token:

python
sts = boto3.client("sts")
creds = sts.assume_role(
    RoleArn="arn:aws:iam::111122223333:role/TenantDataAccess",
    RoleSessionName="svc-orders",
    Tags=[{"Key": "tenant", "Value": claims["custom:tenantId"]}],
    DurationSeconds=900)["Credentials"]
table = boto3.Session(aws_access_key_id=creds["AccessKeyId"],
                      aws_secret_access_key=creds["SecretAccessKey"],
                      aws_session_token=creds["SessionToken"]).resource("dynamodb").Table("Orders")

The role's trust policy must allow sts:TagSession. Even if application code has a bug and queries another tenant's key, IAM denies the call.

S3 and other stores

Use prefixes per tenant (tenants/<id>/) with ABAC policies on s3:prefix or separate S3 Access Points. For RDS use row-level security or separate schemas; for OpenSearch use per-tenant indexes or document-level security. Always include tenant in cache keys so ElastiCache never serves one tenant another's value.

Authenticating service-to-service calls

MethodHowWhen
IAM / SigV4Caller signs requests; resource policy or API IAM auth allows the caller's roleAWS-native services, internal APIs
JWT (Cognito or OIDC)Caller sends bearer token; receiver validates signature and claimsUser context must flow through
Machine-to-machine OAuthCognito client credentials grant with resource server scopesPartner or service clients
mTLSBoth sides present certificatesZero-trust internal meshes
yaml
OrdersApiPolicy:
  Type: AWS::IAM::Policy
  Properties:
    PolicyName: invoke-inventory-api
    Roles: [!Ref OrdersRole]
    PolicyDocument:
      Statement:
        - Effect: Allow
          Action: execute-api:Invoke
          Resource: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${InventoryApi}/prod/GET/items/*"

For Lambda-to-Lambda calls grant lambda:InvokeFunction on the specific function ARN only, and use a function URL with AWS_IAM auth for HTTP access from services.

Propagating identity

Pass the verified tenant and user ID through request context (authorizer context, JWT, or a signed internal header) and never trust values supplied by the client body. Add the tenant ID to structured logs and X-Ray annotations to troubleshoot and audit per tenant. Throttle per tenant with API Gateway usage plans or application-level quotas so one noisy tenant cannot starve others.

Application-level fine-grained authorisation

IAM cannot express rules like "managers approve orders under 10,000". Evaluate such rules in code or externalise them to Amazon Verified Permissions using Cedar policies, feeding it the token claims and the resource attributes.

Real World Example

A B2B SaaS pooled all tenants in a single DynamoDB table. After a code review found a missing tenant filter, they changed the architecture so the API assumes a tenant-scoped role with session tags and an IAM LeadingKeys condition. The same bug could no longer leak data, which they verified in a penetration test. Internal calls between the orders and inventory services use IAM-authorised API Gateway with per-service roles.

Architecture Diagram

Tenant-scoped credentials
Architecture
Multi-tenant API
Tenant userJWT
API + authorizertenant claim
STSsession tag
TableLeadingKeys

A verified token becomes tenant-tagged credentials that IAM enforces on the data layer.

  1. 1The user presents a JWT containing the tenant ID.
  2. 2The authorizer validates it and passes the tenant to the backend.
  3. 3The backend assumes a role with a tenant session tag.
  4. 4IAM allows only items whose partition key matches that tenant.

Best Practices

  • ✓Enforce tenant isolation in IAM and the data model, not only in code filters.
  • ✓Use ABAC with session tags to avoid creating a role per tenant.
  • ✓Give every microservice its own least-privilege role.
  • ✓Take identity from verified tokens, never from client-supplied fields.
  • ✓Put the tenant ID in keys, cache keys, logs and metrics.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Restricting DynamoDB access per user or tenant uses dynamodb:LeadingKeys.
  • Session tags require sts:TagSession in the role trust policy.
  • Service-to-service calls with AWS identities use IAM auth (SigV4); machine clients use Cognito client credentials.
  • Never trust a tenant ID from the request body; derive it from the validated token.

Chapter quiz

Advanced Security: Certificates, Encryption Choices and Data Protection · 10 questions

  1. 1.A public API behind CloudFront must use HTTPS with a certificate that renews automatically. Where should the ACM certificate be requested?

  2. 2.An ACM certificate imported from an external CA is about to expire unnoticed. What helps prevent an outage?

  3. 3.Internal microservices in a VPC need mutual TLS with certificates from your own hierarchy. Which service?

  4. 4.Compliance requires that AWS never has access to plaintext of patient notes stored in S3. What approach satisfies this?

  5. 5.Account B's Lambda role must decrypt objects encrypted with account A's customer managed key. What is required?

  6. 6.After enabling automatic rotation on a customer managed key, what must the application do?

  7. 7.Developers accidentally log users' email addresses to CloudWatch Logs. Which feature adds automatic masking for readers?

  8. 8.A security team wants to discover files containing personal data across hundreds of S3 buckets. Which service should be used?

  9. 9.A pooled SaaS table must guarantee that a request authorised for tenant 42 cannot read tenant 43 rows even if the code forgets a filter. What is the strongest mechanism?

  10. 10.An order service must call an internal inventory API using its own AWS identity with no shared secrets. What is the best option?

0 of 10 answered

Finished this lesson?

0 of 46 lessons done · 0% of the course