You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by da...@apache.org on 2026/08/21 15:19:18 UTC

(allura) branch dc/686 updated (acd9b74f2 -> 0253a6345)

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a change to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git


 discard acd9b74f2 Added migrations instructions to changes, plus some fixes
 discard b4592b9d5 New script to backfill allow forcepush flag
 discard d1326815a Fix for force push on new repos
 discard 7d25e7173 Added scm.force_push.git.enabled flag
 discard 2112216b2 Force push enable of repos
     add c0a25ef09 bump gitpython 3.1.57 -> 3.1.59
     add 62864a68b [#8614] Add backing encrypted fields for User and UserLoginDetails fields
     add ee99615a1 [#8614] Add support for nested lists and tests to the field conversion script
     add 9fca8251b [#8614] Decrypt social networks returned by the profile rest api
     add a565108c8 do github rate-limit logic on 429 status codes too
     add c432537e9 [#8614] Implement field level encryption for User and UserLoginDetails fields
     add 94e1111a5 [#8616] align RestController lookups & checks with web controllers
     add abc2daba4 CHANGES updated for ASF release 1.20.0
     new cfee76536 Force push enable of repos
     new cdda319c0 Added scm.force_push.git.enabled flag
     new afb362991 Fix for force push on new repos
     new d2dbc1362 New script to backfill allow forcepush flag
     new dbeaa6d16 Added migrations instructions to changes, plus some fixes
     new 0253a6345 Fix for CHANGES version

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (acd9b74f2)
            \
             N -- N -- N   refs/heads/dc/686 (0253a6345)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 6 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/auth.py                  |  10 +-
 Allura/allura/controllers/discuss.py               |   4 +
 Allura/allura/ext/user_profile/user_main.py        |  10 +-
 Allura/allura/model/auth.py                        |  19 ++-
 Allura/allura/tests/functional/test_auth.py        |  14 +-
 Allura/allura/tests/functional/test_rest.py        |  17 ++-
 .../allura/tests/functional/test_user_profile.py   |  19 +++
 Allura/allura/tests/model/test_auth.py             | 105 +++++++++++++
 .../tests/scripts/test_convert_encrypted_field.py  | 131 ++++++++++++++++
 CHANGES                                            |  43 +++++-
 ForgeBlog/forgeblog/main.py                        |   7 +-
 ForgeBlog/forgeblog/tests/functional/test_rest.py  |   8 +
 .../forgediscussion/controllers/root.py            |   2 +-
 .../forgediscussion/tests/functional/test_rest.py  |   9 ++
 ForgeImporters/forgeimporters/github/__init__.py   |   4 +-
 .../forgetracker/tests/functional/test_rest.py     |  33 ++++
 ForgeTracker/forgetracker/tracker_main.py          |   2 +
 ForgeWiki/forgewiki/tests/functional/test_rest.py  |  21 +++
 ForgeWiki/forgewiki/wiki_main.py                   |   3 +-
 requirements.txt                                   |   2 +-
 scripts/convert_encrypted_field.py                 | 166 +++++++++++++++++++--
 scripts/migrations/037-field-encryption.sh         |   9 +-
 scripts/migrations/038-field-encryption-cleanup.sh |   9 +-
 23 files changed, 601 insertions(+), 46 deletions(-)
 create mode 100644 Allura/allura/tests/scripts/test_convert_encrypted_field.py


(allura) 06/06: Fix for CHANGES version

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit 0253a634500c65f8708abab55f5efe6e07b505ce
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Fri Aug 21 15:18:35 2026 +0000

    Fix for CHANGES version
---
 CHANGES | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/CHANGES b/CHANGES
index 7fe48ab52..411c0763f 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,4 +1,4 @@
-Version 1.19.2  (Unreleased)
+Version 1.20.1  (Unreleased)
 
 Upgrade Instructions
 


(allura) 05/06: Added migrations instructions to changes, plus some fixes

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit dbeaa6d163630a972d830633078f43ef250028e3
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Thu Aug 20 15:32:16 2026 +0000

    Added migrations instructions to changes, plus some fixes
---
 Allura/allura/lib/repository.py                        |  4 ++--
 CHANGES                                                | 18 ++++++++++++++++++
 ForgeGit/forgegit/git_main.py                          |  4 ++--
 ForgeGit/forgegit/tests/functional/test_controllers.py |  2 +-
 scripts/migrations/force-push-sync-from-repo-config.py | 11 ++++++-----
 5 files changed, 29 insertions(+), 10 deletions(-)

diff --git a/Allura/allura/lib/repository.py b/Allura/allura/lib/repository.py
index 12651e250..eb32bad9b 100644
--- a/Allura/allura/lib/repository.py
+++ b/Allura/allura/lib/repository.py
@@ -304,8 +304,8 @@ def set_default_branch_name(self, branch_name=None, **kw):
     def force_push(self, allowed=None, **kw):
         if not asbool(config.get(f'scm.force_push.{self.app.config.tool_name}.enabled')):
             raise exc.HTTPNotFound()
-        if not self.repo or self.repo.status not in ('ready', 'analyzing'):
-            # init/clone/import recreate the repo dir, discarding config written before they finish
+        if not self.repo or self.repo.status != 'ready':
+            # any other status means the repo is still being built or refreshed
             raise exc.HTTPNotFound()
         if request.method == 'POST':
             allowed = bool(allowed)
diff --git a/CHANGES b/CHANGES
index f3fda21ea..7fe48ab52 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,21 @@
+Version 1.19.2  (Unreleased)
+
+Upgrade Instructions
+
+  Optional new feature: repo admins can turn force push on and off for their own git repos.
+  To enable it, set `scm.force_push.git.enabled = true` in your .ini file (see development.ini).
+  Allura writes `receive.denyNonFastForwards` in each repo's own config.  With the setting off,
+  Allura does not touch any repo's config and shows no admin UI.
+
+  If you enable it, record what each existing repo already permits, so the admin page shows the
+  right value.  Run in the Allura dir (replace your .ini file path):
+    `paster script your-ini-file.ini ../scripts/migrations/force-push-sync-from-repo-config.py -- --dry-run`
+  Check the output, then run it again without `--dry-run` to apply.  The script reads each git
+  repo and writes only to Mongo.  It changes no repository.
+
+New Features
+ * [#686] Repo admins can allow force push on their own git repos, without a support request
+
 Version 1.20.0  (August 2026)
 
 Upgrade Instructions
diff --git a/ForgeGit/forgegit/git_main.py b/ForgeGit/forgegit/git_main.py
index e4c4354bb..fc7ed23ad 100644
--- a/ForgeGit/forgegit/git_main.py
+++ b/ForgeGit/forgegit/git_main.py
@@ -78,8 +78,8 @@ def admin_menu(self):
             '/' + 'set_default_branch_name',
             className='admin_modal'))
         if (asbool(config.get(f'scm.force_push.{self.config.tool_name}.enabled'))
-                and self.repo and self.repo.status in ('ready', 'analyzing')):
-            # hidden until ready: init/clone recreate the repo dir and would discard the setting
+                and self.repo and self.repo.status == 'ready'):
+            # hidden unless ready, matching sidebar_menu; a repo being built or refreshed is not settable
             label = 'Force push (enabled)' if self.repo.force_push_allowed else 'Force push'
             links.append(SitemapEntry(
                 label,
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index 11c305952..da472a7a8 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -587,7 +587,7 @@ def test_force_push_save_writes_even_when_unchanged(self):
     def test_force_push_hidden_until_repo_ready(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
             for status, ready in (('initializing', False), ('cloning', False),
-                                  ('analyzing', True), ('ready', True)):
+                                  ('analyzing', False), ('ready', True)):
                 # re-query: c.app.repo detaches from the session after the first request, so
                 # assigning to it would silently not persist
                 repo = GM.Repository.query.get(_id=c.app.repo._id)
diff --git a/scripts/migrations/force-push-sync-from-repo-config.py b/scripts/migrations/force-push-sync-from-repo-config.py
index 94b6381fa..4c34c1190 100644
--- a/scripts/migrations/force-push-sync-from-repo-config.py
+++ b/scripts/migrations/force-push-sync-from-repo-config.py
@@ -32,7 +32,7 @@
 import logging
 import sys
 
-from ming.odm import session, ThreadLocalODMSession
+from ming.odm import ThreadLocalODMSession
 
 from allura.lib.utils import chunked_find
 from forgegit import model as GM
@@ -64,10 +64,11 @@ def main():
             log.info('%s: force_push_allowed %s => %s',
                      repo.full_fs_path, repo.force_push_allowed, on_disk)
             if not opts.dry_run:
-                repo.force_push_allowed = on_disk
-                session(repo).flush(repo)
-        if not opts.dry_run:
-            ThreadLocalODMSession.flush_all()
+                # targeted $set, not a whole-document save: taskd and the web app write other
+                # fields on this record and a full flush would put back our stale copy of them
+                repo.query.update({'$set': {'force_push_allowed': on_disk}})
+        # drop each chunk from the identity map, or memory grows for the whole run
+        ThreadLocalODMSession.close_all()
     log.info('%s %d git repos: %d updated, %d unreadable',
              'would update' if opts.dry_run else 'synced', counts['seen'],
              counts['changed'], counts['unreadable'])


(allura) 04/06: New script to backfill allow forcepush flag

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit d2dbc13626599c622364e87e13383cdf9b8849a1
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Tue Aug 18 19:23:13 2026 +0000

    New script to backfill allow forcepush flag
---
 Allura/allura/tasks/repo_tasks.py                  |  5 +-
 ForgeGit/forgegit/model/git_repo.py                | 22 ++++---
 .../forgegit/tests/functional/test_controllers.py  | 41 +++++++++---
 ForgeGit/forgegit/tests/model/test_repository.py   | 46 ++++++++++++-
 .../migrations/force-push-sync-from-repo-config.py | 77 ++++++++++++++++++++++
 5 files changed, 167 insertions(+), 24 deletions(-)

diff --git a/Allura/allura/tasks/repo_tasks.py b/Allura/allura/tasks/repo_tasks.py
index d2ca6accd..cb6d76edf 100644
--- a/Allura/allura/tasks/repo_tasks.py
+++ b/Allura/allura/tasks/repo_tasks.py
@@ -201,6 +201,7 @@ def update_head_reference(fs_path, branch_name):
 
 @task
 def update_force_push_config(fs_path: str, allowed: bool):
+    # git's own config writer rather than GitPython's: it edits in place so comments and
+    # formatting survive, and matches the key case-insensitively so a legacy spelling is replaced
     repo = git.Repo(fs_path, odbt=git.GitCmdObjectDB)
-    with repo.config_writer() as cw:  # config_level defaults to 'repository'
-        cw.set_value('receive', 'denyNonFastForwards', 'false' if allowed else 'true')
+    repo.git.config('--replace-all', 'receive.denyNonFastForwards', 'false' if allowed else 'true')
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index 971c6c998..8159f01ec 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -209,20 +209,25 @@ def force_push_allowed_on_disk(self):
         if self._git is None:
             return None
         try:
-            with self._git.config_reader('repository') as cr:
-                return not asbool(cr.get_value('receive', 'denyNonFastForwards', False))
+            denied = self._git.git.config('--bool', '--get', 'receive.denyNonFastForwards')
+        except git.exc.GitCommandError as err:
+            if err.status == 1:
+                return True  # unset, and git does not deny non-fast-forwards by default
+            log.exception('Could not read receive.denyNonFastForwards for %r', self._repo)
+            return None
         except Exception:
             log.exception('Could not read receive.denyNonFastForwards for %r', self._repo)
             return None
+        return not asbool(denied)
 
     def _apply_force_push_config(self):
-        # keep the repo's on-disk setting in step with force_push_allowed; a repo Allura has
-        # never written is left alone entirely, so this is a no-op when the feature is off
+        # `git init --shared=all` denies non-fast-forwards but `git clone --bare` does not, so
+        # clones need this to match a fresh repo; no-op when the feature is off
+        # http://git-scm.com/docs/git-init#Documentation/git-init.txt---sharedltpermissionsgt
         if not asbool(tg.config.get(f'scm.force_push.{self._repo.tool}.enabled')):
             return
-        with self._git.config_writer() as cw:
-            cw.set_value('receive', 'denyNonFastForwards',
-                         'false' if self._repo.force_push_allowed else 'true')
+        self._git.git.config('--replace-all', 'receive.denyNonFastForwards',
+                             'false' if self._repo.force_push_allowed else 'true')
 
     def can_hotcopy(self, source_url):
         enabled = asbool(tg.config.get('scm.git.hotcopy', True))
@@ -246,9 +251,6 @@ def clone_from(self, source_url):
                 if os.path.exists(post_receive):
                     os.rename(post_receive, post_receive + '-user')
                 repo = git.Repo(fullname)
-                # a hotcopy inherits the parent's config verbatim; force push is not inherited
-                with repo.config_writer() as cw:
-                    cw.remove_section('receive')
             else:
                 repo = git.Repo.clone_from(
                     source_url,
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index ff4aa1dfe..11c305952 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -18,6 +18,7 @@
 import re
 import os
 import shutil
+import subprocess
 import tempfile
 import textwrap
 
@@ -585,17 +586,37 @@ def test_force_push_save_writes_even_when_unchanged(self):
 
     def test_force_push_hidden_until_repo_ready(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
-            for status in ('initializing', 'cloning'):
-                c.app.repo.status = status
+            for status, ready in (('initializing', False), ('cloning', False),
+                                  ('analyzing', True), ('ready', True)):
+                # re-query: c.app.repo detaches from the session after the first request, so
+                # assigning to it would silently not persist
+                repo = GM.Repository.query.get(_id=c.app.repo._id)
+                repo.status = status
                 ThreadLocalODMSession.flush_all()
-                assert not any(l.label.startswith('Force push') for l in c.app.admin_menu())
-                self.app.get('/p/test/admin/src-git/force_push', status=404)
-                self.app.post('/p/test/admin/src-git/force_push',
-                              params={'allowed': 'on'}, status=404)
-            c.app.repo.status = 'analyzing'
-            ThreadLocalODMSession.flush_all()
-            assert any(l.label.startswith('Force push') for l in c.app.admin_menu())
-            self.app.get('/p/test/admin/src-git/force_push', status=200)
+                c.app.repo.status = status  # the in-process copy admin_menu() reads
+                assert any(l.label.startswith('Force push')
+                           for l in c.app.admin_menu()) is ready
+                self.app.get('/p/test/admin/src-git/force_push', status=200 if ready else 404)
+                if not ready:
+                    self.app.post('/p/test/admin/src-git/force_push',
+                                  params={'allowed': 'on'}, status=404)
+
+    def test_force_push_checkbox_reflects_repo_state(self):
+        # the form must show what the repo really permits, not just the stored field: a repo
+        # predating this feature has no receive setting and does accept force pushes
+        R = c.app.repo.full_fs_path
+        assert c.app.repo.force_push_allowed is False
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            try:
+                r = self.app.get('/p/test/admin/src-git/force_push')
+                assert 'name="allowed" checked' in squish_spaces(r.text)
+                subprocess.run(['git', '--git-dir', R, 'config',
+                                'receive.denyNonFastForwards', 'true'], check=True)
+                r = self.app.get('/p/test/admin/src-git/force_push')
+                assert 'name="allowed" checked' not in squish_spaces(r.text)
+            finally:
+                subprocess.run(['git', '--git-dir', R, 'config',
+                                '--remove-section', 'receive'], check=False)
 
     def test_force_push_requires_admin(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py
index 919a58a62..b1580def3 100644
--- a/ForgeGit/forgegit/tests/model/test_repository.py
+++ b/ForgeGit/forgegit/tests/model/test_repository.py
@@ -724,6 +724,33 @@ def test_force_push_allowed_effective_falls_back(self):
             self.repo.force_push_allowed = True
             assert self.repo.force_push_allowed_effective() is True
 
+    def test_update_force_push_config_preserves_other_settings(self):
+        # a real repo's config holds unrelated settings and comments; only our key may change
+        path = os.path.join(g.tmpdir, 'cfgtest.git')
+        shutil.rmtree(path, ignore_errors=True)
+        git.Repo.init(path=path, mkdir=True, quiet=True, bare=True)
+        try:
+            with open(os.path.join(path, 'config'), 'a') as f:
+                f.write('# keep me\n'
+                        '[receive]\n\tdenyDeletes = true\n\tdenyNonFastforwards = true\n'
+                        '; keep me too\n'
+                        '[remote "origin"]\n\turl = /srv/git/p/foo/code.git\n'
+                        '\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
+                        '\tfetch = +refs/tags/*:refs/tags/*\n')
+            update_force_push_config(path, True)
+            update_force_push_config(path, False)
+            repo = git.Repo(path)
+            text = open(os.path.join(path, 'config')).read()
+            assert '# keep me' in text
+            assert '; keep me too' in text
+            # the legacy lower-case spelling is replaced in place, not duplicated alongside ours
+            assert text.lower().count('denynonfastforwards') == 1
+            assert repo.git.config('--get', 'receive.denyDeletes') == 'true'
+            assert repo.git.config('--bool', '--get', 'receive.denyNonFastForwards') == 'true'
+            assert len(repo.git.config('--get-all', 'remote.origin.fetch').splitlines()) == 2
+        finally:
+            shutil.rmtree(path, ignore_errors=True)
+
     def _init_scratch_repo(self):
         repo = GM.Repository(name='testgit.git', fs_path=g.tmpdir + '/', url_path='/test/',
                              tool='git', status='creating')
@@ -746,8 +773,23 @@ def test_init_leaves_config_alone_when_disabled(self):
         repo, dirname = self._init_scratch_repo()
         try:
             repo.init()
-            with git.Repo(dirname).config_reader('repository') as cr:
-                assert not cr.has_section('receive')
+            # git init --shared=all writes this itself, in its own lower-case spelling;
+            # with the feature off Allura must not rewrite it
+            text = open(os.path.join(dirname, 'config')).read()
+            assert 'denyNonFastforwards = true' in text
+        finally:
+            shutil.rmtree(dirname, ignore_errors=True)
+
+    def test_clone_denies_force_push_when_enabled(self):
+        # git clone --bare does NOT inherit the deny that git init --shared=all sets, so without
+        # this a fork would accept force pushes while its checkbox showed unticked
+        repo, dirname = self._init_scratch_repo()
+        try:
+            with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+                repo.init()
+                repo._impl.clone_from(pkg_file('forgegit', 'tests/data/testgit.git'))
+            cloned = git.Repo(dirname)
+            assert cloned.git.config('--bool', '--get', 'receive.denyNonFastForwards') == 'true'
         finally:
             shutil.rmtree(dirname, ignore_errors=True)
 
diff --git a/scripts/migrations/force-push-sync-from-repo-config.py b/scripts/migrations/force-push-sync-from-repo-config.py
new file mode 100644
index 000000000..94b6381fa
--- /dev/null
+++ b/scripts/migrations/force-push-sync-from-repo-config.py
@@ -0,0 +1,77 @@
+#       Licensed to the Apache Software Foundation (ASF) under one
+#       or more contributor license agreements.  See the NOTICE file
+#       distributed with this work for additional information
+#       regarding copyright ownership.  The ASF licenses this file
+#       to you under the Apache License, Version 2.0 (the
+#       "License"); you may not use this file except in compliance
+#       with the License.  You may obtain a copy of the License at
+#
+#         http://www.apache.org/licenses/LICENSE-2.0
+#
+#       Unless required by applicable law or agreed to in writing,
+#       software distributed under the License is distributed on an
+#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#       KIND, either express or implied.  See the License for the
+#       specific language governing permissions and limitations
+#       under the License.
+
+"""
+One-time sync of Repository.force_push_allowed from each git repo's own config.
+
+Repos predating the force-push toggle have no force_push_allowed recorded, while their
+receive.denyNonFastForwards may already be true, false, or unset.  This reads each repo and
+stores what it actually permits, so the admin UI and menu label agree with reality.
+
+Reads git; writes only Mongo.  No repo's behaviour changes.
+
+    paster script /var/local/config/production.ini \
+        ../scripts/migrations/force-push-sync-from-repo-config.py -- --dry-run
+"""
+
+import argparse
+import logging
+import sys
+
+from ming.odm import session, ThreadLocalODMSession
+
+from allura.lib.utils import chunked_find
+from forgegit import model as GM
+
+log = logging.getLogger(__name__)
+
+
+def parse_options():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('--dry-run', action='store_true',
+                        help='report what would change without writing to Mongo')
+    return parser.parse_args(sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [])
+
+
+def main():
+    opts = parse_options()
+    counts = dict(seen=0, changed=0, unreadable=0)
+    for chunk in chunked_find(GM.Repository):
+        for repo in chunk:
+            counts['seen'] += 1
+            on_disk = repo._impl.force_push_allowed_on_disk()
+            if on_disk is None:
+                counts['unreadable'] += 1
+                log.warning('unreadable, leaving alone: %s', repo.full_fs_path)
+                continue
+            if on_disk == repo.force_push_allowed:
+                continue
+            counts['changed'] += 1
+            log.info('%s: force_push_allowed %s => %s',
+                     repo.full_fs_path, repo.force_push_allowed, on_disk)
+            if not opts.dry_run:
+                repo.force_push_allowed = on_disk
+                session(repo).flush(repo)
+        if not opts.dry_run:
+            ThreadLocalODMSession.flush_all()
+    log.info('%s %d git repos: %d updated, %d unreadable',
+             'would update' if opts.dry_run else 'synced', counts['seen'],
+             counts['changed'], counts['unreadable'])
+
+
+if __name__ == '__main__':
+    main()


(allura) 02/06: Added scm.force_push.git.enabled flag

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit cdda319c09593eb1f1f1a22e54bb4f57fe611428
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Fri Aug 7 20:10:47 2026 +0000

    Added scm.force_push.git.enabled flag
---
 Allura/development.ini | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)

diff --git a/Allura/development.ini b/Allura/development.ini
index 347c87480..60d349c8a 100644
--- a/Allura/development.ini
+++ b/Allura/development.ini
@@ -466,12 +466,8 @@ repo_refs_cache_threshold = .01
 scm.commit.git.detect_copies = true
 scm.commit.hg.detect_copies = false
 
-; Let repo admins enable/disable force push on their own git repos.  Only turn this on if
-; your git host honors receive.denyNonFastForwards in each repo's own config file; Allura
-; writes that value and nothing else.  When off, Allura never touches any repo's config.
-; Note that turning this off does not revert repos that were already toggled on: they keep
-; receive.denyNonFastForwards = false on disk, with the admin UI hidden so nobody can see or
-; change it.  Revert any enabled repos before disabling this setting.
+; Let repo admins toggle force push on their own git repos; only enable if your git host
+; honors receive.denyNonFastForwards.  Turning it off does not revert repos already enabled.
 ;scm.force_push.git.enabled = true
 
 ; One-click merge is enabled by default, but can be turned off on for each type of repo


(allura) 03/06: Fix for force push on new repos

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit afb36299120cf54c0d14cd949a60ad7886ea568a
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Mon Aug 17 22:02:06 2026 +0000

    Fix for force push on new repos
---
 Allura/allura/lib/repository.py                    | 11 +++--
 Allura/allura/model/repository.py                  |  9 ++++
 ForgeGit/forgegit/git_main.py                      |  7 ++--
 ForgeGit/forgegit/model/git_repo.py                | 23 ++++++++++
 .../forgegit/tests/functional/test_controllers.py  | 24 +++++++++++
 ForgeGit/forgegit/tests/model/test_repository.py   | 49 ++++++++++++++++++++++
 6 files changed, 116 insertions(+), 7 deletions(-)

diff --git a/Allura/allura/lib/repository.py b/Allura/allura/lib/repository.py
index 83c91f7c7..12651e250 100644
--- a/Allura/allura/lib/repository.py
+++ b/Allura/allura/lib/repository.py
@@ -304,8 +304,8 @@ def set_default_branch_name(self, branch_name=None, **kw):
     def force_push(self, allowed=None, **kw):
         if not asbool(config.get(f'scm.force_push.{self.app.config.tool_name}.enabled')):
             raise exc.HTTPNotFound()
-        if not self.repo:
-            # repo is still being created
+        if not self.repo or self.repo.status not in ('ready', 'analyzing'):
+            # init/clone/import recreate the repo dir, discarding config written before they finish
             raise exc.HTTPNotFound()
         if request.method == 'POST':
             allowed = bool(allowed)
@@ -313,9 +313,12 @@ def force_push(self, allowed=None, **kw):
                 M.AuditLog.log('{}: set "{}" {} => {}'.format(
                     self.app.config.options['mount_point'], 'force_push_allowed',
                     self.repo.force_push_allowed, allowed))
-                self.repo.set_force_push_allowed(allowed)
+            # written even when unchanged, so repos predating this feature get the value applied
+            self.repo.set_force_push_allowed(allowed)
             redirect(six.ensure_text(c.app.url))
-        return dict(app=self.app, force_push_allowed=self.repo.force_push_allowed)
+        # shown from the repo itself, not the stored field, so a repo predating this feature
+        # that still accepts force pushes is not displayed as if it refused them
+        return dict(app=self.app, force_push_allowed=self.repo.force_push_allowed_effective())
 
     @without_trailing_slash
     @expose('jinja:allura:templates/repo/checkout_url.html')
diff --git a/Allura/allura/model/repository.py b/Allura/allura/model/repository.py
index 4ba241c8c..136fd968a 100644
--- a/Allura/allura/model/repository.py
+++ b/Allura/allura/model/repository.py
@@ -149,6 +149,9 @@ def _setup_hooks(self, source_path=None):  # pragma no cover
     def set_force_push_allowed(self, allowed):  # pragma no cover
         raise NotImplementedError('set_force_push_allowed')
 
+    def force_push_allowed_on_disk(self):  # pragma no cover
+        raise NotImplementedError('force_push_allowed_on_disk')
+
     # pragma no cover
     def log(self, revs=None, path=None, exclude=None, id_only=True, **kw):
         """
@@ -557,6 +560,12 @@ def set_default_branch(self, name):
     def set_force_push_allowed(self, allowed: bool):
         return self._impl.set_force_push_allowed(allowed)
 
+    def force_push_allowed_effective(self) -> bool:
+        # repos predating this feature have no receive setting, so the stored field can understate
+        # what they actually permit; trust the repo itself when it can be read
+        on_disk = self._impl.force_push_allowed_on_disk()
+        return self.force_push_allowed if on_disk is None else on_disk
+
     def paged_diffs(self, commit_id, start=0, end=None, onlyChangedFiles=False):
         return self._impl.paged_diffs(commit_id, start, end, onlyChangedFiles)
 
diff --git a/ForgeGit/forgegit/git_main.py b/ForgeGit/forgegit/git_main.py
index 516924155..e4c4354bb 100644
--- a/ForgeGit/forgegit/git_main.py
+++ b/ForgeGit/forgegit/git_main.py
@@ -77,9 +77,10 @@ def admin_menu(self):
             c.project.url() + 'admin/' + self.config.options.mount_point +
             '/' + 'set_default_branch_name',
             className='admin_modal'))
-        if asbool(config.get(f'scm.force_push.{self.config.tool_name}.enabled')):
-            # self.repo is None while a repo is still being created
-            label = 'Force push (enabled)' if (self.repo and self.repo.force_push_allowed) else 'Force push'
+        if (asbool(config.get(f'scm.force_push.{self.config.tool_name}.enabled'))
+                and self.repo and self.repo.status in ('ready', 'analyzing')):
+            # hidden until ready: init/clone recreate the repo dir and would discard the setting
+            label = 'Force push (enabled)' if self.repo.force_push_allowed else 'Force push'
             links.append(SitemapEntry(
                 label,
                 c.project.url() + 'admin/' + self.config.options.mount_point +
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index 4ba1faf0c..971c6c998 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -200,8 +200,30 @@ def init(self):
             shared='all')
         self.__dict__['_git'] = repo
         self._setup_special_files()
+        self._apply_force_push_config()
         self._repo.set_status('ready')
 
+    def force_push_allowed_on_disk(self):
+        # what the repo itself currently permits, regardless of what Mongo records;
+        # None if that can't be determined, so callers fall back to the stored field
+        if self._git is None:
+            return None
+        try:
+            with self._git.config_reader('repository') as cr:
+                return not asbool(cr.get_value('receive', 'denyNonFastForwards', False))
+        except Exception:
+            log.exception('Could not read receive.denyNonFastForwards for %r', self._repo)
+            return None
+
+    def _apply_force_push_config(self):
+        # keep the repo's on-disk setting in step with force_push_allowed; a repo Allura has
+        # never written is left alone entirely, so this is a no-op when the feature is off
+        if not asbool(tg.config.get(f'scm.force_push.{self._repo.tool}.enabled')):
+            return
+        with self._git.config_writer() as cw:
+            cw.set_value('receive', 'denyNonFastForwards',
+                         'false' if self._repo.force_push_allowed else 'true')
+
     def can_hotcopy(self, source_url):
         enabled = asbool(tg.config.get('scm.git.hotcopy', True))
         is_local = os.path.exists(source_url)
@@ -234,6 +256,7 @@ def clone_from(self, source_url):
                     bare=True)
             self.__dict__['_git'] = repo
             self._setup_special_files(source_url)
+            self._apply_force_push_config()
         except Exception:
             self._repo.set_status('ready')
             raise
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index a190f4acb..ff4aa1dfe 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -573,6 +573,30 @@ def test_force_push_disabled_by_default(self):
         self.app.post('/p/test/admin/src-git/force_push',
                       params={'allowed': 'on'}, status=404)
 
+    def test_force_push_save_writes_even_when_unchanged(self):
+        # repos predating the feature have no receive section; saving must still apply the value
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            with patch('allura.tasks.repo_tasks.update_force_push_config.post') as post:
+                self.app.post('/p/test/admin/src-git/force_push', params={})
+            assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is False
+            post.assert_called_once_with(c.app.repo.full_fs_path, False)
+            assert M.AuditLog.query.find(
+                {'message': 'src-git: set "force_push_allowed" False => False'}).count() == 0
+
+    def test_force_push_hidden_until_repo_ready(self):
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            for status in ('initializing', 'cloning'):
+                c.app.repo.status = status
+                ThreadLocalODMSession.flush_all()
+                assert not any(l.label.startswith('Force push') for l in c.app.admin_menu())
+                self.app.get('/p/test/admin/src-git/force_push', status=404)
+                self.app.post('/p/test/admin/src-git/force_push',
+                              params={'allowed': 'on'}, status=404)
+            c.app.repo.status = 'analyzing'
+            ThreadLocalODMSession.flush_all()
+            assert any(l.label.startswith('Force push') for l in c.app.admin_menu())
+            self.app.get('/p/test/admin/src-git/force_push', status=200)
+
     def test_force_push_requires_admin(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
             self.app.get('/p/test/admin/src-git/force_push',
diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py
index 451fd4c1a..919a58a62 100644
--- a/ForgeGit/forgegit/tests/model/test_repository.py
+++ b/ForgeGit/forgegit/tests/model/test_repository.py
@@ -702,6 +702,55 @@ def test_set_force_push_allowed(self):
     def test_force_push_allowed_defaults_false(self):
         assert self.repo.force_push_allowed is False
 
+    def test_force_push_allowed_effective(self):
+        git_repo = git.Repo(self.repo.full_fs_path)
+        try:
+            # no receive setting at all: the repo accepts force pushes even though the field is False
+            assert self.repo.force_push_allowed is False
+            assert self.repo.force_push_allowed_effective() is True
+            with git_repo.config_writer() as cw:
+                cw.set_value('receive', 'denyNonFastForwards', 'true')
+            assert self.repo.force_push_allowed_effective() is False
+            with git_repo.config_writer() as cw:
+                cw.set_value('receive', 'denyNonFastForwards', 'false')
+            assert self.repo.force_push_allowed_effective() is True
+        finally:
+            with git_repo.config_writer() as cw:
+                cw.remove_section('receive')
+
+    def test_force_push_allowed_effective_falls_back(self):
+        with mock.patch.object(GM.git_repo.GitImplementation, 'force_push_allowed_on_disk') as on_disk:
+            on_disk.return_value = None
+            self.repo.force_push_allowed = True
+            assert self.repo.force_push_allowed_effective() is True
+
+    def _init_scratch_repo(self):
+        repo = GM.Repository(name='testgit.git', fs_path=g.tmpdir + '/', url_path='/test/',
+                             tool='git', status='creating')
+        dirname = os.path.join(repo.fs_path, repo.name)
+        if os.path.exists(dirname):
+            shutil.rmtree(dirname)
+        return repo, dirname
+
+    def test_init_denies_force_push_when_enabled(self):
+        repo, dirname = self._init_scratch_repo()
+        try:
+            with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+                repo.init()
+            with git.Repo(dirname).config_reader('repository') as cr:
+                assert cr.get_value('receive', 'denyNonFastForwards') is True
+        finally:
+            shutil.rmtree(dirname, ignore_errors=True)
+
+    def test_init_leaves_config_alone_when_disabled(self):
+        repo, dirname = self._init_scratch_repo()
+        try:
+            repo.init()
+            with git.Repo(dirname).config_reader('repository') as cr:
+                assert not cr.has_section('receive')
+        finally:
+            shutil.rmtree(dirname, ignore_errors=True)
+
     def test_default_branch_non_standard_unset(self):
         with mock.patch.object(self.repo, 'get_branches') as gb, \
                 mock.patch.object(self.repo, 'set_default_branch') as set_db:


(allura) 01/06: Force push enable of repos

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch dc/686
in repository https://gitbox.apache.org/repos/asf/allura.git

commit cfee7653663dfc81425e25baf2d93fd8620fc222
Author: Daniel Castillo <da...@slashdotmedia.com>
AuthorDate: Fri Aug 7 17:24:00 2026 +0000

    Force push enable of repos
---
 Allura/allura/lib/repository.py                    | 20 +++++++-
 Allura/allura/model/repository.py                  |  7 +++
 Allura/allura/tasks/repo_tasks.py                  |  7 +++
 Allura/allura/templates/repo/force_push.html       | 46 +++++++++++++++++
 Allura/development.ini                             |  8 +++
 ForgeGit/forgegit/git_main.py                      | 10 ++++
 ForgeGit/forgegit/model/git_repo.py                |  8 +++
 .../forgegit/tests/functional/test_controllers.py  | 60 ++++++++++++++++++++++
 ForgeGit/forgegit/tests/model/test_repository.py   | 28 +++++++++-
 9 files changed, 192 insertions(+), 2 deletions(-)

diff --git a/Allura/allura/lib/repository.py b/Allura/allura/lib/repository.py
index f76374bc9..83c91f7c7 100644
--- a/Allura/allura/lib/repository.py
+++ b/Allura/allura/lib/repository.py
@@ -54,7 +54,7 @@ class RepositoryApp(Application):
         'read': 'Browse repo via web UI. Removing read does not prevent direct repo read access.',
         'write': 'Repo push access.',
         'create': 'Not used.',
-        'admin': 'Set permissions, default branch, and viewable files.',
+        'admin': 'Set permissions, default branch, force push, and viewable files.',
     }
     config_options = Application.config_options + [
         ConfigOption('cloned_from_project_id', ObjectId, None),
@@ -299,6 +299,24 @@ def set_default_branch_name(self, branch_name=None, **kw):
             return dict(app=self.app,
                         default_branch_name=self.app.default_branch_name)
 
+    @without_trailing_slash
+    @expose('jinja:allura:templates/repo/force_push.html')
+    def force_push(self, allowed=None, **kw):
+        if not asbool(config.get(f'scm.force_push.{self.app.config.tool_name}.enabled')):
+            raise exc.HTTPNotFound()
+        if not self.repo:
+            # repo is still being created
+            raise exc.HTTPNotFound()
+        if request.method == 'POST':
+            allowed = bool(allowed)
+            if allowed != self.repo.force_push_allowed:
+                M.AuditLog.log('{}: set "{}" {} => {}'.format(
+                    self.app.config.options['mount_point'], 'force_push_allowed',
+                    self.repo.force_push_allowed, allowed))
+                self.repo.set_force_push_allowed(allowed)
+            redirect(six.ensure_text(c.app.url))
+        return dict(app=self.app, force_push_allowed=self.repo.force_push_allowed)
+
     @without_trailing_slash
     @expose('jinja:allura:templates/repo/checkout_url.html')
     def checkout_url(self):
diff --git a/Allura/allura/model/repository.py b/Allura/allura/model/repository.py
index 23305db25..4ba241c8c 100644
--- a/Allura/allura/model/repository.py
+++ b/Allura/allura/model/repository.py
@@ -146,6 +146,9 @@ def _setup_hooks(self, source_path=None):  # pragma no cover
         the repo.  Optionally provide a path from which to copy existing hooks.'''
         raise NotImplementedError('_setup_hooks')
 
+    def set_force_push_allowed(self, allowed):  # pragma no cover
+        raise NotImplementedError('set_force_push_allowed')
+
     # pragma no cover
     def log(self, revs=None, path=None, exclude=None, id_only=True, **kw):
         """
@@ -387,6 +390,7 @@ class __mongometa__:
     repo_tags = FieldProperty(S.Deprecated)
     upstream_repo = FieldProperty(dict(name=str, url=str))
     default_branch_name = FieldProperty(str)
+    force_push_allowed = FieldProperty(bool, if_missing=False)
     cached_branches = FieldProperty([dict(name=str, object_id=str)])
     cached_tags = FieldProperty([dict(name=str, object_id=str)])
 
@@ -550,6 +554,9 @@ def head(self):
     def set_default_branch(self, name):
         return self._impl.set_default_branch(name)
 
+    def set_force_push_allowed(self, allowed: bool):
+        return self._impl.set_force_push_allowed(allowed)
+
     def paged_diffs(self, commit_id, start=0, end=None, onlyChangedFiles=False):
         return self._impl.paged_diffs(commit_id, start, end, onlyChangedFiles)
 
diff --git a/Allura/allura/tasks/repo_tasks.py b/Allura/allura/tasks/repo_tasks.py
index 7838c5c53..d2ca6accd 100644
--- a/Allura/allura/tasks/repo_tasks.py
+++ b/Allura/allura/tasks/repo_tasks.py
@@ -197,3 +197,10 @@ def update_head_reference(fs_path, branch_name):
         new_branch = [ref for ref in repo.refs if ref.name == branch_name]
         _ref = SymbolicReference.create(repo, 'HEAD', repo.head.reference)
         _ref.reference = new_branch[0]
+
+
+@task
+def update_force_push_config(fs_path: str, allowed: bool):
+    repo = git.Repo(fs_path, odbt=git.GitCmdObjectDB)
+    with repo.config_writer() as cw:  # config_level defaults to 'repository'
+        cw.set_value('receive', 'denyNonFastForwards', 'false' if allowed else 'true')
diff --git a/Allura/allura/templates/repo/force_push.html b/Allura/allura/templates/repo/force_push.html
new file mode 100644
index 000000000..b3a8c2944
--- /dev/null
+++ b/Allura/allura/templates/repo/force_push.html
@@ -0,0 +1,46 @@
+{#-
+       Licensed to the Apache Software Foundation (ASF) under one
+       or more contributor license agreements.  See the NOTICE file
+       distributed with this work for additional information
+       regarding copyright ownership.  The ASF licenses this file
+       to you under the Apache License, Version 2.0 (the
+       "License"); you may not use this file except in compliance
+       with the License.  You may obtain a copy of the License at
+
+         http://www.apache.org/licenses/LICENSE-2.0
+
+       Unless required by applicable law or agreed to in writing,
+       software distributed under the License is distributed on an
+       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+       KIND, either express or implied.  See the License for the
+       specific language governing permissions and limitations
+       under the License.
+-#}
+<form action="{{c.project.url()}}admin/{{app.config.options.mount_point}}/force_push" method="POST">
+    <div class="grid-13">
+        <label>
+            <input type="checkbox" name="allowed" {% if force_push_allowed %}checked{% endif %}/>
+            Allow force push to this repository
+        </label>
+    </div>
+    <div class="grid-13">&nbsp;</div>
+    <div class="grid-13">
+        <p>By default this repository refuses any push that would discard commits. Someone
+        attempting one sees:</p>
+        <p><code>remote: error: denying non-fast-forward refs/heads/master</code></p>
+        <p>Ticking the box above lets <code>git push --force</code> succeed. Be aware that:</p>
+        <ul>
+            <li>Commits discarded by a force push are gone permanently unless someone still
+            has a copy.</li>
+            <li>Pages for discarded commits stay visible on this site, and their entries in
+            the activity feed cannot be removed.</li>
+            <li>This setting stays on until you switch it back off here.</li>
+        </ul>
+    </div>
+    <div class="grid-13">&nbsp;</div>
+    <hr>
+    <div class="grid-13">&nbsp;</div>
+    <div class="grid-13">
+        <input type="submit" value="Save">
+    </div>
+</form>
diff --git a/Allura/development.ini b/Allura/development.ini
index a76316620..347c87480 100644
--- a/Allura/development.ini
+++ b/Allura/development.ini
@@ -466,6 +466,14 @@ repo_refs_cache_threshold = .01
 scm.commit.git.detect_copies = true
 scm.commit.hg.detect_copies = false
 
+; Let repo admins enable/disable force push on their own git repos.  Only turn this on if
+; your git host honors receive.denyNonFastForwards in each repo's own config file; Allura
+; writes that value and nothing else.  When off, Allura never touches any repo's config.
+; Note that turning this off does not revert repos that were already toggled on: they keep
+; receive.denyNonFastForwards = false on disk, with the admin UI hidden so nobody can see or
+; change it.  Revert any enabled repos before disabling this setting.
+;scm.force_push.git.enabled = true
+
 ; One-click merge is enabled by default, but can be turned off on for each type of repo
 scm.merge.git.disabled = false
 scm.merge.hg.disabled = false
diff --git a/ForgeGit/forgegit/git_main.py b/ForgeGit/forgegit/git_main.py
index ddb4013d3..516924155 100644
--- a/ForgeGit/forgegit/git_main.py
+++ b/ForgeGit/forgegit/git_main.py
@@ -19,6 +19,8 @@
 
 # Non-stdlib imports
 from tg import tmpl_context as c
+from tg import config
+from paste.deploy.converters import asbool
 
 from ming.utils import LazyProperty
 from ming.odm.odmsession import ThreadLocalODMSession
@@ -75,6 +77,14 @@ def admin_menu(self):
             c.project.url() + 'admin/' + self.config.options.mount_point +
             '/' + 'set_default_branch_name',
             className='admin_modal'))
+        if asbool(config.get(f'scm.force_push.{self.config.tool_name}.enabled')):
+            # self.repo is None while a repo is still being created
+            label = 'Force push (enabled)' if (self.repo and self.repo.force_push_allowed) else 'Force push'
+            links.append(SitemapEntry(
+                label,
+                c.project.url() + 'admin/' + self.config.options.mount_point +
+                '/' + 'force_push',
+                className='admin_modal'))
         links += super().admin_menu()
         return links
 
diff --git a/ForgeGit/forgegit/model/git_repo.py b/ForgeGit/forgegit/model/git_repo.py
index 3355bbee8..4ba1faf0c 100644
--- a/ForgeGit/forgegit/model/git_repo.py
+++ b/ForgeGit/forgegit/model/git_repo.py
@@ -224,6 +224,9 @@ def clone_from(self, source_url):
                 if os.path.exists(post_receive):
                     os.rename(post_receive, post_receive + '-user')
                 repo = git.Repo(fullname)
+                # a hotcopy inherits the parent's config verbatim; force push is not inherited
+                with repo.config_writer() as cw:
+                    cw.remove_section('receive')
             else:
                 repo = git.Repo.clone_from(
                     source_url,
@@ -644,6 +647,11 @@ def set_default_branch(self, name):
         allura.tasks.repo_tasks.update_head_reference.post(self._repo.full_fs_path, name)
         session(self._repo).flush(self._repo)
 
+    def set_force_push_allowed(self, allowed: bool):
+        self._repo.force_push_allowed = allowed
+        allura.tasks.repo_tasks.update_force_push_config.post(self._repo.full_fs_path, allowed)
+        session(self._repo).flush(self._repo)
+
     def _get_last_commit(self, commit_id, paths):
         # git apparently considers merge commits to have "touched" a path
         # if the path is changed in either branch being merged, even though
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index 4b6c18224..a190f4acb 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -547,6 +547,37 @@ def test_set_default_branch(self):
         assert 'bad</a>' not in r
         assert 'README</a>' in r
 
+    def test_force_push_toggle(self):
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            r = self.app.get('/p/test/admin/src-git/force_push')
+            assert 'name="allowed"' in r
+            self.app.post('/p/test/admin/src-git/force_push', params={'allowed': 'on'})
+            assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is True
+            assert M.AuditLog.query.find(
+                {'message': 'src-git: set "force_push_allowed" False => True'}).count() == 1
+
+            self.app.post('/p/test/admin/src-git/force_push', params={})
+            assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is False
+            assert M.AuditLog.query.find(
+                {'message': 'src-git: set "force_push_allowed" True => False'}).count() == 1
+
+    def test_force_push_menu_entry(self):
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            assert any(l.label == 'Force push' for l in c.app.admin_menu())
+            c.app.repo.force_push_allowed = True
+            assert any(l.label == 'Force push (enabled)' for l in c.app.admin_menu())
+
+    def test_force_push_disabled_by_default(self):
+        assert not any(l.label.startswith('Force push') for l in c.app.admin_menu())
+        self.app.get('/p/test/admin/src-git/force_push', status=404)
+        self.app.post('/p/test/admin/src-git/force_push',
+                      params={'allowed': 'on'}, status=404)
+
+    def test_force_push_requires_admin(self):
+        with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
+            self.app.get('/p/test/admin/src-git/force_push',
+                         extra_environ=dict(username='test-user'), status=403)
+
     def test_index_branch_unicode(self):
         # more realistic case is the default branch having unicode, but passing the branch name is easier
         resp = self.app.get('/p/test/src-git/', params={'branch': 'ƒ∂ß'})
@@ -725,6 +756,35 @@ def test_fork_display(self):
         assert 'Clone of' in r
         assert 'Test forked repository' in r
 
+    def test_fork_does_not_inherit_force_push(self):
+        # Set parent repo to have force_push_allowed = True BEFORE creating fork
+        h.set_context('test', 'src-git', neighborhood='Projects')
+        parent_repo = c.app.repo
+        parent_repo.force_push_allowed = True
+        ThreadLocalODMSession.flush_all()
+
+        # Create a new fork with parent now having force_push_allowed = True
+        to_project = M.Project.query.get(
+            shortname='test2', neighborhood_id=c.project.neighborhood_id)
+        r = self.app.post('/src-git/fork', params=dict(
+            project_id=str(to_project._id),
+            mount_point='code_force_test',
+            mount_label='Test fork for force_push'))
+        assert "{status: 'error'}" not in str(r.follow())
+
+        # Initialize the forked repo and verify force_push_allowed was not inherited
+        cloned_from = parent_repo
+        with h.push_context('test2', 'code_force_test', neighborhood='Projects'):
+            c.app.repo.init_as_clone(
+                cloned_from.full_fs_path,
+                cloned_from.app.config.script_name(),
+                cloned_from.full_fs_path,
+                bypass_path_check_for_tests=True,
+            )
+            assert c.app.repo.force_push_allowed is False
+            with c.app.repo._impl._git.config_reader('repository') as cr:
+                assert not cr.has_section('receive')
+
     def test_fork_links_go_to_fork(self):
         r = self._fork_page()
         hrefs = (a.get('href') for a in r.html('a'))
diff --git a/ForgeGit/forgegit/tests/model/test_repository.py b/ForgeGit/forgegit/tests/model/test_repository.py
index bb6ac5e40..451fd4c1a 100644
--- a/ForgeGit/forgegit/tests/model/test_repository.py
+++ b/ForgeGit/forgegit/tests/model/test_repository.py
@@ -34,7 +34,7 @@
 
 from alluratest.controller import setup_basic_test, setup_global_objects
 from allura.lib import helpers as h
-from allura.tasks.repo_tasks import tarball, update_head_reference
+from allura.tasks.repo_tasks import tarball, update_head_reference, update_force_push_config
 from allura.tests import decorators as td
 from allura.tests.model.test_repo import RepoImplTestBase
 from allura import model as M
@@ -676,6 +676,32 @@ def test_update_default_branch(self):
             update_head_reference(self.repo.full_fs_path, 'master')
             assert impl._git.head.reference.name == 'master'
 
+    def test_update_force_push_config(self):
+        fs_path = self.repo.full_fs_path
+        git_repo = git.Repo(fs_path)
+        try:
+            update_force_push_config(fs_path, True)
+            with git_repo.config_reader('repository') as cr:
+                assert cr.get_value('receive', 'denyNonFastForwards') is False
+            update_force_push_config(fs_path, False)
+            with git_repo.config_reader('repository') as cr:
+                assert cr.get_value('receive', 'denyNonFastForwards') is True
+        finally:
+            with git_repo.config_writer() as cw:
+                cw.remove_section('receive')
+
+    def test_set_force_push_allowed(self):
+        # setup_with_tools() ends with close_all(), so self.repo is detached and
+        # session() on it returns None; re-query to get a session-attached instance
+        repo = GM.Repository.query.get(_id=self.repo._id)
+        with mock.patch('allura.tasks.repo_tasks.update_force_push_config.post') as post:
+            repo.set_force_push_allowed(True)
+            assert repo.force_push_allowed is True
+            post.assert_called_once_with(repo.full_fs_path, True)
+
+    def test_force_push_allowed_defaults_false(self):
+        assert self.repo.force_push_allowed is False
+
     def test_default_branch_non_standard_unset(self):
         with mock.patch.object(self.repo, 'get_branches') as gb, \
                 mock.patch.object(self.repo, 'set_default_branch') as set_db: