Skip to content

[public-api] Authentication interceptors for connect API #13693

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

Merged
merged 1 commit into from
Oct 10, 2022
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
4 changes: 2 additions & 2 deletions components/public-api-server/go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 33 additions & 0 deletions components/public-api-server/pkg/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

import (
"errors"
"fmt"
"net/http"
"strings"
)

var (
NoAccessToken = errors.New("missing access token")
InvalidAccessToken = errors.New("invalid access token")
)

const bearerPrefix = "Bearer "
const authorizationHeaderKey = "Authorization"

func BearerTokenFromHeaders(h http.Header) (string, error) {
authorization := strings.TrimSpace(h.Get(authorizationHeaderKey))
if authorization == "" {
return "", fmt.Errorf("empty authorization header: %w", NoAccessToken)
}

if !strings.HasPrefix(authorization, bearerPrefix) {
return "", fmt.Errorf("authorization header does not have a Bearer prefix: %w", NoAccessToken)
}

return strings.TrimPrefix(authorization, bearerPrefix), nil
}
69 changes: 69 additions & 0 deletions components/public-api-server/pkg/auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

import (
"net/http"
"testing"

"github.com/stretchr/testify/require"
)

func TestBearerTokenFromHeaders(t *testing.T) {
type Scenario struct {
Name string

// Input
Header http.Header

// Output
Token string
Error error
}

for _, s := range []Scenario{
{
Name: "happy case",
Header: addToHeader(http.Header{}, "Authorization", "Bearer foo"),
Token: "foo",
},
{
Name: "leading and trailing spaces are trimmed",
Header: addToHeader(http.Header{}, "Authorization", " Bearer foo "),
Token: "foo",
},
{
Name: "anything after Bearer is extracted",
Header: addToHeader(http.Header{}, "Authorization", "Bearer foo bar"),
Token: "foo bar",
},
{
Name: "duplicate bearer",
Header: addToHeader(http.Header{}, "Authorization", "Bearer Bearer foo"),
Token: "Bearer foo",
},
{
Name: "missing Bearer prefix fails",
Header: addToHeader(http.Header{}, "Authorization", "foo"),
Error: NoAccessToken,
},
{
Name: "missing Authorization header fails",
Header: http.Header{},
Error: NoAccessToken,
},
} {
t.Run(s.Name, func(t *testing.T) {
token, err := BearerTokenFromHeaders(s.Header)
require.ErrorIs(t, err, s.Error)
require.Equal(t, s.Token, token)
})
}
}

func addToHeader(h http.Header, key, value string) http.Header {
h.Add(key, value)
return h
}
25 changes: 25 additions & 0 deletions components/public-api-server/pkg/auth/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

import "context"

type contextKey int

const (
authContextKey contextKey = iota
)

func TokenToContext(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, authContextKey, token)
}

func TokenFromContext(ctx context.Context) string {
if val, ok := ctx.Value(authContextKey).(string); ok {
return val
}

return ""
}
23 changes: 23 additions & 0 deletions components/public-api-server/pkg/auth/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

import (
"context"
"testing"

"github.com/stretchr/testify/require"
)

func TestTokenToAndFromContext(t *testing.T) {
token := "my_token"

extracted := TokenFromContext(TokenToContext(context.Background(), token))
require.Equal(t, token, extracted)
}

func TestTokenFromContext_EmptyWhenNotSet(t *testing.T) {
require.Equal(t, "", TokenFromContext(context.Background()))
}
51 changes: 51 additions & 0 deletions components/public-api-server/pkg/auth/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

import (
"context"

"github.com/bufbuild/connect-go"
)

// NewServerInterceptor creates a server-side interceptor which validates that an incoming request contains a Bearer Authorization header
func NewServerInterceptor() connect.UnaryInterceptorFunc {
interceptor := func(next connect.UnaryFunc) connect.UnaryFunc {
return connect.UnaryFunc(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {

if req.Spec().IsClient {
return next(ctx, req)
}

headers := req.Header()

token, err := BearerTokenFromHeaders(headers)
if err != nil {
return nil, connect.NewError(connect.CodeUnauthenticated, err)

}
return next(TokenToContext(ctx, token), req)
})
}

return connect.UnaryInterceptorFunc(interceptor)
}

// NewClientInterceptor creates a client-side interceptor which injects token as a Bearer Authorization header
func NewClientInterceptor(token string) connect.UnaryInterceptorFunc {
interceptor := func(next connect.UnaryFunc) connect.UnaryFunc {
return connect.UnaryFunc(func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {

if !req.Spec().IsClient {
return next(ctx, req)
}

req.Header().Add(authorizationHeaderKey, bearerPrefix+token)
return next(ctx, req)
})
}

return connect.UnaryInterceptorFunc(interceptor)
}
97 changes: 97 additions & 0 deletions components/public-api-server/pkg/auth/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package auth

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

"github.com/bufbuild/connect-go"
"github.com/stretchr/testify/require"
)

