Files
NexusOS/tests/test_mail_creds.py
T
Athena 26b471d259 Merge origin/main (v1.2.0: Projects, modules, in-app updates)
Reconciles 17 commits of this session's work (self-alteration tools,
vendored Curry, slash-command dispatch, Windows toolchain/gate fixes)
against origin/main's v1.2.0 sync (Projects/RAG scoping, a new modules/
system for mail and network, in-app updates, the standalone memory
microservice folded into an in-process curator, KDE desktop theme
overhaul). Nine real conflicts, each resolved by hand after reading both
sides' actual diffs rather than picking one side wholesale:

- synapse/tools.py, tests/test_tools.py: origin/main's diff here was
  small and clean (read_file/list_files, two new tests) despite git's
  diff3 flagging the whole file as one conflict blob -- reset to this
  branch's version and hand-spliced their addition in at the same
  points they used, rather than trying to reconcile a false 800-line
  conflict. Found and fixed a real bug while verifying: _list_files
  returned backslash-separated paths on Windows, which don't match the
  forward-slash glob patterns the tool's own schema documents.
- synapse/main.py: kept this branch's cue-based standing advertisement
  of render_preview/run_snippet (independent of any playbook granting
  them) AND adopted origin/main's fix for routed reference playbooks
  not bringing their own tools along -- dropping either would have been
  a real regression, not just a style difference. Also: the standalone
  memory service (port 8001) is gone upstream, so its dead CORS/kill-
  target entries were removed; NEXUS_BACKEND_PORT parameterization and
  the manage_ollama-conditional kill logic (this branch's remote-Ollama
  support) were kept over origin/main's hardcoded equivalents.
- synapse/memory/store.py: kept this branch's _delete_message_vectors
  helper (already reused elsewhere, batches to stay under SQLite's
  variable limit) over origin/main's inline duplicate of the same fix.
- synapse/nexus_config.py, nexusos_cli/ncp.py: dropped the now-dead
  memory-service port/service entries; kept NEXUS_BACKEND_PORT env
  override and the manage_ollama-conditional kill-target list.
- CLAUDE.md, README.md: merged both sides' additions, no real conflict.

Found and fixed three more issues while independently verifying the
merged tree, none of them mine or origin/main's alone -- only visible
once both sides actually ran together:

- modules/ (the new mail+network package) was never added to
  pyproject.toml's wheel `packages` list OR the sdist's `include`
  allowlist, so `from modules.registry import ROUTERS` in main.py would
  ImportError on any wheel install. Fixed both; bin/check.sh's
  packaging gate now asserts modules/ actually ships. tests/
  test_packaging_deps.py's FIRST_PARTY/SHIPPED_PACKAGES sets were
  updated to recognize the new package.
- tests/test_mail_creds.py's 0600-mode assertions are POSIX-only --
  NTFS has no equivalent permission bits, so os.open(path, 0o600) on
  Windows just creates a normal file and stat.S_IMODE reports 0o666
  regardless. Made the assertions platform-aware rather than skip real
  coverage (the temp-file-cleanup and password round-trip checks in the
  same test still run on Windows) or paper over a genuine OS
  limitation with a fake pass.
- tests/test_kde_theme.py used bare Path.read_text() in fifteen places;
  Windows' default locale encoding (cp1252, not UTF-8) can't decode a
  real UTF-8 byte in the QML it reads, and did fail on one of the
  fifteen. Fixed all fifteen, not just the one that happened to trip
  today, since the other fourteen were equally fragile.

Verified: full bin/check.sh reports OK end-to-end on this Windows
checkout -- pytest (tests + management): 295 passed, 0 failed, 9
skipped; eslint clean; frontend node:test 57/57; PowerShell/shell
parse clean; wheel + sdist pass twine check and now correctly carry
modules/ (60 files, up from 52 pre-merge). synapse.main:app builds
with 74 routes (up from 54 pre-merge, matching the new Projects/mail/
network endpoints).
2026-08-26 02:09:23 -05:00

75 lines
3.3 KiB
Python

"""Credential handling for the mail module.
Both checks guard fixes for real defects: the account file used to be written at
the umask and chmodded afterwards, and the IMAP/SMTP connections used to take
Python's stdlib SSL context, which verifies nothing.
The 0600-mode assertions are POSIX-only: NTFS has no rwx-owner/group/other bit
model, so os.open(..., 0o600) on Windows creates a normal read-write file and
stat.S_IMODE reports 0o666 regardless of the mode argument -- Python's mode
param there only round-trips the read-only *attribute*, not real ACL-based
per-user access control (that needs pywin32/icacls, out of scope for a local
single-user app whose own user-profile directory is already the actual access
boundary on Windows). Skip rather than assert something the OS can't provide.
"""
import json
import os
import ssl
import stat
import sys
import pytest
from modules.mail import backend as mail
_WINDOWS_NO_POSIX_MODE = pytest.mark.skipif(
sys.platform == "win32",
reason="0600 is a POSIX permission model; NTFS has no equivalent bits to assert on",
)
def test_account_file_is_never_group_or_world_readable(tmp_path, monkeypatch):
monkeypatch.setattr(mail, "_ACCOUNT_FILE", tmp_path / "mail_accounts.json")
mail._write_accounts([{**mail._DEFAULTS, "id": "abc", "username": "u", "password": "secret"}])
# The mode assertion only means something on POSIX; the rest of this test
# (no temp file left behind, password round-trip) is platform-independent
# and must keep running on Windows.
if sys.platform != "win32":
mode = stat.S_IMODE((tmp_path / "mail_accounts.json").stat().st_mode)
assert mode == 0o600, f"account file is {oct(mode)}, expected 0o600"
assert not list(tmp_path.glob("*.tmp")), "temp file left behind"
# The password round-trips to disk but never to the API.
assert mail.load_accounts()[0]["password"] == "secret"
assert "password" not in mail.public_account(mail.get_account("abc"))
assert mail.public_account(mail.get_account("abc"))["has_password"] is True
assert json.loads((tmp_path / "mail_accounts.json").read_text())["accounts"]
@_WINDOWS_NO_POSIX_MODE
def test_account_file_is_0600_while_it_is_being_written(tmp_path, monkeypatch):
"""The old code wrote at the umask and chmodded afterwards, so the file sat
world-readable for the length of the write. Assert the handle it is written
through is already 0600 -- the pre-fix version never wrote through a handle
at all (json.dumps to a string, then write_text), so this fails against it."""
monkeypatch.setattr(mail, "_ACCOUNT_FILE", tmp_path / "mail_accounts.json")
seen = {}
real_dump = mail.json.dump
def spy(obj, fh, **kw):
seen["mode"] = stat.S_IMODE(os.fstat(fh.fileno()).st_mode)
return real_dump(obj, fh, **kw)
monkeypatch.setattr(mail.json, "dump", spy)
mail._write_accounts([{**mail._DEFAULTS, "id": "abc", "username": "u", "password": "secret"}])
assert seen["mode"] == 0o600, f"written through a {oct(seen['mode'])} handle"
def test_tls_context_verifies_certificate_and_hostname():
# ssl._create_stdlib_context(), the imaplib/smtplib fallback, gives
# CERT_NONE + check_hostname False -- which is what this replaced.
assert mail._TLS.verify_mode is ssl.CERT_REQUIRED
assert mail._TLS.check_hostname is True