fix: oauth authorization support for azurecr (#451)

* fix: oauth authorization support for azurecr

* fix: oauth when destroying images

* refactor: run make fmt
This commit is contained in:
William Sedlacek 2022-09-09 04:59:18 -07:00 committed by GitHub
parent 0d82189137
commit d0eae33123
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 62 additions and 71 deletions

View file

@ -50,6 +50,12 @@ func isECRRepositoryURL(url string) bool {
return ecrRexp.MatchString(url) return ecrRexp.MatchString(url)
} }
func isAzureCRRepositoryURL(url string) bool {
// Regexp is based on the azurecr urls shown https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-portal?tabs=azure-cli#push-image-to-registry
var azurecrRexp = regexp.MustCompile(`^.*\.azurecr\.io$`)
return azurecrRexp.MatchString(url)
}
func setupHTTPHeadersForRegistryRequests(req *http.Request, fallback bool) { func setupHTTPHeadersForRegistryRequests(req *http.Request, fallback bool) {
// We accept schema v2 manifests and manifest lists, and also OCI types // We accept schema v2 manifests and manifest lists, and also OCI types
req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json") req.Header.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json")

View file

@ -81,7 +81,7 @@ func getImageDigest(registry string, registryWithProtocol string, image, tag, us
} }
if username != "" { if username != "" {
if registry != "ghcr.io" && !isECRRepositoryURL(registry) && registry != "gcr.io" { if registry != "ghcr.io" && !isECRRepositoryURL(registry) && !isAzureCRRepositoryURL(registry) && registry != "gcr.io" {
req.SetBasicAuth(username, password) req.SetBasicAuth(username, password)
} else { } else {
if isECRRepositoryURL(registry) { if isECRRepositoryURL(registry) {
@ -147,6 +147,7 @@ func getImageDigest(registry string, registryWithProtocol string, image, tag, us
type TokenResponse struct { type TokenResponse struct {
Token string Token string
AccessToken string `json:"access_token"`
} }
// Parses key/value pairs from a WWW-Authenticate header // Parses key/value pairs from a WWW-Authenticate header
@ -214,9 +215,17 @@ func getAuthToken(authHeader string, username string, password string, client *h
return "", fmt.Errorf("Error parsing OAuth token response: %s", err) return "", fmt.Errorf("Error parsing OAuth token response: %s", err)
} }
if token.Token != "" {
return token.Token, nil return token.Token, nil
} }
if token.AccessToken != "" {
return token.AccessToken, nil
}
return "", fmt.Errorf("Error unsupported OAuth response")
}
func doDigestRequest(req *http.Request, client *http.Client) (*http.Response, error) { func doDigestRequest(req *http.Request, client *http.Client) (*http.Response, error) {
digestResponse, err := client.Do(req) digestResponse, err := client.Do(req)
if err != nil { if err != nil {

View file

@ -818,7 +818,6 @@ func TestAccDockerContainer_uploadSource(t *testing.T) {
}) })
} }
//
func TestAccDockerContainer_uploadSourceHash(t *testing.T) { func TestAccDockerContainer_uploadSourceHash(t *testing.T) {
var c types.ContainerJSON var c types.ContainerJSON
var firstRunId string var firstRunId string

View file

@ -14,7 +14,6 @@ import (
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -483,7 +482,16 @@ func deleteDockerRegistryImage(pushOpts internalPushImageOptions, registryWithPr
} }
if username != "" { if username != "" {
if pushOpts.Registry != "ghcr.io" && !isECRRepositoryURL(pushOpts.Registry) && !isAzureCRRepositoryURL(pushOpts.Registry) && pushOpts.Registry != "gcr.io" {
req.SetBasicAuth(username, password) req.SetBasicAuth(username, password)
} else {
if isECRRepositoryURL(pushOpts.Registry) {
password = normalizeECRPasswordForHTTPUsage(password)
req.Header.Add("Authorization", "Basic "+password)
} else {
req.Header.Add("Authorization", "Bearer "+base64.StdEncoding.EncodeToString([]byte(password)))
}
}
} }
setupHTTPHeadersForRegistryRequests(req, fallback) setupHTTPHeadersForRegistryRequests(req, fallback)
@ -500,41 +508,16 @@ func deleteDockerRegistryImage(pushOpts internalPushImageOptions, registryWithPr
// Either OAuth is required or the basic auth creds were invalid // Either OAuth is required or the basic auth creds were invalid
case http.StatusUnauthorized: case http.StatusUnauthorized:
if strings.HasPrefix(resp.Header.Get("www-authenticate"), "Bearer") { if !strings.HasPrefix(resp.Header.Get("www-authenticate"), "Bearer") {
auth := parseAuthHeader(resp.Header.Get("www-authenticate")) return fmt.Errorf("Bad credentials: " + resp.Status)
params := url.Values{} }
params.Set("service", auth["service"])
params.Set("scope", auth["scope"]) token, err := getAuthToken(resp.Header.Get("www-authenticate"), username, password, client)
tokenRequest, err := http.NewRequest("GET", auth["realm"]+"?"+params.Encode(), nil)
if err != nil { if err != nil {
return fmt.Errorf("Error creating registry request: %s", err) return err
} }
if username != "" { req.Header.Set("Authorization", "Bearer "+token)
tokenRequest.SetBasicAuth(username, password)
}
tokenResponse, err := client.Do(tokenRequest)
if err != nil {
return fmt.Errorf("Error during registry request: %s", err)
}
if tokenResponse.StatusCode != http.StatusOK {
return fmt.Errorf("Got bad response from registry: " + tokenResponse.Status)
}
body, err := ioutil.ReadAll(tokenResponse.Body)
if err != nil {
return fmt.Errorf("Error reading response body: %s", err)
}
token := &TokenResponse{}
err = json.Unmarshal(body, token)
if err != nil {
return fmt.Errorf("Error parsing OAuth token response: %s", err)
}
req.Header.Set("Authorization", "Bearer "+token.Token)
oauthResp, err := client.Do(req) oauthResp, err := client.Do(req)
if err != nil { if err != nil {
return err return err
@ -545,11 +528,6 @@ func deleteDockerRegistryImage(pushOpts internalPushImageOptions, registryWithPr
default: default:
return fmt.Errorf("Got bad response from registry: " + resp.Status) return fmt.Errorf("Got bad response from registry: " + resp.Status)
} }
}
return fmt.Errorf("Bad credentials: " + resp.Status)
// Some unexpected status was given, return an error // Some unexpected status was given, return an error
default: default:
return fmt.Errorf("Got bad response from registry: " + resp.Status) return fmt.Errorf("Got bad response from registry: " + resp.Status)

View file

@ -38,7 +38,6 @@ const (
// As a convention the test configurations are in // As a convention the test configurations are in
// 'testdata/<resourceType>/<resourceName>/<testName>.tf', e.g. // 'testdata/<resourceType>/<resourceName>/<testName>.tf', e.g.
// 'testdata/resources/docker_container/testAccDockerContainerPrivateImage.tf' // 'testdata/resources/docker_container/testAccDockerContainerPrivateImage.tf'
//
func loadTestConfiguration(t *testing.T, resourceType resourceType, resourceName, testName string) string { func loadTestConfiguration(t *testing.T, resourceType resourceType, resourceName, testName string) string {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {