remove ccirrelo/supervisor, update

everything seems to work even though sirupsen is upper case?

:cyfap:
This commit is contained in:
Reed Allman
2017-09-05 11:36:47 -07:00
parent 78ba35fb23
commit 27e43c5d94
397 changed files with 13691 additions and 8828 deletions

View File

@@ -23,11 +23,11 @@ import (
func TestAuthInfoWriter(t *testing.T) {
hand := ClientAuthInfoWriterFunc(func(r ClientRequest, _ strfmt.Registry) error {
r.SetHeaderParam("authorization", "Bearer the-token-goes-here")
return nil
return r.SetHeaderParam("authorization", "Bearer the-token-goes-here")
})
tr := new(trw)
hand.AuthenticateRequest(tr, nil)
err := hand.AuthenticateRequest(tr, nil)
assert.NoError(t, err)
assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get("Authorization"))
}

View File

@@ -32,8 +32,7 @@ func init() {
func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
r.SetHeaderParam("Authorization", "Basic "+encoded)
return nil
return r.SetHeaderParam("Authorization", "Basic "+encoded)
})
}
@@ -41,15 +40,13 @@ func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
if in == "query" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
r.SetQueryParam(name, value)
return nil
return r.SetQueryParam(name, value)
})
}
if in == "header" {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
r.SetHeaderParam(name, value)
return nil
return r.SetHeaderParam(name, value)
})
}
return nil
@@ -58,7 +55,6 @@ func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
// BearerToken provides a header based oauth2 bearer access token auth info writer
func BearerToken(token string) runtime.ClientAuthInfoWriter {
return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
r.SetHeaderParam("Authorization", "Bearer "+token)
return nil
return r.SetHeaderParam("Authorization", "Bearer "+token)
})
}

View File

