feat: block direct MCP imports and unsanctioned keychain access (Closes #558)
Require a sanctioned MCP daemon (or pytest) before get_auth_header and keychain credential fill so raw shell imports cannot bypass preflight gates.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Tests for sanctioned MCP daemon guards (#558)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import mcp_daemon_guard
|
||||
import gitea_auth
|
||||
|
||||
|
||||
class TestMcpDaemonGuard(unittest.TestCase):
|
||||
def test_unsanctioned_blocks_mutation_runtime(self):
|
||||
env = {k: v for k, v in os.environ.items() if k not in {
|
||||
mcp_daemon_guard.SANCTIONED_DAEMON_ENV,
|
||||
mcp_daemon_guard.ALLOW_DIRECT_IMPORT_ENV,
|
||||
"PYTEST_CURRENT_TEST",
|
||||
}}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
with self.assertRaises(mcp_daemon_guard.UnsanctionedRuntimeError):
|
||||
mcp_daemon_guard.assert_sanctioned_mutation_runtime("test")
|
||||
|
||||
def test_pytest_allows_runtime(self):
|
||||
# Running under pytest already sets PYTEST_CURRENT_TEST.
|
||||
mcp_daemon_guard.assert_sanctioned_mutation_runtime("pytest")
|
||||
|
||||
def test_mark_sanctioned_allows(self):
|
||||
env = {k: v for k, v in os.environ.items() if k != "PYTEST_CURRENT_TEST"}
|
||||
env[mcp_daemon_guard.SANCTIONED_DAEMON_ENV] = "1"
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
mcp_daemon_guard.assert_sanctioned_mutation_runtime("daemon")
|
||||
|
||||
def test_keychain_blocked_without_sanction(self):
|
||||
env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k
|
||||
not in {
|
||||
mcp_daemon_guard.SANCTIONED_DAEMON_ENV,
|
||||
mcp_daemon_guard.ALLOW_DIRECT_IMPORT_ENV,
|
||||
mcp_daemon_guard.ALLOW_KEYCHAIN_CLI_ENV,
|
||||
"PYTEST_CURRENT_TEST",
|
||||
}
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
with self.assertRaises(mcp_daemon_guard.UnsanctionedRuntimeError):
|
||||
mcp_daemon_guard.assert_keychain_access_allowed()
|
||||
|
||||
def test_get_auth_header_blocked_when_unsanctioned(self):
|
||||
env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k
|
||||
not in {
|
||||
mcp_daemon_guard.SANCTIONED_DAEMON_ENV,
|
||||
mcp_daemon_guard.ALLOW_DIRECT_IMPORT_ENV,
|
||||
"PYTEST_CURRENT_TEST",
|
||||
}
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
with self.assertRaises(mcp_daemon_guard.UnsanctionedRuntimeError):
|
||||
gitea_auth.get_auth_header("gitea.prgs.cc")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user