/
challenge.go
66 lines (53 loc) · 1.94 KB
/
challenge.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
package cloudauth
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/Azure/azure-sdk-for-go/services/preview/containerregistry/runtime/2019-08-15-preview/containerregistry"
)
const authValueIndex = 2
type AuthDirective struct {
Service string
Realm string
}
type LoginChallenger func(ctx context.Context, loginServerURL string) (*AuthDirective, error)
func ChallengeLoginServer(ctx context.Context, loginServerURL string) (*AuthDirective, error) {
v2Support := containerregistry.NewV2SupportClient(loginServerURL)
challenge, err := v2Support.Check(ctx)
// A 401 will also return an error so just check first
if !challenge.IsHTTPStatus(http.StatusUnauthorized) {
if err != nil {
return nil, err
}
defer challenge.Body.Close()
return nil, fmt.Errorf("registry did not issue a valid AAD challenge, status: %d", challenge.StatusCode)
}
// Www-Authenticate: Bearer realm="https://xxx.azurecr.io/oauth2/token",service="xxx.azurecr.io"
authHeader, ok := challenge.Header["Www-Authenticate"]
if !ok {
return nil, fmt.Errorf("challenge response does not contain header 'Www-Authenticate'")
}
if len(authHeader) != 1 {
return nil, fmt.Errorf("registry did not issue a valid challenge, authenticate header [%s]",
strings.Join(authHeader, ", "))
}
authSections := strings.SplitN(authHeader[0], " ", authValueIndex)
if !strings.EqualFold("Bearer", authSections[0]) {
return nil, fmt.Errorf("Www-Authenticate: expected realm: Bearer, actual: %s", authSections[0])
}
authParams := map[string]string{}
params := strings.Split(authSections[1], ",")
for _, p := range params {
parts := strings.SplitN(strings.TrimSpace(p), "=", authValueIndex)
authParams[parts[0]] = strings.Trim(parts[1], `"`)
}
// verify headers
if authParams["realm"] == "" {
return nil, fmt.Errorf("Www-Authenticate: missing header \"realm\"")
}
return &AuthDirective{
Service: authParams["service"], // optional
Realm: authParams["realm"],
}, nil
}