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

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/url"
	"time"

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

	"gitlab.com/gitlab-org/labkit/log"

	"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")
)

var tokenTimeout = 30 * time.Second

// 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 {
		log.WithError(err).Fatal("could not parse GitLab server URL")
	}

	return &Client{
		secretKey: secretKey,
		baseURL:   url,
		httpClient: &http.Client{
			Timeout:   5 * time.Second,
			Transport: httptransport.Transport,
		},
	}
}

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

// GetVirtualDomain returns VirtualDomain configuration for the given host
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
	}

	var domain api.VirtualDomain
	err = json.NewDecoder(resp.Body).Decode(&domain)
	if err != nil {
		return nil, err
	}

	return &domain, nil
}

func (gc *Client) get(path string, params map[string]string) (*http.Response, error) {
	endpoint, err := gc.endpoint(path, params)
	if err != nil {
		return nil, err
	}

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

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

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

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

	values := url.Values{}
	for key, value := range params {
		values.Add(key, value)
	}
	endpoint.RawQuery = values.Encode()

	return endpoint, nil
}

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

	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
}