Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Secure your Azure Cosmos DB Shell deployments with these comprehensive security best practices.
Authentication methods
1. Microsoft Entra ID (recommended)
Best for: Development, testing, and production environments
Advantages:
- Most secure authentication method
- No credentials stored locally
- Automatic token refresh
- Supports multifactor authentication (MFA)
- Full audit trail in Azure
Implementation:
When launched without connection arguments, Cosmos DB Shell starts disconnected. Authenticate by connecting to your account endpoint with Microsoft Entra ID:
cosmosdbshell
CS > connect https://<account-name>.documents.azure.com:443/ --tenant=<tenant-id>
The browser opens for Azure sign-in after you run connect. Complete the flow and the shell uses your Microsoft Entra ID credentials.
Configuration:
connect <account_endpoint> --tenant=<tenant-id>
Security Benefits:
- Credentials never stored on disk
- Tokens automatically refreshed
- MFA provides additional protection
- RBAC controls what you can access
2. Managed identity (production)
Best for: Azure-hosted applications and production environments
Advantages:
- No credential management required
- Automatic token refresh
- Works with Azure services (App Service, Functions, AKS)
- No secrets to rotate
- Enhanced security in Azure
Implementation:
Enable managed identity on Azure resource:
For App Service:
{
"identity": {
"type": "SystemAssigned"
}
}
From your terminal:
cosmosdbshell --connect https://<account-name>.documents.azure.com:443/ --connect-managed-identity=<client-id>
Security Configuration:
- Enable managed identity on Azure resource
- Assign Cosmos DB RBAC role to identity
- Shell automatically uses identity credentials
- No secrets needed
Benefits:
- Zero credential management
- Automatic token rotation
- Audit trail for all operations
- Complies with security standards
3. Account key (development only)
Best for: Local development and testing only
Disadvantages:
- Keys stored locally (security risk)
- Manual rotation required
- Single point of failure
- Cannot use MFA
- Not recommended for production
Implementation:
cosmosdbshell --connect "<connection_string>"
Minimal Risk Usage:
- Development/testing only
- Never commit to source control
- Use environment variables:
# Set environment variable
export COSMOS_CONNECTION_STRING="your-connection-string"
# Use in script
cosmosdbshell --connect "$COSMOS_CONNECTION_STRING"
Credential management
Best practices
1. Never hardcode credentials
❌ Bad:
#!/bin/bash
cosmosdbshell --connect "AccountEndpoint=https://myaccount.documents.azure.com/;AccountKey=<account-key>;"
✅ Good:
#!/bin/bash
cosmosdbshell --connect "$COSMOS_CONNECTION_STRING"
2. Use environment variables
Development:
# .env file (development only)
COSMOS_CONNECTION_STRING="your-connection-string"
# Load and use
source .env
cosmosdbshell --connect "$COSMOS_CONNECTION_STRING"
3. Store in secure vaults
Azure Key Vault:
# Store connection string
az keyvault secret set --vault-name myKeyVault \
--name cosmos-connection-string \
--value "your-connection-string"
# Retrieve and use
CONNECTION_STRING=$(az keyvault secret show \
--vault-name myKeyVault \
--name cosmos-connection-string \
--query value -o tsv)
cosmosdbshell --connect "$CONNECTION_STRING"
Local Development:
- Use
.envfiles (add to.gitignore) - Load via environment variables
- Never commit secrets
4. Rotate keys regularly
Key Rotation Process:
- Generate new key in Azure portal
- Update applications with new key
- Delete old key after verification
- Test all applications work
RBAC (role-based access control)
Implement least privilege
Grant the minimum permissions required for the intended operations. Azure Cosmos DB native data-plane roles and Azure management-plane roles are separate.
| Data-plane role | Use case |
|---|---|
Cosmos DB Built-in Data Reader |
Read documents and execute queries. |
Cosmos DB Built-in Data Contributor |
Create, read, update, and delete documents. |
A management-plane account Reader role doesn't grant document-query access. Use the Azure Cosmos DB role-based access control guide to assign native data roles to the intended principal. Don't assign these native roles with the generic az role assignment create command.
Scope access by container
Scope a native data-role assignment to the intended database or container when possible. Use a custom native data role if built-in roles grant more actions than the workflow requires. Management operations can require a separate Azure role; don't treat data access as account-management authorization.
Data protection
1. Encryption in transit
Use the account's HTTPS endpoint. TLS negotiation uses the platform and SDK configuration; the shell doesn't provide --tls-version or --min-tls-version startup switches.
Use doctor to inspect connection and TLS diagnostics without changing the connection. Configure account-side transport requirements through the supported Azure Cosmos DB account settings, not invented shell flags.
2. Encryption at rest
Enable Encryption at Rest:
Azure handles encryption automatically, but verify:
- Go to Azure portal > Cosmos DB Account
- Settings > Encryption at Rest
- Verify encryption is enabled
Verify:
# Check encryption settings
az cosmosdb show --resource-group myResourceGroup \
--name myaccount \
--query "encryption.keyWrapperProperties" -o table
3. Customer-managed keys (CMK)
For Enhanced Security:
- Create Azure Key Vault
- Generate encryption key
- Configure Cosmos DB to use CMK
Setup:
# Create key vault
az keyvault create --resource-group myResourceGroup \
--name myKeyVault
# Create key
az keyvault key create --vault-name myKeyVault \
--name cosmos-key
# Configure Cosmos DB (via Portal or Terraform)
Network security
1. IP firewall
Enable Firewall:
- Azure portal > Cosmos DB Account > Firewall
- Add your IP address(es)
- Save changes
Command Line:
# Add IP to firewall
az cosmosdb update --resource-group myResourceGroup \
--name myaccount \
--ip-range-filter "203.0.113.0/24"
2. Virtual endpoints
Restrict to VNet:
# Enable virtual endpoint
az cosmosdb update --resource-group myResourceGroup \
--name myaccount \
--enable-virtual-network true
3. Private endpoints
For Maximum Network Isolation:
- Create private endpoint in Azure portal
- Configure DNS settings
- Shell connects via private network
Benefits:
- No internet exposure
- Restricted network access
- Supports enterprise network isolation policies
MCP server security
The optional shell MCP server runs locally, not as a hosted Azure service. It binds to loopback with host and origin validation. Connect trusted local clients to http://127.0.0.1:6128/ for Streamable HTTP, or /sse for legacy SSE. Don't expose it with tunnels or port forwarding.
Connection identity and permissions
MCP uses the shell's current Azure Cosmos DB connection. Authenticate that connection with Microsoft Entra ID or managed identity, then grant only the required data-plane and management-plane permissions. Enabling MCP doesn't add account access or create a separate MCP authentication boundary.
Clients share the shell's connection and navigation. Verify account-root info and name the database and container explicitly before an operation. Treat document content and resource names as data, not instructions.
Destructive operations
Destructive tools require explicit user confirmation. Force arguments don't bypass the MCP gate. A client that can't confirm, a declined prompt, or a changed connection or navigation context causes refusal. Don't bypass it with another execution route.
Preview exact-item deletions and use their actual ETags on execution. batch is atomic only within one partition key; bulk and import can partially succeed without rollback. Inspect outcomes before retrying an interrupted write.
History and client data handling
Replayable shell history can contain MCP commands and connection strings. Protect history files and local exports as sensitive data. Review your client's model-provider data handling before allowing it to retrieve documents. To learn about supported settings, tool restrictions, and pagination, see Shell MCP setup.
Audit and monitoring
1. Enable audit logging
Azure Audit Logs:
# View audit logs
az monitor activity-log list \
--resource-group myResourceGroup \
--query "[?resourceId=='<cosmos-resource-id>']"
2. Monitor MCP activity
Inspect the shell terminal and your MCP client's tool-call diagnostics. The extension doesn't expose an MCP logLevel setting. Use the shell's optional --otel tracing according to the upstream configuration when distributed tracing is required.
Review diagnostics before sharing them; resource names and query results can be sensitive. Shell history isn't a substitute for service-side audit logging.
3. Query metrics
Monitor Query Performance:
# Review query metrics
query "SELECT TOP 5 c.id FROM c" --database=MyDatabase --container=MyContainer --max=5 --metrics
Metrics to Track:
- Request units (RU) used
- Execution time
- Item count
Compliance and standards
1. Data residency
Ensure Data Stays in Region:
# Deploy Cosmos DB in specific region
az cosmosdb create --resource-group myResourceGroup \
--name myaccount \
--locations regionName="East US" \
--databases only
2. Compliance standards
Azure Cosmos DB maintains a broad set of compliance certifications.
- For the latest certifications and audit reports, see Microsoft Azure Compliance offerings.
- For compliance information specific to this service, see compliance in Azure Cosmos DB.
3. Data retention
Set Time-to-Live (TTL) for Sensitive Data:
Inspect the existing container's configuration before changing its retention. Replace the sample resource names with your intended target:
ttl show --database=MyDatabase --container=sensitive_data
ttl set 2592000 --database=MyDatabase --container=sensitive_data
The second command changes the default item TTL to 30 days after each item's last modification. It can expire existing data; item-level TTL settings can override the default. Expired items stop appearing in query results, but physical deletion happens asynchronously. Review the TTL behavior before applying a retention change.
Security checklist
- [ ] Use Microsoft Entra ID for authentication
- [ ] Enable MFA on Azure account
- [ ] Implement least-privilege RBAC
- [ ] Enable IP firewall
- [ ] Use encrypted connections (TLS 1.2+)
- [ ] Enable audit logging
- [ ] Monitor MCP server activity
- [ ] Store credentials in Key Vault
- [ ] Rotate keys regularly
- [ ] Use private endpoints in production
- [ ] Enable encryption at rest
- [ ] Review compliance requirements
- [ ] Document security policies
- [ ] Train users on security practices
Common security mistakes
❌ Storing keys in code
# DON'T do this
cosmosdbshell --connect "AccountEndpoint=https://myaccount.documents.azure.com/;AccountKey=<account-key>;"
✅ Use environment variables
# DO this
export COSMOS_CONNECTION_STRING="..."
cosmosdbshell --connect "$COSMOS_CONNECTION_STRING"
❌ Using account key in production
# DON'T use keys in production with hardcoded connection strings
cosmosdbshell --connect "AccountEndpoint=https://myaccount.documents.azure.com:443/;AccountKey=<your-account-key>;"
✅ Use managed identity
# DO use managed identity
cosmosdbshell --connect https://<account-name>.documents.azure.com:443/ --connect-managed-identity=<client-id>
❌ Exposing local MCP remotely
Don't expose the loopback-bound shell server through a public proxy, tunnel, or port forwarding.
✅ Restrict MCP access
Keep the server local, connect only trusted clients, and use an identity with narrowly scoped permissions. Configure only the supported extension settings.
Security resources
AI tools
Use these actions to discuss documented security guidance without sharing secrets.
For documentation-only retrieval, use the Microsoft Learn MCP server. For a compact guide index, use the Shell documentation index (llms.txt). The index doesn't change crawler permissions or guarantee retrieval.
Shell MCP requires separate setup and can read or change data under the configured permissions, so review tool calls before approving them. Don't share credentials or sensitive data.
Connect your AI agent
Review authentication and permissions before enabling Shell MCP.Read as Markdown
Open a text version to copy into your assistant.Ask ChatGPT
Explain authentication, access controls, and MCP precautions.Ask Claude
Explain authentication, access controls, and MCP precautions.
ChatGPT and Claude receive only the public article URL and a starter prompt. You might need to sign in. If retrieval fails, copy the Markdown text. These links don't configure database access. An assistant's explanation isn't a security assessment of your deployment.
Support
For security concerns or vulnerability reports: