podman
276 строк · 8.8 Кб
1// Copyright 2015 go-swagger maintainers
2//
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//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package security
16
17import (
18"context"
19"net/http"
20"strings"
21
22"github.com/go-openapi/errors"
23
24"github.com/go-openapi/runtime"
25)
26
27const (
28query = "query"
29header = "header"
30)
31
32// HttpAuthenticator is a function that authenticates a HTTP request
33func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator {
34return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
35if request, ok := params.(*http.Request); ok {
36return handler(request)
37}
38if scoped, ok := params.(*ScopedAuthRequest); ok {
39return handler(scoped.Request)
40}
41return false, nil, nil
42})
43}
44
45// ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes
46func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator {
47return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) {
48if request, ok := params.(*ScopedAuthRequest); ok {
49return handler(request)
50}
51return false, nil, nil
52})
53}
54
55// UserPassAuthentication authentication function
56type UserPassAuthentication func(string, string) (interface{}, error)
57
58// UserPassAuthenticationCtx authentication function with context.Context
59type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, interface{}, error)
60
61// TokenAuthentication authentication function
62type TokenAuthentication func(string) (interface{}, error)
63
64// TokenAuthenticationCtx authentication function with context.Context
65type TokenAuthenticationCtx func(context.Context, string) (context.Context, interface{}, error)
66
67// ScopedTokenAuthentication authentication function
68type ScopedTokenAuthentication func(string, []string) (interface{}, error)
69
70// ScopedTokenAuthenticationCtx authentication function with context.Context
71type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, interface{}, error)
72
73var DefaultRealmName = "API"
74
75type secCtxKey uint8
76
77const (
78failedBasicAuth secCtxKey = iota
79oauth2SchemeName
80)
81
82func FailedBasicAuth(r *http.Request) string {
83return FailedBasicAuthCtx(r.Context())
84}
85
86func FailedBasicAuthCtx(ctx context.Context) string {
87v, ok := ctx.Value(failedBasicAuth).(string)
88if !ok {
89return ""
90}
91return v
92}
93
94func OAuth2SchemeName(r *http.Request) string {
95return OAuth2SchemeNameCtx(r.Context())
96}
97
98func OAuth2SchemeNameCtx(ctx context.Context) string {
99v, ok := ctx.Value(oauth2SchemeName).(string)
100if !ok {
101return ""
102}
103return v
104}
105
106// BasicAuth creates a basic auth authenticator with the provided authentication function
107func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator {
108return BasicAuthRealm(DefaultRealmName, authenticate)
109}
110
111// BasicAuthRealm creates a basic auth authenticator with the provided authentication function and realm name
112func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.Authenticator {
113if realm == "" {
114realm = DefaultRealmName
115}
116
117return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
118if usr, pass, ok := r.BasicAuth(); ok {
119p, err := authenticate(usr, pass)
120if err != nil {
121*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
122}
123return true, p, err
124}
125*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
126return false, nil, nil
127})
128}
129
130// BasicAuthCtx creates a basic auth authenticator with the provided authentication function with support for context.Context
131func BasicAuthCtx(authenticate UserPassAuthenticationCtx) runtime.Authenticator {
132return BasicAuthRealmCtx(DefaultRealmName, authenticate)
133}
134
135// BasicAuthRealmCtx creates a basic auth authenticator with the provided authentication function and realm name with support for context.Context
136func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
137if realm == "" {
138realm = DefaultRealmName
139}
140
141return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
142if usr, pass, ok := r.BasicAuth(); ok {
143ctx, p, err := authenticate(r.Context(), usr, pass)
144if err != nil {
145ctx = context.WithValue(ctx, failedBasicAuth, realm)
146}
147*r = *r.WithContext(ctx)
148return true, p, err
149}
150*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
151return false, nil, nil
152})
153}
154
155// APIKeyAuth creates an authenticator that uses a token for authorization.
156// This token can be obtained from either a header or a query string
157func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator {
158inl := strings.ToLower(in)
159if inl != query && inl != header {
160// panic because this is most likely a typo
161panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\"."))
162}
163
164var getToken func(*http.Request) string
165switch inl {
166case header:
167getToken = func(r *http.Request) string { return r.Header.Get(name) }
168case query:
169getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
170}
171
172return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
173token := getToken(r)
174if token == "" {
175return false, nil, nil
176}
177
178p, err := authenticate(token)
179return true, p, err
180})
181}
182
183// APIKeyAuthCtx creates an authenticator that uses a token for authorization with support for context.Context.
184// This token can be obtained from either a header or a query string
185func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime.Authenticator {
186inl := strings.ToLower(in)
187if inl != query && inl != header {
188// panic because this is most likely a typo
189panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\"."))
190}
191
192var getToken func(*http.Request) string
193switch inl {
194case header:
195getToken = func(r *http.Request) string { return r.Header.Get(name) }
196case query:
197getToken = func(r *http.Request) string { return r.URL.Query().Get(name) }
198}
199
200return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
201token := getToken(r)
202if token == "" {
203return false, nil, nil
204}
205
206ctx, p, err := authenticate(r.Context(), token)
207*r = *r.WithContext(ctx)
208return true, p, err
209})
210}
211
212// ScopedAuthRequest contains both a http request and the required scopes for a particular operation
213type ScopedAuthRequest struct {
214Request *http.Request
215RequiredScopes []string
216}
217
218// BearerAuth for use with oauth2 flows
219func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator {
220const prefix = "Bearer "
221return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
222var token string
223hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
224if strings.HasPrefix(hdr, prefix) {
225token = strings.TrimPrefix(hdr, prefix)
226}
227if token == "" {
228qs := r.Request.URL.Query()
229token = qs.Get("access_token")
230}
231//#nosec
232ct, _, _ := runtime.ContentType(r.Request.Header)
233if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
234token = r.Request.FormValue("access_token")
235}
236
237if token == "" {
238return false, nil, nil
239}
240
241rctx := context.WithValue(r.Request.Context(), oauth2SchemeName, name)
242*r.Request = *r.Request.WithContext(rctx)
243p, err := authenticate(token, r.RequiredScopes)
244return true, p, err
245})
246}
247
248// BearerAuthCtx for use with oauth2 flows with support for context.Context.
249func BearerAuthCtx(name string, authenticate ScopedTokenAuthenticationCtx) runtime.Authenticator {
250const prefix = "Bearer "
251return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) {
252var token string
253hdr := r.Request.Header.Get(runtime.HeaderAuthorization)
254if strings.HasPrefix(hdr, prefix) {
255token = strings.TrimPrefix(hdr, prefix)
256}
257if token == "" {
258qs := r.Request.URL.Query()
259token = qs.Get("access_token")
260}
261//#nosec
262ct, _, _ := runtime.ContentType(r.Request.Header)
263if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
264token = r.Request.FormValue("access_token")
265}
266
267if token == "" {
268return false, nil, nil
269}
270
271rctx := context.WithValue(r.Request.Context(), oauth2SchemeName, name)
272ctx, p, err := authenticate(rctx, token, r.RequiredScopes)
273*r.Request = *r.Request.WithContext(ctx)
274return true, p, err
275})
276}
277