Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/monarch_mcp_server/secure_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,20 @@ def __init__(self) -> None:

def _save_token_file(self, token: str) -> None:
_TOKEN_DIR.mkdir(parents=True, exist_ok=True)
# Write with owner-only permissions
_TOKEN_FILE.write_text(token)
_TOKEN_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR) # 600
_TOKEN_DIR.chmod(stat.S_IRWXU) # 700
# Create the file already locked to owner-only (0600) instead of
# write_text()-then-chmod, which leaves a window where the token is
# world-readable under a default umask.
fd = os.open(
_TOKEN_FILE,
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
stat.S_IRUSR | stat.S_IWUSR,
)
with os.fdopen(fd, "w") as f:
f.write(token)
# O_CREAT honors the mode only when creating; enforce it for an
# existing file too.
_TOKEN_FILE.chmod(stat.S_IRUSR | stat.S_IWUSR) # 600
logger.info(f"✅ Token saved to {_TOKEN_FILE}")

def _load_token_file(self) -> Optional[str]:
Expand Down
35 changes: 35 additions & 0 deletions tests/test_secure_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,38 @@ def fake_create(**kwargs):
def test_no_session_returns_none(self, storage_keyring):
session, _ = storage_keyring
assert session.get_authenticated_client() is None


class TestFileFallbackPermissions:
"""The plaintext file fallback must never expose the token to other users."""

def test_token_file_created_locked_not_via_write_text(self, tmp_path, monkeypatch):
"""The token file must be created already locked to 0600, not written
world-readable and chmod'd afterward (which leaves a race window)."""
import stat as _stat

monkeypatch.setattr(ss_module, "_TOKEN_DIR", tmp_path / "store")
monkeypatch.setattr(ss_module, "_TOKEN_FILE", tmp_path / "store" / "token")

# A revert to write_text()-then-chmod would trip this and fail loudly.
def _boom(*_a, **_k):
raise AssertionError("token file must not be created via write_text()")

monkeypatch.setattr(ss_module.Path, "write_text", _boom)

create_modes = []
real_open = ss_module.os.open

def _recording_open(path, flags, mode=0o777):
create_modes.append(mode)
return real_open(path, flags, mode)

monkeypatch.setattr(ss_module.os, "open", _recording_open)

session = ss_module.SecureMonarchSession()
session._save_token_file("super-secret-token")

token_file = tmp_path / "store" / "token"
assert token_file.read_text() == "super-secret-token"
assert create_modes and all(m == 0o600 for m in create_modes)
assert _stat.S_IMODE(token_file.stat().st_mode) == 0o600