A collection of utilities focused on streamlining MongoDB security
Project description
MongoDB IAM Utilities for Python
This repository is a utility project focused on streamlining IAM processes for MongoDB, leveraging the native driver (Python in this case), with the understanding that similar projects could be developed for other platforms. Its goal is to simplify and accelerate security-related tasks, making IAM management more efficient.
iam-util (Role Rectifier) is a Python package that helps manage and validate user roles and privileges in MongoDB databases. It allows developers to:
- ✅ Retrieve all roles assigned to a user across multiple databases.
- ✅ Identify custom roles (excluding built-in roles).
- ✅ Retrieve detailed privileges of specific roles.
- ✅ Verify missing and extra permissions for a given list of required permissions.
This package is designed for system administrators, DevOps engineers, and developers who manage MongoDB access control and want to ensure role consistency and security.
📌 Installation
pip install mongodb-solution-assurance-iam-util
Alternatively, install it directly from the source:
git clone https://github.com/mongodb-industry-solutions/user-access-checks.git
cd user-access-checks
mv .env.example .env
pip install -r requirements.txt
🔬 Test
Run tests using pytest:
pytest
or with Make
make test
🛠 Usage Example
Connect to MongoDB and Retrieve User Roles
import os
from dotenv import load_dotenv # Import dotenv to load environment variables
from mongodb_solution_assurance_iam_util import MongoRoleManager # Import the custom role manager
# Load environment variables from the `.env` file
# This ensures sensitive values (like credentials) are not hardcoded in the script.
load_dotenv()
# Create the MongoDB connection string using environment variables
db_username = os.environ.get("DB_USERNAME") # Retrieve the database username
db_password = os.environ.get("DB_PASSWORD") # Retrieve the database password
db_host = os.environ.get("DB_HOST") # Retrieve the database host
db_cluster = os.environ.get("DB_CLUSTER") # Retrieve the cluster name
# Format the connection string required for MongoDB
connectionString = f"mongodb+srv://{db_username}:{db_password}@{db_host}/?retryWrites=true&w=majority&appName={db_cluster}"
def main():
"""
Main function to handle MongoDB role permissions verification.
"""
# Print the connection string for debugging purposes (optional and for testing purpose only).
print("Connection string:", connectionString)
# --------------------------------
# OUTPUT:
# Connection string: mongodb+srv://<username>:<password>@<host>/?retryWrites=true&w=majority&appName=<cluster>
# Define the list of required permissions that need to be verified
required_permissions = [
"search", # Permission to search documents
"read", # Permission to read documents
"find", # Permission to find documents based on a query
"insert", # Permission to insert new documents
"update", # Permission to update existing documents
"remove", # Permission to remove documents
"collMod", # Permission to modify collections
]
# Initialize the MongoRoleManager with the connection string
role_manager = MongoRoleManager(connectionString)
# Verify that the necessary permissions are available for the database
res = role_manager.verifyPermissions(required_permissions)
# Print the verification result to the console
print("--------------------------------")
print(res)
# --------------------------------
# OUTPUT:
# {
# 'extra': ['viewRole', 'dropCollection', 'killAnyCursor', 'analyze'],
# 'missing': ['search', 'read'],
# 'present': ['remove', 'update', 'find', 'insert', 'collMod']
# }
# Get user roles
userRoles = role_manager.getUserRoles()
# Print the list of roles associated with the user in the connection string
print("--------------------------------")
print(userRoles)
# OUTPUT:
# --------------------------------
# ['readWrite', 'read', 'PowerSyncCustomRole']
# Ensure the script runs only when executed directly (not imported as a module)
if __name__ == "__main__":
main()
This code snippet establishes a connection to a MongoDB database using a constructed connection string, then utilizes a MongoRoleManager instance to retrieve the roles assigned to the authenticated user. It serves to programmatically access and display the user's role-based access control within the MongoDB environment, facilitating security audits and role management.
🚀 Verify Missing & Extra Permissions
Checking access privileges for the user defined in the connection string of the previous example:
requiredPermissions = [
"search",
"read",
"find",
"insert",
"update",
"remove",
"collMod",
]
permissions = role_manager.verifyPermissions(requiredPermissions)
## over-privileged
print("Extra Permissions:", permissions["extra"])
## under-privilidged
print("Missing Permissions:", permissions["missing"])
## required-privileged
print("Valid Permissions:", permissions["present"])
The provided code snippet demonstrates how to effectively verify and manage user permissions within a MongoDB environment. Utilizing the verifyPermissions method, it compares a list of requiredPermissions against the actual privileges granted to the user, as determined by their assigned roles.
This process then categorizes permissions into three distinct groups:
- Extra Permissions: highlights any privileges exceeding the required set, indicating potential over-privileging.
- Missing Permissions: identifies necessary permissions that are absent, revealing under-privileging.
- Valid Permissions: confirms the required privileges that are correctly assigned.
This functionality allows for precise auditing and adjustment of user access, ensuring adherence to security best practices and minimizing risks associated with excessive or insufficient permissions.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mongodb_solution_assurance_iam_util-1.0.0.tar.gz.
File metadata
- Download URL: mongodb_solution_assurance_iam_util-1.0.0.tar.gz
- Upload date:
- Size: 12.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7fb09bf05aacb39a6af1c881f1b751cae01230277843ea5c66c244bab9b180c8
|
|
| MD5 |
b9fd35dc3a209b0b9854ddcb2a2d2d53
|
|
| BLAKE2b-256 |
9858f311dfc13a0de93e41cd5066670a92e3d5c2a70e71319b3ae37f9be08715
|
File details
Details for the file mongodb_solution_assurance_iam_util-1.0.0-py3-none-any.whl.
File metadata
- Download URL: mongodb_solution_assurance_iam_util-1.0.0-py3-none-any.whl
- Upload date:
- Size: 10.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0d5ce5292d6331e820a256ce04adf354d596208882145d8b1da744eed284f6f3
|
|
| MD5 |
1fbc6f97d4f60e3c67f71360046dbfbe
|
|
| BLAKE2b-256 |
004554c4fce6ff4eb01123fdda764e5a9cba7dd37062830841e4d18d564a7ddc
|