蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 mongosh 认证参数解析、createUser RBAC 鉴权、security.authorization 门禁及 dropUser 验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-user.py
explore-user.py181 行
"""Offline MongoDB user management, RBAC roles, auth & security.authorization verifier (Ch09 user)."""
import hashlib
import json

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"

ROLE_PRIVILEGES = {
    "read": {"find"},
    "readWrite": {"find", "insert", "update", "delete"},
    "dbAdmin": {"createIndex", "dropCollection", "collStats", "renameCollection"},
    "dbOwner": {"find", "insert", "update", "delete", "createIndex", "dropCollection", "createUser"},
}


class OfflineAuthServer:
    def __init__(self):
        self.authorization_enabled = False
        self.users = {}  # (auth_db, username) -> {"pwd_hash": ..., "roles": [...]}

    @staticmethod
    def _hash_pwd(user: str, pwd: str) -> str:
        return hashlib.sha256(f"{user}:{pwd}".encode("utf-8")).hexdigest()

    def create_user(self, auth_db: str, user: str, pwd: str, roles: list):
        self.users[(auth_db, user)] = {
            "pwd_hash": self._hash_pwd(user, pwd),
            "roles": list(roles),
        }
        return {"ok": 1}

    def auth(self, auth_db: str, user: str, pwd: str) -> int:
        rec = self.users.get((auth_db, user))
        if not rec or rec["pwd_hash"] != self._hash_pwd(user, pwd):
            return 0
        return 1

    def check_permission(self, auth_db: str, user: str | None, target_db: str, action: str) -> bool:
        if not self.authorization_enabled:
            return True
        if user is None or (auth_db, user) not in self.users:
            return False
        for role_spec in self.users[(auth_db, user)]["roles"]:
            if role_spec["db"] == target_db and action in ROLE_PRIVILEGES.get(role_spec["role"], set()):
                return True
        return False

    def drop_user(self, auth_db: str, user: str) -> bool:
        return self.users.pop((auth_db, user), None) is not None


def case_mongosh_host_port_auth_cli():
    argv = [
        "mongosh",
        "--host",
        "localhost",
        "--port",
        "27017",
        "-u",
        "testuser",
        "-p",
        "password123",
        "--authenticationDatabase",
        "testdb",
    ]
    parsed = {
        "host": argv[argv.index("--host") + 1],
        "port": int(argv[argv.index("--port") + 1]),
        "user": argv[argv.index("-u") + 1],
        "auth_db": argv[argv.index("--authenticationDatabase") + 1],
    }
    expected = {"host": "localhost", "port": 27017, "user": "testuser", "auth_db": "testdb"}
    return {
        "name": "mongosh_host_port_auth_cli",
        "summary": "解析 mongosh --host/--port/-u/-p/--authenticationDatabase 认证连接命令行参数。",
        "expected": expected,
        "actual": parsed,
        "passed": parsed == expected,
    }


def case_create_user_and_rbac_roles():
    srv = OfflineAuthServer()
    srv.authorization_enabled = True
    res = srv.create_user(
        "testdb",
        "testuser",
        "password123",
        [
            {"role": "readWrite", "db": "testdb"},
            {"role": "dbAdmin", "db": "testdb"},
        ],
    )
    actual = {
        "create_ok": res["ok"] == 1,
        "can_insert_testdb": srv.check_permission("testdb", "testuser", "testdb", "insert"),
        "can_create_index_testdb": srv.check_permission("testdb", "testuser", "testdb", "createIndex"),
        "denied_other_db": not srv.check_permission("testdb", "testuser", "prod_db", "find"),
    }
    expected = {
        "create_ok": True,
        "can_insert_testdb": True,
        "can_create_index_testdb": True,
        "denied_other_db": True,
    }
    return {
        "name": "create_user_and_rbac_roles",
        "summary": "验证 db.createUser 分配 readWrite 与 dbAdmin 角色后的本库授权与跨库隔离拦截。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_auth_and_security_authorization_config():
    conf = "security:\n  authorization: \"enabled\"\n"
    enabled = 'authorization: "enabled"' in conf
    srv = OfflineAuthServer()
    srv.create_user("testdb", "testuser", "password123", [{"role": "readWrite", "db": "testdb"}])
    anon_before = srv.check_permission("testdb", None, "testdb", "find")
    srv.authorization_enabled = enabled
    anon_after = srv.check_permission("testdb", None, "testdb", "find")
    good_auth = srv.auth("testdb", "testuser", "password123")
    bad_auth = srv.auth("testdb", "testuser", "wrongpwd")
    actual = {
        "anon_allowed_before_enable": anon_before,
        "anon_blocked_after_enable": not anon_after,
        "good_auth_result": good_auth,
        "bad_auth_result": bad_auth,
    }
    expected = {
        "anon_allowed_before_enable": True,
        "anon_blocked_after_enable": True,
        "good_auth_result": 1,
        "bad_auth_result": 0,
    }
    return {
        "name": "auth_and_security_authorization_config",
        "summary": "验证 security.authorization: enabled 生效前后匿名访问拦截与 db.auth 凭据校验。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_drop_user_and_relogin_rejection():
    srv = OfflineAuthServer()
    srv.authorization_enabled = True
    srv.create_user("testdb", "testuser", "password123", [{"role": "readWrite", "db": "testdb"}])
    auth_before = srv.auth("testdb", "testuser", "password123")
    dropped = srv.drop_user("testdb", "testuser")
    auth_after = srv.auth("testdb", "testuser", "password123")
    can_read_after = srv.check_permission("testdb", "testuser", "testdb", "find")
    actual = {
        "auth_before": auth_before,
        "dropped": dropped,
        "auth_after": auth_after,
        "can_read_after": can_read_after,
    }
    expected = {"auth_before": 1, "dropped": True, "auth_after": 0, "can_read_after": False}
    return {
        "name": "drop_user_and_relogin_rejection",
        "summary": "验证 db.dropUser 删除用户后无法再次认证且操作权限立即失效。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_mongosh_host_port_auth_cli(),
        case_create_user_and_rbac_roles(),
        case_auth_and_security_authorization_config(),
        case_drop_user_and_relogin_rejection(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mongodb-user-lab/explore-user.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-user.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1775.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习