func TestNewServerInterceptor(t *testing.T) {
requestPayload := "request"
type TokenResponse struct {
Token string `json:"token"`
}

type Header struct {
Key string
Value string
}

handler := connect.UnaryFunc(func(ctx context.Context, ar connect.AnyRequest) (connect.AnyResponse, error) {
token := TokenFromContext(ctx)
return connect.NewResponse(&TokenResponse{Token: token}), nil
})

scenarios := []struct {
Name string

Headers []Header

ExpectedError error
ExpectedToken string
}{
{
Name: "no headers return Unathenticated",
Headers: nil,
ExpectedError: connect.NewError(connect.CodeUnauthenticated, fmt.Errorf("empty authorization header: %w", NoAccessToken)),
},
{
Name: "authorization header with bearer token returns ok",
Headers: []Header{{Key: "Authorization", Value: "Bearer foo"}},
ExpectedToken: "foo",
},
}

for _, s := range scenarios {
t.Run(s.Name, func(t *testing.T) {
ctx := context.Background()
request := connect.NewRequest(&requestPayload)

for _, header := range s.Headers {
request.Header().Add(header.Key, header.Value)
}

resp, err := NewServerInterceptor()(handler)(ctx, request)

require.Equal(t, s.ExpectedError, err)
if err == nil {
require.Equal(t, &TokenResponse{
Token: s.ExpectedToken,
}, resp.Any())
}

})
}
}

func TestNewClientInterceptor(t *testing.T) {
expectedToken := "my_token"

tokenOnRequest := ""
// Setup a test server where we capture the token supplied, we don't actually care for the response.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Header)
token, err := BearerTokenFromHeaders(r.Header)
require.NoError(t, err)

// Capture the token supplied in the request so we can test for it
tokenOnRequest = token
w.WriteHeader(http.StatusNotFound)
}))

client := connect.NewClient[any, any](http.DefaultClient, srv.URL, connect.WithInterceptors(
NewClientInterceptor(expectedToken),
))

_, _ = client.CallUnary(context.Background(), connect.NewRequest[any](nil))
require.Equal(t, expectedToken, tokenOnRequest)
}
42 changes: 41 additions & 1 deletion components/public-api-server/pkg/server/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/bufbuild/connect-go"
"github.com/gitpod-io/gitpod/common-go/baseserver"
"github.com/gitpod-io/gitpod/public-api-server/pkg/auth"
v1 "github.com/gitpod-io/gitpod/public-api/v1"
"github.com/gitpod-io/gitpod/public-api/v1/v1connect"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -113,7 +114,7 @@ func TestPublicAPIServer_WorkspaceServiceHandler(t *testing.T) {
require.NoError(t, register(srv, gitpodAPI))
baseserver.StartServerForTests(t, srv)

client := v1connect.NewWorkspacesServiceClient(http.DefaultClient, srv.HTTPAddress())
client := v1connect.NewWorkspacesServiceClient(http.DefaultClient, srv.HTTPAddress(), connect.WithInterceptors(auth.NewClientInterceptor("token")))

_, err = client.ListWorkspaces(ctx, connect.NewRequest(&v1.ListWorkspacesRequest{}))
require.Equal(t, connect.CodeUnimplemented.String(), connect.CodeOf(err).String())
Expand Down Expand Up @@ -158,3 +159,42 @@ func requireErrorStatusCode(t *testing.T, expected codes.Code, err error) {
require.True(t, ok)
require.Equalf(t, expected, st.Code(), "expected: %s but got: %s", expected.String(), st.String())
}

func TestConnectWorkspaceService_RequiresAuth(t *testing.T) {
srv := baseserver.NewForTests(t,
baseserver.WithHTTP(baseserver.MustUseRandomLocalAddress(t)),
baseserver.WithGRPC(baseserver.MustUseRandomLocalAddress(t)),
)

gitpodAPI, err := url.Parse("wss://main.preview.gitpod-dev.com/api/v1")
require.NoError(t, err)

require.NoError(t, register(srv, gitpodAPI))

baseserver.StartServerForTests(t, srv)

clientWithoutAuth := v1connect.NewWorkspacesServiceClient(http.DefaultClient, srv.HTTPAddress())
_, err = clientWithoutAuth.GetWorkspace(context.Background(), connect.NewRequest(&v1.GetWorkspaceRequest{WorkspaceId: "123"}))
require.Error(t, err)
require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))

}

func TestConnectPrebuildsService_RequiresAuth(t *testing.T) {
srv := baseserver.NewForTests(t,
baseserver.WithHTTP(baseserver.MustUseRandomLocalAddress(t)),
baseserver.WithGRPC(baseserver.MustUseRandomLocalAddress(t)),
)

gitpodAPI, err := url.Parse("wss://main.preview.gitpod-dev.com/api/v1")
require.NoError(t, err)

require.NoError(t, register(srv, gitpodAPI))

baseserver.StartServerForTests(t, srv)

clientWithoutAuth := v1connect.NewPrebuildsServiceClient(http.DefaultClient, srv.HTTPAddress())
_, err = clientWithoutAuth.GetPrebuild(context.Background(), connect.NewRequest(&v1.GetPrebuildRequest{PrebuildId: "123"}))
require.Error(t, err)
require.Equal(t, connect.CodeUnauthenticated, connect.CodeOf(err))
}
Loading