@@ -25,7 +25,8 @@ func TestBasicAuth(t *testing.T) {
r, _ := newRequest("GET", "/", nil)
writer := BasicAuth("someone", "with a password")
writer.AuthenticateRequest(r, nil)
err := writer.AuthenticateRequest(r, nil)
assert.NoError(t, err)
req := new(http.Request)
req.Header = make(http.Header)
@@ -41,7 +42,8 @@ func TestAPIKeyAuth_Query(t *testing.T) {
r, _ := newRequest("GET", "/", nil)
writer := APIKeyAuth("api_key", "query", "the-shared-key")
writer.AuthenticateRequest(r, nil)
err := writer.AuthenticateRequest(r, nil)
assert.NoError(t, err)
assert.Equal(t, "the-shared-key", r.query.Get("api_key"))
}
@@ -50,7 +52,8 @@ func TestAPIKeyAuth_Header(t *testing.T) {
r, _ := newRequest("GET", "/", nil)
writer := APIKeyAuth("x-api-token", "header", "the-shared-key")
writer.AuthenticateRequest(r, nil)
err := writer.AuthenticateRequest(r, nil)
assert.NoError(t, err)
assert.Equal(t, "the-shared-key", r.header.Get("x-api-token"))
}
@@ -59,7 +62,8 @@ func TestBearerTokenAuth(t *testing.T) {
r, _ := newRequest("GET", "/", nil)
writer := BearerToken("the-shared-token")
writer.AuthenticateRequest(r, nil)
err := writer.AuthenticateRequest(r, nil)
assert.NoError(t, err)
assert.Equal(t, "Bearer the-shared-token", r.header.Get("Authorization"))
}

View File

@@ -38,20 +38,20 @@ var testProducers = map[string]runtime.Producer{
func TestBuildRequest_SetHeaders(t *testing.T) {
r, _ := newRequest("GET", "/flats/{id}/", nil)
// single value
r.SetHeaderParam("X-Rate-Limit", "500")
_ = r.SetHeaderParam("X-Rate-Limit", "500")
assert.Equal(t, "500", r.header.Get("X-Rate-Limit"))
r.SetHeaderParam("X-Rate-Limit", "400")
_ = r.SetHeaderParam("X-Rate-Limit", "400")
assert.Equal(t, "400", r.header.Get("X-Rate-Limit"))
// multi value
r.SetHeaderParam("X-Accepts", "json", "xml", "yaml")
_ = r.SetHeaderParam("X-Accepts", "json", "xml", "yaml")
assert.EqualValues(t, []string{"json", "xml", "yaml"}, r.header["X-Accepts"])
}
func TestBuildRequest_SetPath(t *testing.T) {
r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil)
r.SetPathParam("id", "1345")
_ = r.SetPathParam("id", "1345")
assert.Equal(t, "1345", r.pathParams["id"])
}
@@ -59,20 +59,20 @@ func TestBuildRequest_SetQuery(t *testing.T) {
r, _ := newRequest("GET", "/flats/{id}/", nil)
// single value
r.SetQueryParam("hello", "there")
_ = r.SetQueryParam("hello", "there")
assert.Equal(t, "there", r.query.Get("hello"))
// multi value
r.SetQueryParam("goodbye", "cruel", "world")
_ = r.SetQueryParam("goodbye", "cruel", "world")
assert.Equal(t, []string{"cruel", "world"}, r.query["goodbye"])
}
func TestBuildRequest_SetForm(t *testing.T) {
// non-multipart
r, _ := newRequest("POST", "/flats", nil)
r.SetFormParam("hello", "world")
_ = r.SetFormParam("hello", "world")
assert.Equal(t, "world", r.formFields.Get("hello"))
r.SetFormParam("goodbye", "cruel", "world")
_ = r.SetFormParam("goodbye", "cruel", "world")
assert.Equal(t, []string{"cruel", "world"}, r.formFields["goodbye"])
}
@@ -107,16 +107,16 @@ func TestBuildRequest_SetBody(t *testing.T) {
r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil)
bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}}
r.SetBodyParam(bd)
_ = r.SetBodyParam(bd)
assert.Equal(t, bd, r.payload)
}
func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) {
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetBodyParam(nil)
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetBodyParam(nil)
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("POST", "/flats/{id}/", reqWrtr)
@@ -133,14 +133,14 @@ func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) {
func TestBuildRequest_BuildHTTP_Payload(t *testing.T) {
bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}}
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetBodyParam(bd)
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetBodyParam(bd)
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
@@ -160,14 +160,14 @@ func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) {
Hobby string `xml:"hobby"`
}{{xml.Name{}, "Tom", "Organ trail"}, {xml.Name{}, "John", "Bird watching"}}
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetBodyParam(bd)
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetBodyParam(bd)
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime)
req, err := r.BuildHTTP(runtime.XMLMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
@@ -183,14 +183,14 @@ func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) {
func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) {
bd := "Tom: Organ trail; John: Bird watching"
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetBodyParam(bd)
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetBodyParam(bd)
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime)
req, err := r.BuildHTTP(runtime.TextMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
@@ -205,14 +205,14 @@ func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) {
func TestBuildRequest_BuildHTTP_Form(t *testing.T) {
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetFormParam("something", "some value")
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetFormParam("something", "some value")
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
@@ -227,14 +227,14 @@ func TestBuildRequest_BuildHTTP_Form(t *testing.T) {
func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) {
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetFormParam("something", "some value")
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetFormParam("something", "some value")
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime)
req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
@@ -252,15 +252,15 @@ func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) {
func TestBuildRequest_BuildHTTP_Files(t *testing.T) {
cont, _ := ioutil.ReadFile("./runtime.go")
reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error {
req.SetFormParam("something", "some value")
req.SetFileParam("file", mustGetFile("./runtime.go"))
req.SetQueryParam("hello", "world")
req.SetPathParam("id", "1234")
req.SetHeaderParam("X-Rate-Limit", "200")
_ = req.SetFormParam("something", "some value")
_ = req.SetFileParam("file", mustGetFile("./runtime.go"))
_ = req.SetQueryParam("hello", "world")
_ = req.SetPathParam("id", "1234")
_ = req.SetHeaderParam("X-Rate-Limit", "200")
return nil
})
r, _ := newRequest("GET", "/flats/{id}/", reqWrtr)
r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
_ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime)
req, err := r.BuildHTTP(runtime.JSONMime, testProducers, nil)
if assert.NoError(t, err) && assert.NotNil(t, req) {
assert.Equal(t, "200", req.Header.Get("x-rate-limit"))

View File

@@ -214,10 +214,10 @@ func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error
}
var accept []string
for _, mimeType := range operation.ProducesMediaTypes {
accept = append(accept, mimeType)
accept = append(accept, operation.ProducesMediaTypes...)
if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil {
return nil, err
}
request.SetHeaderParam(runtime.HeaderAccept, accept...)
if auth == nil && r.DefaultAuthentication != nil {
auth = r.DefaultAuthentication

View File

@@ -77,7 +77,7 @@ func TestRuntime_Concurrent(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
@@ -153,7 +153,7 @@ func TestRuntime_Canary(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
@@ -204,7 +204,7 @@ func TestRuntime_XMLCanary(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.XMLMime)
rw.WriteHeader(http.StatusOK)
xmlgen := xml.NewEncoder(rw)
xmlgen.Encode(result)
_ = xmlgen.Encode(result)
}))
defer server.Close()
@@ -245,7 +245,7 @@ func TestRuntime_TextCanary(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add(runtime.HeaderContentType, runtime.TextMime)
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(result))
_, _ = rw.Write([]byte(result))
}))
defer server.Close()
@@ -305,7 +305,7 @@ func TestRuntime_CustomTransport(t *testing.T) {
resp.Header.Set("content-type", "application/json")
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
enc.Encode(result)
_ = enc.Encode(result)
resp.Body = ioutil.NopCloser(buf)
return &resp, nil
})
@@ -354,7 +354,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode([]task{})
_ = jsongen.Encode([]task{})
} else {
rw.WriteHeader(http.StatusUnauthorized)
}
@@ -407,7 +407,7 @@ func TestRuntime_AuthCanary(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime)
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
@@ -455,13 +455,12 @@ func TestRuntime_PickConsumer(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
req.SetBodyParam(bytes.NewBufferString("hello"))
return nil
return req.SetBodyParam(bytes.NewBufferString("hello"))
})
hu, _ := url.Parse(server.URL)
@@ -509,7 +508,7 @@ func TestRuntime_ContentTypeCanary(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
@@ -563,7 +562,7 @@ func TestRuntime_ChunkedResponse(t *testing.T) {
rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8")
rw.WriteHeader(http.StatusOK)
jsongen := json.NewEncoder(rw)
jsongen.Encode(result)
_ = jsongen.Encode(result)
}))
defer server.Close()
@@ -605,26 +604,26 @@ func TestRuntime_DebugValue(t *testing.T) {
original := os.Getenv("DEBUG")
// Emtpy DEBUG means Debug is False
os.Setenv("DEBUG", "")
_ = os.Setenv("DEBUG", "")
runtime := New("", "/", []string{"https"})
assert.False(t, runtime.Debug)
// Non-Empty Debug means Debug is True
os.Setenv("DEBUG", "1")
_ = os.Setenv("DEBUG", "1")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
os.Setenv("DEBUG", "true")
_ = os.Setenv("DEBUG", "true")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
os.Setenv("DEBUG", "foo")
_ = os.Setenv("DEBUG", "foo")
runtime = New("", "/", []string{"https"})
assert.True(t, runtime.Debug)
// Make sure DEBUG is initial value once again
os.Setenv("DEBUG", original)
_ = os.Setenv("DEBUG", original)
}
func TestRuntime_OverrideScheme(t *testing.T) {

View File

@@ -56,13 +56,13 @@ func (t *trw) SetTimeout(timeout time.Duration) error {
func TestRequestWriterFunc(t *testing.T) {
hand := ClientRequestWriterFunc(func(r ClientRequest, reg strfmt.Registry) error {
r.SetHeaderParam("blah", "blah blah")
r.SetBodyParam(struct{ Name string }{"Adriana"})
_ = r.SetHeaderParam("blah", "blah blah")
_ = r.SetBodyParam(struct{ Name string }{"Adriana"})
return nil
})
tr := new(trw)
hand.WriteToRequest(tr, nil)
_ = hand.WriteToRequest(tr, nil)
assert.Equal(t, "blah blah", tr.Headers.Get("blah"))
assert.Equal(t, "Adriana", tr.Body.(struct{ Name string }).Name)
}

View File

@@ -52,7 +52,7 @@ func TestResponseReaderFunc(t *testing.T) {
actual.Header = r.GetHeader("blah")
return actual, nil
})
reader.ReadResponse(response{}, nil)
_, _ = reader.ReadResponse(response{}, nil)
assert.Equal(t, "the content", actual.Body)
assert.Equal(t, "the message", actual.Message)
assert.Equal(t, "the header", actual.Header)

View File

@@ -15,8 +15,10 @@
package runtime
import (
"github.com/go-openapi/strfmt"
"io"
"net/http"
"github.com/go-openapi/strfmt"
)
// OperationHandlerFunc an adapter for a function to the OperationHandler interface
@@ -77,6 +79,21 @@ type Authenticator interface {
Authenticate(interface{}) (bool, interface{}, error)
}
// AuthorizerFunc turns a function into an authorizer
type AuthorizerFunc func(*http.Request, interface{}) error
// Authorize authorizes the processing of the request for the principal
func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error {
return f(r, principal)
}
// Authorizer represents an authorization strategy
// implementations of Authorizer know how to authorize the principal object
// using the request data and returns error if unauthorized
type Authorizer interface {
Authorize(*http.Request, interface{}) error
}
// Validatable types implementing this interface allow customizing their validation
// this will be used instead of the reflective valditation based on the spec document.
// the implementations are assumed to have been generated by the swagger tool so they should

View File

@@ -15,7 +15,10 @@
package petstore
import (
goerrors "errors"
"io"
"net/http"
"strings"
gotest "testing"
"github.com/go-openapi/errors"
@@ -46,6 +49,8 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) {
api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) {
if username == "admin" && password == "admin" {
return "admin", nil
} else if username == "topuser" && password == "topuser" {
return "topuser", nil
}
return nil, errors.Unauthenticated("basic")
}))
@@ -55,6 +60,12 @@ func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) {
}
return nil, errors.Unauthenticated("token")
}))
api.RegisterAuthorizer(runtime.AuthorizerFunc(func(r *http.Request, user interface{}) error {
if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/pets") && user.(string) != "admin" {
return goerrors.New("unauthorized")
}
return nil
}))
api.RegisterOperation("get", "/pets", new(stubOperationHandler))
api.RegisterOperation("post", "/pets", new(stubOperationHandler))
api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler))
@@ -94,6 +105,7 @@ func NewRootAPI(t gotest.TB) (*loads.Document, *untyped.API) {
}
return nil, errors.Unauthenticated("token")
}))
api.RegisterAuthorizer(security.Authorized())
api.RegisterOperation("get", "/pets", new(stubOperationHandler))
api.RegisterOperation("post", "/pets", new(stubOperationHandler))
api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler))

