package preflight import ( "context" "encoding/pem" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "github.com/aritmolab/thothii/tools/tht/internal/config" ) func TestGitProbeAuthenticatesAndRejectsWrongBranchAndCredentials(t *testing.T) { status := 200 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, password, ok := r.BasicAuth() if !ok || user != "reader" || password != "PRIVATE_SENTINEL" { w.WriteHeader(401) return } if r.Method != "GET" || r.URL.Path != "/workspaces.git/info/refs" || r.URL.RawQuery != "service=git-upload-pack" { t.Error("unexpected Git mutation/request") w.WriteHeader(400) return } w.WriteHeader(status) _, _ = w.Write([]byte("0044" + strings.Repeat("a", 40) + " refs/heads/main\n")) })) defer server.Close() root, _ := filepath.EvalSymlinks(t.TempDir()) ca := filepath.Join(root, "ca.pem") credentials := filepath.Join(root, "credentials") _ = os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0o600) _ = os.WriteFile(credentials, []byte(strings.Replace(server.URL, "https://", "https://reader:PRIVATE_SENTINEL@", 1)), 0o600) installation := config.Installation{WorkspaceRepository: config.WorkspaceRepository{Remote: server.URL + "/workspaces.git", Branch: "main", Access: "https"}} value := func(name string) string { if name == "THT_WORKSPACE_GIT_CA_FILE" { return ca } return credentials } if err := checkGit(context.Background(), installation, value); err != nil { t.Fatal(err) } installation.WorkspaceRepository.Branch = "missing" if checkGit(context.Background(), installation, value) == nil { t.Fatal("missing branch accepted") } installation.WorkspaceRepository.Branch = "main" status = 503 if checkGit(context.Background(), installation, value) == nil { t.Fatal("unavailable existing Git accepted") } status = 200 _ = os.WriteFile(credentials, []byte(strings.Replace(server.URL, "https://", "https://reader:rotated@", 1)), 0o600) if checkGit(context.Background(), installation, value) == nil { t.Fatal("bad credential accepted") } }