/
auth_challenge.go
137 lines (123 loc) · 3.72 KB
/
auth_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
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
/******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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 client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/sapcc/keppel/internal/keppel"
)
// AuthChallenge contains the parsed contents of a Www-Authenticate header
// returned by a registry.
type AuthChallenge struct {
Realm string
Service string
Scope string
}
var challengeFieldRx = regexp.MustCompile(`^(\w+)\s*=\s*"([^"]*)"\s*,?\s*`)
// ParseAuthChallenge parses the auth challenge from the response headers of an
// unauthenticated request to a registry API.
func ParseAuthChallenge(hdr http.Header) (AuthChallenge, error) {
input := hdr.Get("Www-Authenticate")
if input == "" {
return AuthChallenge{}, errors.New("missing Www-Authenticate header")
}
if !strings.HasPrefix(input, "Bearer ") {
parts := strings.SplitN(input, " ", 2)
return AuthChallenge{}, fmt.Errorf("cannot handle Www-Authenticate challenge of type %q", parts[0])
}
input = strings.TrimSpace(strings.TrimPrefix(input, "Bearer "))
var c AuthChallenge
for input != "" {
// find next challenge field (because of the ^ anchor, this always yields a
// prefix of `input`)
match := challengeFieldRx.FindStringSubmatch(input)
if match == nil {
return AuthChallenge{}, fmt.Errorf("malformed Www-Authenticate header: %s", hdr.Get("Www-Authenticate"))
}
// remove challenge field from input for next loop iteration
input = strings.TrimPrefix(input, match[0])
key, value := match[1], match[2]
switch key {
case "realm":
c.Realm = value
case "service":
c.Service = value
case "scope":
c.Scope = value
}
}
if c.Realm == "" {
return AuthChallenge{}, fmt.Errorf("missing realm in Www-Authenticate: Bearer %s", input)
}
if c.Service == "" {
return AuthChallenge{}, fmt.Errorf("missing service in Www-Authenticate: Bearer %s", input)
}
if c.Scope == "" {
return AuthChallenge{}, fmt.Errorf("missing scope in Www-Authenticate: Bearer %s", input)
}
return c, nil
}
// GetToken obtains a token that satisfies this challenge.
func (c AuthChallenge) GetToken(ctx context.Context, userName, password string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.Realm, http.NoBody)
if err != nil {
return "", err
}
if userName != "" {
req.Header.Set("Authorization", keppel.BuildBasicAuthHeader(userName, password))
}
q := make(url.Values)
q.Set("service", c.Service)
q.Set("scope", c.Scope)
req.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
respBytes, err := io.ReadAll(resp.Body)
if err == nil {
err = resp.Body.Close()
} else {
resp.Body.Close()
}
if err != nil {
return "", err
}
var data struct {
AccessToken string `json:"access_token"`
Token string `json:"token"`
}
err = json.Unmarshal(respBytes, &data)
switch {
case err != nil:
return "", err
case data.Token != "":
return data.Token, nil
case data.AccessToken != "":
return data.AccessToken, nil
default:
return "", errors.New("no token was returned")
}
}