View File

@@ -68,12 +68,12 @@ func TestBindRequest_DeleteNoBody(t *testing.T) {
ri, rCtx, ok := ctx.RouteInfo(req)
if assert.True(t, ok) {
req = rCtx
err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error {
bverr := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error {
return nil
}))
assert.NoError(t, err)
//assert.Equal(t, io.EOF, err)
assert.NoError(t, bverr)
//assert.Equal(t, io.EOF, bverr)
}
}

View File

@@ -75,7 +75,6 @@ type Context struct {
analyzer *analysis.Spec
api RoutableAPI
router Router
formats strfmt.Registry
}
type routableUntypedAPI struct {
@@ -173,6 +172,9 @@ func (r *routableUntypedAPI) ProducersFor(mediaTypes []string) map[string]runtim
func (r *routableUntypedAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator {
return r.api.AuthenticatorsFor(schemes)
}
func (r *routableUntypedAPI) Authorizer() runtime.Authorizer {
return r.api.Authorizer()
}
func (r *routableUntypedAPI) Formats() strfmt.Registry {
return r.api.Formats()
}
@@ -225,12 +227,9 @@ const (
ctxContentType
ctxResponseFormat
ctxMatchedRoute
ctxAllowedMethods
ctxBoundParams
ctxSecurityPrincipal
ctxSecurityScopes
ctxConsumer
)
type contentTypeValue struct {
@@ -396,6 +395,11 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interfa
}
continue
}
if route.Authorizer != nil {
if err := route.Authorizer.Authorize(request, usr); err != nil {
return nil, nil, errors.New(http.StatusForbidden, err.Error())
}
}
rCtx = stdContext.WithValue(rCtx, ctxSecurityPrincipal, usr)
rCtx = stdContext.WithValue(rCtx, ctxSecurityScopes, route.Scopes[scheme])
return usr, request.WithContext(rCtx), nil
@@ -542,7 +546,7 @@ func (c *Context) APIHandler(builder Builder) http.Handler {
Title: title,
}
return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(builder)))
return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)))
}
// RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec

