← Back to DevBytes

DocumentDB Security: IAM Policies and Network Security

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:

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:

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

Putting It All Together: A Secure Deployment Checklist

Here’s a quick sequence to secure a DocumentDB cluster from scratch:

  1. Create a VPC with private subnets (no internet gateway attached).
  2. Define a security group that allows inbound 27017 only from application security groups and a bastion host CIDR.
  3. Launch the cluster with --enable-iam-database-authentication and --storage-encrypted.
  4. Apply a custom parameter group with tls=required.
  5. Create database users mapped to IAM roles for your applications.
  6. 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.
  7. Set up a VPC endpoint for rds with an endpoint policy mirroring your IAM management policy.
  8. Integrate token generation into your application connection code.
  9. 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.

🚀 Need a reliable AI agent for your project?

Deploy Hermes Agent in 10 minutes. Managed hosting, zero DevOps.

Get Started — $23.99/mo
← Back to all articles