margin-core 0.1.0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {margin_core-0.1.0 → margin_core-0.1.1}/CHANGELOG.md +11 -0
  2. {margin_core-0.1.0 → margin_core-0.1.1}/PKG-INFO +1 -1
  3. {margin_core-0.1.0 → margin_core-0.1.1}/pyproject.toml +1 -1
  4. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/__init__.py +1 -1
  5. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/git.py +28 -3
  6. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/github.py +34 -9
  7. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_core_skeleton.py +1 -1
  8. margin_core-0.1.1/tests/test_security.py +178 -0
  9. {margin_core-0.1.0 → margin_core-0.1.1}/.gitignore +0 -0
  10. {margin_core-0.1.0 → margin_core-0.1.1}/LICENSE +0 -0
  11. {margin_core-0.1.0 → margin_core-0.1.1}/README.md +0 -0
  12. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/_fs.py +0 -0
  13. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/agent.py +0 -0
  14. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/config.py +0 -0
  15. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/errors.py +0 -0
  16. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/inputs.py +0 -0
  17. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/__init__.py +0 -0
  18. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/_chat_completions.py +0 -0
  19. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/_http.py +0 -0
  20. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/anthropic.py +0 -0
  21. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/base.py +0 -0
  22. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/catalog.py +0 -0
  23. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/factory.py +0 -0
  24. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/local.py +0 -0
  25. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/mock.py +0 -0
  26. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/openai.py +0 -0
  27. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/llm/pricing.py +0 -0
  28. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/__init__.py +0 -0
  29. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/base.py +0 -0
  30. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/filters.py +0 -0
  31. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/loaders/local.py +0 -0
  32. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/logging.py +0 -0
  33. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/models.py +0 -0
  34. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/py.typed +0 -0
  35. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/registry.py +0 -0
  36. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/reporting/__init__.py +0 -0
  37. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/reporting/json_report.py +0 -0
  38. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/reporting/markdown_report.py +0 -0
  39. {margin_core-0.1.0 → margin_core-0.1.1}/src/margin_core/runner.py +0 -0
  40. {margin_core-0.1.0 → margin_core-0.1.1}/tests/conftest.py +0 -0
  41. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_agent.py +0 -0
  42. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_config.py +0 -0
  43. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_filters.py +0 -0
  44. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_github_loader.py +0 -0
  45. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_history_scope.py +0 -0
  46. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_inputs.py +0 -0
  47. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_llm.py +0 -0
  48. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_llm_session.py +0 -0
  49. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_local_llm.py +0 -0
  50. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_local_loader.py +0 -0
  51. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_models.py +0 -0
  52. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_preclone_check.py +0 -0
  53. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_registry.py +0 -0
  54. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_reporting.py +0 -0
  55. {margin_core-0.1.0 → margin_core-0.1.1}/tests/test_user_settings.py +0 -0
@@ -4,6 +4,17 @@ All notable changes to this package are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.1.1] - 2026-10-21
8
+
9
+ ### Security
10
+ - A repository's own git config could make git run a program while margin read its history,
11
+ for example through `core.fsmonitor`. Every git command now overrides the repository's
12
+ config, turns hooks off and skips Git LFS downloads. This mattered most in Docker, where
13
+ git's own ownership check is turned off for the shared folder.
14
+ - Cancelling a run while a repository was being cloned could leave a half-written clone in
15
+ the temp folder. git now runs as a child process that is stopped before the folder is
16
+ deleted.
17
+
7
18
  ## [0.1.0] - 2026-10-21
8
19
 
9
20
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: margin-core
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: The shared core of margin: the agent contract, results with evidence, model clients and code loaders.
5
5
  Project-URL: Homepage, https://github.com/Waddah0-0/margin
