/
url_util.go
218 lines (186 loc) · 6.05 KB
/
url_util.go
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
)
const (
// Default port for HTTP.
HTTPDefaultPort = "80"
// Default port for HTTPS.
HTTPSDefaultPort = "443"
)
// ParseURI parses uri into scheme, hostname, port, path with err(if exist).
// If uri has no scheme, it will be regarded as https.
// If uri has no port, it will use 80 for non-TLS and 443 for TLS.
// Ensures the path has no trailing slash.
// Strips out query parameters from the path.
func ParseURI(uri string) (string, string, uint32, string, error) {
arr := strings.Split(uri, "://")
if len(arr) == 1 {
// Set the default scheme.
uri = fmt.Sprintf("https://%s", uri)
}
u, err := url.Parse(uri)
if err != nil {
return "", "", 0, "", err
}
_, port, err := net.SplitHostPort(u.Host)
if err != nil {
if e, ok := err.(*net.AddrError); ok && strings.Contains(e.Error(), "missing port") {
// Determine the default port.
port = HTTPSDefaultPort
if !strings.HasSuffix(u.Scheme, "s") {
port = HTTPDefaultPort
}
} else {
return "", "", 0, "", err
}
}
portVal, err := strconv.Atoi(port)
if err != nil {
return "", "", 0, "", fmt.Errorf("parse \"%v\": %v", uri, err)
}
pathNoTrailingSlash := strings.TrimSuffix(u.Path, "/")
return u.Scheme, u.Hostname(), uint32(portVal), pathNoTrailingSlash, nil
}
// ParseURIIntoURL is the same as ParseURI, but it returns the URL in a
// standard struct.
func ParseURIIntoURL(uri string) (url.URL, error) {
scheme, hostname, port, path, err := ParseURI(uri)
if err != nil {
return url.URL{}, err
}
host := fmt.Sprintf("%v:%v", hostname, port)
if isIpv6Hostname(hostname) {
// IPv6 hostname should be embraced by brackets
host = fmt.Sprintf("[%v]:%d", hostname, port)
}
return url.URL{
Scheme: scheme,
Host: host,
Path: path,
}, nil
}
func isIpv6Hostname(hostname string) bool {
return strings.Contains(hostname, ":")
}
// ParseBackendProtocol parses a scheme string and http protocol string into BackendProtocol and UseTLS bool.
func ParseBackendProtocol(scheme string, httpProtocol string) (BackendProtocol, bool, error) {
scheme = strings.ToLower(scheme)
httpProtocol = strings.ToLower(httpProtocol)
// Default tls to false, even if scheme is invalid.
tls := false
if strings.HasSuffix(scheme, "s") {
tls = true
scheme = strings.TrimSuffix(scheme, "s")
}
switch scheme {
case "http":
// Default the http protocol to http/1.1.
switch httpProtocol {
case "", "http/1.1":
return HTTP1, tls, nil
case "h2":
return HTTP2, tls, nil
default:
return UNKNOWN, tls, fmt.Errorf(`unknown backend http protocol [%v], should be one of "http/1.1", "h2", or not set`, httpProtocol)
}
case "grpc":
return GRPC, tls, nil
default:
return UNKNOWN, tls, fmt.Errorf(`unknown backend scheme [%v], should be one of "http(s)" or "grpc(s)"`, scheme)
}
}
// IsBackendGRPC returns if the backend address requires gRPC support.
func IsBackendGRPC(address string) (bool, error) {
scheme, _, _, _, err := ParseURI(address)
if err != nil {
return false, fmt.Errorf("error parsing uri: %v", err)
}
// httpProtocol doesn't matter for `grpc://` scheme.
protocol, _, err := ParseBackendProtocol(scheme, "")
if err != nil {
return false, fmt.Errorf("error parsing local backend protocol: %v", err)
}
return protocol == GRPC, nil
}
// Note: the path of openID discovery may be https
var getRemoteContent = func(path string) ([]byte, error) {
req, _ := http.NewRequest("GET", path, nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Fetching JwkUri returns not 200 OK: %v", resp.Status)
}
return ioutil.ReadAll(resp.Body)
}
func ResolveJwksUriUsingOpenID(uri string) (string, error) {
if !strings.HasPrefix(uri, "http") {
uri = fmt.Sprintf("https://%s", uri)
}
uri = strings.TrimSuffix(uri, "/")
uri = fmt.Sprintf("%s%s", uri, OpenIDDiscoveryCfgURLSuffix)
body, err := getRemoteContent(uri)
if err != nil {
return "", fmt.Errorf("Failed to fetch jwks_uri from %s: %v", uri, err)
}
var data map[string]interface{}
if err := json.Unmarshal(body, &data); err != nil {
return "", err
}
jwksURI, ok := data["jwks_uri"].(string)
if !ok {
return "", fmt.Errorf("Invalid jwks_uri %v in openID discovery configuration", data["jwks_uri"])
}
return jwksURI, nil
}
func IamIdentityTokenPath(IamServiceAccount string) string {
return fmt.Sprintf("/v1/projects/-/serviceAccounts/%s:generateIdToken", IamServiceAccount)
}
func IamAccessTokenPath(IamServiceAccount string) string {
return fmt.Sprintf("/v1/projects/-/serviceAccounts/%s:generateAccessToken", IamServiceAccount)
}
func ExtractAddressFromURI(uri string) (string, error) {
_, hostname, port, _, err := ParseURI(uri)
if err != nil {
return "", fmt.Errorf("Fail to parse uri %s with error %v", uri, err)
}
return fmt.Sprintf("%s:%v", hostname, port), nil
}
var (
FetchRolloutIdURL = func(serviceControlUrl, serviceName string) string {
return fmt.Sprintf("%v/v1/services/%s:report",
serviceControlUrl, serviceName)
}
FetchRolloutsURL = func(serviceManagementUrl, serviceName string) string {
return fmt.Sprintf("%s/v1/services/%s/rollouts?filter=status=SUCCESS",
serviceManagementUrl, serviceName)
}
FetchConfigURL = func(serviceManagementUrl, serviceName, configId string) string {
return fmt.Sprintf("%s/v1/services/%s/configs/%s?view=FULL",
serviceManagementUrl, serviceName, configId)
}
)