BlueGit

timfa bluegit

fix: commit de pipeline-editor ook in een lege repository

Een repository zonder commits heeft nog geen master. De eerste commit
wordt zonder parent gemaakt. Git krijgt een vaste identiteit en een
werkmap onder de state, niet onder /tmp of de homedirectory.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa

Authored 2026-10-22 · 3 weeks ago

Hash
a437eecd14069734fba7d35dd5b61734165f91bb
Parent
67d7d3bd
Pipeline
Failed
9 files changed +515 −77
internal/gitrepo/commit_test.go added +169 −0
@@ -0,0 +1,169 @@
1 package gitrepo
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "gitlab.com/Timfa/bluegit/internal/access"
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14 )
15
16 // TestCommitOnBranchHardened bootst de system-service na: een andere uid
17 // via een user-namespace, een alleen-lezen homedirectory, geen git-identiteit
18 // in de omgeving, en een lege repository zonder master.
19 func TestCommitOnBranchHardened(t *testing.T) {
20 if os.Getenv("BLUEGIT_SANDBOX") == "inner" {
21 commitSandboxInner(t)
22 return
23 }
24 if _, err := exec.LookPath("git"); err != nil {
25 t.Skip("git ontbreekt")
26 }
27 if _, err := exec.LookPath("unshare"); err != nil {
28 t.Skip("unshare ontbreekt")
29 }
30 base := t.TempDir()
31 home := filepath.Join(base, "home")
32 state := filepath.Join(base, "state", "tmp")
33 bare := filepath.Join(base, "repo.git")
34 if err := os.MkdirAll(home, 0o755); err != nil {
35 t.Fatal(err)
36 }
37 if err := os.MkdirAll(state, 0o755); err != nil {
38 t.Fatal(err)
39 }
40 if err := os.WriteFile(filepath.Join(home, "secret"), []byte("x\n"), 0o644); err != nil {
41 t.Fatal(err)
42 }
43 gitInit(t, bare)
44 hook := "#!/bin/sh\nwhile read old new ref; do\n" +
45 " printf '%s %s\\n' \"$BLUEGIT_ROLE\" \"$ref\" >> " + shellQuote(filepath.Join(base, "roles")) + "\n" +
46 " if [ \"$ref\" = \"refs/heads/master\" ] && [ \"$BLUEGIT_ROLE\" != \"maintainer\" ]; then\n" +
47 " echo \"branch master is protected; only a maintainer may change it\" >&2\n" +
48 " exit 1\n" +
49 " fi\ndone\nexit 0\n"
50 if err := os.WriteFile(filepath.Join(bare, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
51 t.Fatal(err)
52 }
53 env := dropEnv(os.Environ(), "HOME=", "TMPDIR=", "GIT_AUTHOR_", "GIT_COMMITTER_")
54 env = append(env,
55 "BLUEGIT_SANDBOX=inner",
56 "BLUEGIT_SANDBOX_BASE="+base,
57 "HOME="+home,
58 "TMPDIR="+home,
59 "GIT_AUTHOR_NAME=hostile",
60 "GIT_AUTHOR_EMAIL=hostile@example.com",
61 "GIT_COMMITTER_NAME=hostile",
62 "GIT_COMMITTER_EMAIL=hostile@example.com",
63 )
64 cmd := exec.Command("unshare", "-U", "-r", "-m", "--", os.Args[0], "-test.run", "^TestCommitOnBranchHardened$", "-test.count=1", "-test.v")
65 cmd.Env = env
66 out, err := cmd.CombinedOutput()
67 if err != nil {
68 t.Fatalf("sandbox: %v\n%s", err, out)
69 }
70 if !strings.Contains(string(out), "sandbox-ok") {
71 t.Fatalf("sandbox zonder bevestiging:\n%s", out)
72 }
73 roles, err := os.ReadFile(filepath.Join(base, "roles"))
74 if err != nil {
75 t.Fatal(err)
76 }
77 if !strings.Contains(string(roles), "maintainer refs/heads/master") {
78 t.Fatalf("hook zag de beheerder niet:\n%s", roles)
79 }
80 if !strings.Contains(string(roles), "developer refs/heads/master") {
81 t.Fatalf("hook zag de ontwikkelaar niet:\n%s", roles)
82 }
83 }
84
85 func commitSandboxInner(t *testing.T) {
86 if os.Getuid() != 0 {
87 t.Fatalf("uid %d, verwacht de namespace-root", os.Getuid())
88 }
89 base := os.Getenv("BLUEGIT_SANDBOX_BASE")
90 home := filepath.Join(base, "home")
91 bare := filepath.Join(base, "repo.git")
92 if out, err := exec.Command("mount", "-o", "bind,ro", home, home).CombinedOutput(); err != nil {
93 t.Fatalf("mount: %v\n%s", err, out)
94 }
95 if f, err := os.OpenFile(filepath.Join(home, "nope"), os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
96 f.Close()
97 t.Fatal("homedirectory was beschrijfbaar")
98 }
99 os.Setenv("HOME", home)
100 os.Setenv("TMPDIR", home)
101 os.Setenv("GIT_AUTHOR_NAME", "hostile")
102 os.Setenv("GIT_AUTHOR_EMAIL", "hostile@example.com")
103 os.Setenv("GIT_COMMITTER_NAME", "hostile")
104 os.Setenv("GIT_COMMITTER_EMAIL", "hostile@example.com")
105
106 work := filepath.Join(base, "state", "tmp", "edit")
107 body := "image: alpine:latest\n"
108 err := CommitOnBranch(context.Background(), "git", bare, work, "master", "timfa", "timfa@users.git.timfalken.com", "Add blue-ci-cd.yml", "", map[string]string{"blue-ci-cd.yml": body}, access.RoleMaintainer, []string{"master"})
109 if err != nil {
110 t.Fatal(err)
111 }
112 got := gitShow(t, bare, "show", "master:blue-ci-cd.yml")
113 if !strings.Contains(got, "alpine:latest") {
114 t.Fatalf("bestand: %s", got)
115 }
116 who := strings.TrimSpace(gitShow(t, bare, "log", "-1", "--format=%an %ae"))
117 if who != "timfa timfa@users.git.timfalken.com" {
118 t.Fatalf("identiteit %q", who)
119 }
120 if out, err := exec.Command("git", "--git-dir", bare, "rev-parse", "--verify", "master^").CombinedOutput(); err == nil {
121 t.Fatalf("eerste commit heeft een parent: %s", out)
122 }
123 err = CommitOnBranch(context.Background(), "git", bare, work, "master", "ada", "ada@users.git.timfalken.com", "ada op master", "", map[string]string{"blue-ci-cd.yml": "image: nope\n"}, access.RoleDeveloper, []string{"master"})
124 if err == nil {
125 t.Fatal("developer committe op beschermde master")
126 }
127 var ie i18n.Error
128 if !errors.As(err, &ie) || ie.Key != "edit.protected" {
129 t.Fatalf("weigering: %v", err)
130 }
131 if strings.Contains(gitShow(t, bare, "show", "master:blue-ci-cd.yml"), "nope") {
132 t.Fatal("master veranderde door de ontwikkelaar")
133 }
134 t.Log("sandbox-ok")
135 }
136
137 func gitInit(t *testing.T, bare string) {
138 t.Helper()
139 if out, err := exec.Command("git", "init", "--bare", "--initial-branch", "master", bare).CombinedOutput(); err != nil {
140 t.Fatalf("init: %v\n%s", err, out)
141 }
142 }
143
144 func gitShow(t *testing.T, bare string, args ...string) string {
145 t.Helper()
146 cmd := append([]string{"--git-dir", bare}, args...)
147 out, err := exec.Command("git", cmd...).CombinedOutput()
148 if err != nil {
149 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
150 }
151 return string(out)
152 }
153
154 func dropEnv(env []string, prefixes ...string) []string {
155 var out []string
156 for _, e := range env {
157 skip := false
158 for _, p := range prefixes {
159 if strings.HasPrefix(e, p) {
160 skip = true
161 break
162 }
163 }
164 if !skip {
165 out = append(out, e)
166 }
167 }
168 return out
169 }
@@ -0,0 +1,169 @@
1package gitrepo
2
3import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "gitlab.com/Timfa/bluegit/internal/access"
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14)
15
16// TestCommitOnBranchHardened bootst de system-service na: een andere uid
17// via een user-namespace, een alleen-lezen homedirectory, geen git-identiteit
18// in de omgeving, en een lege repository zonder master.
19func TestCommitOnBranchHardened(t *testing.T) {
20 if os.Getenv("BLUEGIT_SANDBOX") == "inner" {
21 commitSandboxInner(t)
22 return
23 }
24 if _, err := exec.LookPath("git"); err != nil {
25 t.Skip("git ontbreekt")
26 }
27 if _, err := exec.LookPath("unshare"); err != nil {
28 t.Skip("unshare ontbreekt")
29 }
30 base := t.TempDir()
31 home := filepath.Join(base, "home")
32 state := filepath.Join(base, "state", "tmp")
33 bare := filepath.Join(base, "repo.git")
34 if err := os.MkdirAll(home, 0o755); err != nil {
35 t.Fatal(err)
36 }
37 if err := os.MkdirAll(state, 0o755); err != nil {
38 t.Fatal(err)
39 }
40 if err := os.WriteFile(filepath.Join(home, "secret"), []byte("x\n"), 0o644); err != nil {
41 t.Fatal(err)
42 }
43 gitInit(t, bare)
44 hook := "#!/bin/sh\nwhile read old new ref; do\n" +
45 " printf '%s %s\\n' \"$BLUEGIT_ROLE\" \"$ref\" >> " + shellQuote(filepath.Join(base, "roles")) + "\n" +
46 " if [ \"$ref\" = \"refs/heads/master\" ] && [ \"$BLUEGIT_ROLE\" != \"maintainer\" ]; then\n" +
47 " echo \"branch master is protected; only a maintainer may change it\" >&2\n" +
48 " exit 1\n" +
49 " fi\ndone\nexit 0\n"
50 if err := os.WriteFile(filepath.Join(bare, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
51 t.Fatal(err)
52 }
53 env := dropEnv(os.Environ(), "HOME=", "TMPDIR=", "GIT_AUTHOR_", "GIT_COMMITTER_")
54 env = append(env,
55 "BLUEGIT_SANDBOX=inner",
56 "BLUEGIT_SANDBOX_BASE="+base,
57 "HOME="+home,
58 "TMPDIR="+home,
59 "GIT_AUTHOR_NAME=hostile",
60 "GIT_AUTHOR_EMAIL=hostile@example.com",
61 "GIT_COMMITTER_NAME=hostile",
62 "GIT_COMMITTER_EMAIL=hostile@example.com",
63 )
64 cmd := exec.Command("unshare", "-U", "-r", "-m", "--", os.Args[0], "-test.run", "^TestCommitOnBranchHardened$", "-test.count=1", "-test.v")
65 cmd.Env = env
66 out, err := cmd.CombinedOutput()
67 if err != nil {
68 t.Fatalf("sandbox: %v\n%s", err, out)
69 }
70 if !strings.Contains(string(out), "sandbox-ok") {
71 t.Fatalf("sandbox zonder bevestiging:\n%s", out)
72 }
73 roles, err := os.ReadFile(filepath.Join(base, "roles"))
74 if err != nil {
75 t.Fatal(err)
76 }
77 if !strings.Contains(string(roles), "maintainer refs/heads/master") {
78 t.Fatalf("hook zag de beheerder niet:\n%s", roles)
79 }
80 if !strings.Contains(string(roles), "developer refs/heads/master") {
81 t.Fatalf("hook zag de ontwikkelaar niet:\n%s", roles)
82 }
83}
84
85func commitSandboxInner(t *testing.T) {
86 if os.Getuid() != 0 {
87 t.Fatalf("uid %d, verwacht de namespace-root", os.Getuid())
88 }
89 base := os.Getenv("BLUEGIT_SANDBOX_BASE")
90 home := filepath.Join(base, "home")
91 bare := filepath.Join(base, "repo.git")
92 if out, err := exec.Command("mount", "-o", "bind,ro", home, home).CombinedOutput(); err != nil {
93 t.Fatalf("mount: %v\n%s", err, out)
94 }
95 if f, err := os.OpenFile(filepath.Join(home, "nope"), os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
96 f.Close()
97 t.Fatal("homedirectory was beschrijfbaar")
98 }
99 os.Setenv("HOME", home)
100 os.Setenv("TMPDIR", home)
101 os.Setenv("GIT_AUTHOR_NAME", "hostile")
102 os.Setenv("GIT_AUTHOR_EMAIL", "hostile@example.com")
103 os.Setenv("GIT_COMMITTER_NAME", "hostile")
104 os.Setenv("GIT_COMMITTER_EMAIL", "hostile@example.com")
105
106 work := filepath.Join(base, "state", "tmp", "edit")
107 body := "image: alpine:latest\n"
108 err := CommitOnBranch(context.Background(), "git", bare, work, "master", "timfa", "timfa@users.git.timfalken.com", "Add blue-ci-cd.yml", "", map[string]string{"blue-ci-cd.yml": body}, access.RoleMaintainer, []string{"master"})
109 if err != nil {
110 t.Fatal(err)
111 }
112 got := gitShow(t, bare, "show", "master:blue-ci-cd.yml")
113 if !strings.Contains(got, "alpine:latest") {
114 t.Fatalf("bestand: %s", got)
115 }
116 who := strings.TrimSpace(gitShow(t, bare, "log", "-1", "--format=%an %ae"))
117 if who != "timfa timfa@users.git.timfalken.com" {
118 t.Fatalf("identiteit %q", who)
119 }
120 if out, err := exec.Command("git", "--git-dir", bare, "rev-parse", "--verify", "master^").CombinedOutput(); err == nil {
121 t.Fatalf("eerste commit heeft een parent: %s", out)
122 }
123 err = CommitOnBranch(context.Background(), "git", bare, work, "master", "ada", "ada@users.git.timfalken.com", "ada op master", "", map[string]string{"blue-ci-cd.yml": "image: nope\n"}, access.RoleDeveloper, []string{"master"})
124 if err == nil {
125 t.Fatal("developer committe op beschermde master")
126 }
127 var ie i18n.Error
128 if !errors.As(err, &ie) || ie.Key != "edit.protected" {
129 t.Fatalf("weigering: %v", err)
130 }
131 if strings.Contains(gitShow(t, bare, "show", "master:blue-ci-cd.yml"), "nope") {
132 t.Fatal("master veranderde door de ontwikkelaar")
133 }
134 t.Log("sandbox-ok")
135}
136
137func gitInit(t *testing.T, bare string) {
138 t.Helper()
139 if out, err := exec.Command("git", "init", "--bare", "--initial-branch", "master", bare).CombinedOutput(); err != nil {
140 t.Fatalf("init: %v\n%s", err, out)
141 }
142}
143
144func gitShow(t *testing.T, bare string, args ...string) string {
145 t.Helper()
146 cmd := append([]string{"--git-dir", bare}, args...)
147 out, err := exec.Command("git", cmd...).CombinedOutput()
148 if err != nil {
149 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
150 }
151 return string(out)
152}
153
154func dropEnv(env []string, prefixes ...string) []string {
155 var out []string
156 for _, e := range env {
157 skip := false
158 for _, p := range prefixes {
159 if strings.HasPrefix(e, p) {
160 skip = true
161 break
162 }
163 }
164 if !skip {
165 out = append(out, e)
166 }
167 }
168 return out
169}
internal/gitrepo/repo.go +18 −21
@@ -435,7 +435,12 @@ func CreateTag(ctx context.Context, gitBin, dir, name, rev, message, author, ema
435 435 if len(message) > 5000 {
436 436 return i18n.E("err.tagLong")
437 437 }
438 env := identityEnv(author, email)
438 home, err := os.MkdirTemp(dir, "home-")
439 if err != nil {
440 return classifyGit(err)
441 }
442 defer os.RemoveAll(home)
443 env := CommandEnv(author, email, home, home)
439 444 if message == "" {
440 445 _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha)
441 446 return err
@@ -646,30 +651,22 @@ func BranchOfRef(ref string) (string, bool) {
646 651 // Merge voegt source samen in target en pusht het resultaat.
647 652 // De push gaat door de hook, dus role en patterns moeten kloppen.
648 653 func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error {
649 if err := os.RemoveAll(work); err != nil {
650 return err
651 }
652 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
653 return err
654 repo, env, err := prepareWork(work, author, email)
655 if err != nil {
656 return classifyGit(err)
654 657 }
655 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
656 return err
658 if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil {
659 return classifyGit(err)
657 660 }
658 env := append(os.Environ(),
659 "GIT_AUTHOR_NAME="+author,
660 "GIT_AUTHOR_EMAIL="+email,
661 "GIT_COMMITTER_NAME="+author,
662 "GIT_COMMITTER_EMAIL="+email,
663 )
664 if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil {
665 return fmt.Errorf("doelbranch %s: %w", target, err)
661 if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", target); err != nil {
662 return classifyGit(fmt.Errorf("doelbranch %s: %w", target, err))
666 663 }
667 if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
668 return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt")
664 if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
665 return i18n.E("err.mergeConflict")
669 666 }
670 pushEnv := append(env, PushEnv(role, patterns, nil)...)
671 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil {
672 return err
667 pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...)
668 if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", target); err != nil {
669 return classifyGit(err)
673 670 }
674 671 return nil
675 672 }
@@ -435,7 +435,12 @@ func CreateTag(ctx context.Context, gitBin, dir, name, rev, message, author, ema
435 if len(message) > 5000 {
435 if len(message) > 5000 {
436 return i18n.E("err.tagLong")
436 return i18n.E("err.tagLong")
437 }
437 }
438 env := identityEnv(author, email)
438 home, err := os.MkdirTemp(dir, "home-")
439 if err != nil {
440 return classifyGit(err)
441 }
442 defer os.RemoveAll(home)
443 env := CommandEnv(author, email, home, home)
439 if message == "" {
444 if message == "" {
440 _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha)
445 _, err = run(ctx, gitBin, env, "-C", dir, "tag", name, sha)
441 return err
446 return err
@@ -646,30 +651,22 @@ func BranchOfRef(ref string) (string, bool) {
646// Merge voegt source samen in target en pusht het resultaat.
651// Merge voegt source samen in target en pusht het resultaat.
647// De push gaat door de hook, dus role en patterns moeten kloppen.
652// De push gaat door de hook, dus role en patterns moeten kloppen.
648func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error {
653func Merge(ctx context.Context, gitBin, bare, work, source, target, author, email, message string, role access.Role, patterns []string) error {
649 if err := os.RemoveAll(work); err != nil {
654 repo, env, err := prepareWork(work, author, email)
650 return err
655 if err != nil {
651 }
656 return classifyGit(err)
652 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
653 return err
654 }
657 }
655 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
658 if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil {
656 return err
659 return classifyGit(err)
657 }
660 }
658 env := append(os.Environ(),
661 if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", target); err != nil {
659 "GIT_AUTHOR_NAME="+author,
662 return classifyGit(fmt.Errorf("doelbranch %s: %w", target, err))
660 "GIT_AUTHOR_EMAIL="+email,
661 "GIT_COMMITTER_NAME="+author,
662 "GIT_COMMITTER_EMAIL="+email,
663 )
664 if _, err := run(ctx, gitBin, env, "-C", work, "checkout", target); err != nil {
665 return fmt.Errorf("doelbranch %s: %w", target, err)
666 }
663 }
667 if _, err := run(ctx, gitBin, env, "-C", work, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
664 if _, err := run(ctx, gitBin, env, "-C", repo, "merge", "--no-ff", "--no-edit", "-m", message, source); err != nil {
668 return fmt.Errorf("samenvoegen lukt niet, er is een conflict of de branch ontbreekt")
665 return i18n.E("err.mergeConflict")
669 }
666 }
670 pushEnv := append(env, PushEnv(role, patterns, nil)...)
667 pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...)
671 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", target); err != nil {
668 if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", target); err != nil {
672 return err
669 return classifyGit(err)
673 }
670 }
674 return nil
671 return nil
675}
672}
internal/gitrepo/suggest.go +96 −24
@@ -2,6 +2,7 @@ package gitrepo
2 2
3 3 import (
4 4 "context"
5 "errors"
5 6 "os"
6 7 "path/filepath"
7 8 "sort"
@@ -108,62 +109,76 @@ func ApplySuggestions(files map[string]string, edits []SuggestionEdit) (map[stri
108 109
109 110 // CommitOnBranch schrijft files op branch en pusht één commit.
110 111 // De push loopt door de hook, met role en de beschermde patronen.
112 // Een repository zonder commits krijgt deze branch als eerste commit, zonder parent.
113 // Git draait met een eigen HOME en TMPDIR onder work, niet met die van het proces:
114 // ProtectHome maakt de homedirectory onleesbaar en /tmp is niet de werkmap.
111 115 func CommitOnBranch(ctx context.Context, gitBin, bare, work, branch, author, email, title, description string, files map[string]string, role access.Role, patterns []string) error {
112 if err := os.RemoveAll(work); err != nil {
113 return err
114 }
115 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
116 return err
116 repo, env, err := prepareWork(work, author, email)
117 if err != nil {
118 return classifyGit(err)
117 119 }
118 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
119 return err
120 if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil {
121 return classifyGit(err)
120 122 }
121 if _, err := run(ctx, gitBin, nil, "-C", work, "checkout", branch); err != nil {
122 return err
123 if _, err := run(ctx, gitBin, env, "-C", repo, "rev-parse", "--verify", "--quiet", "HEAD"); err != nil {
124 if _, err := run(ctx, gitBin, env, "-C", repo, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil {
125 return classifyGit(err)
126 }
127 } else if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", branch); err != nil {
128 return classifyGit(err)
123 129 }
124 130 var paths []string
125 131 for path, body := range files {
126 132 if !safeWorkPath(path) {
127 133 return i18n.E("err.sugFile")
128 134 }
129 dst := filepath.Join(work, filepath.FromSlash(path))
135 dst := filepath.Join(repo, filepath.FromSlash(path))
130 136 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
131 return err
137 return classifyGit(err)
132 138 }
133 139 if err := os.WriteFile(dst, []byte(body), 0o644); err != nil {
134 return err
140 return classifyGit(err)
135 141 }
136 142 paths = append(paths, path)
137 143 }
138 144 sort.Strings(paths)
139 args := append([]string{"-C", work, "add", "--"}, paths...)
140 if _, err := run(ctx, gitBin, nil, args...); err != nil {
141 return err
145 args := append([]string{"-C", repo, "add", "--"}, paths...)
146 if _, err := run(ctx, gitBin, env, args...); err != nil {
147 return classifyGit(err)
142 148 }
143 env := identityEnv(author, email)
144 commit := []string{"-C", work, "-c", "commit.gpgsign=false", "commit", "-m", title}
149 commit := []string{"-C", repo, "-c", "commit.gpgsign=false", "commit", "-m", title}
145 150 if strings.TrimSpace(description) != "" {
146 151 commit = append(commit, "-m", description)
147 152 }
148 153 if _, err := run(ctx, gitBin, env, commit...); err != nil {
149 return err
154 return classifyGit(err)
150 155 }
151 pushEnv := append(env, PushEnv(role, patterns, nil)...)
152 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", "HEAD:"+branch); err != nil {
153 return err
156 pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...)
157 if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", "HEAD:"+branch); err != nil {
158 return classifyGit(err)
154 159 }
155 160 return nil
156 161 }
157 162
158 func identityEnv(author, email string) []string {
159 env := make([]string, 0, len(os.Environ())+4)
163 // CommandEnv is de omgeving voor elke git-aanroep die een commit maakt.
164 // HOME en TMPDIR wijzen naar mappen die het proces zelf mag schrijven.
165 // Naam en e-mail staan expliciet, zodat een lege of afgeschermde identiteit niet meetelt.
166 func CommandEnv(author, email, home, tmp string) []string {
167 env := make([]string, 0, len(os.Environ())+8)
160 168 for _, e := range os.Environ() {
161 if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") {
169 if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") || strings.HasPrefix(e, "GIT_CONFIG") {
170 continue
171 }
172 if strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "TMPDIR=") {
162 173 continue
163 174 }
164 175 env = append(env, e)
165 176 }
166 177 return append(env,
178 "HOME="+home,
179 "TMPDIR="+tmp,
180 "GIT_CONFIG_GLOBAL=/dev/null",
181 "GIT_CONFIG_SYSTEM=/dev/null",
167 182 "GIT_AUTHOR_NAME="+author,
168 183 "GIT_AUTHOR_EMAIL="+email,
169 184 "GIT_COMMITTER_NAME="+author,
@@ -171,6 +186,63 @@ func identityEnv(author, email string) []string {
171 186 )
172 187 }
173 188
189 // prepareWork maakt work leeg en zet er een eigen home en tmp in.
190 // De kloon komt in work/repo, zodat die mappen geen deel van de tree zijn.
191 func prepareWork(work, author, email string) (string, []string, error) {
192 if err := os.RemoveAll(work); err != nil {
193 return "", nil, err
194 }
195 if err := os.MkdirAll(work, 0o755); err != nil {
196 return "", nil, err
197 }
198 home := filepath.Join(work, "home")
199 tmp := filepath.Join(work, "tmp")
200 if err := os.MkdirAll(home, 0o700); err != nil {
201 return "", nil, err
202 }
203 if err := os.MkdirAll(tmp, 0o700); err != nil {
204 return "", nil, err
205 }
206 return filepath.Join(work, "repo"), CommandEnv(author, email, home, tmp), nil
207 }
208
209 // Cause koppelt een vertaalbare melding aan de ruwe git-tekst.
210 // Error() is de git-tekst voor het journal. Unwrap levert de vertaling.
211 func Cause(key, git string, args ...any) error {
212 return gitCause{git: git, err: i18n.E(key, args...)}
213 }
214
215 type gitCause struct {
216 git string
217 err error
218 }
219
220 func (g gitCause) Error() string { return g.git }
221 func (g gitCause) Unwrap() error { return g.err }
222
223 func classifyGit(err error) error {
224 if err == nil {
225 return nil
226 }
227 var ie i18n.Error
228 if errors.As(err, &ie) {
229 return err
230 }
231 low := strings.ToLower(err.Error())
232 switch {
233 case strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added"):
234 return Cause("edit.same", err.Error())
235 case strings.Contains(low, "protected") || strings.Contains(low, "beschermd") || strings.Contains(low, "geschützt") || strings.Contains(low, "protégée"):
236 return Cause("edit.protected", err.Error())
237 case strings.Contains(low, "author identity") || strings.Contains(low, "user.email") || strings.Contains(low, "user.name") || strings.Contains(low, "tell me who you are"):
238 return Cause("edit.failIdentity", err.Error())
239 case strings.Contains(low, "permission denied") || strings.Contains(low, "read-only") || strings.Contains(low, "unable to access") || strings.Contains(low, "operation not permitted"):
240 return Cause("edit.failWrite", err.Error())
241 default:
242 return Cause("edit.failGit", err.Error())
243 }
244 }
245
174 246 func safeWorkPath(p string) bool {
175 247 if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") {
176 248 return false
@@ -2,6 +2,7 @@ package gitrepo
2
2
3import (
3import (
4 "context"
4 "context"
5 "errors"
5 "os"
6 "os"
6 "path/filepath"
7 "path/filepath"
7 "sort"
8 "sort"
@@ -108,62 +109,76 @@ func ApplySuggestions(files map[string]string, edits []SuggestionEdit) (map[stri
108
109
109// CommitOnBranch schrijft files op branch en pusht één commit.
110// CommitOnBranch schrijft files op branch en pusht één commit.
110// De push loopt door de hook, met role en de beschermde patronen.
111// De push loopt door de hook, met role en de beschermde patronen.
112// Een repository zonder commits krijgt deze branch als eerste commit, zonder parent.
113// Git draait met een eigen HOME en TMPDIR onder work, niet met die van het proces:
114// ProtectHome maakt de homedirectory onleesbaar en /tmp is niet de werkmap.
111func CommitOnBranch(ctx context.Context, gitBin, bare, work, branch, author, email, title, description string, files map[string]string, role access.Role, patterns []string) error {
115func CommitOnBranch(ctx context.Context, gitBin, bare, work, branch, author, email, title, description string, files map[string]string, role access.Role, patterns []string) error {
112 if err := os.RemoveAll(work); err != nil {
116 repo, env, err := prepareWork(work, author, email)
113 return err
117 if err != nil {
114 }
118 return classifyGit(err)
115 if err := os.MkdirAll(filepath.Dir(work), 0o755); err != nil {
116 return err
117 }
119 }
118 if _, err := run(ctx, gitBin, nil, "clone", bare, work); err != nil {
120 if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil {
119 return err
121 return classifyGit(err)
120 }
122 }
121 if _, err := run(ctx, gitBin, nil, "-C", work, "checkout", branch); err != nil {
123 if _, err := run(ctx, gitBin, env, "-C", repo, "rev-parse", "--verify", "--quiet", "HEAD"); err != nil {
122 return err
124 if _, err := run(ctx, gitBin, env, "-C", repo, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil {
125 return classifyGit(err)
126 }
127 } else if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", branch); err != nil {
128 return classifyGit(err)
123 }
129 }
124 var paths []string
130 var paths []string
125 for path, body := range files {
131 for path, body := range files {
126 if !safeWorkPath(path) {
132 if !safeWorkPath(path) {
127 return i18n.E("err.sugFile")
133 return i18n.E("err.sugFile")
128 }
134 }
129 dst := filepath.Join(work, filepath.FromSlash(path))
135 dst := filepath.Join(repo, filepath.FromSlash(path))
130 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
136 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
131 return err
137 return classifyGit(err)
132 }
138 }
133 if err := os.WriteFile(dst, []byte(body), 0o644); err != nil {
139 if err := os.WriteFile(dst, []byte(body), 0o644); err != nil {
134 return err
140 return classifyGit(err)
135 }
141 }
136 paths = append(paths, path)
142 paths = append(paths, path)
137 }
143 }
138 sort.Strings(paths)
144 sort.Strings(paths)
139 args := append([]string{"-C", work, "add", "--"}, paths...)
145 args := append([]string{"-C", repo, "add", "--"}, paths...)
140 if _, err := run(ctx, gitBin, nil, args...); err != nil {
146 if _, err := run(ctx, gitBin, env, args...); err != nil {
141 return err
147 return classifyGit(err)
142 }
148 }
143 env := identityEnv(author, email)
149 commit := []string{"-C", repo, "-c", "commit.gpgsign=false", "commit", "-m", title}
144 commit := []string{"-C", work, "-c", "commit.gpgsign=false", "commit", "-m", title}
145 if strings.TrimSpace(description) != "" {
150 if strings.TrimSpace(description) != "" {
146 commit = append(commit, "-m", description)
151 commit = append(commit, "-m", description)
147 }
152 }
148 if _, err := run(ctx, gitBin, env, commit...); err != nil {
153 if _, err := run(ctx, gitBin, env, commit...); err != nil {
149 return err
154 return classifyGit(err)
150 }
155 }
151 pushEnv := append(env, PushEnv(role, patterns, nil)...)
156 pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...)
152 if _, err := run(ctx, gitBin, pushEnv, "-C", work, "push", "origin", "HEAD:"+branch); err != nil {
157 if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", "HEAD:"+branch); err != nil {
153 return err
158 return classifyGit(err)
154 }
159 }
155 return nil
160 return nil
156}
161}
157
162
158func identityEnv(author, email string) []string {
163// CommandEnv is de omgeving voor elke git-aanroep die een commit maakt.
159 env := make([]string, 0, len(os.Environ())+4)
164// HOME en TMPDIR wijzen naar mappen die het proces zelf mag schrijven.
165// Naam en e-mail staan expliciet, zodat een lege of afgeschermde identiteit niet meetelt.
166func CommandEnv(author, email, home, tmp string) []string {
167 env := make([]string, 0, len(os.Environ())+8)
160 for _, e := range os.Environ() {
168 for _, e := range os.Environ() {
161 if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") {
169 if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") || strings.HasPrefix(e, "GIT_CONFIG") {
170 continue
171 }
172 if strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "TMPDIR=") {
162 continue
173 continue
163 }
174 }
164 env = append(env, e)
175 env = append(env, e)
165 }
176 }
166 return append(env,
177 return append(env,
178 "HOME="+home,
179 "TMPDIR="+tmp,
180 "GIT_CONFIG_GLOBAL=/dev/null",
181 "GIT_CONFIG_SYSTEM=/dev/null",
167 "GIT_AUTHOR_NAME="+author,
182 "GIT_AUTHOR_NAME="+author,
168 "GIT_AUTHOR_EMAIL="+email,
183 "GIT_AUTHOR_EMAIL="+email,
169 "GIT_COMMITTER_NAME="+author,
184 "GIT_COMMITTER_NAME="+author,
@@ -171,6 +186,63 @@ func identityEnv(author, email string) []string {
171 )
186 )
172}
187}
173
188
189// prepareWork maakt work leeg en zet er een eigen home en tmp in.
190// De kloon komt in work/repo, zodat die mappen geen deel van de tree zijn.
191func prepareWork(work, author, email string) (string, []string, error) {
192 if err := os.RemoveAll(work); err != nil {
193 return "", nil, err
194 }
195 if err := os.MkdirAll(work, 0o755); err != nil {
196 return "", nil, err
197 }
198 home := filepath.Join(work, "home")
199 tmp := filepath.Join(work, "tmp")
200 if err := os.MkdirAll(home, 0o700); err != nil {
201 return "", nil, err
202 }
203 if err := os.MkdirAll(tmp, 0o700); err != nil {
204 return "", nil, err
205 }
206 return filepath.Join(work, "repo"), CommandEnv(author, email, home, tmp), nil
207}
208
209// Cause koppelt een vertaalbare melding aan de ruwe git-tekst.
210// Error() is de git-tekst voor het journal. Unwrap levert de vertaling.
211func Cause(key, git string, args ...any) error {
212 return gitCause{git: git, err: i18n.E(key, args...)}
213}
214
215type gitCause struct {
216 git string
217 err error
218}
219
220func (g gitCause) Error() string { return g.git }
221func (g gitCause) Unwrap() error { return g.err }
222
223func classifyGit(err error) error {
224 if err == nil {
225 return nil
226 }
227 var ie i18n.Error
228 if errors.As(err, &ie) {
229 return err
230 }
231 low := strings.ToLower(err.Error())
232 switch {
233 case strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added"):
234 return Cause("edit.same", err.Error())
235 case strings.Contains(low, "protected") || strings.Contains(low, "beschermd") || strings.Contains(low, "geschützt") || strings.Contains(low, "protégée"):
236 return Cause("edit.protected", err.Error())
237 case strings.Contains(low, "author identity") || strings.Contains(low, "user.email") || strings.Contains(low, "user.name") || strings.Contains(low, "tell me who you are"):
238 return Cause("edit.failIdentity", err.Error())
239 case strings.Contains(low, "permission denied") || strings.Contains(low, "read-only") || strings.Contains(low, "unable to access") || strings.Contains(low, "operation not permitted"):
240 return Cause("edit.failWrite", err.Error())
241 default:
242 return Cause("edit.failGit", err.Error())
243 }
244}
245
174func safeWorkPath(p string) bool {
246func safeWorkPath(p string) bool {
175 if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") {
247 if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") {
176 return false
248 return false
internal/i18n/catalog.go +4 −0
@@ -266,6 +266,10 @@ var en = map[string]string{
266 266 "edit.same": "Nothing changed.",
267 267 "edit.saved": "Committed.",
268 268 "edit.fail": "The file could not be committed.",
269 "edit.failGit": "The file could not be committed. Git rejected the change.",
270 "edit.failWrite": "The file could not be committed. The server could not write its temporary files.",
271 "edit.failIdentity": "The file could not be committed. Git has no name or email for the author.",
272 "edit.failBranch": "The file could not be committed. That branch cannot be created from here.",
269 273 "edit.protected": "This branch is protected.",
270 274 "edit.badBranch": "That branch name cannot be used.",
271 275 "edit.needMessage": "A commit message is required.",
@@ -266,6 +266,10 @@ var en = map[string]string{
266 "edit.same": "Nothing changed.",
266 "edit.same": "Nothing changed.",
267 "edit.saved": "Committed.",
267 "edit.saved": "Committed.",
268 "edit.fail": "The file could not be committed.",
268 "edit.fail": "The file could not be committed.",
269 "edit.failGit": "The file could not be committed. Git rejected the change.",
270 "edit.failWrite": "The file could not be committed. The server could not write its temporary files.",
271 "edit.failIdentity": "The file could not be committed. Git has no name or email for the author.",
272 "edit.failBranch": "The file could not be committed. That branch cannot be created from here.",
269 "edit.protected": "This branch is protected.",
273 "edit.protected": "This branch is protected.",
270 "edit.badBranch": "That branch name cannot be used.",
274 "edit.badBranch": "That branch name cannot be used.",
271 "edit.needMessage": "A commit message is required.",
275 "edit.needMessage": "A commit message is required.",
internal/i18n/catalog_lang.go +12 −0
@@ -272,6 +272,10 @@ var nl = map[string]string{
272 272 "edit.same": "Er is niets gewijzigd.",
273 273 "edit.saved": "Gecommit.",
274 274 "edit.fail": "Het bestand kon niet worden gecommit.",
275 "edit.failGit": "Het bestand kon niet worden gecommit. Git weigerde de wijziging.",
276 "edit.failWrite": "Het bestand kon niet worden gecommit. De server kon zijn tijdelijke bestanden niet schrijven.",
277 "edit.failIdentity": "Het bestand kon niet worden gecommit. Git heeft geen naam of e-mail voor de auteur.",
278 "edit.failBranch": "Het bestand kon niet worden gecommit. Die branch kan vanaf hier niet worden gemaakt.",
275 279 "edit.protected": "Deze branch is beschermd.",
276 280 "edit.badBranch": "Die branchnaam kan niet.",
277 281 "edit.needMessage": "Een commitbericht is verplicht.",
@@ -878,6 +882,10 @@ var de = map[string]string{
878 882 "edit.same": "Nichts geändert.",
879 883 "edit.saved": "Committet.",
880 884 "edit.fail": "Die Datei konnte nicht committet werden.",
885 "edit.failGit": "Die Datei konnte nicht committet werden. Git hat die Änderung abgelehnt.",
886 "edit.failWrite": "Die Datei konnte nicht committet werden. Der Server konnte seine temporären Dateien nicht schreiben.",
887 "edit.failIdentity": "Die Datei konnte nicht committet werden. Git hat keinen Namen oder keine E-Mail für den Autor.",
888 "edit.failBranch": "Die Datei konnte nicht committet werden. Dieser Branch kann von hier aus nicht erstellt werden.",
881 889 "edit.protected": "Dieser Branch ist geschützt.",
882 890 "edit.badBranch": "Dieser Branchname geht nicht.",
883 891 "edit.needMessage": "Eine Commit-Nachricht ist nötig.",
@@ -1484,6 +1492,10 @@ var fr = map[string]string{
1484 1492 "edit.same": "Rien n'a changé.",
1485 1493 "edit.saved": "Commit créé.",
1486 1494 "edit.fail": "Le fichier n'a pas pu être commité.",
1495 "edit.failGit": "Le fichier n'a pas pu être commité. Git a refusé la modification.",
1496 "edit.failWrite": "Le fichier n'a pas pu être commité. Le serveur n'a pas pu écrire ses fichiers temporaires.",
1497 "edit.failIdentity": "Le fichier n'a pas pu être commité. Git n'a pas de nom ni d'adresse pour l'auteur.",
1498 "edit.failBranch": "Le fichier n'a pas pu être commité. Cette branche ne peut pas être créée d'ici.",
1487 1499 "edit.protected": "Cette branche est protégée.",
1488 1500 "edit.badBranch": "Ce nom de branche est inutilisable.",
1489 1501 "edit.needMessage": "Un message de commit est requis.",
@@ -272,6 +272,10 @@ var nl = map[string]string{
272 "edit.same": "Er is niets gewijzigd.",
272 "edit.same": "Er is niets gewijzigd.",
273 "edit.saved": "Gecommit.",
273 "edit.saved": "Gecommit.",
274 "edit.fail": "Het bestand kon niet worden gecommit.",
274 "edit.fail": "Het bestand kon niet worden gecommit.",
275 "edit.failGit": "Het bestand kon niet worden gecommit. Git weigerde de wijziging.",
276 "edit.failWrite": "Het bestand kon niet worden gecommit. De server kon zijn tijdelijke bestanden niet schrijven.",
277 "edit.failIdentity": "Het bestand kon niet worden gecommit. Git heeft geen naam of e-mail voor de auteur.",
278 "edit.failBranch": "Het bestand kon niet worden gecommit. Die branch kan vanaf hier niet worden gemaakt.",
275 "edit.protected": "Deze branch is beschermd.",
279 "edit.protected": "Deze branch is beschermd.",
276 "edit.badBranch": "Die branchnaam kan niet.",
280 "edit.badBranch": "Die branchnaam kan niet.",
277 "edit.needMessage": "Een commitbericht is verplicht.",
281 "edit.needMessage": "Een commitbericht is verplicht.",
@@ -878,6 +882,10 @@ var de = map[string]string{
878 "edit.same": "Nichts geändert.",
882 "edit.same": "Nichts geändert.",
879 "edit.saved": "Committet.",
883 "edit.saved": "Committet.",
880 "edit.fail": "Die Datei konnte nicht committet werden.",
884 "edit.fail": "Die Datei konnte nicht committet werden.",
885 "edit.failGit": "Die Datei konnte nicht committet werden. Git hat die Änderung abgelehnt.",
886 "edit.failWrite": "Die Datei konnte nicht committet werden. Der Server konnte seine temporären Dateien nicht schreiben.",
887 "edit.failIdentity": "Die Datei konnte nicht committet werden. Git hat keinen Namen oder keine E-Mail für den Autor.",
888 "edit.failBranch": "Die Datei konnte nicht committet werden. Dieser Branch kann von hier aus nicht erstellt werden.",
881 "edit.protected": "Dieser Branch ist geschützt.",
889 "edit.protected": "Dieser Branch ist geschützt.",
882 "edit.badBranch": "Dieser Branchname geht nicht.",
890 "edit.badBranch": "Dieser Branchname geht nicht.",
883 "edit.needMessage": "Eine Commit-Nachricht ist nötig.",
891 "edit.needMessage": "Eine Commit-Nachricht ist nötig.",
@@ -1484,6 +1492,10 @@ var fr = map[string]string{
1484 "edit.same": "Rien n'a changé.",
1492 "edit.same": "Rien n'a changé.",
1485 "edit.saved": "Commit créé.",
1493 "edit.saved": "Commit créé.",
1486 "edit.fail": "Le fichier n'a pas pu être commité.",
1494 "edit.fail": "Le fichier n'a pas pu être commité.",
1495 "edit.failGit": "Le fichier n'a pas pu être commité. Git a refusé la modification.",
1496 "edit.failWrite": "Le fichier n'a pas pu être commité. Le serveur n'a pas pu écrire ses fichiers temporaires.",
1497 "edit.failIdentity": "Le fichier n'a pas pu être commité. Git n'a pas de nom ni d'adresse pour l'auteur.",
1498 "edit.failBranch": "Le fichier n'a pas pu être commité. Cette branche ne peut pas être créée d'ici.",
1487 "edit.protected": "Cette branche est protégée.",
1499 "edit.protected": "Cette branche est protégée.",
1488 "edit.badBranch": "Ce nom de branche est inutilisable.",
1500 "edit.badBranch": "Ce nom de branche est inutilisable.",
1489 "edit.needMessage": "Un message de commit est requis.",
1501 "edit.needMessage": "Un message de commit est requis.",
internal/server/editor.go +79 −26
@@ -2,11 +2,13 @@ package server
2 2
3 3 import (
4 4 "encoding/json"
5 "errors"
5 6 "html/template"
6 7 "net/http"
7 8 "net/url"
8 9 "os"
9 10 "os/exec"
11 "path/filepath"
10 12 "strconv"
11 13 "strings"
12 14
@@ -14,6 +16,7 @@ import (
14 16 "gitlab.com/Timfa/bluegit/internal/ci"
15 17 "gitlab.com/Timfa/bluegit/internal/gitrepo"
16 18 "gitlab.com/Timfa/bluegit/internal/highlight"
19 "gitlab.com/Timfa/bluegit/internal/i18n"
17 20 "gitlab.com/Timfa/bluegit/internal/store"
18 21 )
19 22
@@ -162,28 +165,20 @@ func (s *Server) saveCIEditor(w http.ResponseWriter, r *http.Request) {
162 165 return
163 166 }
164 167 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
165 if err := s.ensureBranch(r, dir, branch, base); err != nil {
166 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
167 return
168 }
169 work, err := os.MkdirTemp("", "bluegit-edit-")
168 work, err := s.scratchDir("ci-edit")
170 169 if err != nil {
171 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
170 s.redirect(w, r, back, "", s.commitProblem(r, err))
172 171 return
173 172 }
174 173 defer os.RemoveAll(work)
174 if err := s.ensureBranch(r, dir, branch, base, work); err != nil {
175 s.redirect(w, r, back, "", s.commitProblem(r, err))
176 return
177 }
175 178 email := u.Username + "@users.git.timfalken.com"
176 179 err = gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, message, "", map[string]string{ciFile: body}, role, patterns)
177 180 if err != nil {
178 low := strings.ToLower(err.Error())
179 if strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added") {
180 s.redirect(w, r, back, "", s.tr(r, "edit.same"))
181 return
182 }
183 if s.Log != nil {
184 s.Log.Error("ci-editor", "err", err)
185 }
186 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
181 s.redirect(w, r, back, "", s.commitProblem(r, err))
187 182 return
188 183 }
189 184 if openMR {
@@ -315,21 +310,79 @@ func (s *Server) includeFrom(r *http.Request, dir, ref string) func(string) ([]b
315 310 }
316 311 }
317 312
318 func (s *Server) ensureBranch(r *http.Request, dir, branch, base string) error {
319 if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
320 return nil
313 func (s *Server) ensureBranch(r *http.Request, dir, branch, base, work string) error {
314 home := filepath.Join(work, "home")
315 if err := os.MkdirAll(home, 0o700); err != nil {
316 return gitrepo.Cause("edit.failWrite", err.Error())
321 317 }
322 if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) == "" {
323 return os.ErrNotExist
318 env := gitrepo.CommandEnv("bluegit", "bluegit@users.git.timfalken.com", home, home)
319 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
320 return nil
324 321 }
325 cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
326 if out, err := cmd.CombinedOutput(); err != nil {
327 if s.Log != nil {
328 s.Log.Error("ci-branch", "err", err, "out", string(out))
322 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) != "" {
323 cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
324 cmd.Env = env
325 if out, err := cmd.CombinedOutput(); err != nil {
326 return gitrepo.Cause("edit.failBranch", strings.TrimSpace(string(out)))
329 327 }
330 return err
328 return nil
329 }
330 // Nog geen enkele commit. De gekozen branch wordt de eerste, zonder parent.
331 // Een beheerder, ook de eigenaar, mag dat ook op een beschermde branch.
332 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "HEAD") == "" {
333 return nil
334 }
335 return i18n.E("edit.failBranch")
336 }
337
338 func (s *Server) gitEnv(r *http.Request, dir string, env []string, args ...string) string {
339 bin := s.Git
340 if bin == "" {
341 bin = "git"
342 }
343 cmd := exec.CommandContext(r.Context(), bin, append([]string{"-C", dir}, args...)...)
344 cmd.Env = env
345 out, err := cmd.Output()
346 if err != nil {
347 return ""
348 }
349 return strings.TrimSpace(string(out))
350 }
351
352 // scratchDir is een werkmap onder de state (/var/lib/bluegit/tmp of STATE_DIRECTORY).
353 // /tmp en de homedirectory van de service zijn dat niet: ProtectSystem en ProtectHome sluiten die.
354 func (s *Server) scratchDir(prefix string) (string, error) {
355 root := strings.TrimSpace(s.StateDir)
356 if root == "" {
357 root = strings.TrimSpace(os.Getenv("STATE_DIRECTORY"))
358 }
359 if root == "" {
360 root = strings.TrimSpace(s.StoragePath())
361 }
362 if root == "" {
363 return "", i18n.E("edit.failWrite")
364 }
365 dir := filepath.Join(root, "tmp")
366 if err := os.MkdirAll(dir, 0o750); err != nil {
367 return "", gitrepo.Cause("edit.failWrite", err.Error())
368 }
369 d, err := os.MkdirTemp(dir, prefix+"-")
370 if err != nil {
371 return "", gitrepo.Cause("edit.failWrite", err.Error())
372 }
373 return d, nil
374 }
375
376 // commitProblem logt de ruwe git-fout en geeft de vertaalde reden voor de pagina.
377 func (s *Server) commitProblem(r *http.Request, err error) string {
378 if err != nil && s.Log != nil {
379 s.Log.Error("git-commit", "err", err)
380 }
381 var ie i18n.Error
382 if errors.As(err, &ie) {
383 return s.trErr(r, err)
331 384 }
332 return nil
385 return s.tr(r, "edit.failGit")
333 386 }
334 387
335 388 func validBranchName(s string) bool {
@@ -2,11 +2,13 @@ package server
2
2
3import (
3import (
4 "encoding/json"
4 "encoding/json"
5 "errors"
5 "html/template"
6 "html/template"
6 "net/http"
7 "net/http"
7 "net/url"
8 "net/url"
8 "os"
9 "os"
9 "os/exec"
10 "os/exec"
11 "path/filepath"
10 "strconv"
12 "strconv"
11 "strings"
13 "strings"
12
14
@@ -14,6 +16,7 @@ import (
14 "gitlab.com/Timfa/bluegit/internal/ci"
16 "gitlab.com/Timfa/bluegit/internal/ci"
15 "gitlab.com/Timfa/bluegit/internal/gitrepo"
17 "gitlab.com/Timfa/bluegit/internal/gitrepo"
16 "gitlab.com/Timfa/bluegit/internal/highlight"
18 "gitlab.com/Timfa/bluegit/internal/highlight"
19 "gitlab.com/Timfa/bluegit/internal/i18n"
17 "gitlab.com/Timfa/bluegit/internal/store"
20 "gitlab.com/Timfa/bluegit/internal/store"
18)
21)
19
22
@@ -162,28 +165,20 @@ func (s *Server) saveCIEditor(w http.ResponseWriter, r *http.Request) {
162 return
165 return
163 }
166 }
164 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
167 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
165 if err := s.ensureBranch(r, dir, branch, base); err != nil {
168 work, err := s.scratchDir("ci-edit")
166 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
167 return
168 }
169 work, err := os.MkdirTemp("", "bluegit-edit-")
170 if err != nil {
169 if err != nil {
171 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
170 s.redirect(w, r, back, "", s.commitProblem(r, err))
172 return
171 return
173 }
172 }
174 defer os.RemoveAll(work)
173 defer os.RemoveAll(work)
174 if err := s.ensureBranch(r, dir, branch, base, work); err != nil {
175 s.redirect(w, r, back, "", s.commitProblem(r, err))
176 return
177 }
175 email := u.Username + "@users.git.timfalken.com"
178 email := u.Username + "@users.git.timfalken.com"
176 err = gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, message, "", map[string]string{ciFile: body}, role, patterns)
179 err = gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, message, "", map[string]string{ciFile: body}, role, patterns)
177 if err != nil {
180 if err != nil {
178 low := strings.ToLower(err.Error())
181 s.redirect(w, r, back, "", s.commitProblem(r, err))
179 if strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added") {
180 s.redirect(w, r, back, "", s.tr(r, "edit.same"))
181 return
182 }
183 if s.Log != nil {
184 s.Log.Error("ci-editor", "err", err)
185 }
186 s.redirect(w, r, back, "", s.tr(r, "edit.fail"))
187 return
182 return
188 }
183 }
189 if openMR {
184 if openMR {
@@ -315,21 +310,79 @@ func (s *Server) includeFrom(r *http.Request, dir, ref string) func(string) ([]b
315 }
310 }
316}
311}
317
312
318func (s *Server) ensureBranch(r *http.Request, dir, branch, base string) error {
313func (s *Server) ensureBranch(r *http.Request, dir, branch, base, work string) error {
319 if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
314 home := filepath.Join(work, "home")
320 return nil
315 if err := os.MkdirAll(home, 0o700); err != nil {
316 return gitrepo.Cause("edit.failWrite", err.Error())
321 }
317 }
322 if gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) == "" {
318 env := gitrepo.CommandEnv("bluegit", "bluegit@users.git.timfalken.com", home, home)
323 return os.ErrNotExist
319 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "refs/heads/"+branch) != "" {
320 return nil
324 }
321 }
325 cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
322 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "refs/heads/"+base) != "" {
326 if out, err := cmd.CombinedOutput(); err != nil {
323 cmd := exec.CommandContext(r.Context(), s.Git, "-C", dir, "branch", branch, base)
327 if s.Log != nil {
324 cmd.Env = env
328 s.Log.Error("ci-branch", "err", err, "out", string(out))
325 if out, err := cmd.CombinedOutput(); err != nil {
326 return gitrepo.Cause("edit.failBranch", strings.TrimSpace(string(out)))
329 }
327 }
330 return err
328 return nil
329 }
330 // Nog geen enkele commit. De gekozen branch wordt de eerste, zonder parent.
331 // Een beheerder, ook de eigenaar, mag dat ook op een beschermde branch.
332 if s.gitEnv(r, dir, env, "rev-parse", "--verify", "--quiet", "HEAD") == "" {
333 return nil
334 }
335 return i18n.E("edit.failBranch")
336}
337
338func (s *Server) gitEnv(r *http.Request, dir string, env []string, args ...string) string {
339 bin := s.Git
340 if bin == "" {
341 bin = "git"
342 }
343 cmd := exec.CommandContext(r.Context(), bin, append([]string{"-C", dir}, args...)...)
344 cmd.Env = env
345 out, err := cmd.Output()
346 if err != nil {
347 return ""
348 }
349 return strings.TrimSpace(string(out))
350}
351
352// scratchDir is een werkmap onder de state (/var/lib/bluegit/tmp of STATE_DIRECTORY).
353// /tmp en de homedirectory van de service zijn dat niet: ProtectSystem en ProtectHome sluiten die.
354func (s *Server) scratchDir(prefix string) (string, error) {
355 root := strings.TrimSpace(s.StateDir)
356 if root == "" {
357 root = strings.TrimSpace(os.Getenv("STATE_DIRECTORY"))
358 }
359 if root == "" {
360 root = strings.TrimSpace(s.StoragePath())
361 }
362 if root == "" {
363 return "", i18n.E("edit.failWrite")
364 }
365 dir := filepath.Join(root, "tmp")
366 if err := os.MkdirAll(dir, 0o750); err != nil {
367 return "", gitrepo.Cause("edit.failWrite", err.Error())
368 }
369 d, err := os.MkdirTemp(dir, prefix+"-")
370 if err != nil {
371 return "", gitrepo.Cause("edit.failWrite", err.Error())
372 }
373 return d, nil
374}
375
376// commitProblem logt de ruwe git-fout en geeft de vertaalde reden voor de pagina.
377func (s *Server) commitProblem(r *http.Request, err error) string {
378 if err != nil && s.Log != nil {
379 s.Log.Error("git-commit", "err", err)
380 }
381 var ie i18n.Error
382 if errors.As(err, &ie) {
383 return s.trErr(r, err)
331 }
384 }
332 return nil
385 return s.tr(r, "edit.failGit")
333}
386}
334
387
335func validBranchName(s string) bool {
388func validBranchName(s string) bool {
internal/server/editor_test.go +122 −0
@@ -6,6 +6,7 @@ import (
6 6 "net/http/cookiejar"
7 7 "net/http/httptest"
8 8 "net/url"
9 "os"
9 10 "os/exec"
10 11 "path/filepath"
11 12 "strings"
@@ -313,3 +314,124 @@ func TestPipelineEditorMissingFile(t *testing.T) {
313 314 t.Fatalf("master: %s", got)
314 315 }
315 316 }
317
318 func TestPipelineEditorEmptyRepo(t *testing.T) {
319 if _, err := exec.LookPath("git"); err != nil {
320 t.Skip("git ontbreekt")
321 }
322 storage := t.TempDir()
323 state := t.TempDir()
324 home := t.TempDir()
325 if err := os.WriteFile(filepath.Join(home, "secret"), []byte("x\n"), 0o644); err != nil {
326 t.Fatal(err)
327 }
328 if err := os.Chmod(home, 0o555); err != nil {
329 t.Fatal(err)
330 }
331 t.Cleanup(func() { _ = os.Chmod(home, 0o755) })
332 t.Setenv("HOME", home)
333 t.Setenv("TMPDIR", home)
334 t.Setenv("GIT_AUTHOR_NAME", "hostile")
335 t.Setenv("GIT_AUTHOR_EMAIL", "hostile@example.com")
336 t.Setenv("GIT_COMMITTER_NAME", "hostile")
337 t.Setenv("GIT_COMMITTER_EMAIL", "hostile@example.com")
338
339 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
340 if err != nil {
341 t.Fatal(err)
342 }
343 t.Cleanup(func() { _ = st.Close() })
344 cfg := config.Config{
345 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
346 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
347 Git: config.Git{Binary: "git", DefaultBranch: "master"},
348 }
349 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: state}
350 ts := httptest.NewServer(srv.Handler())
351 t.Cleanup(ts.Close)
352 jar, _ := cookiejar.New(nil)
353 tim := &http.Client{Jar: jar}
354 res, err := tim.Get(ts.URL + "/login")
355 if err != nil {
356 t.Fatal(err)
357 }
358 page := read(t, res)
359 res, err = tim.PostForm(ts.URL+"/new/repo", url.Values{
360 "csrf": {csrfOf(t, page)}, "name": {"leeg"}, "visibility": {"public"},
361 })
362 if err != nil {
363 t.Fatal(err)
364 }
365 _ = read(t, res)
366
367 res, err = tim.Get(ts.URL + "/tim/leeg/-/ci/editor")
368 if err != nil {
369 t.Fatal(err)
370 }
371 editor := read(t, res)
372 for _, want := range []string{"There is no blue-ci-cd.yml on this branch yet.", "No issues found", `name="branch" value="master"`} {
373 if !strings.Contains(editor, want) {
374 t.Errorf("editor mist %q", want)
375 }
376 }
377 if strings.Contains(editor, `name="open_mr"`) {
378 t.Fatal("eigenaar ziet een merge-request op master")
379 }
380 job := "image: alpine:latest\nbuild:\n stage: build\n script:\n - echo from-owner\n"
381 res, err = tim.PostForm(ts.URL+"/tim/leeg/-/ci/editor", url.Values{
382 "csrf": {csrfOf(t, editor)}, "base": {"master"}, "branch": {"master"}, "message": {"Add blue-ci-cd.yml"}, "body": {job},
383 })
384 if err != nil {
385 t.Fatal(err)
386 }
387 saved := read(t, res)
388 if !strings.Contains(saved, "Committed.") || strings.Contains(saved, "could not be committed") {
389 t.Fatalf("lege repo:\n%s", saved)
390 }
391 dir := gitrepo.Dir(storage, "tim", "leeg")
392 if got := mustGit(t, dir, "show", "master:blue-ci-cd.yml"); !strings.Contains(got, "echo from-owner") {
393 t.Fatalf("bestand: %s", got)
394 }
395 if who := strings.TrimSpace(mustGit(t, dir, "log", "-1", "--format=%an %ae", "master")); who != "tim tim@users.git.timfalken.com" {
396 t.Fatalf("identiteit %q", who)
397 }
398 if _, err := exec.Command("git", "--git-dir", dir, "rev-parse", "--verify", "master^").CombinedOutput(); err == nil {
399 t.Fatal("eerste commit heeft een parent")
400 }
401 scratch := filepath.Join(state, "tmp")
402 if _, err := os.Stat(scratch); err != nil {
403 t.Fatalf("werkmap niet onder de state: %v", err)
404 }
405
406 ctx := res.Request.Context()
407 repo, err := st.RepoByPath(ctx, "tim", "leeg")
408 if err != nil {
409 t.Fatal(err)
410 }
411 ada, err := st.UpsertUser(ctx, 3, "ada", "", false)
412 if err != nil {
413 t.Fatal(err)
414 }
415 if err := st.SetMember(ctx, "repo", repo.ID, "ada", "developer"); err != nil {
416 t.Fatal(err)
417 }
418 adaC := clientAs(t, ts.URL, st, ada.ID)
419 res, err = adaC.Get(ts.URL + "/tim/leeg/-/ci/editor?ref=master")
420 if err != nil {
421 t.Fatal(err)
422 }
423 adaPage := read(t, res)
424 res, err = adaC.PostForm(ts.URL+"/tim/leeg/-/ci/editor", url.Values{
425 "csrf": {csrfOf(t, adaPage)}, "base": {"master"}, "branch": {"master"}, "message": {"ada op master"}, "body": {job + "\n"},
426 })
427 if err != nil {
428 t.Fatal(err)
429 }
430 denied := read(t, res)
431 if !strings.Contains(denied, "This branch is protected.") {
432 t.Fatalf("beschermd:\n%s", denied)
433 }
434 if strings.Contains(mustGit(t, dir, "show", "master:blue-ci-cd.yml"), "ada op master") {
435 t.Fatal("developer veranderde master")
436 }
437 }
@@ -6,6 +6,7 @@ import (
6 "net/http/cookiejar"
6 "net/http/cookiejar"
7 "net/http/httptest"
7 "net/http/httptest"
8 "net/url"
8 "net/url"
9 "os"
9 "os/exec"
10 "os/exec"
10 "path/filepath"
11 "path/filepath"
11 "strings"
12 "strings"
@@ -313,3 +314,124 @@ func TestPipelineEditorMissingFile(t *testing.T) {
313 t.Fatalf("master: %s", got)
314 t.Fatalf("master: %s", got)
314 }
315 }
315}
316}
317
318func TestPipelineEditorEmptyRepo(t *testing.T) {
319 if _, err := exec.LookPath("git"); err != nil {
320 t.Skip("git ontbreekt")
321 }
322 storage := t.TempDir()
323 state := t.TempDir()
324 home := t.TempDir()
325 if err := os.WriteFile(filepath.Join(home, "secret"), []byte("x\n"), 0o644); err != nil {
326 t.Fatal(err)
327 }
328 if err := os.Chmod(home, 0o555); err != nil {
329 t.Fatal(err)
330 }
331 t.Cleanup(func() { _ = os.Chmod(home, 0o755) })
332 t.Setenv("HOME", home)
333 t.Setenv("TMPDIR", home)
334 t.Setenv("GIT_AUTHOR_NAME", "hostile")
335 t.Setenv("GIT_AUTHOR_EMAIL", "hostile@example.com")
336 t.Setenv("GIT_COMMITTER_NAME", "hostile")
337 t.Setenv("GIT_COMMITTER_EMAIL", "hostile@example.com")
338
339 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
340 if err != nil {
341 t.Fatal(err)
342 }
343 t.Cleanup(func() { _ = st.Close() })
344 cfg := config.Config{
345 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
346 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
347 Git: config.Git{Binary: "git", DefaultBranch: "master"},
348 }
349 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true", StateDir: state}
350 ts := httptest.NewServer(srv.Handler())
351 t.Cleanup(ts.Close)
352 jar, _ := cookiejar.New(nil)
353 tim := &http.Client{Jar: jar}
354 res, err := tim.Get(ts.URL + "/login")
355 if err != nil {
356 t.Fatal(err)
357 }
358 page := read(t, res)
359 res, err = tim.PostForm(ts.URL+"/new/repo", url.Values{
360 "csrf": {csrfOf(t, page)}, "name": {"leeg"}, "visibility": {"public"},
361 })
362 if err != nil {
363 t.Fatal(err)
364 }
365 _ = read(t, res)
366
367 res, err = tim.Get(ts.URL + "/tim/leeg/-/ci/editor")
368 if err != nil {
369 t.Fatal(err)
370 }
371 editor := read(t, res)
372 for _, want := range []string{"There is no blue-ci-cd.yml on this branch yet.", "No issues found", `name="branch" value="master"`} {
373 if !strings.Contains(editor, want) {
374 t.Errorf("editor mist %q", want)
375 }
376 }
377 if strings.Contains(editor, `name="open_mr"`) {
378 t.Fatal("eigenaar ziet een merge-request op master")
379 }
380 job := "image: alpine:latest\nbuild:\n stage: build\n script:\n - echo from-owner\n"
381 res, err = tim.PostForm(ts.URL+"/tim/leeg/-/ci/editor", url.Values{
382 "csrf": {csrfOf(t, editor)}, "base": {"master"}, "branch": {"master"}, "message": {"Add blue-ci-cd.yml"}, "body": {job},
383 })
384 if err != nil {
385 t.Fatal(err)
386 }
387 saved := read(t, res)
388 if !strings.Contains(saved, "Committed.") || strings.Contains(saved, "could not be committed") {
389 t.Fatalf("lege repo:\n%s", saved)
390 }
391 dir := gitrepo.Dir(storage, "tim", "leeg")
392 if got := mustGit(t, dir, "show", "master:blue-ci-cd.yml"); !strings.Contains(got, "echo from-owner") {
393 t.Fatalf("bestand: %s", got)
394 }
395 if who := strings.TrimSpace(mustGit(t, dir, "log", "-1", "--format=%an %ae", "master")); who != "tim tim@users.git.timfalken.com" {
396 t.Fatalf("identiteit %q", who)
397 }
398 if _, err := exec.Command("git", "--git-dir", dir, "rev-parse", "--verify", "master^").CombinedOutput(); err == nil {
399 t.Fatal("eerste commit heeft een parent")
400 }
401 scratch := filepath.Join(state, "tmp")
402 if _, err := os.Stat(scratch); err != nil {
403 t.Fatalf("werkmap niet onder de state: %v", err)
404 }
405
406 ctx := res.Request.Context()
407 repo, err := st.RepoByPath(ctx, "tim", "leeg")
408 if err != nil {
409 t.Fatal(err)
410 }
411 ada, err := st.UpsertUser(ctx, 3, "ada", "", false)
412 if err != nil {
413 t.Fatal(err)
414 }
415 if err := st.SetMember(ctx, "repo", repo.ID, "ada", "developer"); err != nil {
416 t.Fatal(err)
417 }
418 adaC := clientAs(t, ts.URL, st, ada.ID)
419 res, err = adaC.Get(ts.URL + "/tim/leeg/-/ci/editor?ref=master")
420 if err != nil {
421 t.Fatal(err)
422 }
423 adaPage := read(t, res)
424 res, err = adaC.PostForm(ts.URL+"/tim/leeg/-/ci/editor", url.Values{
425 "csrf": {csrfOf(t, adaPage)}, "base": {"master"}, "branch": {"master"}, "message": {"ada op master"}, "body": {job + "\n"},
426 })
427 if err != nil {
428 t.Fatal(err)
429 }
430 denied := read(t, res)
431 if !strings.Contains(denied, "This branch is protected.") {
432 t.Fatalf("beschermd:\n%s", denied)
433 }
434 if strings.Contains(mustGit(t, dir, "show", "master:blue-ci-cd.yml"), "ada op master") {
435 t.Fatal("developer veranderde master")
436 }
437}
internal/server/repo_handlers.go +8 −2
@@ -2,6 +2,7 @@ package server
2 2
3 3 import (
4 4 "net/http"
5 "os"
5 6 "strconv"
6 7 "strings"
7 8
@@ -328,11 +329,16 @@ func (s *Server) mergeMR(w http.ResponseWriter, r *http.Request) {
328 329 }
329 330 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
330 331 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
331 work := s.StoragePath() + "/tmp/merge-" + strconv.FormatInt(mr.ID, 10)
332 work, err := s.scratchDir("merge")
333 if err != nil {
334 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.commitProblem(r, err))
335 return
336 }
337 defer os.RemoveAll(work)
332 338 email := u.Username + "@users.git.timfalken.com"
333 339 msg := "Merge branch '" + mr.SourceBranch + "' into '" + mr.TargetBranch + "'"
334 340 if err := gitrepo.Merge(r.Context(), s.Git, dir, work, mr.SourceBranch, mr.TargetBranch, u.Username, email, msg, role, patterns); err != nil {
335 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.trErr(r, err))
341 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.commitProblem(r, err))
336 342 return
337 343 }
338 344 _ = s.Store.SetMergeRequestStatus(r.Context(), mr.ID, "merged")
@@ -2,6 +2,7 @@ package server
2
2
3import (
3import (
4 "net/http"
4 "net/http"
5 "os"
5 "strconv"
6 "strconv"
6 "strings"
7 "strings"
7
8
@@ -328,11 +329,16 @@ func (s *Server) mergeMR(w http.ResponseWriter, r *http.Request) {
328 }
329 }
329 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
330 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
330 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
331 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
331 work := s.StoragePath() + "/tmp/merge-" + strconv.FormatInt(mr.ID, 10)
332 work, err := s.scratchDir("merge")
333 if err != nil {
334 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.commitProblem(r, err))
335 return
336 }
337 defer os.RemoveAll(work)
332 email := u.Username + "@users.git.timfalken.com"
338 email := u.Username + "@users.git.timfalken.com"
333 msg := "Merge branch '" + mr.SourceBranch + "' into '" + mr.TargetBranch + "'"
339 msg := "Merge branch '" + mr.SourceBranch + "' into '" + mr.TargetBranch + "'"
334 if err := gitrepo.Merge(r.Context(), s.Git, dir, work, mr.SourceBranch, mr.TargetBranch, u.Username, email, msg, role, patterns); err != nil {
340 if err := gitrepo.Merge(r.Context(), s.Git, dir, work, mr.SourceBranch, mr.TargetBranch, u.Username, email, msg, role, patterns); err != nil {
335 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.trErr(r, err))
341 s.redirect(w, r, repoURL(repo)+"/-/merge-requests/"+strconv.FormatInt(mr.Number, 10), "", s.commitProblem(r, err))
336 return
342 return
337 }
343 }
338 _ = s.Store.SetMergeRequestStatus(r.Context(), mr.ID, "merged")
344 _ = s.Store.SetMergeRequestStatus(r.Context(), mr.ID, "merged")
internal/server/suggest.go +7 −4
@@ -144,14 +144,17 @@ func (s *Server) applySuggestions(w http.ResponseWriter, r *http.Request) {
144 144 return
145 145 }
146 146 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
147 work := s.StoragePath() + "/tmp/suggest-" + strconv.FormatInt(mr.ID, 10)
147 work, err := s.scratchDir("suggest")
148 if err != nil {
149 s.redirect(w, r, back, "", s.commitProblem(r, err))
150 return
151 }
152 defer os.RemoveAll(work)
148 153 email := u.Username + "@users.git.timfalken.com"
149 154 if err := gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, title, r.FormValue("description"), updated, role, patterns); err != nil {
150 _ = os.RemoveAll(work)
151 s.redirect(w, r, back, "", s.trErr(r, err))
155 s.redirect(w, r, back, "", s.commitProblem(r, err))
152 156 return
153 157 }
154 _ = os.RemoveAll(work)
155 158 after, _ := gitrepo.Refs(r.Context(), s.Git, dir)
156 159 s.AfterPush(repo, u, before, after)
157 160 s.redirect(w, r, back, s.tr(r, "flash.suggestions"), "")
@@ -144,14 +144,17 @@ func (s *Server) applySuggestions(w http.ResponseWriter, r *http.Request) {
144 return
144 return
145 }
145 }
146 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
146 before, _ := gitrepo.Refs(r.Context(), s.Git, dir)
147 work := s.StoragePath() + "/tmp/suggest-" + strconv.FormatInt(mr.ID, 10)
147 work, err := s.scratchDir("suggest")
148 if err != nil {
149 s.redirect(w, r, back, "", s.commitProblem(r, err))
150 return
151 }
152 defer os.RemoveAll(work)
148 email := u.Username + "@users.git.timfalken.com"
153 email := u.Username + "@users.git.timfalken.com"
149 if err := gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, title, r.FormValue("description"), updated, role, patterns); err != nil {
154 if err := gitrepo.CommitOnBranch(r.Context(), s.Git, dir, work, branch, u.Username, email, title, r.FormValue("description"), updated, role, patterns); err != nil {
150 _ = os.RemoveAll(work)
155 s.redirect(w, r, back, "", s.commitProblem(r, err))
151 s.redirect(w, r, back, "", s.trErr(r, err))
152 return
156 return
153 }
157 }
154 _ = os.RemoveAll(work)
155 after, _ := gitrepo.Refs(r.Context(), s.Git, dir)
158 after, _ := gitrepo.Refs(r.Context(), s.Git, dir)
156 s.AfterPush(repo, u, before, after)
159 s.AfterPush(repo, u, before, after)
157 s.redirect(w, r, back, s.tr(r, "flash.suggestions"), "")
160 s.redirect(w, r, back, s.tr(r, "flash.suggestions"), "")