Skip to content

Add GitLab support #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ func NewAPIWithVersion(ctx context.Context, globalConfig *conf.GlobalConfigurati
r.Use(api.loadInstanceConfig)
}
r.With(api.requireAuthentication).Mount("/github", NewGitHubGateway())
r.With(api.requireAuthentication).Mount("/gitlab", NewGitLabGateway())
r.With(api.requireAuthentication).Get("/settings", api.Settings)
})

if globalConfig.MultiInstanceMode {
Expand Down
122 changes: 122 additions & 0 deletions api/gitlab.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package api

import (
"errors"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
)

// GitLabGateway acts as a proxy to Gitlab
type GitLabGateway struct {
proxy *httputil.ReverseProxy
}

var gitlabPathRegexp = regexp.MustCompile("^/gitlab/?")
var gitlabAllowedRegexp = regexp.MustCompile("^/gitlab/repository/(files|commits|tree)/?")

func NewGitLabGateway() *GitLabGateway {
return &GitLabGateway{
proxy: &httputil.ReverseProxy{
Director: gitlabDirector,
Transport: &GitLabTransport{},
},
}
}

func gitlabDirector(r *http.Request) {
ctx := r.Context()
target := getProxyTarget(ctx)
accessToken := getAccessToken(ctx)

targetQuery := target.RawQuery
r.Host = target.Host
r.URL.Scheme = target.Scheme
r.URL.Host = target.Host
r.URL.Path = singleJoiningSlash(target.Path, gitlabPathRegexp.ReplaceAllString(r.URL.Path, "/"))
if targetQuery == "" || r.URL.RawQuery == "" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a little confusing - but totally fine.

if targetQuery == "" {
  r.URL.RawQuery = r.URL.RawQuery 
} else if r.URL.RawQuery == "" {
  r.URL.RawQuery = targetQuery
} else {
  r.URL.RawQuery = targetQuery + "&" + r.URL.RawQuery 
}

r.URL.RawQuery = targetQuery + r.URL.RawQuery
} else {
r.URL.RawQuery = targetQuery + "&" + r.URL.RawQuery
}
if _, ok := r.Header["User-Agent"]; !ok {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you're removing it if it is not set? I'm confused. Also, personally, I'd use the Get and Del methods.

if h :=  r.Header.Get("User-Agent"); h == "" {
  r.Header.Del("User-Agent")
}

// explicitly disable User-Agent so it's not set to default value
r.Header.Set("User-Agent", "")
}
if r.Method != http.MethodOptions {
r.Header.Set("Authorization", "Bearer "+accessToken)
}

log := getLogEntry(r)
log.Infof("Proxying to GitLab: %v", r.URL.String())
}

func (gl *GitLabGateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
config := getConfig(ctx)
if config == nil || config.GitLab.AccessToken == "" {
handleError(notFoundError("No GitLab Settings Configured"), w, r)
return
}

if err := gl.authenticate(w, r); err != nil {
handleError(unauthorizedError(err.Error()), w, r)
return
}

endpoint := config.GitLab.Endpoint
apiURL := singleJoiningSlash(endpoint, "/repos/"+config.GitLab.Repo)
target, err := url.Parse(apiURL)
if err != nil {
handleError(internalServerError("Unable to process GitLab endpoint"), w, r)
return
}
ctx = withProxyTarget(ctx, target)
ctx = withAccessToken(ctx, config.GitLab.AccessToken)
gl.proxy.ServeHTTP(w, r.WithContext(ctx))
}

func (gl *GitLabGateway) authenticate(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
claims := getClaims(ctx)
config := getConfig(ctx)

if claims == nil {
return errors.New("Access to endpoint not allowed: no claims found in Bearer token")
}

if !gitlabAllowedRegexp.MatchString(r.URL.Path) {
return errors.New("Access to endpoint not allowed: this part of GitLab's API has been restricted")
}

if len(config.Roles) == 0 {
return nil
}

roles, ok := claims.AppMetaData["roles"]
if ok {
roleStrings, _ := roles.([]interface{})
for _, data := range roleStrings {
role, _ := data.(string)
for _, adminRole := range config.Roles {
if role == adminRole {
return nil
}
}
}
}

return errors.New("Access to endpoint not allowed: your role doesn't allow access")
}

type GitLabTransport struct{}

func (t *GitLabTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := http.DefaultTransport.RoundTrip(r)
if err == nil {
// remove CORS headers from GitHub and use our own
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/Hub/Lab/

resp.Header.Del("Access-Control-Allow-Origin")
}
return resp, err
}
22 changes: 22 additions & 0 deletions api/settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package api

import "net/http"

type Settings struct {
GitHub bool `json:"github_enabled"`
GitLab bool `json:"gitlab_enabled"`
Roles []string `json:"roles"`
}

func (a *API) Settings(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := getConfig(ctx)

settings := Settings{
GitHub: config.GitHub.Repo != "",
GitLab: config.GitLab.Repo != "",
Roles: config.Roles,
}

return sendJSON(w, http.StatusOK, &settings)
}
7 changes: 7 additions & 0 deletions conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ type GitHubConfig struct {
Repo string `envconfig:"REPO" json:"repo"` // Should be "owner/repo" format
}

type GitLabConfig struct {
AccessToken string `envconfig:"ACCESS_TOKEN" json:"access_token,omitempty"`
Endpoint string `envconfig:"ENDPOINT" json:"endpoint"`
Repo string `envconfig:"REPO" json:"repo"` // Should be "owner/repo" format
}

// DBConfiguration holds all the database related configuration.
type DBConfiguration struct {
Dialect string `json:"dialect"`
Expand Down Expand Up @@ -47,6 +53,7 @@ type GlobalConfiguration struct {
type Configuration struct {
JWT JWTConfiguration `json:"jwt"`
GitHub GitHubConfig `envconfig:"GITHUB" json:"github"`
GitLab GitLabConfig `envconfig:"GITLAB" json:"gitlab"`
Roles []string `envconfig:"ROLES" json:"roles"`
}

Expand Down