fix(git): restrict hook permissions (#39008) (#39016)

Backport #39008 by @bircni

Create delegate hook files and directories without group or other write
access, including correcting existing hook directories.

_Assisted-by: Codex:GPT-5_

---------

Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
Giteabot
2026-08-21 05:40:30 -07:00
committed by GitHub
parent 76c768edca
commit bf7b6f8bd4
2 changed files with 42 additions and 4 deletions
+8 -4
View File
@@ -118,15 +118,19 @@ func createDelegateHooks(hookDir string) (err error) {
oldHookPath := filepath.Join(hookDir, hookName)
newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
return fmt.Errorf("create hooks dir '%s': %w", filepath.Join(hookDir, hookName+".d"), err)
hookDDir := filepath.Join(hookDir, hookName+".d")
if err := os.MkdirAll(hookDDir, 0o755); err != nil {
return fmt.Errorf("create hooks dir '%s': %w", hookDDir, err)
}
if err := os.Chmod(hookDDir, 0o755); err != nil {
return fmt.Errorf("chmod hooks dir '%s': %w", hookDDir, err)
}
// WARNING: This will override all old server-side hooks
if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %w ", oldHookPath, err)
}
if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o777); err != nil {
if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o755); err != nil {
return fmt.Errorf("write old hook file '%s': %w", oldHookPath, err)
}
@@ -137,7 +141,7 @@ func createDelegateHooks(hookDir string) (err error) {
if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %w", newHookPath, err)
}
if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o777); err != nil {
if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o755); err != nil {
return fmt.Errorf("write new hook file '%s': %w", newHookPath, err)
}
+34
View File
@@ -0,0 +1,34 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package gitrepo
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestCreateDelegateHooksPermissions(t *testing.T) {
hookDir := t.TempDir()
existingHookDir := filepath.Join(hookDir, "post-receive.d")
require.NoError(t, os.MkdirAll(existingHookDir, 0o777))
require.NoError(t, os.Chmod(existingHookDir, 0o777))
require.NoError(t, createDelegateHooks(hookDir))
hookNames, _, _ := getHookTemplates()
for _, hookName := range hookNames {
for _, path := range []string{
filepath.Join(hookDir, hookName),
filepath.Join(hookDir, hookName+".d"),
filepath.Join(hookDir, hookName+".d", "gitea"),
} {
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o755), info.Mode().Perm(), path)
}
}
}