Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for bearer authn #4

Merged
merged 2 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ COPY dist/api-mock_linux_${TARGETARCH}*/api-mock /usr/local/bin/
USER 1001
EXPOSE 8080
ENV PRETTYLOG=false \
API_TOKEN="" \
FAILURE_RESP_BODY="{\"success\": false}" \
FAILURE_RESP_CODE=400 \
METHODS="GET,POST" \
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ The API mock can be configured with the following environment variables:
| Variable | Description | Default |
| -------- | ----------- | ------- |
| `PORT` | The port to listen on | `8080` |
| `API_TOKEN` | Bearer token to authenticate requests | `` |
| `FAILURE_RESP_BODY` | The response body to return when mocking a failure | `{"success": "false"}` |
| `FAILURE_RESP_CODE` | The HTTP status code to return when mocking a failure | `400` |
| `SUCCESS_RESP_BODY` | The response body to return when mocking a success | `{"success": "true"}` |
Expand Down
4 changes: 4 additions & 0 deletions internal/service/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/go-chi/render"

"github.com/juan131/api-mock/internal/logger"
"github.com/juan131/api-mock/pkg/authn"
)

const uriPrefix string = "/v1/mock"
Expand Down Expand Up @@ -48,6 +49,9 @@ func (svc *service) MakeRouter() {
// Endpoints handled by the service
router.Route(uriPrefix, func(r chi.Router) {
r.Use(logger.RequestLogger())
if svc.cfg.apiToken != "" {
r.Use(authn.BearerTokenAuth(svc.cfg.apiToken))
}
r.Use(httprate.Limit(
svc.cfg.rateLimit, // requests
time.Second, // per duration
Expand Down
5 changes: 4 additions & 1 deletion internal/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type service struct {
// SvcConfig is the service configuration
type SvcConfig struct {
port int // server listening port
apiToken string // api token
methods, subRoutes []string // supported sub-routes
failureCode int // response code for failed requests
failureRespBody map[string]interface{} // response body for failed requests
Expand Down Expand Up @@ -79,7 +80,9 @@ func Make(cfg *SvcConfig) Service {
//nolint:cyclop // many env variables to parse
func LoadConfigFromEnv() (*SvcConfig, error) {
var err error
svc := SvcConfig{}
svc := SvcConfig{
apiToken: os.Getenv("API_TOKEN"),
}

portENV := os.Getenv("PORT")
if portENV != "" {
Expand Down
5 changes: 4 additions & 1 deletion internal/service/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

func Test_LoadConfigFromEnv(t *testing.T) {
type env struct {
port, failureRespCode, failureRespBody, successRespCode, successRespBody, successRatio, rateLimit, rateExceededRespBody, methods, subRoutes string
port, apiToken, failureRespCode, failureRespBody, successRespCode, successRespBody, successRatio, rateLimit, rateExceededRespBody, methods, subRoutes string
}
tests := []struct {
name string
Expand All @@ -34,6 +34,7 @@ func Test_LoadConfigFromEnv(t *testing.T) {
name: "Valid configuration",
env: env{
port: "8080",
apiToken: "some-token",
failureRespCode: "400",
failureRespBody: `{"success": false}`,
successRespCode: "200",
Expand All @@ -46,6 +47,7 @@ func Test_LoadConfigFromEnv(t *testing.T) {
},
want: &SvcConfig{
port: 8080,
apiToken: "some-token",
failureCode: http.StatusBadRequest,
failureRespBody: map[string]interface{}{"success": false},
successCode: http.StatusOK,
Expand Down Expand Up @@ -134,6 +136,7 @@ func Test_LoadConfigFromEnv(t *testing.T) {
test := testToRun
t.Run(test.name, func(tt *testing.T) {
tt.Setenv("PORT", test.env.port)
tt.Setenv("API_TOKEN", test.env.apiToken)
tt.Setenv("FAILURE_RESP_CODE", test.env.failureRespCode)
tt.Setenv("FAILURE_RESP_BODY", test.env.failureRespBody)
tt.Setenv("SUCCESS_RESP_CODE", test.env.successRespCode)
Expand Down
24 changes: 24 additions & 0 deletions pkg/authn/authn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package authn

import (
"net/http"
"strings"
)

const authenticateHeader string = `Bearer realm="example", error="invalid_token", error_description="invalid access token"`

// BearerTokenAuth implements a simple middleware handler for adding
// bearer http auth based on tokens to a route.
func BearerTokenAuth(token string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if strings.TrimPrefix(authHeader, "Bearer ") != token {
w.Header().Add("WWW-Authenticate", authenticateHeader)
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
60 changes: 60 additions & 0 deletions pkg/authn/authn_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package authn

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chi/chi"
)

const defaultToken string = "some-token"

func TestBearerTokenAuth(t *testing.T) {
tests := []struct {
name string
authHeader string
want int
}{
{
"valid auth",
fmt.Sprintf("Bearer %s", defaultToken),
http.StatusOK,
},
{
"missing token",
"",
http.StatusUnauthorized,
},
{
"invalid token",
"Bearer foo",
http.StatusUnauthorized,
},
}
t.Parallel()
for _, testToRun := range tests {
test := testToRun
t.Run(test.name, func(tt *testing.T) {
tt.Parallel()

r := chi.NewRouter()
r.Use(BearerTokenAuth(defaultToken))
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Authorization", test.authHeader)
recorder := httptest.NewRecorder()
r.ServeHTTP(recorder, req)
res := recorder.Result()
defer res.Body.Close()

if res.StatusCode != test.want {
tt.Errorf("response status code is incorrect, got %d, want %d", res.StatusCode, test.want)
}
})
}
}