6
6
  Project-URL: Source, https://github.com/Waddah0-0/margin/tree/main/packages/core
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "margin-core"
3
- version = "0.1.0"
3
+ version = "0.1.1"
4
4
  description = "The shared core of margin: the agent contract, results with evidence, model clients and code loaders."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -33,7 +33,7 @@ from margin_core.models import (
33
33
  from margin_core.registry import AgentRegistry, default_registry, get_agent, list_agents
34
34
  from margin_core.runner import run_agent
35
35
 
36
- __version__ = "0.1.0"
36
+ __version__ = "0.1.1"
37
37
 
38
38
  __all__ = [
39
39
  "AgentInfo",
@@ -1,4 +1,5 @@
1
- """Thin wrappers around the ``git`` CLI. Repository code is never executed."""
1
+ """Thin wrappers around the ``git`` CLI. Repository code is never executed: see
2
+ :data:`SAFE_GIT_CONFIG`."""
2
3
 
3
4
  from __future__ import annotations
4
5
 
@@ -29,8 +30,23 @@ def git_available() -> bool:
29
30
  return shutil.which("git") is not None
30
31
 
31
32
 
33
+ # Passed on every git command line, where they override any config, including a repository's
34
+ # own .git/config. A folder we are pointed at is untrusted: its config could name programs for
35
+ # git to run (core.fsmonitor), hooks could run on checkout, and Git LFS could download files
36
+ # from another server past our size limits.
37
+ SAFE_GIT_CONFIG = (
38
+ "core.fsmonitor=false",
39
+ "core.hooksPath=" + os.devnull,
40
+ "filter.lfs.smudge=",
41
+ "filter.lfs.process=",
42
+ "filter.lfs.required=false",
43
+ "i18n.logOutputEncoding=UTF-8",
44
+ )
45
+
46
+
32
47
  def safe_git_env() -> dict[str, str]:
33
- """Environment that prevents git from ever prompting (terminal, GUI, credential manager)."""
48
+ """Environment that prevents git from ever prompting (terminal, GUI, credential manager)
49
+ and from fetching Git LFS content."""
34
50
  env = dict(os.environ)
35
51
  env.update(
36
52
  {
@@ -38,14 +54,23 @@ def safe_git_env() -> dict[str, str]:
38
54
  "GIT_ASKPASS": "",
39
55
  "SSH_ASKPASS": "",
40
56
  "GCM_INTERACTIVE": "never",
57
+ "GIT_LFS_SKIP_SMUDGE": "1",
41
58
  }
42
59
  )
43
60
  return env
44
61
 
45
62
 
63
+ def git_command(args: list[str]) -> list[str]:
64
+ """``git <args>`` with the safety settings in front."""
65
+ cmd = ["git"]
66
+ for setting in SAFE_GIT_CONFIG:
67
+ cmd += ["-c", setting]
68
+ return cmd + args
69
+
70
+
46
71
  def run_git(args: list[str], cwd: Path | None = None, timeout_s: float = 60.0) -> str:
47
72
  """Run ``git <args>`` and return stdout (UTF-8). Raises :class:`GitCommandError`."""
48
- cmd = ["git", "-c", "i18n.logOutputEncoding=UTF-8", *args]
73
+ cmd = git_command(args)
49
74
  proc = subprocess.run(
50
75
  cmd,
51
76
  cwd=cwd,
@@ -14,8 +14,8 @@ it is never given to ``git``.
14
14
  from __future__ import annotations
15
15
 
16
16
  import asyncio
17
+ import contextlib
17
18
  import re
18
- import subprocess
19
19
  import tempfile
20
20
  from collections.abc import Sequence
21
21
  from pathlib import Path
@@ -27,7 +27,7 @@ from margin_core.config import get_settings
27
27
  from margin_core.errors import InvalidTargetError, LimitExceededError, LoaderError
28
28
  from margin_core.loaders.base import Loader, LoaderLimits, Workspace
29
29
  from margin_core.loaders.filters import FilterConfig
30
- from margin_core.loaders.git import GitCommandError, git_available, run_git
30
+ from margin_core.loaders.git import git_available, git_command, safe_git_env
31
31
  from margin_core.loaders.local import LocalLoader
32
32
 
33
33
  GITHUB_URL_RE = re.compile(
@@ -129,7 +129,7 @@ class GitHubLoader(Loader):
129
129
  )
130
130
  return None
131
131
 
132
- def _clone(self, url: str, dest: Path, branch: str | None) -> None:
132
+ def _clone_command(self, url: str, dest: Path, branch: str | None) -> list[str]:
133
133
  args = [
134
134
  "-c",
135
135
  "core.symlinks=false",
@@ -143,15 +143,32 @@ class GitHubLoader(Loader):
143
143
  ]
144
144
  if branch:
145
145
  args += ["--branch", branch]
146
- args += ["--", url, str(dest)]
146
+ return git_command([*args, "--", url, str(dest)])
147
+
148
+ async def _clone(self, url: str, dest: Path, branch: str | None) -> None:
149
+ """Clone as a child process we can kill. If the run is cancelled or the clone times
150
+ out, git is stopped and waited for before anything is deleted, so a half-written clone
151
+ never outlives the run."""
152
+ proc = await asyncio.create_subprocess_exec(
153
+ *self._clone_command(url, dest, branch),
154
+ stdin=asyncio.subprocess.DEVNULL,
155
+ stdout=asyncio.subprocess.DEVNULL,
156
+ stderr=asyncio.subprocess.PIPE,
157
+ env=safe_git_env(),
158
+ )
147
159
  try:
148
- run_git(args, timeout_s=self.limits.clone_timeout_s)
149
- except subprocess.TimeoutExpired as exc:
160
+ _, stderr = await asyncio.wait_for(proc.communicate(), self.limits.clone_timeout_s)
161
+ except TimeoutError as exc:
162
+ await _stop(proc)
150
163
  raise LimitExceededError(
151
164
  f"Clone timed out after {self.limits.clone_timeout_s:.0f}s"
152
165
  ) from exc
153
- except GitCommandError as exc:
154
- raise LoaderError(f"Could not clone {url}: {exc}") from exc
166
+ except BaseException: # cancelled
167
+ await _stop(proc)
168
+ raise
169
+ if proc.returncode != 0:
170
+ message = stderr.decode("utf-8", errors="replace").strip()
171
+ raise LoaderError(f"Could not clone {url}: {message}")
155
172
 
156
173
  async def load(
157
174
  self,
@@ -169,7 +186,7 @@ class GitHubLoader(Loader):
169
186
  tmp = Path(tempfile.mkdtemp(prefix="margin-"))
170
187
  try:
171
188
  dest = tmp / "repo"
172
- await asyncio.to_thread(self._clone, url, dest, branch)
189
+ await self._clone(url, dest, branch)
173
190
  size = await asyncio.to_thread(directory_size, dest)
174
191
  if size > self.limits.max_repo_size_bytes:
175
192
  raise LimitExceededError(
@@ -184,3 +201,11 @@ class GitHubLoader(Loader):
184
201
  if size_warning:
185
202
  ws.warnings.append(size_warning)
186
203
  return ws
204
+
205
+
206
+ async def _stop(proc: asyncio.subprocess.Process) -> None:
207
+ """Kill a child process and wait until it has really exited."""
208
+ if proc.returncode is None:
209
+ with contextlib.suppress(ProcessLookupError):
210
+ proc.kill()
211
+ await asyncio.shield(proc.wait())
@@ -2,4 +2,4 @@ from margin_core import __version__
2
2
 
3
3
 
4
4
  def test_core_version() -> None:
5
- assert __version__ == "0.1.0"
5
+ assert __version__ == "0.1.1"
@@ -0,0 +1,178 @@
1
+ """The security guarantees, each shown by an attempt to break it.
2
+
3
+ - a folder we are pointed at cannot make git run its programs (config, hooks, LFS);
4
+ - files outside the workspace cannot be read, by path or through a symlink;
5
+ - cancelling a run during a clone stops git and leaves nothing behind;
6
+ - secrets (API keys, the GitHub token) never appear in logs or error messages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+ import pytest
21
+ from margin_core.errors import InvalidTargetError
22
+ from margin_core.loaders import load_workspace
23
+ from margin_core.loaders.base import Workspace
24
+ from margin_core.loaders.git import SAFE_GIT_CONFIG, git_command, run_git
25
+ from margin_core.loaders.github import GitHubLoader
26
+
27
+ needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
28
+
29
+
30
+ def _git(repo: Path, *args: str) -> None:
31
+ subprocess.run(
32
+ ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args],
33
+ cwd=repo, check=True, capture_output=True,
34
+ ) # fmt: skip
35
+
36
+
37
+ def _trap(marker: Path) -> str:
38
+ """A command that, if git ever runs it, leaves ``marker`` behind."""
39
+ script = f"open({str(marker)!r}, 'w').write('ran')"
40
+ return f'"{sys.executable}" -c "{script}"'.replace("\\", "/")
41
+
42
+
43
+ # ---- 1. untrusted repository config -------------------------------------------------------
44
+
45
+
46
+ @needs_git
47
+ async def test_a_repository_cannot_make_git_run_its_programs(tmp_path: Path) -> None:
48
+ repo, marker = tmp_path / "hostile", tmp_path / "fsmonitor-ran"
49
+ repo.mkdir()
50
+ _git(repo, "init", "-q")
51
+ (repo / "app.py").write_text("x = 1\n", encoding="utf-8")
52
+ _git(repo, "add", ".")
53
+ _git(repo, "commit", "-q", "-m", "init")
54
+ # the repository's own config names a program for git to run on index reads
55
+ _git(repo, "config", "core.fsmonitor", _trap(marker))
56
+
57
+ # sanity: the trap is armed. Plain git, as a careless tool would call it, runs it.
58
+ subprocess.run(["git", "status"], cwd=repo, capture_output=True, check=False) # noqa: ASYNC221
59
+ if not marker.exists():
60
+ pytest.skip("this git does not run core.fsmonitor here; nothing to prove")
61
+ marker.unlink()
62
+
63
+ async with await load_workspace(str(repo)) as ws:
64
+ assert ws.git is not None
65
+ await ws.git.commits(max_count=10)
66
+ await ws.git.changed_files(max_count=10)
67
+ run_git(["status"], cwd=repo) # even an index-reading command, through margin's wrapper
68
+ assert not marker.exists(), "margin let the repository run a program"
69
+
70
+
71
+ def test_every_git_command_carries_the_safety_settings() -> None:
72
+ cmd = git_command(["log"])
73
+ for setting in SAFE_GIT_CONFIG:
74
+ assert cmd[cmd.index(setting) - 1] == "-c"
75
+ assert "core.fsmonitor=false" in cmd and "filter.lfs.smudge=" in cmd
76
+ assert cmd[-1] == "log"
77
+
78
+
79
+ # ---- 2. reading outside the workspace ------------------------------------------------------
80
+
81
+
82
+ def test_paths_cannot_leave_the_workspace(tmp_path: Path) -> None:
83
+ root = tmp_path / "ws"
84
+ root.mkdir()
85
+ (root / "ok.py").write_text("fine", encoding="utf-8")
86
+ (tmp_path / "secret.txt").write_text("secret", encoding="utf-8")
87
+ ws = Workspace(root=root, source=str(root))
88
+ assert ws.read_text("ok.py") == "fine"
89
+ for escape in ["../secret.txt", "sub/../../secret.txt", str(tmp_path / "secret.txt")]:
90
+ with pytest.raises(InvalidTargetError, match="escapes"):
91
+ ws.read_text(escape)
92
+ assert not ws.exists("../secret.txt")
93
+
94
+
95
+ def test_symlinks_cannot_lead_out_of_the_workspace(tmp_path: Path) -> None:
96
+ root = tmp_path / "ws"
97
+ root.mkdir()
98
+ (tmp_path / "secret.txt").write_text("secret", encoding="utf-8")
99
+ try:
100
+ (root / "link.py").symlink_to(tmp_path / "secret.txt")
101
+ except OSError:
102
+ pytest.skip("symlinks not permitted on this system (covered on Linux CI)")
103
+ with pytest.raises(InvalidTargetError, match="escapes"):
104
+ Workspace(root=root, source=str(root)).read_text("link.py")
105
+
106
+
107
+ # ---- 3. cancelling during a clone ------------------------------------------------------------
108
+
109
+
110
+ @needs_git
111
+ async def test_cancelling_during_a_clone_stops_git_and_leaves_nothing(
112
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
113
+ ) -> None:
114
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) # where the clone folder goes
115
+ started = tmp_path / "clone-started"
116
+ # stands in for a long clone: keeps writing into the destination until killed
117
+ slow_clone = (
118
+ "import pathlib, sys, time\n"
119
+ "dest = pathlib.Path(sys.argv[1]); dest.mkdir(parents=True)\n"
120
+ f"pathlib.Path({str(started)!r}).write_text('1')\n"
121
+ "for i in range(600):\n"
122
+ " (dest / f'f{i}').write_text('x'); time.sleep(0.05)\n"
123
+ )
124
+ loader = GitHubLoader(allow_non_github_urls=True)
125
+ monkeypatch.setattr(
126
+ loader, "_clone_command",
127
+ lambda url, dest, branch: [sys.executable, "-c", slow_clone, str(dest)],
128
+ ) # fmt: skip
129
+ task = asyncio.create_task(loader.load("file:///anything"))
130
+ for _ in range(100):
131
+ if started.exists():
132
+ break
133
+ await asyncio.sleep(0.05)
134
+ assert started.exists(), "the fake clone never started"
135
+ task.cancel()
136
+ with pytest.raises(asyncio.CancelledError):
137
+ await task
138
+ await asyncio.sleep(0.3) # a process that was not stopped would keep writing
139
+ leftovers = [p.name for p in tmp_path.iterdir() if p.name.startswith("margin-")] # noqa: ASYNC240
140
+ assert leftovers == [], f"cancelled clone left {leftovers}"
141
+
142
+
143
+ # ---- 4. secrets ------------------------------------------------------------------------------
144
+
145
+ SENTINEL = "sk-SENTINEL-0123456789abcdef"
146
+
147
+
148
+ async def test_secrets_never_reach_logs_or_errors(
149
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
150
+ ) -> None:
151
+ import httpx
152
+ from margin_core.config import get_settings
153
+ from margin_core.llm import create_llm
154
+ from margin_core.llm.catalog import check_connection, list_models
155
+
156
+ for name in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "LOCAL_LLM_API_KEY", "GITHUB_TOKEN"):
157
+ monkeypatch.setenv(name, SENTINEL)
158
+ monkeypatch.setenv("LOCAL_LLM_BASE_URL", "http://127.0.0.1:9") # nothing listens there
159
+ caplog.set_level(logging.DEBUG)
160
+
161
+ texts = [repr(get_settings()), str(get_settings().model_dump())]
162
+ for provider in ("anthropic", "openai", "local"):
163
+ texts.append(repr(create_llm(provider, "m")))
164
+ texts.append((await check_connection(provider, "m")).message)
165
+ try:
166
+ await list_models(provider, timeout_s=2)
167
+ except Exception as exc: # noqa: BLE001 - we only care what the error says
168
+ texts.append(str(exc))
169
+
170
+ def refuse(request: httpx.Request) -> httpx.Response:
171
+ return httpx.Response(500, text="server error")
172
+
173
+ loader = GitHubLoader(http_client=httpx.AsyncClient(transport=httpx.MockTransport(refuse)))
174
+ texts.append(str(await loader.check_remote_size("owner", "repo")))
175
+
176
+ everything = "\n".join(texts + [r.getMessage() for r in caplog.records])
177
+ assert SENTINEL not in everything
178
+ assert os.environ["GITHUB_TOKEN"] == SENTINEL # it was set; it just never leaked
File without changes
File without changes
File without changes