Welcome to mirror list, hosted at ThFree Co, Russian Federation.

client.go « client « gitlab « source « internal - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 59776a8fd9e39835b4f953d0cd7eae673789d9b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package client

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	jwt "github.com/dgrijalva/jwt-go"

	"gitlab.com/gitlab-org/gitlab-pages/internal/httptransport"
	"gitlab.com/gitlab-org/gitlab-pages/internal/source/gitlab/api"
)

// Client is a HTTP client to access Pages internal API
type Client struct {
	secretKey      []byte
	baseURL        *url.URL
	httpClient     *http.Client
	jwtTokenExpiry time.Duration
}

// NewClient initializes and returns new Client baseUrl is
// appConfig.GitLabServer secretKey is appConfig.GitLabAPISecretKey
func NewClient(baseURL string, secretKey []byte, connectionTimeout, jwtTokenExpiry time.Duration) (*Client, error) {
	if len(baseURL) == 0 || len(secretKey) == 0 {
		return nil, errors.New("GitLab API URL or API secret has not been provided")
	}

	url, err := url.Parse(baseURL)
	if err != nil {
		return nil, err
	}

	if connectionTimeout == 0 {
		return nil, errors.New("GitLab HTTP client connection timeout has not been provided")
	}

	if jwtTokenExpiry == 0 {
		return nil, errors.New("GitLab JWT token expiry has not been provided")
	}

	return &Client{
		secretKey: secretKey,
		baseURL:   url,
		httpClient: &http.Client{
			Timeout:   connectionTimeout,
			Transport: httptransport.Transport,
		},
		jwtTokenExpiry: jwtTokenExpiry,
	}, nil
}

// NewFromConfig creates a new client from Config struct
func NewFromConfig(config Config) (*Client, error) {
	return NewClient(config.GitlabServerURL(), config.GitlabAPISecret(), config.GitlabClientConnectionTimeout(), config.GitlabJWTTokenExpiry())
}

// Resolve returns a VirtualDomain configuration wrapped into a Lookup for a
// given host. It implements api.Resolve type.
func (gc *Client) Resolve(ctx context.Context, host string) *api.Lookup {
	lookup := gc.GetLookup(ctx, host)

	return &lookup
}

// GetLookup returns a VirtualDomain configuration wrapped into a Lookup for a
// given host
func (gc *Client) GetLookup(ctx context.Context, host string) api.Lookup {
	params := url.Values{}
	params.Set("host", host)

	resp, err := gc.get(ctx, "/api/v4/internal/pages", params)
	if err != nil {
		return api.Lookup{Name: host, Error: err}
	}

	if resp == nil {
		return api.Lookup{Name: host}
	}

	lookup := api.Lookup{Name: host}
	lookup.Error = json.NewDecoder(resp.Body).Decode(&lookup.Domain)

	return lookup
}

func (gc *Client) get(ctx context.Context, path string, params url.Values) (*http.Response, error) {
	endpoint, err := gc.endpoint(path, params)
	if err != nil {
		return nil, err
	}

	req, err := gc.request(ctx, "GET", endpoint)
	if err != nil {
		return nil, err
	}

	resp, err := gc.httpClient.Do(req)
	if err != nil {
		return nil, err
	}

	if resp == nil {
		return nil, errors.New("unknown response")
	}

	// StatusOK means we should return the API response
	if resp.StatusCode == http.StatusOK {
		return resp, nil
	}

	io.Copy(ioutil.Discard, resp.Body)
	resp.Body.Close()

	// StatusNoContent means that a domain does not exist, it is not an error
	if resp.StatusCode == http.StatusNoContent {
		return nil, nil
	}

	return nil, fmt.Errorf("HTTP status: %d", resp.StatusCode)
}

func (gc *Client) endpoint(path string, params url.Values) (*url.URL, error) {
	endpoint, err := gc.baseURL.Parse(path)
	if err != nil {
		return nil, err
	}

	endpoint.RawQuery = params.Encode()

	return endpoint, nil
}

func (gc *Client) request(ctx context.Context, method string, endpoint *url.URL) (*http.Request, error) {
	req, err := http.NewRequest(method, endpoint.String(), nil)
	if err != nil {
		return nil, err
	}

	req = req.WithContext(ctx)

	token, err := gc.token()
	if err != nil {
		return nil, err
	}
	req.Header.Set("Gitlab-Pages-Api-Request", token)

	return req, nil
}

func (gc *Client) token() (string, error) {
	claims := jwt.StandardClaims{
		Issuer:    "gitlab-pages",
		ExpiresAt: time.Now().UTC().Add(gc.jwtTokenExpiry).Unix(),
	}

	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(gc.secretKey)
	if err != nil {
		return "", err
	}

	return token, nil
}