Files
archie/internal/worktree/http_test.go
T
sam db346b159d fix(webui): mark cookies Secure behind a TLS proxy; run gosec in the gate (#1919)
Cookies took Secure from r.TLS, which is nil behind a proxy that terminates
TLS, so sign-in cookies went out without it. Every dashboard cookie now goes
through one builder that reads the scheme the way the origin check does.

The worktree reset and the agent worker's chown walk use os.Root, so a
symlink swapped in mid-walk can't point them outside the worktree.

gosec runs in golangci-lint, tests included. G104, G115, G204 and G304 are
excluded in config; each remaining finding is fixed or suppressed at the site
with its reason.
2026-11-13 03:16:15 +11:00

174 lines
5.9 KiB
Go

package worktree
import (
"net/http"
"net/http/cgi" //nolint:gosec // G504: serves git http-backend; the Httpoxy CVE predates Go 1.6.3.
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
git "github.com/go-git/go-git/v6"
gitconfig "github.com/go-git/go-git/v6/config"
"github.com/go-git/go-git/v6/plumbing"
)
func TestForgeHTTPAuthentication(t *testing.T) {
t.Parallel()
root := t.TempDir()
bare, err := git.PlainInit(filepath.Join(root, "org", "repo.git"), true)
if err != nil {
t.Fatal(err)
}
if err := bare.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName("main"))); err != nil {
t.Fatal(err)
}
cfg, err := bare.Config()
if err != nil {
t.Fatal(err)
}
cfg.Raw.Section("http").SetOption("receivepack", "true")
if err := bare.SetConfig(cfg); err != nil {
t.Fatal(err)
}
seedDir := t.TempDir()
seed, err := git.PlainInit(seedDir, false)
if err != nil {
t.Fatal(err)
}
seedConfig, err := seed.Config()
if err != nil {
t.Fatal(err)
}
seedConfig.Raw.Section("commit").SetOption("gpgsign", "false")
if err := seed.SetConfig(seedConfig); err != nil {
t.Fatal(err)
}
if err := seed.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName("main"))); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(seedDir, "seed.txt"), []byte("seed"), 0o600); err != nil {
t.Fatal(err)
}
manager := &Manager{BotUser: "archie", BotEmail: "archie@example.test", Token: "secret-for-origin"}
if _, err := manager.CommitAll(t.Context(), seedDir, "seed"); err != nil {
t.Fatal(err)
}
if _, err := seed.CreateRemote(&gitconfig.RemoteConfig{Name: "origin", URLs: []string{filepath.Join(root, "org", "repo.git")}}); err != nil {
t.Fatal(err)
}
if err := seed.PushContext(t.Context(), &git.PushOptions{}); err != nil {
t.Fatal(err)
}
gitPath, err := exec.LookPath("git")
if err != nil {
t.Fatal(err)
}
backend := &cgi.Handler{Path: gitPath, Args: []string{"http-backend"}, Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}}
for i, tc := range []struct {
name string
redirect, foreign, dumb bool
}{
{name: "direct"}, {name: "same origin", redirect: true}, {name: "cross origin", foreign: true}, {name: "dumb HTTP", dumb: true},
} {
// One issue per transport: subtests share the bare repo, and a shared
// branch would make the second push a non-fast-forward (or, when two
// commits land in the same second, an identical-hash no-op).
issue := i + 1
t.Run(tc.name, func(t *testing.T) {
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "" {
t.Error("forge credential reached another origin")
}
w.WriteHeader(http.StatusUnauthorized)
}))
defer target.Close()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if tc.foreign {
http.Redirect(w, r, target.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks.
return
}
user, password, ok := r.BasicAuth()
if !ok || user != "archie" || password != manager.Token {
http.Error(w, "authentication required", http.StatusUnauthorized)
return
}
if tc.dumb {
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("not a smart Git endpoint"))
return
}
if tc.redirect && !strings.HasPrefix(r.URL.Path, "/redirect/") {
http.Redirect(w, r, "/redirect"+r.URL.RequestURI(), http.StatusTemporaryRedirect) //nolint:gosec // G710: the foreign redirect is what the test checks.
return
}
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/redirect")
backend.ServeHTTP(w, r)
}))
defer server.Close()
m := &Manager{
BotUser: manager.BotUser, BotEmail: manager.BotEmail, Token: manager.Token,
BaseURL: server.URL, WorkDir: t.TempDir(),
}
dir, branch, err := m.Prepare(t.Context(), "org", "repo", "main", issue, "test", "", "", Fresh)
if tc.foreign || tc.dumb {
if err == nil {
t.Fatal("unsupported or unauthenticated endpoint succeeded")
}
expected := "origin boundary"
if tc.dumb {
expected = "dumb HTTP protocol is not supported"
}
if !strings.Contains(err.Error(), expected) || strings.Contains(err.Error(), m.Token) {
t.Fatalf("not actionable or leaked token: %v", err)
}
return
}
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "change.txt"), []byte("change"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := m.CommitAll(t.Context(), dir, "change"); err != nil {
t.Fatal(err)
}
if err := m.Push(t.Context(), dir, branch); err != nil {
t.Fatal(err)
}
if _, err := bare.Reference(plumbing.NewBranchReferenceName(branch), true); err != nil {
t.Fatalf("pushed branch missing: %v", err)
}
if _, _, err := m.Prepare(t.Context(), "org", "repo", "main", issue, "test", "", "", Target(branch)); err != nil {
t.Fatalf("authenticated fetch: %v", err)
}
if err := m.CheckAccess(t.Context(), "org", "repo", "main"); err != nil {
t.Fatalf("read-only access check: %v", err)
}
if err := m.CheckAccess(t.Context(), "org", "repo", "missing"); err == nil {
t.Fatal("missing base branch verified")
}
cloned, err := git.PlainOpen(dir)
if err != nil {
t.Fatal(err)
}
changed, err := cloned.Config()
if err != nil {
t.Fatal(err)
}
changed.Remotes["origin"].URLs = []string{target.URL + "/org/repo.git"}
if err := cloned.SetConfig(changed); err != nil {
t.Fatal(err)
}
if err := m.PushRepository(t.Context(), "org", "repo", issue, branch); err != nil {
t.Fatalf("push to authorised connection: %v", err)
}
if _, _, err := m.Prepare(t.Context(), "org", "repo", "main", issue, "test", "", "", Fresh); err == nil {
t.Fatal("prepared worktree from another origin was reused")
}
})
}
}