diff options
author | Grzegorz Bizon <grzesiek.bizon@gmail.com> | 2019-11-28 12:17:38 +0300 |
---|---|---|
committer | Grzegorz Bizon <grzesiek.bizon@gmail.com> | 2019-11-28 12:17:38 +0300 |
commit | f6e438fc249656ad13ad3eb4cc59cecb959353a8 (patch) | |
tree | 43cd091e42322a252a5004dbee9d6ac051e56c6f | |
parent | 84812ac14c428b7af6d6a185bc1894b7ea47dc45 (diff) | |
parent | 29b0a2d8ebc10ef9fa070d5634ab5d18938c935e (diff) |
Merge branch 'master' into feature/gitlab-source-enum-domains
* master:
Improve GitLab client tests
Change GitLab API JWT expire time to 5s
Read the context of api-secret-key file and store it in app config
Improve gitlab client tests
Ensure there is response before defer close it in gitlab.GetVirtualDomain
Document acrguments for gitlab.NewClient
Add HTTP client to consume GitLab internal API for Pages
-rw-r--r-- | acceptance_test.go | 6 | ||||
-rw-r--r-- | app_config.go | 21 | ||||
-rw-r--r-- | internal/source/gitlab/client/client.go | 12 | ||||
-rw-r--r-- | internal/source/gitlab/client/client_test.go | 52 | ||||
-rw-r--r-- | internal/source/gitlab/client/config.go | 2 | ||||
-rw-r--r-- | main.go | 1 |
6 files changed, 52 insertions, 42 deletions
diff --git a/acceptance_test.go b/acceptance_test.go index 3ed69254..4a50553d 100644 --- a/acceptance_test.go +++ b/acceptance_test.go @@ -1527,12 +1527,6 @@ func TestTLSVersions(t *testing.T) { } } -func TestApiSecretKeyFlagIsSupported(t *testing.T) { - skipUnlessEnabled(t) - teardown := RunPagesProcess(t, *pagesBinary, listeners, "", "-api-secret-key", "/path/to/secret.key") - defer teardown() -} - func TestGitlabDomainsSource(t *testing.T) { skipUnlessEnabled(t) diff --git a/app_config.go b/app_config.go index 379a3696..639ece85 100644 --- a/app_config.go +++ b/app_config.go @@ -25,14 +25,15 @@ type appConfig struct { LogFormat string LogVerbose bool - StoreSecret string - GitLabServer string - ClientID string - ClientSecret string - RedirectURI string - SentryDSN string - SentryEnvironment string - CustomHeaders []string + StoreSecret string + GitLabServer string + GitLabAPISecretKey []byte + ClientID string + ClientSecret string + RedirectURI string + SentryDSN string + SentryEnvironment string + CustomHeaders []string } // GitlabServerURL returns URL to a GitLab instance. @@ -41,6 +42,6 @@ func (config appConfig) GitlabServerURL() string { } // GitlabClientSecret returns GitLab server access token. -func (config appConfig) GitlabClientSecret() []byte { - return []byte(config.ClientSecret) +func (config appConfig) GitlabAPISecret() []byte { + return config.GitLabAPISecretKey } diff --git a/internal/source/gitlab/client/client.go b/internal/source/gitlab/client/client.go index b6a7b059..a612f751 100644 --- a/internal/source/gitlab/client/client.go +++ b/internal/source/gitlab/client/client.go @@ -29,7 +29,8 @@ var ( errNotFound = errors.New("Not Found") ) -// NewClient initializes and returns new Client +// NewClient initializes and returns new Client baseUrl is +// appConfig.GitLabServer secretKey is appConfig.GitLabAPISecretKey func NewClient(baseURL string, secretKey []byte) *Client { url, err := url.Parse(baseURL) if err != nil { @@ -48,7 +49,7 @@ func NewClient(baseURL string, secretKey []byte) *Client { // NewFromConfig creates a new client from Config struct func NewFromConfig(config Config) *Client { - return NewClient(config.GitlabServerURL(), config.GitlabClientSecret()) + return NewClient(config.GitlabServerURL(), config.GitlabAPISecret()) } // GetVirtualDomain returns VirtualDomain configuration for the given host @@ -56,10 +57,13 @@ func (gc *Client) GetVirtualDomain(host string) (*api.VirtualDomain, error) { params := map[string]string{"host": host} resp, err := gc.get("/api/v4/internal/pages", params) + if resp != nil { + defer resp.Body.Close() + } + if err != nil { return nil, err } - defer resp.Body.Close() var domain api.VirtualDomain err = json.NewDecoder(resp.Body).Decode(&domain) @@ -133,7 +137,7 @@ func (gc *Client) request(method string, endpoint *url.URL) (*http.Request, erro func (gc *Client) token() (string, error) { claims := jwt.StandardClaims{ Issuer: "gitlab-pages", - ExpiresAt: time.Now().Add(1 * time.Minute).Unix(), + ExpiresAt: time.Now().Add(5 * time.Second).Unix(), } token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(gc.secretKey) diff --git a/internal/source/gitlab/client/client_test.go b/internal/source/gitlab/client/client_test.go index 678cef78..d689b687 100644 --- a/internal/source/gitlab/client/client_test.go +++ b/internal/source/gitlab/client/client_test.go @@ -7,7 +7,6 @@ import ( "net/http/httptest" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" jwt "github.com/dgrijalva/jwt-go" @@ -50,15 +49,30 @@ func TestGetVirtualDomainAuthenticatedRequest(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/api/v4/internal/pages", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method) - assert.Equal(t, "group.gitlab.io", r.FormValue("host")) - - if checkRequest(r.Header.Get("Gitlab-Pages-Api-Request")) { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, `{"certificate":"foo","key":"bar","lookup_paths":[{"project_id":123,"access_control":false,"source":{"type":"file","path":"mygroup/myproject/public/"},"https_only":true,"prefix":"/myproject/"}]}`) - } else { - w.WriteHeader(http.StatusUnauthorized) - } + require.Equal(t, "GET", r.Method) + require.Equal(t, "group.gitlab.io", r.FormValue("host")) + + validateToken(t, r.Header.Get("Gitlab-Pages-Api-Request")) + + response := `{ + "certificate": "foo", + "key": "bar", + "lookup_paths": [ + { + "project_id": 123, + "access_control": false, + "source": { + "type": "file", + "path": "mygroup/myproject/public/" + }, + "https_only": true, + "prefix": "/myproject/" + } + ] + }` + + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, response) }) server := httptest.NewServer(mux) @@ -82,25 +96,21 @@ func TestGetVirtualDomainAuthenticatedRequest(t *testing.T) { require.Equal(t, "mygroup/myproject/public/", lookupPath.Source.Path) } -func checkRequest(tokenString string) bool { - token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { +func validateToken(t *testing.T, tokenString string) { + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return secretKey(), nil }) + require.NoError(t, err) claims, ok := token.Claims.(jwt.MapClaims) - if !ok || !token.Valid { - return false - } - - if _, ok := claims["exp"]; !ok { - return false - } - - return claims["iss"] == "gitlab-pages" + require.True(t, ok) + require.True(t, token.Valid) + require.NotNil(t, claims["exp"]) + require.Equal(t, "gitlab-pages", claims["iss"]) } func secretKey() []byte { diff --git a/internal/source/gitlab/client/config.go b/internal/source/gitlab/client/config.go index dd8112da..49c13a60 100644 --- a/internal/source/gitlab/client/config.go +++ b/internal/source/gitlab/client/config.go @@ -4,5 +4,5 @@ package client // capable of comunicating with GitLab type Config interface { GitlabServerURL() string - GitlabClientSecret() []byte + GitlabAPISecret() []byte } @@ -144,6 +144,7 @@ func configFromFlags() appConfig { }{ {&config.RootCertificate, *pagesRootCert}, {&config.RootKey, *pagesRootKey}, + {&config.GitLabAPISecretKey, *gitLabAPISecretKey}, } { if file.path != "" { *file.contents = readFile(file.path) |