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: a230e52978d745f1d321800eb0d0e4d9950f069b (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
package client

import (
	"context"
	"encoding/json"
	"errors"
	"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
}

var (
	errUnknown      = errors.New("Unknown")
	errNoContent    = errors.New("No Content")
	errUnauthorized = errors.New("Unauthorized")
	errNotFound     = errors.New("Not Found")
)

// TODO make these values configurable https://gitlab.com/gitlab-org/gitlab-pages/issues/274
var tokenTimeout = 30 * time.Second
var connectionTimeout = 10 * time.Second

// NewClient initializes and returns new Client baseUrl is
// appConfig.GitLabServer secretKey is appConfig.GitLabAPISecretKey
func NewClient(baseURL string, secretKey []byte) (*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
	}

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

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

// GetLookup returns a VirtualDomain configuration wrap into a Lookup for a
// given host
func (gc *Client) GetLookup(ctx context.Context, host string) api.Lookup {
	lookup := api.Lookup{Name: host}

	params := url.Values{}
	params.Set("host", host)

	resp, status, err := gc.get(ctx, "/api/v4/internal/pages", params)
	if resp != nil {
		defer resp.Body.Close()
	} else {
		err = errors.New("empty response returned")
	}

	lookup.Status = status
	lookup.Error = err

	if err != nil {
		return lookup
	}

	err = json.NewDecoder(resp.Body).Decode(&lookup.Domain)
	if err != nil {
		lookup.Error = err
		return lookup
	}

	return lookup
}

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

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

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

	switch {
	case resp.StatusCode == http.StatusOK:
		return resp, resp.StatusCode, nil
	case resp.StatusCode == http.StatusNoContent:
		return resp, resp.StatusCode, errNoContent
	case resp.StatusCode == http.StatusUnauthorized:
		return resp, resp.StatusCode, errUnauthorized
	case resp.StatusCode == http.StatusNotFound:
		return resp, resp.StatusCode, errNotFound
	default:
		return resp, resp.StatusCode, errUnknown
	}
}

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("GET", 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().Add(tokenTimeout).Unix(),
	}

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

	return token, nil
}