Understanding DocumentDB Security: IAM Policies and Network Protection
Amazon DocumentDB (with MongoDB compatibility) is a fully managed, highly durable database service. Security is not a bolt-on featureâit is woven into every layer of the service. Two foundational pillars of DocumentDB security are IAM policies (who can do what with the cluster) and network security (how traffic reaches the cluster). This tutorial gives you a complete developer-oriented walkthrough: what these mechanisms are, why they matter, how to implement them with practical code, and the best practices you should follow from day one.
What Is DocumentDB Security?
đ Deploy your AI agent in 10 minutes
Managed Hermes hosting. Zero DevOps. 100M tokens/mo included.
Try it free →DocumentDB security is the combination of controls that protect your cluster data, management plane, and network connectivity. It encompasses:
- Authentication & Authorization: IAM-based authentication for the database itself, plus IAM policies that govern management operations (create/delete clusters, modify instances, snapshots, etc.).
- Network isolation: Deploying clusters inside an Amazon Virtual Private Cloud (VPC) with security groups and, optionally, VPC endpoints to keep traffic within the AWS backbone.
- Encryption: Encryption at rest (automatically enforced by AWS KMS) and encryption in transit (TLS/SSL enforced via cluster parameter groups).
- Auditing: Amazon CloudTrail monitors management API calls; database auditing can be enabled via built-in profiler/audit logging.
For developers, the most impactful areas are IAM database authentication (so you can replace hardâcoded passwords with temporary AWS credentials) and network security groups that restrict which IPs or resources can reach the cluster.
Why It Matters
A misconfigured DocumentDB cluster can expose sensitive data to the public internet, allow unauthorized users to manipulate the database, or become a pivot point for lateral movement in your cloud environment. Proper IAM policies ensure the principle of least privilegeâonly the exact actions needed are allowed. Network security ensures your cluster isn't reachable from untrusted networks. Together they dramatically shrink the attack surface and help meet compliance requirements (PCI-DSS, HIPAA, GDPR).
Additionally, using IAM database authentication eliminates the operational headache of rotating static passwords. Temporary, autoâexpiring credentials reduce the risk of credential leakage.
How to Use IAM Policies with DocumentDB
IAM policies define permissions for AWS management actions. DocumentDB uses the rds service prefix (because it is part of the RDS family) but with specific resource ARNs. You attach these policies to IAM users, groups, or roles.
IAM Policy for Cluster Management
The following policy allows a developer to describe clusters and create snapshots, but not delete production clusters. It separates permissions by environment using tags.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds:DescribeDBClusters",
"rds:DescribeDBInstances",
"rds:DescribeDBClusterSnapshots",
"rds:CreateDBClusterSnapshot",
"rds:ListTagsForResource"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"rds:CreateDBInstance",
"rds:ModifyDBInstance"
],
"Resource": "arn:aws:rds:us-east-1:123456789012:cluster:*",
"Condition": {
"StringEquals": {
"aws:ResourceTag/env": "development"
}
}
},
{
"Effect": "Deny",
"Action": [
"rds:DeleteDBCluster",
"rds:DeleteDBInstance"
],
"Resource": "arn:aws:rds:us-east-1:123456789012:cluster:*",
"Condition": {
"StringNotEquals": {
"aws:ResourceTag/retention": "temporary"
}
}
}
]
}
Key points: The Deny block overrides any allow if the tag condition doesnât match, preventing accidental deletion of important clusters. Always scope resources as tightly as possibleâavoid wildcard * for destructive actions.
Attaching the Policy via AWS CLI
# Create the policy
aws iam create-policy \
--policy-name DocDB-DevPolicy \
--policy-document file://docdb-policy.json
# Attach to a developer user
aws iam attach-user-policy \
--user-name dev_user \
--policy-arn arn:aws:iam::123456789012:policy/DocDB-DevPolicy
IAM Database Authentication (Connect to DocumentDB without a password)
Instead of a username and password stored in a config file, you can use your AWS IAM credentials to authenticate directly to DocumentDB. This requires enabling IAM DB authentication on the cluster and creating a database user linked to an IAM role or user.
Step 1: Enable IAM authentication on the cluster (if not already enabled)
aws docdb modify-db-cluster \
--db-cluster-identifier my-cluster \
--enable-iam-database-authentication true \
--apply-immediately
Step 2: Create a database user that maps to an IAM user or role
Connect to the cluster using a master user (or an already authorized IAM user) and run:
// Inside the MongoDB shell or a driver
db.createUser(
{
user: "arn:aws:iam::123456789012:user/developer",
pwd: 1,
roles: [ { role: "readWrite", db: "appdb" } ],
authenticationRestrictions: [ ]
}
);
// Alternatively, for an IAM role:
db.createUser(
{
user: "arn:aws:iam::123456789012:role/app-server-role",
pwd: 1,
roles: [ { role: "readWrite", db: "appdb" } ],
authenticationRestrictions: [ ]
}
);
Step 3: Generate an authentication token and connect
The token is a temporary, SigV4âsigned string that acts as the password. You generate it using the AWS CLI or an SDK and then pass it in the connection string.
# Generate a token (valid for 15 minutes) for the cluster endpoint
aws docdb generate-db-auth-token \
--region us-east-1 \
--hostname my-cluster.cluster-id.us-east-1.docdb.amazonaws.com \
--port 27017 \
--username arn:aws:iam::123456789012:user/developer
Example connection in Node.js using the MongoDB driver:
const { MongoClient } = require('mongodb');
const { execSync } = require('child_process');
// Generate the token on the fly
const authToken = execSync(
`aws docdb generate-db-auth-token --region us-east-1 --hostname ${host} --port ${port} --username ${userArn}`
).toString().trim();
const uri = `mongodb://${encodeURIComponent(userArn)}:${encodeURIComponent(authToken)}@${host}:${port}/?tls=true&tlsCAFile=rds-combined-ca-bundle.pem&replicaSet=rs0`;
const client = new MongoClient(uri);
await client.connect();
// Connection established with IAM authentication
Important: The token expires after 15 minutes. Your application should generate a fresh token for each new connection or implement a reconnect logic that re-generates the token. Many drivers now support builtâin AWS authentication, simplifying this process.
Network Security for DocumentDB
DocumentDB clusters are always deployed inside a VPC. They do not have a publicly accessible endpoint by default. Network security revolves around:
- Security Groups (SGs): Stateful virtual firewalls that control inbound/outbound traffic to the cluster instances.
- VPC endpoints: Private connectivity to the DocumentDB control plane (for management API calls) without traversing the public internet.
- TLS/SSL enforcement: Ensuring all traffic is encrypted in transit.
Configuring Security Groups
A security group acts as the first line of defense. The following example creates a security group that only allows inbound TCP traffic on port 27017 from a specific application server's security group and from a bastion host IP for administrative access.
# Create a security group for the DocumentDB cluster
aws ec2 create-security-group \
--group-name docdb-cluster-sg \
--description "Security group for DocumentDB cluster" \
--vpc-id vpc-0abcd1234
# Inbound rule: allow from app-server security group on port 27017
aws ec2 authorize-security-group-ingress \
--group-id sg-0a1b2c3d \
--protocol tcp \
--port 27017 \
--source-group sg-0appserversg
# Inbound rule: allow from a specific bastion IP for admin tasks
aws ec2 authorize-security-group-ingress \
--group-id sg-0a1b2c3d \
--protocol tcp \
--port 27017 \
--cidr 10.0.0.5/32
Note: Avoid opening 0.0.0.0/0 on port 27017. Even for development, restrict to known CIDR blocks (e.g., your VPN range).
VPC Endpoint for DocumentDB Control Plane
While the data plane (the cluster endpoint) always lives inside your VPC, the management API calls (create cluster, modify instances) normally go to the public rds.amazonaws.com endpoint. For a fully private environment, create an interface VPC endpoint for the RDS service (which includes DocumentDB). Then attach an endpoint policy to restrict which actions can be performed via that endpoint.
# Create an interface VPC endpoint for rds (covers DocumentDB management)
aws ec2 create-vpc-endpoint \
--vpc-id vpc-0abcd1234 \
--service-name com.amazonaws.us-east-1.rds \
--vpc-endpoint-type Interface \
--subnet-ids subnet-0a1b2c3d subnet-0e5f6g7h \
--security-group-ids sg-0endpointsg \
--policy-document file://endpoint-policy.json
Example endpoint policy that only allows readâonly actions and snapshot creation:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": [
"rds:DescribeDBClusters",
"rds:DescribeDBInstances",
"rds:DescribeDBClusterSnapshots",
"rds:CreateDBClusterSnapshot"
],
"Resource": "*"
}
]
}
After creation, applications in the VPC will resolve rds.us-east-1.amazonaws.com to the private endpoint IPs. This ensures management traffic never leaves the AWS network.
Enforcing TLS/SSL Encryption in Transit
DocumentDB supports TLS 1.2/1.3 connections. You should enforce it at the cluster level so that nonâTLS connections are rejected. This is controlled via a cluster parameter group.
# Create a custom parameter group
aws docdb create-db-cluster-parameter-group \
--db-cluster-parameter-group-name enforce-tls \
--db-parameter-group-family docdb4.0 \
--description "Enforce TLS connections"
# Modify the tls parameter to 'required'
aws docdb modify-db-cluster-parameter-group \
--db-cluster-parameter-group-name enforce-tls \
--parameters "ParameterName=tls,ParameterValue=required,ApplyMethod=pending-reboot"
# Apply the parameter group to your cluster
aws docdb modify-db-cluster \
--db-cluster-identifier my-cluster \
--db-cluster-parameter-group-name enforce-tls
# Reboot the cluster for the change to take effect
aws docdb reboot-db-instance --db-instance-identifier my-cluster-instance-1
Now any client must connect with tls=true and the correct CA certificate. Example MongoDB URI:
mongodb://username:password@my-cluster.cluster-id.us-east-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=rds-combined-ca-bundle.pem&replicaSet=rs0
Best Practices
-
Least privilege IAM: Start with empty policies and add only required actions. Use
Conditionblocks with tags, source IP, or VPC endpoint to restrict permissions further. - Use IAM database authentication for applications: Eliminate longâlived passwords. Rotate credentials automatically by relying on the 15âminute token expiry. For Lambda functions, associate an execution role and use it to authenticate.
- Never expose the cluster to the internet: DocumentDB clusters should never have a public IP. Keep them strictly inside a VPC and use security groups to allow only specific, trusted sources.
- Use separate security groups for different environments: A development cluster should have different inbound rules than production. Consider using infrastructure as code (CloudFormation, Terraform) to manage them consistently.
- Enable VPC endpoints: For production systems, create VPC endpoints for the RDS (DocumentDB) control plane and attach restrictive endpoint policies. This also improves latency and avoids NAT gateway costs for management calls.
-
Enforce TLS always: Set the
tlsparameter torequiredin the cluster parameter group. Use the official RDS CA bundle and keep it updated. - Audit and monitor: Enable CloudTrail for all management events. For data plane auditing, enable DocumentDBâs profiler/audit log and ship it to CloudWatch Logs or a SIEM. Monitor for unusual connection patterns or permission changes.
- Use encryption at rest: While DocumentDB encrypts storage by default, you can specify a custom AWS KMS key. Rotate keys periodically and restrict key access with IAM policies.
Putting It All Together: A Secure Deployment Checklist
Hereâs a quick sequence to secure a DocumentDB cluster from scratch:
- Create a VPC with private subnets (no internet gateway attached).
- Define a security group that allows inbound 27017 only from application security groups and a bastion host CIDR.
- Launch the cluster with
--enable-iam-database-authenticationand--storage-encrypted. - Apply a custom parameter group with
tls=required. - Create database users mapped to IAM roles for your applications.
- Attach IAM policies to those roles that allow only necessary management actions (if the application ever calls the control plane) and no destructive actions unless tagged appropriately.
- Set up a VPC endpoint for
rdswith an endpoint policy mirroring your IAM management policy. - Integrate token generation into your application connection code.
- Enable CloudTrail and configure alarms for sensitive API calls (like
DeleteDBCluster).
Conclusion
DocumentDB security is a shared responsibility. AWS ensures the underlying infrastructure is hardened, but you control the fineâgrained access and network posture. By combining IAM policiesâboth for management actions and database authenticationâwith strict VPC network controls, you create a robust defense-in-depth model. Start with least privilege, enforce TLS, isolate clusters in private subnets, and move away from static passwords. These steps transform DocumentDB from a simple database into a secure, audit-ready data store that fits seamlessly into your security architecture.