You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by gc...@apache.org on 2026/09/17 20:55:37 UTC
(allura) branch master updated (6903a0543 -> 281c0ba2c)
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git
from 6903a0543 bumping gitpython 3.1.59 -> 3.1.62
new 45090eb14 [#8618] read git blob content via a one-off subprocess, not the shared cat-file pipe
new 17b40870a [#8618] harden rev_parse() against git's relative-ref syntax
new 281c0ba2c [#8618] optimze the way to read the raw stream and a small change since now the content is bytes
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
Allura/allura/controllers/repository.py | 7 +-
ForgeGit/forgegit/model/git_repo.py | 92 +++++++++++++++-------
.../forgegit/tests/functional/test_controllers.py | 45 +++++++++++
ForgeGit/forgegit/tests/model/test_repository.py | 73 ++++++++++++++++-
4 files changed, 184 insertions(+), 33 deletions(-)
(allura) 02/03: [#8618] harden rev_parse() against git's relative-ref syntax
Posted by gc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git
commit 17b40870a524a5738b52d0ccf69fe8fbe10d90eb
Author: Dave Brondsema <da...@brondsema.net>
AuthorDate: Wed Sep 9 14:08:50 2026 -0400
[#8618] harden rev_parse() against git's relative-ref syntax
Co-Authored-By: Claude Sonnet 5 <no...@anthropic.com>
---
ForgeGit/forgegit/model/git_repo.py | 40 +++++++++++++++++++-----
ForgeGit/forgegit/tests/model/test_repository.py | 35 ++++++++++++++++++++-
2 files changed, 67 insertions(+), 8 deletions(-)
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index ae24595a4..2cbadb070 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -18,6 +18,7 @@
import sys
import os
+import re
import shutil
import string
import logging
@@ -59,6 +60,13 @@
max_open_handles=128)
+# Characters gitrevisions(7) treats as syntax rather than literal ref/hash content
+# (~N, ^N, :path, a..b range, @{...}), plus the control/space/glob characters
+# git-check-ref-format(1) bans from ref names outright. Anything else -- e.g. the
+# punctuation @ $ ! # % & is legal in a git branch/tag name and must not be rejected here.
+_UNSAFE_REV_CHARS_RE = re.compile(r'[\x00-\x1f\x7f ~^:?*\[\\]')
+
+
class GitLibCmdWrapper:
def __init__(self, client):
@@ -270,7 +278,7 @@ def commit(self, rev):
if result is None:
# find the id by branch/tag name
try:
- impl = self._git.rev_parse(str(rev) + '^0')
+ impl = self.rev_parse(rev, require_commit=True)
result = cache.get(M.repository.Commit, dict(_id=impl.hexsha))
except Exception:
url = ''
@@ -279,7 +287,7 @@ def commit(self, rev):
url = ' at ' + request.url
except Exception:
pass
- log.info(f"couldn't run rev_parse({str(rev) + '^0'}){url}", exc_info=True)
+ log.info(f"couldn't run rev_parse({rev!r}){url}", exc_info=True)
if result:
result.set_context(self._repo)
return result
@@ -319,7 +327,7 @@ def refresh_commit_info(self, oid, seen, lazy=True):
ci_doc = CommitDoc.m.get(_id=oid)
if ci_doc and lazy:
return False
- ci = self._git.rev_parse(oid)
+ ci = self.rev_parse(oid)
args = dict(
tree_id=ci.tree.hexsha,
committed=Object(
@@ -560,8 +568,26 @@ def _object(self, oid):
binsha += bytes((int(e + o, 16),))
return git.Object.new_from_sha(self._git, binsha)
- def rev_parse(self, rev):
- return self._git.rev_parse(rev)
+ def rev_parse(self, rev, require_commit: bool = False):
+ '''Resolve a plain commit hash or branch/tag name to a git object.
+
+ Only accepts safe rev syntax -- not relative-ref forms like ~N, ^N, :path, a..b range, @{...}
+
+ :param require_commit: dereference a tag object down to the commit it points to (git's `<rev>^0` syntax).
+ '''
+ if not self._is_safe_rev(rev):
+ raise ValueError(f'Unsafe rev spec: {rev!r}')
+ resolved = f'{rev}^0' if require_commit else str(rev)
+ return self._git.rev_parse(resolved)
+
+ @staticmethod
+ def _is_safe_rev(rev) -> bool:
+ rev = str(rev)
+ if not rev or rev.startswith('-'):
+ return False # a leading dash risks being read as a git rev-parse option
+ if '..' in rev or '@{' in rev:
+ return False
+ return not _UNSAFE_REV_CHARS_RE.search(rev)
def symbolics_for_commit(self, commit):
try:
@@ -573,7 +599,7 @@ def symbolics_for_commit(self, commit):
return [], []
def compute_tree_new(self, commit, tree_path='/'):
- ci = self._git.rev_parse(commit._id)
+ ci = self.rev_parse(commit._id)
tree = self.refresh_tree_info(ci.tree, set())
return tree._id
@@ -602,7 +628,7 @@ def is_empty(self):
def is_file(self, path, rev=None):
path = path.strip('/')
- ci = self._git.rev_parse(rev)
+ ci = self.rev_parse(rev)
try:
node = ci.tree / path
return node.type == 'blob'
diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py
index eed4c38cd..5bc0ff32c 100644
--- a/ForgeGit/forgegit/tests/model/test_repository.py
+++ b/ForgeGit/forgegit/tests/model/test_repository.py
@@ -599,7 +599,8 @@ def test_ls_with_prev(self):
c.lcid_cache = {} # else it'll be a mock
# build the previous last-commit-doc. This causes different behavior when generating the next one.
- self.repo.commit('HEAD^').tree.ls()
+ # 'HEAD^' would be more readable, but commit() no longer accepts relative-ref syntax
+ self.repo.commit('df30427c488aeab84b2352bdf88a3b19223f9d7a').tree.ls()
self.test_ls()
@@ -640,6 +641,38 @@ def test_blob_size(self):
assert self.repo._impl.blob_size(tree['README']) == 28
assert self.repo._impl.blob_size(tree['bad']) == 9
+ def test_rev_parse_rejects_unsafe_rev(self):
+ impl = self.repo._impl
+ for unsafe_rev in ('zz~1', 'zz^1', 'zz^0', 'HEAD@{0}', 'zz:README', 'zz..master', '-zz'):
+ with pytest.raises(ValueError):
+ impl.rev_parse(unsafe_rev)
+
+ def test_rev_parse_allows_punctuation_legal_in_ref_names(self):
+ impl = self.repo._impl
+ for safe_rev in ('feature@2024', 'release/$version', 'foo!bar', 'a+b', 'x,y', 'name#1', "it's-fine"):
+ assert impl._is_safe_rev(safe_rev)
+
+ def test_rev_parse_require_commit(self):
+ # require_commit appends git's `^0` dereference suffix internally --
+ # after the safety check, not as a caller-supplied suffix that could itself smuggle in unsafe syntax
+ impl = self.repo._impl
+ obj = impl.rev_parse('master', require_commit=True)
+ assert obj.hexsha == '1e146e67985dcd71c74de79613719bef7bddca4a'
+
+ def test_commit_rejects_relative_ref_syntax(self):
+ # commit()'s docstring says rev can be "_id or a branch/tag name" -- it must
+ # not also accept git's relative-ref forms (~N, ^N, :path, a..b, @{...}).
+ for unsafe_rev in ('zz~1', 'zz^1', 'zz^0', 'HEAD@{0}', 'zz:README', 'zz..master', '-zz'):
+ assert self.repo.commit(unsafe_rev) is None
+
+ def test_commit_resolves_safe_revs(self):
+ # plain hashes (short and long) and branch/tag names must still resolve
+ full_hexsha = '1e146e67985dcd71c74de79613719bef7bddca4a'
+ for safe_rev in (full_hexsha, full_hexsha[:7], 'master'):
+ result = self.repo.commit(safe_rev)
+ assert result is not None
+ assert result._id == full_hexsha
+
def test_tarball_status(self):
tmpdir = tg.config['scm.repos.tarball.root']
if os.path.isfile(os.path.join(tmpdir, "git/t/te/test/testgit.git/test-src-git-HEAD.zip")):
(allura) 03/03: [#8618] optimze the way to read the raw stream and a small change since now the content is bytes
Posted by gc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git
commit 281c0ba2c680877ba525e92593390700488d8670
Author: Guillermo Cruz <gu...@slashdotmedia.com>
AuthorDate: Thu Sep 17 20:24:50 2026 +0000
[#8618] optimze the way to read the raw stream and a small change since now the content is bytes
---
Allura/allura/controllers/repository.py | 7 ++++---
ForgeGit/forgegit/model/git_repo.py | 20 ++++----------------
2 files changed, 8 insertions(+), 19 deletions(-)
diff --git a/Allura/allura/controllers/repository.py b/Allura/allura/controllers/repository.py
index dbfad7eb0..4e36494d0 100644
--- a/Allura/allura/controllers/repository.py
+++ b/Allura/allura/controllers/repository.py
@@ -971,9 +971,10 @@ def diff(self, prev_commit, fmt=None, prev_file=None, **kw):
diff = 'File too large to view diff'
return dict(a=a, b=b, diff=diff)
- # could consider making Blob.__iter__ do unicode conversion?
- la = [h.really_unicode(line) for line in a]
- lb = [h.really_unicode(line) for line in b]
+ # Blob.__iter__ yields fixed-size chunks (not lines), so read the full
+ # content and split into lines ourselves; bounded by the size check above.
+ la = [h.really_unicode(line) for line in b''.join(a).splitlines(keepends=True)]
+ lb = [h.really_unicode(line) for line in b''.join(b).splitlines(keepends=True)]
adesc = 'a' + h.really_unicode(apath)
bdesc = 'b' + h.really_unicode(b.path())
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index 2cbadb070..33a397e98 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -871,25 +871,13 @@ def read(self):
def __iter__(self):
'''
- Yields one line at a time, reading from the stream
+ Yields fixed-size chunks, reading from the stream.
'''
- buffer = b''
while True:
- # Replenish buffer until we have a line break
- while b'\n' not in buffer:
- chars = self._stream.read(self.CHUNK_SIZE)
- if not chars:
- break
- buffer += chars
- if not buffer:
- break
- eol = buffer.find(b'\n')
- if eol == -1:
- # end without \n
- yield buffer
+ chars = self._stream.read(self.CHUNK_SIZE)
+ if not chars:
break
- yield buffer[:eol + 1]
- buffer = buffer[eol + 1:]
+ yield chars
self._proc.wait() # reached naturally, not via close()/abandonment: reap now
def close(self):
(allura) 01/03: [#8618] read git blob content via a one-off subprocess, not the shared cat-file pipe
Posted by gc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git
commit 45090eb14c45a03ce83e86358f2ddafa4f2a6fd1
Author: Dave Brondsema <da...@brondsema.net>
AuthorDate: Wed Sep 9 13:30:42 2026 -0400
[#8618] read git blob content via a one-off subprocess, not the shared cat-file pipe
open_blob() now runs a dedicated `git cat-file -p <sha>` subprocess per read
instead of going through GitPython's persistent, shared `cat-file --batch`
process. A raw file download hands its blob content off to the WSGI layer as
a streaming response, and that response's consumption (and therefore its
cleanup) is outside our control: a vanished client or a WSGI server that
doesn't reliably close an abandoned response iterator can leave the shared
process holding unread bytes. Because MongoDB session cleanup for a streaming
response is deferred until the response is closed or exhausted, a later,
unrelated request on the same repo can end up reusing that same dirty
session and pipe, misreading the leftover bytes as its own response.
blob_size() stays on the shared persistent process: it always finishes in
one synchronous call and is never handed off to a response iterator, so it
isn't exposed to this risk, and keeping it on the fast path avoids adding
subprocess-spawn overhead to the common file-view/size-check case.
Co-Authored-By: Claude Sonnet 5 <no...@anthropic.com>
Claude-Session: https://claude.ai/code/session_012x5jtE8bYdSJRQuXBC2jzg
---
ForgeGit/forgegit/model/git_repo.py | 32 ++++++++++++---
.../forgegit/tests/functional/test_controllers.py | 45 ++++++++++++++++++++++
ForgeGit/forgegit/tests/model/test_repository.py | 38 ++++++++++++++++++
3 files changed, 109 insertions(+), 6 deletions(-)
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index 6a3b900ac..ae24595a4 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -524,11 +524,23 @@ def _iter_commits_with_refs(self, *args, **kwargs):
commit_lines.append(line)
def open_blob(self, blob):
- return _OpenedGitBlob(
- self._object(blob._id).data_stream)
+ # A dedicated `git cat-file -p <sha>` subprocess, not GitPython's persistent,
+ # shared `cat-file --batch` process (used by e.g. `.data_stream`/`.parents`/
+ # `.tree`). This blob's bytes get streamed straight into an HTTP response.
+ # If that is ever abandoned partway through, only this one throwaway
+ # subprocess is affected, and GitPython's own AutoInterrupt wrapper kills it
+ # on garbage collection. Nothing else ever shares this pipe, so nothing else
+ # can be corrupted by bytes left over in it.
+ proc = self._git.git.cat_file(blob._id, p=True, as_process=True) # -p: print the object's content
+ return _OpenedGitBlob(proc)
def blob_size(self, blob):
- return self._object(blob._id).data_stream.size
+ # Unlike open_blob(), this always finishes in one synchronous call -- never handed off to an HTTP response
+ # so it's safe to use GitPython's shared persistent process
+ stream = self._object(blob._id).data_stream
+ size = stream.size
+ del stream # drain any unread body bytes before the persistent process is reused
+ return size
def _setup_hooks(self, source_path=None):
'Set up the git post-commit hook'
@@ -822,11 +834,14 @@ def merge_request_commits(self, mr):
class _OpenedGitBlob:
CHUNK_SIZE = 4096
- def __init__(self, stream):
- self._stream = stream
+ def __init__(self, proc: git.Git.AutoInterrupt):
+ self._proc = proc
+ self._stream = proc.stdout
def read(self):
- return self._stream.read()
+ data = self._stream.read()
+ self._proc.wait() # reap the process now, and raise if git itself failed
+ return data
def __iter__(self):
'''
@@ -849,8 +864,13 @@ def __iter__(self):
break
yield buffer[:eol + 1]
buffer = buffer[eol + 1:]
+ self._proc.wait() # reached naturally, not via close()/abandonment: reap now
def close(self):
+ # no explicit cleanup needed: AutoInterrupt.__del__ closes the pipes and
+ # terminates the process (if still running) once `self._proc` is
+ # garbage collected, whether that's because of this close() call, the
+ # generator in __iter__() being closed early, or neither ever happening
pass
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index 8210429f4..29cd5f888 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -331,6 +331,51 @@ def test_file_raw(self):
assert (resp.headers.get('Content-Disposition') ==
'attachment;filename="with%22%26%3Aspecials.txt"')
+ def _start_raw_download(self, url):
+ '''
+ Call the real WSGI stack for a `format=raw` blob download, but return the response iterator
+ after reading only its first chunk -- bypassing WebTest's normal do_request(), which always fully drains it
+ '''
+ environ = self.app._make_environ()
+ url, qs = url.split('?', 1)
+ environ['QUERY_STRING'] = qs
+ req = self.app.RequestClass.blank(url, environ)
+ _status, _headers, app_iter, exc_info = req.call_application(
+ self.app.app, catch_exc_info=True)
+ del exc_info
+ it = iter(app_iter)
+ next(it)
+ return app_iter, it
+
+ def test_abandoned_raw_download_does_not_corrupt_next_request(self):
+ # Regression test: a client that disconnects or WSGI server that doesn't close
+ # an abandoned response iterator from a raw download
+ # It must not corrupt later requests. This used to fail:
+ # GitPython's persistent `cat-file` subprocess still held unread bytes
+ ci_master = '/p/test/src-git/ci/1e146e67985dcd71c74de79613719bef7bddca4a/'
+ ci_zz = '/p/test/src-git/ci/5c47243c8e424136fd5cdd18cd94d34c66d1955c/'
+
+ with patch.object(GM.git_repo._OpenedGitBlob, 'CHUNK_SIZE', 5):
+ # hold _abandoned_download on `self` so it doesn't get garbage collected
+ self._abandoned_download = self._start_raw_download(ci_master + 'tree/README?format=raw')
+
+ resp = self.app.get(ci_zz + 'tree/bad?format=raw')
+ assert resp.body == b'Not root\n'
+
+ def test_closed_raw_download_does_not_corrupt_next_request(self):
+ # Same as above, but the first download's iterator is properly closed. Control case.
+ ci_master = '/p/test/src-git/ci/1e146e67985dcd71c74de79613719bef7bddca4a/'
+ ci_zz = '/p/test/src-git/ci/5c47243c8e424136fd5cdd18cd94d34c66d1955c/'
+
+ with patch.object(GM.git_repo._OpenedGitBlob, 'CHUNK_SIZE', 5):
+ app_iter, it = self._start_raw_download(ci_master + 'tree/README?format=raw')
+ it.close()
+ if hasattr(app_iter, 'close'):
+ app_iter.close()
+
+ resp = self.app.get(ci_zz + 'tree/bad?format=raw')
+ assert resp.body == b'Not root\n'
+
def test_file_too_large(self):
ci = self._get_ci()
with h.push_config(tg.config, **{'scm.view.max_file_bytes': '3'}):
diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py
index f5c5591b4..eed4c38cd 100644
--- a/ForgeGit/forgegit/tests/model/test_repository.py
+++ b/ForgeGit/forgegit/tests/model/test_repository.py
@@ -20,6 +20,7 @@
import stat
import datetime
import email.iterators
+import threading
import pytest
import mock
import git
@@ -602,6 +603,43 @@ def test_ls_with_prev(self):
self.test_ls()
+ def test_open_blob_thread_safety(self):
+ # regression test: open_blob() spawns its own one-off `git cat-file` subprocess
+ # to avoid concurrent read corruption
+ impl = self.repo._impl
+ tree = self.repo.commit('zz').tree
+ blob_readme = tree['README']
+ blob_bad = tree['bad']
+ errors = []
+
+ def read_readme():
+ for _ in range(50):
+ data = impl.open_blob(blob_readme).read()
+ if data != b'This is readme\nAnother Line\n':
+ errors.append(('readme', data))
+
+ def read_bad():
+ for _ in range(50):
+ data = impl.open_blob(blob_bad).read()
+ if data != b'Not root\n':
+ errors.append(('bad', data))
+
+ threads = (
+ [threading.Thread(target=read_readme) for _ in range(5)]
+ + [threading.Thread(target=read_bad) for _ in range(5)]
+ )
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert errors == []
+
+ def test_blob_size(self):
+ tree = self.repo.commit('zz').tree
+ assert self.repo._impl.blob_size(tree['README']) == 28
+ assert self.repo._impl.blob_size(tree['bad']) == 9
+
def test_tarball_status(self):
tmpdir = tg.config['scm.repos.tarball.root']
if os.path.isfile(os.path.join(tmpdir, "git/t/te/test/testgit.git/test-src-git-HEAD.zip")):