Skip to content

Commit 628ca60

Browse files
authored
Respect an http error returned by the authentication function (#142)
1 parent 64b1ba3 commit 628ca60

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

oapi_validate.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,12 @@ func ValidateRequestFromContext(ctx echo.Context, router *openapi3filter.Router,
126126
Internal: err,
127127
}
128128
case *openapi3filter.SecurityRequirementsError:
129+
for _, err := range e.Errors {
130+
httpErr, ok := err.(*echo.HTTPError)
131+
if ok {
132+
return httpErr
133+
}
134+
}
129135
return &echo.HTTPError{
130136
Code: http.StatusForbidden,
131137
Message: e.Error(),
@@ -135,8 +141,8 @@ func ValidateRequestFromContext(ctx echo.Context, router *openapi3filter.Router,
135141
// This should never happen today, but if our upstream code changes,
136142
// we don't want to crash the server, so handle the unexpected error.
137143
return &echo.HTTPError{
138-
Code: http.StatusInternalServerError,
139-
Message: fmt.Sprintf("error validating request: %s", err),
144+
Code: http.StatusInternalServerError,
145+
Message: fmt.Sprintf("error validating request: %s", err),
140146
Internal: err,
141147
}
142148
}

oapi_validate_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,15 @@ paths:
8787
responses:
8888
'204':
8989
description: no content
90+
/protected_resource_401:
91+
get:
92+
operationId: getProtectedResource
93+
security:
94+
- BearerAuth:
95+
- unauthorized
96+
responses:
97+
'401':
98+
description: no content
9099
components:
91100
securitySchemes:
92101
BearerAuth:
@@ -127,6 +136,9 @@ func TestOapiRequestValidator(t *testing.T) {
127136
if s == "someScope" {
128137
return nil
129138
}
139+
if s == "unauthorized" {
140+
return echo.ErrUnauthorized
141+
}
130142
}
131143
return errors.New("forbidden")
132144
},
@@ -234,4 +246,16 @@ func TestOapiRequestValidator(t *testing.T) {
234246
assert.False(t, called, "Handler should not have been called")
235247
called = false
236248
}
249+
250+
e.GET("/protected_resource_401", func(c echo.Context) error {
251+
called = true
252+
return c.NoContent(http.StatusNoContent)
253+
})
254+
// Call a protected function without credentials
255+
{
256+
rec := doGet(t, e, "http://deepmap.ai/protected_resource_401")
257+
assert.Equal(t, http.StatusUnauthorized, rec.Code)
258+
assert.False(t, called, "Handler should not have been called")
259+
called = false
260+
}
237261
}

0 commit comments

Comments
 (0)