Make EndpointToScope resilient to subdomains (#16737)

This commit is contained in:
Charles Lowell 2022-01-04 14:06:32 -08:00 коммит произвёл GitHub
Родитель 6264636169
Коммит 0ba8458a57
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 42 добавлений и 2 удалений

Просмотреть файл

@ -14,7 +14,9 @@ import (
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
@ -179,9 +181,25 @@ func (r *NopClosingBytesReader) Seek(offset int64, whence int) (int64, error) {
}
const defaultScope = "/.default"
const chinaCloudARMScope = "https://management.core.chinacloudapi.cn/" + defaultScope
const publicCloudARMScope = "https://management.core.windows.net/" + defaultScope
const usGovCloudARMScope = "https://management.core.usgovcloudapi.net/" + defaultScope
// EndpointToScope converts the provided URL endpoint to its default scope.
func EndpointToScope(endpoint string) string {
parsed, err := url.Parse(endpoint)
if err == nil {
host := parsed.Hostname()
switch {
case strings.HasSuffix(host, "management.azure.com"):
return publicCloudARMScope
case strings.HasSuffix(host, "management.usgovcloudapi.net"):
return usGovCloudARMScope
case strings.HasSuffix(host, "management.chinacloudapi.cn"):
return chinaCloudARMScope
}
}
// fall back to legacy behavior when endpoint doesn't parse or match a known cloud's ARM endpoint
if endpoint[len(endpoint)-1] != '/' {
endpoint += "/"
}

Просмотреть файл

@ -98,8 +98,30 @@ func TestHasStatusCode(t *testing.T) {
}
func TestEndpointToScope(t *testing.T) {
if s := EndpointToScope("https://management.usgovcloudapi.net"); s != "https://management.usgovcloudapi.net//.default" {
t.Fatalf("unexpected scope %s", s)
knownClouds := map[string][]string{
chinaCloudARMScope: {"https://foo.management.chinacloudapi.cn", "https://management.chinacloudapi.cn"},
publicCloudARMScope: {"https://centraluseuap.management.azure.com", "https://management.azure.com"},
usGovCloudARMScope: {"https://foo.management.usgovcloudapi.net", "https://management.usgovcloudapi.net"},
}
for expected, endpoints := range knownClouds {
for _, endpoint := range endpoints {
if actual := EndpointToScope(endpoint); actual != expected {
t.Fatalf(`unexpected scope "%s" for endpoint "%s"`, actual, endpoint)
}
if actual := EndpointToScope(endpoint + "/"); actual != expected {
t.Fatalf(`unexpected scope "%s" for endpoint "%s"/`, actual, endpoint)
}
}
}
// legacy behavior for unknown clouds: add "//.default" suffix to endpoint
for _, endpoint := range []string{"localhost", "http://foo.bar"} {
if actual := EndpointToScope(endpoint); actual != endpoint+"//.default" {
t.Fatalf(`unexpected scope "%s" for endpoint "%s"`, actual, endpoint)
}
if actual := EndpointToScope(endpoint + "/"); actual != endpoint+"//.default" {
t.Fatalf(`unexpected scope "%s" for endpoint "%s"/`, actual, endpoint)
}
}
}