View File

@@ -39,13 +39,6 @@ func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) {
return nil, nil
}
type testBinder struct {
}
func (t *testBinder) BindRequest(r *http.Request, m *MatchedRoute) error {
return nil
}
func init() {
loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc)
}
@@ -138,6 +131,32 @@ func TestContextAuthorize(t *testing.T) {
assert.Equal(t, request, reqCtx)
}
func TestContextAuthorize_WithAuthorizer(t *testing.T) {
spec, api := petstore.NewAPI(t)
ctx := NewContext(spec, api, nil)
ctx.router = DefaultRouter(spec, ctx.api)
request, _ := runtime.JSONRequest("POST", "/api/pets", nil)
ri, reqWithCtx, ok := ctx.RouteInfo(request)
assert.True(t, ok)
assert.NotNil(t, reqWithCtx)
request = reqWithCtx
request.SetBasicAuth("topuser", "topuser")
p, reqWithCtx, err := ctx.Authorize(request, ri)
assert.Error(t, err)
assert.Nil(t, p)
assert.Nil(t, reqWithCtx)
request.SetBasicAuth("admin", "admin")
p, reqWithCtx, err = ctx.Authorize(request, ri)
assert.NoError(t, err)
assert.Equal(t, "admin", p)
assert.NotNil(t, reqWithCtx)
}
func TestContextNegotiateContentType(t *testing.T) {
spec, api := petstore.NewAPI(t)
ctx := NewContext(spec, api, nil)
@@ -240,6 +259,7 @@ func TestContextRender(t *testing.T) {
ri, request, _ = ctx.RouteInfo(request)
ctx.Respond(recorder, request, ri.Produces, ri, nil)
assert.Equal(t, 204, recorder.Code)
}
func TestContextValidResponseFormat(t *testing.T) {
@@ -266,7 +286,7 @@ func TestContextValidResponseFormat(t *testing.T) {
assert.Equal(t, ct, cached)
// check if the cast works and fetch from cache too
mt, request = ctx.ResponseFormat(request, []string{ct})
mt, _ = ctx.ResponseFormat(request, []string{ct})
assert.Equal(t, ct, mt)
}

View File

@@ -46,8 +46,8 @@ func init() {
var t octetType
isCtl := c <= 31 || c == 127
isChar := 0 <= c && c <= 127
isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0
if strings.IndexRune(" \t\r\n", rune(c)) >= 0 {
isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c))
if strings.ContainsRune(" \t\r\n", rune(c)) {
t |= isSpace
}
if isChar && !isCtl && !isSeparator {
@@ -167,11 +167,13 @@ func parseValueAndParams(s string) (value string, params map[string]string) {
return
}
// AcceptSpec ...
type AcceptSpec struct {
Value string
Q float64
}
// ParseAccept2 ...
func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) {
for _, en := range ParseList(header, key) {
v, p := parseValueAndParams(en)

View File

@@ -193,28 +193,28 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams
}
if mt == "multipart/form-data" {
if err := request.ParseMultipartForm(defaultMaxMemory); err != nil {
if err = request.ParseMultipartForm(defaultMaxMemory); err != nil {
return errors.NewParseError(p.Name, p.parameter.In, "", err)
}
}
if err := request.ParseForm(); err != nil {
if err = request.ParseForm(); err != nil {
return errors.NewParseError(p.Name, p.parameter.In, "", err)
}
if p.parameter.Type == "file" {
file, header, err := request.FormFile(p.parameter.Name)
if err != nil {
return errors.NewParseError(p.Name, p.parameter.In, "", err)
file, header, ffErr := request.FormFile(p.parameter.Name)
if ffErr != nil {
return errors.NewParseError(p.Name, p.parameter.In, "", ffErr)
}
target.Set(reflect.ValueOf(runtime.File{Data: file, Header: header}))
return nil
}
if request.MultipartForm != nil {
data, custom, hasKey, err := p.readValue(runtime.Values(request.MultipartForm.Value), target)
if err != nil {
return err
data, custom, hasKey, rvErr := p.readValue(runtime.Values(request.MultipartForm.Value), target)
if rvErr != nil {
return rvErr
}
if custom {
return nil

View File

@@ -28,9 +28,9 @@ import (
"github.com/stretchr/testify/assert"
)
type email struct {
Address string
}
// type email struct {
// Address string
// }
type paramFactory func(string) *spec.Parameter

View File

@@ -51,7 +51,7 @@ func Redoc(opts RedocOpts, next http.Handler) http.Handler {
tmpl := template.Must(template.New("redoc").Parse(redocTemplate))
buf := bytes.NewBuffer(nil)
tmpl.Execute(buf, opts)
_ = tmpl.Execute(buf, opts)
b := buf.Bytes()
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
@@ -59,14 +59,14 @@ func Redoc(opts RedocOpts, next http.Handler) http.Handler {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
rw.Write(b)
_, _ = rw.Write(b)
return
}
if next == nil {
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusNotFound)
rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
return
}
next.ServeHTTP(rw, r)

View File

@@ -54,7 +54,7 @@ func (o *untypedRequestBinder) Bind(request *http.Request, routeParams RoutePara
debugLog("binding %d parameters for %s %s", len(o.Parameters), request.Method, request.URL.EscapedPath())
for fieldName, param := range o.Parameters {
binder := o.paramBinders[fieldName]
debugLog("binding paramter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath())
debugLog("binding parameter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath())
var target reflect.Value
if !isMap {
binder.Name = fieldName

View File

@@ -67,21 +67,6 @@ type jsonRequestSlice struct {
Friend []friend
}
type jsonRequestAllTypes struct {
Confirmed bool
Planned strfmt.Date
Delivered strfmt.DateTime
Age int32
ID int64
Score float32
Factor float64
Friend friend
Name string
Tags []string
Picture []byte
RequestID int64
}
func parametersForAllTypes(fmt string) map[string]spec.Parameter {
if fmt == "" {
fmt = "csv"
@@ -299,7 +284,7 @@ func TestRequestBindingForValid(t *testing.T) {
binder := newUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default)
lval := []string{"one", "two", "three"}
queryString := ""
var queryString string
switch fmt {
case "multi":
queryString = strings.Join(lval, "&tags=")
@@ -428,8 +413,8 @@ func TestBindingFileUpload(t *testing.T) {
part, err := writer.CreateFormFile("file", "plain-jane.txt")
assert.NoError(t, err)
part.Write([]byte("the file contents"))
writer.WriteField("name", "the-name")
_, _ = part.Write([]byte("the file contents"))
_ = writer.WriteField("name", "the-name")
assert.NoError(t, writer.Close())
urlStr := "http://localhost:8002/hello"
@@ -462,8 +447,8 @@ func TestBindingFileUpload(t *testing.T) {
part, err = writer.CreateFormFile("bad-name", "plain-jane.txt")
assert.NoError(t, err)
part.Write([]byte("the file contents"))
writer.WriteField("name", "the-name")
_, _ = part.Write([]byte("the file contents"))
_ = writer.WriteField("name", "the-name")
assert.NoError(t, writer.Close())
req, _ = http.NewRequest("POST", urlStr, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
@@ -473,7 +458,7 @@ func TestBindingFileUpload(t *testing.T) {
req, _ = http.NewRequest("POST", urlStr, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.MultipartReader()
_, _ = req.MultipartReader()
data = fileRequest{}
assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data))

View File

@@ -92,6 +92,7 @@ type RoutableAPI interface {
ConsumersFor([]string) map[string]runtime.Consumer
ProducersFor([]string) map[string]runtime.Producer
AuthenticatorsFor(map[string]spec.SecurityScheme) map[string]runtime.Authenticator
Authorizer() runtime.Authorizer
Formats() strfmt.Registry
DefaultProduces() string
DefaultConsumes() string
@@ -112,7 +113,6 @@ type defaultRouteBuilder struct {
type defaultRouter struct {
spec *loads.Document
api RoutableAPI
routers map[string]*denco.Router
}
@@ -153,6 +153,7 @@ type routeEntry struct {
Formats strfmt.Registry
Binder *untypedRequestBinder
Authenticators map[string]runtime.Authenticator
Authorizer runtime.Authorizer
Scopes map[string][]string
}
@@ -248,6 +249,7 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper
Formats: d.api.Formats(),
Binder: newUntypedRequestBinder(parameters, d.spec.Spec(), d.api.Formats()),
Authenticators: d.api.AuthenticatorsFor(definitions),
Authorizer: d.api.Authorizer(),
Scopes: scopes,
})
d.records[mn] = append(d.records[mn], record)
@@ -258,7 +260,7 @@ func (d *defaultRouteBuilder) Build() *defaultRouter {
routers := make(map[string]*denco.Router)
for method, records := range d.records {
router := denco.New()
router.Build(records)
_ = router.Build(records)
routers[method] = router
}
return &defaultRouter{

View File

@@ -27,12 +27,12 @@ func newSecureAPI(ctx *Context, next http.Handler) http.Handler {
return
}
if _, rCtx, err := ctx.Authorize(r, route); err != nil {
_, rCtx, err := ctx.Authorize(r, route)
if err != nil {
ctx.Respond(rw, r, route.Produces, route, err)
return
} else {
r = rCtx
}
r = rCtx
next.ServeHTTP(rw, r)
})

View File

@@ -33,7 +33,7 @@ func Spec(basePath string, b []byte, next http.Handler) http.Handler {
if r.URL.Path == pth {
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
rw.Write(b)
_, _ = rw.Write(b)
return
}

View File

@@ -57,6 +57,7 @@ type API struct {
consumers map[string]runtime.Consumer
producers map[string]runtime.Producer
authenticators map[string]runtime.Authenticator
authorizer runtime.Authorizer
operations map[string]map[string]runtime.OperationHandler
ServeError func(http.ResponseWriter, *http.Request, error)
Models map[string]func() interface{}
@@ -105,6 +106,11 @@ func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) {
d.authenticators[scheme] = handler
}
// RegisterAuthorizer registers an authorizer handler in this api
func (d *API) RegisterAuthorizer(handler runtime.Authorizer) {
d.authorizer = handler
}
// RegisterConsumer registers a consumer for a media type.
func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) {
if d.consumers == nil {
@@ -178,6 +184,11 @@ func (d *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[stri
return result
}
// AuthorizersFor returns the registered authorizer
func (d *API) Authorizer() runtime.Authorizer {
return d.authorizer
}
// Validate validates this API for any missing items
func (d *API) Validate() error {
return d.validate()

View File

@@ -16,6 +16,7 @@ package untyped
import (
"io"
"net/http"
"sort"
"testing"
@@ -31,6 +32,10 @@ func stubAutenticator() runtime.Authenticator {
return runtime.AuthenticatorFunc(func(_ interface{}) (bool, interface{}, error) { return false, nil, nil })
}
func stubAuthorizer() runtime.Authorizer {
return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil })
}
type stubConsumer struct {
}
@@ -63,7 +68,9 @@ func TestUntypedAPIRegistrations(t *testing.T) {
api.RegisterProducer("application/yada-2", new(stubProducer))
api.RegisterOperation("get", "/{someId}", new(stubOperationHandler))
api.RegisterAuth("basic", stubAutenticator())
api.RegisterAuthorizer(stubAuthorizer())
assert.NotNil(t, api.authorizer)
assert.NotEmpty(t, api.authenticators)
_, ok := api.authenticators["basic"]
@@ -79,6 +86,9 @@ func TestUntypedAPIRegistrations(t *testing.T) {
_, ok = api.operations["GET"]["/{someId}"]
assert.True(t, ok)
authorizer := api.Authorizer()
assert.NotNil(t, authorizer)
h, ok := api.OperationHandlerFor("get", "/{someId}")
assert.True(t, ok)
assert.NotNil(t, h)

View File

@@ -59,8 +59,8 @@ func TestUntypedFileUpload(t *testing.T) {
part, err := writer.CreateFormFile("file", "plain-jane.txt")
assert.NoError(t, err)
part.Write([]byte("the file contents"))
writer.WriteField("name", "the-name")
_, _ = part.Write([]byte("the file contents"))
_ = writer.WriteField("name", "the-name")
assert.NoError(t, writer.Close())
urlStr := "http://localhost:8002/hello"
@@ -95,8 +95,8 @@ func TestUntypedFileUpload(t *testing.T) {
part, err = writer.CreateFormFile("bad-name", "plain-jane.txt")
assert.NoError(t, err)
part.Write([]byte("the file contents"))
writer.WriteField("name", "the-name")
_, _ = part.Write([]byte("the file contents"))
_ = writer.WriteField("name", "the-name")
assert.NoError(t, writer.Close())
req, _ = http.NewRequest("POST", urlStr, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
@@ -106,7 +106,7 @@ func TestUntypedFileUpload(t *testing.T) {
req, _ = http.NewRequest("POST", urlStr, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.MultipartReader()
_, _ = req.MultipartReader()
data = make(map[string]interface{})
assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data))

View File

@@ -24,30 +24,6 @@ import (
"github.com/go-openapi/swag"
)
// NewValidation starts a new validation middleware
func newValidation(ctx *Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
matched, rCtx, _ := ctx.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
if matched == nil {
ctx.NotFound(rw, r)
return
}
_, r, result := ctx.BindAndValidate(r, matched)
if result != nil {
ctx.Respond(rw, r, matched.Produces, matched, result)
return
}
debugLog("no result for %s %s", r.Method, r.URL.EscapedPath())
next.ServeHTTP(rw, r)
})
}
type validation struct {
context *Context
result []error
@@ -56,15 +32,6 @@ type validation struct {
bound map[string]interface{}
}
type untypedBinder map[string]interface{}
func (ub untypedBinder) BindRequest(r *http.Request, route *MatchedRoute, consumer runtime.Consumer) error {
if err := route.Binder.Bind(r, route.Params, consumer, ub); err != nil {
return err
}
return nil
}
// ContentType validates the content type of a request
func validateContentType(allowed []string, actual string) error {
debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", "))

View File

@@ -26,11 +26,33 @@ import (
"github.com/stretchr/testify/assert"
)
func newTestValidation(ctx *Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
matched, rCtx, _ := ctx.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
if matched == nil {
ctx.NotFound(rw, r)
return
}
_, r, result := ctx.BindAndValidate(r, matched)
if result != nil {
ctx.Respond(rw, r, matched.Produces, matched, result)
return
}
next.ServeHTTP(rw, r)
})
}
func TestContentTypeValidation(t *testing.T) {
spec, api := petstore.NewAPI(t)
context := NewContext(spec, api, nil)
context.router = DefaultRouter(spec, context.api)
mw := newValidation(context, http.HandlerFunc(terminator))
mw := newTestValidation(context, http.HandlerFunc(terminator))
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("GET", "/api/pets", nil)
@@ -82,7 +104,7 @@ func TestResponseFormatValidation(t *testing.T) {
spec, api := petstore.NewAPI(t)
context := NewContext(spec, api, nil)
context.router = DefaultRouter(spec, context.api)
mw := newValidation(context, http.HandlerFunc(terminator))
mw := newTestValidation(context, http.HandlerFunc(terminator))
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`)))

View File

@@ -0,0 +1,27 @@
// Copyright 2015 go-swagger maintainers
//
// 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 security
import (
"net/http"
"github.com/go-openapi/runtime"
)
// Authorized provides a default implementation of the Authorizer interface where all
// requests are authorized (successful)
func Authorized() runtime.Authorizer {
return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil })
}

View File

@@ -0,0 +1,28 @@
// Copyright 2015 go-swagger maintainers
//
// 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 security
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAuthorized(t *testing.T) {
authorizer := Authorized()
err := authorizer.Authorize(nil, nil)
assert.NoError(t, err)
}

View File

@@ -49,7 +49,7 @@ func TestValidBearerAuth(t *testing.T) {
mpbody := bytes.NewBuffer(nil)
writer := multipart.NewWriter(mpbody)
writer.WriteField("access_token", "token123")
_ = writer.WriteField("access_token", "token123")
writer.Close()
req4, _ := http.NewRequest("POST", "/blah", mpbody)
req4.Header.Set("Content-Type", writer.FormDataContentType())
@@ -90,7 +90,7 @@ func TestInvalidBearerAuth(t *testing.T) {
mpbody := bytes.NewBuffer(nil)
writer := multipart.NewWriter(mpbody)
writer.WriteField("access_token", "token124")
_ = writer.WriteField("access_token", "token124")
writer.Close()
req4, _ := http.NewRequest("POST", "/blah", mpbody)
req4.Header.Set("Content-Type", writer.FormDataContentType())
@@ -131,7 +131,7 @@ func TestMissingBearerAuth(t *testing.T) {
mpbody := bytes.NewBuffer(nil)
writer := multipart.NewWriter(mpbody)
writer.WriteField("access_toke", "token123")
_ = writer.WriteField("access_toke", "token123")
writer.Close()
req4, _ := http.NewRequest("POST", "/blah", mpbody)
req4.Header.Set("Content-Type", writer.FormDataContentType())

View File

@@ -55,13 +55,16 @@ func IsDateTime(str string) bool {
const (
// RFC3339Millis represents a ISO8601 format to millis instead of to nanos
RFC3339Millis = "2006-01-02T15:04:05.000Z07:00"
// RFC3339Micro represents a ISO8601 format to micro instead of to nano
RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00"
// DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6
DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$`
)
var (
dateTimeFormats = []string{RFC3339Millis, time.RFC3339, time.RFC3339Nano}
dateTimeFormats = []string{RFC3339Micro, RFC3339Millis, time.RFC3339, time.RFC3339Nano}
rxDateTime = regexp.MustCompile(DateTimePattern)
MarshalFormat = RFC3339Millis
)
// ParseDateTime parses a string that represents an ISO8601 time or a unix epoch
@@ -96,7 +99,7 @@ func NewDateTime() DateTime {
}
func (t DateTime) String() string {
return time.Time(t).Format(RFC3339Millis)
return time.Time(t).Format(MarshalFormat)
}
// MarshalText implements the text marshaller interface
@@ -145,7 +148,7 @@ func (t DateTime) MarshalJSON() ([]byte, error) {
}
func (t DateTime) MarshalEasyJSON(w *jwriter.Writer) {
w.String(time.Time(t).Format(RFC3339Millis))
w.String(time.Time(t).Format(MarshalFormat))
}
func (t *DateTime) UnmarshalJSON(data []byte) error {