Debian Codegraph @

registry/remote/auth/example_test.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 http://www.apache.org/licenses/LICENSE-2.0
7 Unless required by applicable law or agreed to in writing, software
8 distributed under the License is distributed on an "AS IS" BASIS,
9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 See the License for the specific language governing permissions and
11 limitations under the License.
12 */
13
14 // Package auth_test includes the testable examples for the http client.
15 package auth_test
16
17 import (
18 "context"
19 "encoding/base64"
20 "fmt"
21 "net/http"
22 "net/http/httptest"
23 "net/url"
24 "os"
25 "strings"
26 "testing"
27
28 . "oras.land/oras-go/v2/registry/internal/doc"
29 "oras.land/oras-go/v2/registry/remote/auth"
30 )
31
32 const (
33 username = "test_user"
34 password = "test_password"
35 accessToken = "test/access/token"
36 refreshToken = "test/refresh/token"
37 _ = ExampleUnplayable
38 )
39
40 var (
41 host string
42 expectedHostAddress string
43 targetURL string
44 clientConfigTargetURL string
45 basicAuthTargetURL string
46 accessTokenTargetURL string
47 refreshTokenTargetURL string
48 tokenScopes = []string{
49 "repository:dst:pull,push",
50 "repository:src:pull",
51 }
52 )
53
54 func TestMain(m *testing.M) {
55 // create an authorization server
56 as := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
57 if r.Method != http.MethodGet && r.Method != http.MethodPost {
58 w.WriteHeader(http.StatusUnauthorized)
59 panic("unexecuted attempt of authorization service")
60 }
61 if err := r.ParseForm(); err != nil {
62 w.WriteHeader(http.StatusUnauthorized)
63 panic("failed to parse form")
64 }
65 if got := r.PostForm.Get("service"); got != host {
66 w.WriteHeader(http.StatusUnauthorized)
67 }
68 // handles refresh token requests
69 if got := r.PostForm.Get("grant_type"); got != "refresh_token" {
70 w.WriteHeader(http.StatusUnauthorized)
71 }
72 scope := strings.Join(tokenScopes, " ")
73 if got := r.PostForm.Get("scope"); got != scope {
74 w.WriteHeader(http.StatusUnauthorized)
75 }
76 if got := r.PostForm.Get("refresh_token"); got != refreshToken {
77 w.WriteHeader(http.StatusUnauthorized)
78 }
79 // writes back access token
80 if _, err := fmt.Fprintf(w, `{"access_token":%q}`, accessToken); err != nil {
81 panic(err)
82 }
83 }))
84 defer as.Close()
85
86 // create a test server
87 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
88 path := r.URL.Path
89 if r.Method != http.MethodGet {
90 w.WriteHeader(http.StatusNotFound)
91 panic("unexpected access")
92 }
93 switch path {
94 case "/basicAuth":
95 wantedAuthHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
96 authHeader := r.Header.Get("Authorization")
97 if authHeader != wantedAuthHeader {
98 w.Header().Set("Www-Authenticate", `Basic realm="Test Server"`)
99 w.WriteHeader(http.StatusUnauthorized)
100 }
101 case "/clientConfig":
102 wantedAuthHeader := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
103 authHeader := r.Header.Get("Authorization")
104 if authHeader != wantedAuthHeader {
105 w.Header().Set("Www-Authenticate", `Basic realm="Test Server"`)
106 w.WriteHeader(http.StatusUnauthorized)
107 }
108 case "/accessToken":
109 wantedAuthHeader := "Bearer " + accessToken
110 if auth := r.Header.Get("Authorization"); auth != wantedAuthHeader {
111 challenge := fmt.Sprintf("Bearer realm=%q,service=%q,scope=%q", as.URL, host, strings.Join(tokenScopes, " "))
112 w.Header().Set("Www-Authenticate", challenge)
113 w.WriteHeader(http.StatusUnauthorized)
114 }
115 case "/refreshToken":
116 wantedAuthHeader := "Bearer " + accessToken
117 if auth := r.Header.Get("Authorization"); auth != wantedAuthHeader {
118 challenge := fmt.Sprintf("Bearer realm=%q,service=%q,scope=%q", as.URL, host, strings.Join(tokenScopes, " "))
119 w.Header().Set("Www-Authenticate", challenge)
120 w.WriteHeader(http.StatusUnauthorized)
121 }
122 case "/simple":
123 w.WriteHeader(http.StatusOK)
124 default:
125 w.WriteHeader(http.StatusNotAcceptable)
126 }
127 }))
128 defer ts.Close()
129 host = ts.URL
130 uri, _ := url.Parse(host)
131 expectedHostAddress = uri.Host
132 targetURL = fmt.Sprintf("%s/simple", host)
133 basicAuthTargetURL = fmt.Sprintf("%s/basicAuth", host)
134 clientConfigTargetURL = fmt.Sprintf("%s/clientConfig", host)
135 accessTokenTargetURL = fmt.Sprintf("%s/accessToken", host)
136 refreshTokenTargetURL = fmt.Sprintf("%s/refreshToken", host)
137
138 os.Exit(m.Run())
139 }
140
141 // ExampleClient_Do_minimalClient gives an example of a minimal working client.
142 func ExampleClient_Do_minimalClient() {
143 var client auth.Client
144 // targetURL can be any URL. For example, https://registry.wabbit-networks.io/v2/
145 req, err := http.NewRequest(http.MethodGet, targetURL, nil)
146 if err != nil {
147 panic(err)
148 }
149 resp, err := client.Do(req)
150 if err != nil {
151 panic(err)
152 }
153
154 fmt.Println(resp.StatusCode)
155 // Output:
156 // 200
157 }
158
159 // ExampleClient_Do_basicAuth gives an example of using client with credentials.
160 func ExampleClient_Do_basicAuth() {
161 client := &auth.Client{
162 // expectedHostAddress is of form ipaddr:port
163 Credential: auth.StaticCredential(expectedHostAddress, auth.Credential{
164 Username: username,
165 Password: password,
166 }),
167 }
168 // basicAuthTargetURL can be any URL. For example, https://registry.wabbit-networks.io/v2/
169 req, err := http.NewRequest(http.MethodGet, basicAuthTargetURL, nil)
170 if err != nil {
171 panic(err)
172 }
173 resp, err := client.Do(req)
174 if err != nil {
175 panic(err)
176 }
177
178 fmt.Println(resp.StatusCode)
179 // Output:
180 // 200
181 }
182
183 // ExampleClient_Do_clientConfigurations shows the client configurations available,
184 // including using cache, setting user agent and configuring OAuth2.
185 func ExampleClient_Do_clientConfigurations() {
186 client := &auth.Client{
187 // expectedHostAddress is of form ipaddr:port
188 Credential: auth.StaticCredential(expectedHostAddress, auth.Credential{
189 Username: username,
190 Password: password,
191 }),
192 // ForceAttemptOAuth2 controls whether to follow OAuth2 with password grant.
193 ForceAttemptOAuth2: true,
194 // Cache caches credentials for accessing the remote registry.
195 Cache: auth.NewCache(),
196 }
197 // SetUserAgent sets the user agent for all out-going requests.
198 client.SetUserAgent("example user agent")
199 // Tokens carry restrictions about what resources they can access and how.
200 // Such restrictions are represented and enforced as Scopes.
201 // Reference: https://distribution.github.io/distribution/spec/auth/scope/
202 scopes := []string{
203 "repository:dst:pull,push",
204 "repository:src:pull",
205 }
206 // WithScopes returns a context with scopes added.
207 ctx := auth.WithScopes(context.Background(), scopes...)
208
209 // clientConfigTargetURL can be any URL. For example, https://registry.wabbit-networks.io/v2/
210 req, err := http.NewRequestWithContext(ctx, http.MethodGet, clientConfigTargetURL, nil)
211 if err != nil {
212 panic(err)
213 }
214 resp, err := client.Do(req)
215 if err != nil {
216 panic(err)
217 }
218
219 fmt.Println(resp.StatusCode)
220 // Output:
221 // 200
222 }
223
224 // ExampleClient_Do_withAccessToken gives an example of using client with an access token.
225 func ExampleClient_Do_withAccessToken() {
226 client := &auth.Client{
227 // expectedHostAddress is of form ipaddr:port
228 Credential: auth.StaticCredential(expectedHostAddress, auth.Credential{
229 AccessToken: accessToken,
230 }),
231 }
232 // accessTokenTargetURL can be any URL. For example, https://registry.wabbit-networks.io/v2/
233 req, err := http.NewRequest(http.MethodGet, accessTokenTargetURL, nil)
234 if err != nil {
235 panic(err)
236 }
237 resp, err := client.Do(req)
238 if err != nil {
239 panic(err)
240 }
241
242 fmt.Println(resp.StatusCode)
243 // Output:
244 // 200
245 }
246
247 // ExampleClient_Do_withRefreshToken gives an example of using client with a refresh token.
248 func ExampleClient_Do_withRefreshToken() {
249 client := &auth.Client{
250 // expectedHostAddress is of form ipaddr:port
251 Credential: auth.StaticCredential(expectedHostAddress, auth.Credential{
252 RefreshToken: refreshToken,
253 }),
254 }
255
256 // refreshTokenTargetURL can be any URL. For example, https://registry.wabbit-networks.io/v2/
257 req, err := http.NewRequest(http.MethodGet, refreshTokenTargetURL, nil)
258 if err != nil {
259 panic(err)
260 }
261 resp, err := client.Do(req)
262 if err != nil {
263 panic(err)
264 }
265
266 fmt.Println(resp.StatusCode)
267 // Output:
268 // 200
269 }