Add support of git url redirect for custom git domain (#971)

This commit is contained in:
Johannes Batzill 2024-01-17 08:58:28 +00:00 committed by Harness
parent 7f54bd2f50
commit 5ad3f8567a
2 changed files with 13 additions and 10 deletions

View File

@ -16,35 +16,38 @@ package repo
import ( import (
"net/http" "net/http"
"strconv"
"github.com/harness/gitness/app/api/controller/repo"
"github.com/harness/gitness/app/api/render" "github.com/harness/gitness/app/api/render"
"github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/api/request"
"github.com/harness/gitness/app/url" "github.com/harness/gitness/app/url"
) )
// HandleGitRedirect redirects from the vanilla git clone URL to the repo UI page. // 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) { return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session, _ := request.AuthSessionFrom(ctx)
repoRef, err := request.GetRepoRefFromPath(r) repoRef, err := request.GetRepoRefFromPath(r)
if err != nil { if err != nil {
render.TranslatedUserError(w, err) render.TranslatedUserError(w, err)
return return
} }
// find repo to ensure we get repo path (repoRef might be the repo ID) // Explicitly return error in case the user is trying to use the repoID for redirect.
repo, err := repoCtrl.Find(ctx, session, repoRef) if _, err := strconv.ParseInt(repoRef, 10, 64); err == nil {
if err != nil { render.BadRequestf(w, "Endpoint only supports repo path.")
render.TranslatedUserError(w, err)
return 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( http.Redirect(
w, w,
r, r,
urlProvider.GenerateUIRepoURL(repo.Path), repoURL,
http.StatusMovedPermanently, http.StatusMovedPermanently,
) )
} }

View File

@ -65,7 +65,7 @@ func NewGitHandler(
// routes that aren't coming from git // routes that aren't coming from git
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
// redirect to repo (meant for UI, in case user navigates to clone url in browser) // 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) // routes that are coming from git (where we block the usage of session tokens)