From 5ad3f8567ab8c5163d1920562a1b9ee136c7fd2b Mon Sep 17 00:00:00 2001 From: Johannes Batzill Date: Wed, 17 Jan 2024 08:58:28 +0000 Subject: [PATCH] Add support of git url redirect for custom git domain (#971) --- app/api/handler/repo/find_redirect.go | 21 ++++++++++++--------- app/router/git.go | 2 +- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/app/api/handler/repo/find_redirect.go b/app/api/handler/repo/find_redirect.go index 49a9ef0ea..146f04b94 100644 --- a/app/api/handler/repo/find_redirect.go +++ b/app/api/handler/repo/find_redirect.go @@ -16,35 +16,38 @@ package repo import ( "net/http" + "strconv" - "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/render" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/url" ) // HandleGitRedirect redirects from the vanilla git clone URL to the repo UI page. -func HandleGitRedirect(repoCtrl *repo.Controller, urlProvider url.Provider) http.HandlerFunc { +func HandleGitRedirect(urlProvider url.Provider) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - session, _ := request.AuthSessionFrom(ctx) repoRef, err := request.GetRepoRefFromPath(r) if err != nil { render.TranslatedUserError(w, err) return } - // find repo to ensure we get repo path (repoRef might be the repo ID) - repo, err := repoCtrl.Find(ctx, session, repoRef) - if err != nil { - render.TranslatedUserError(w, err) + // Explicitly return error in case the user is trying to use the repoID for redirect. + if _, err := strconv.ParseInt(repoRef, 10, 64); err == nil { + render.BadRequestf(w, "Endpoint only supports repo path.") return } + // Always use the raw, user-provided path to generate the redirect URL. + // NOTE: + // Technically, we could find the repo first and use repo.Path. + // However, the auth cookie isn't available in case of custom git domains, and thus the auth would fail. + repoURL := urlProvider.GenerateUIRepoURL(repoRef) + http.Redirect( w, r, - urlProvider.GenerateUIRepoURL(repo.Path), + repoURL, http.StatusMovedPermanently, ) } diff --git a/app/router/git.go b/app/router/git.go index 468127a4a..cf45517be 100644 --- a/app/router/git.go +++ b/app/router/git.go @@ -65,7 +65,7 @@ func NewGitHandler( // routes that aren't coming from git r.Group(func(r chi.Router) { // redirect to repo (meant for UI, in case user navigates to clone url in browser) - r.Get("/", handlerrepo.HandleGitRedirect(repoCtrl, urlProvider)) + r.Get("/", handlerrepo.HandleGitRedirect(urlProvider)) }) // routes that are coming from git (where we block the usage of session tokens)