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

Authentication processor 2/4 - Add auth context and interface #1808

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
17 changes: 17 additions & 0 deletions config/configauth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Authentication configuration for receivers

This module allows server types, such as gRPC and HTTP, to be configured to perform authentication for requests and/or RPCs. Each server type is responsible for getting the request/RPC metadata and passing down to the authenticator. Currently, only bearer token authentication is supported, although the module is ready to accept new authenticators.

Examples:
```yaml
receivers:
somereceiver:
grpc:
authentication:
attribute: authorization
oidc:
issuer_url: https://auth.example.com/
issuer_ca_path: /etc/pki/tls/cert.pem
client_id: my-oidc-client
username_claim: email
```
49 changes: 49 additions & 0 deletions config/configauth/configauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright The OpenTelemetry Authors
//
// 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 configauth

// Authentication defines the auth settings for the receiver
type Authentication struct {
// The attribute (header name) to look for auth data. Optional, default value: "authentication".
Attribute string `mapstructure:"attribute"`

// OIDC configures this receiver to use the given OIDC provider as the backend for the authentication mechanism.
// Required.
OIDC *OIDC `mapstructure:"oidc"`
}

// OIDC defines the OpenID Connect properties for this processor
type OIDC struct {
// IssuerURL is the base URL for the OIDC provider.
// Required.
IssuerURL string `mapstructure:"issuer_url"`

// Audience of the token, used during the verification.
// For example: "https://accounts.google.com" or "https://login.salesforce.com".
// Required.
Audience string `mapstructure:"audience"`

// The local path for the issuer CA's TLS server cert.
// Optional.
IssuerCAPath string `mapstructure:"issuer_ca_path"`

// The claim to use as the username, in case the token's 'sub' isn't the suitable source.
// Optional.
UsernameClaim string `mapstructure:"username_claim"`

// The claim that holds the subject's group membership information.
// Optional.
GroupsClaim string `mapstructure:"groups_claim"`
}
15 changes: 15 additions & 0 deletions config/configauth/empty_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright The OpenTelemetry Authors
//
// 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 configauth
95 changes: 95 additions & 0 deletions internal/auth/authenticator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright The OpenTelemetry Authors
//
// 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 auth
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this file be in config/configauth/internal/?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only the interface, or the whole package? In any case, I would prefer to keep the config package clean from the implementation, as seems to be the case today.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's why I am suggesting an internal package inside the configauth which will not be exported. But this way we have localization, the current internal/auth is only used by configauth

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Except that the gRPC and HTTP receivers will use a default implementation for the interceptors/handlers, also located in this package.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, let's move forward with this (I don't believe that we cannot just have it in the internal here). But let's see.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll collect the non-blocking comments in an issue, so that I can solve them in a follow-up PR. To be honest, my biggest contention right now in changing this PR is in rebasing the other two PRs again.

Copy link
Member Author

@jpkrohling jpkrohling Sep 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tracker: #1824


import (
"context"
"errors"
"io"

"google.golang.org/grpc"
"google.golang.org/grpc/metadata"

"go.opentelemetry.io/collector/config/configauth"
)

var (
errNoOIDCProvided = errors.New("no OIDC information provided")
errMetadataNotFound = errors.New("no request metadata found")
errNotImplemented = errors.New("not implemented")
defaultAttribute = "authorization"
)

// Authenticator will authenticate the incoming request/RPC
type Authenticator interface {
io.Closer

// Authenticate checks whether the given context contains valid auth data. Successfully authenticated calls will always return a nil error and a context with the auth data.
Authenticate(context.Context, map[string][]string) (context.Context, error)

// Start will
Start(context.Context) error

// UnaryInterceptor is a helper method to provide a gRPC-compatible UnaryInterceptor, typically calling the authenticator's Authenticate method.
UnaryInterceptor(context.Context, interface{}, *grpc.UnaryServerInfo, grpc.UnaryHandler) (interface{}, error)

// StreamInterceptor is a helper method to provide a gRPC-compatible StreamInterceptor, typically calling the authenticator's Authenticate method.
StreamInterceptor(interface{}, grpc.ServerStream, *grpc.StreamServerInfo, grpc.StreamHandler) error
}

type authenticateFunc func(context.Context, map[string][]string) (context.Context, error)

// New creates an authenticator based on the given configuration
func New(cfg configauth.Authentication) (Authenticator, error) {
if cfg.OIDC == nil {
return nil, errNoOIDCProvided
}

if len(cfg.Attribute) == 0 {
cfg.Attribute = defaultAttribute
}

return nil, errNotImplemented
}

func defaultUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, authenticate authenticateFunc) (interface{}, error) {
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errMetadataNotFound
}

ctx, err := authenticate(ctx, headers)
if err != nil {
return nil, err
}

return handler(ctx, req)
}

func defaultStreamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, authenticate authenticateFunc) error {
ctx := stream.Context()
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return errMetadataNotFound
}

// TODO: how to replace the context from the stream?
_, err := authenticate(ctx, headers)
if err != nil {
return err
}

return handler(srv, stream)
}
197 changes: 197 additions & 0 deletions internal/auth/authenticator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
// Copyright The OpenTelemetry Authors
//
// 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 auth

import (
"context"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"

"go.opentelemetry.io/collector/config/configauth"
)

func TestNew(t *testing.T) {
// test
p, err := New(configauth.Authentication{
OIDC: &configauth.OIDC{
Audience: "some-audience",
IssuerURL: "http://example.com",
},
})

// verify
assert.Nil(t, p)
assert.Equal(t, errNotImplemented, err)
}

func TestMissingOIDC(t *testing.T) {
// test
p, err := New(configauth.Authentication{})

// verify
assert.Nil(t, p)
assert.Equal(t, errNoOIDCProvided, err)
}

func TestDefaultUnaryInterceptorAuthSucceeded(t *testing.T) {
// prepare
handlerCalled := false
authCalled := false
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
authCalled = true
return context.Background(), nil
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handlerCalled = true
return nil, nil
}
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "some-auth-data"))

// test
res, err := defaultUnaryInterceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler, authFunc)

// verify
assert.Nil(t, res)
assert.NoError(t, err)
assert.True(t, authCalled)
assert.True(t, handlerCalled)
}

func TestDefaultUnaryInterceptorAuthFailure(t *testing.T) {
// prepare
authCalled := false
expectedErr := fmt.Errorf("not authenticated")
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
authCalled = true
return context.Background(), expectedErr
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
assert.FailNow(t, "the handler should not have been called on auth failure!")
return nil, nil
}
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "some-auth-data"))

// test
res, err := defaultUnaryInterceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler, authFunc)

// verify
assert.Nil(t, res)
assert.Equal(t, expectedErr, err)
assert.True(t, authCalled)
}

func TestDefaultUnaryInterceptorMissingMetadata(t *testing.T) {
// prepare
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
assert.FailNow(t, "the auth func should not have been called!")
return context.Background(), nil
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
assert.FailNow(t, "the handler should not have been called!")
return nil, nil
}

// test
res, err := defaultUnaryInterceptor(context.Background(), nil, &grpc.UnaryServerInfo{}, handler, authFunc)

// verify
assert.Nil(t, res)
assert.Equal(t, errMetadataNotFound, err)
}

func TestDefaultStreamInterceptorAuthSucceeded(t *testing.T) {
// prepare
handlerCalled := false
authCalled := false
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
authCalled = true
return context.Background(), nil
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
handlerCalled = true
return nil
}
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "some-auth-data"))
streamServer := &mockServerStream{
ctx: ctx,
}

// test
err := defaultStreamInterceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler, authFunc)

// verify
assert.NoError(t, err)
assert.True(t, authCalled)
assert.True(t, handlerCalled)
}

func TestDefaultStreamInterceptorAuthFailure(t *testing.T) {
// prepare
authCalled := false
expectedErr := fmt.Errorf("not authenticated")
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
authCalled = true
return context.Background(), expectedErr
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
assert.FailNow(t, "the handler should not have been called on auth failure!")
return nil
}
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "some-auth-data"))
streamServer := &mockServerStream{
ctx: ctx,
}

// test
err := defaultStreamInterceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler, authFunc)

// verify
assert.Equal(t, expectedErr, err)
assert.True(t, authCalled)
}

func TestDefaultStreamInterceptorMissingMetadata(t *testing.T) {
// prepare
authFunc := func(context.Context, map[string][]string) (context.Context, error) {
assert.FailNow(t, "the auth func should not have been called!")
return context.Background(), nil
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
assert.FailNow(t, "the handler should not have been called!")
return nil
}
streamServer := &mockServerStream{
ctx: context.Background(),
}

// test
err := defaultStreamInterceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler, authFunc)

// verify
assert.Equal(t, errMetadataNotFound, err)
}

type mockServerStream struct {
grpc.ServerStream
ctx context.Context
}

func (m *mockServerStream) Context() context.Context {
return m.ctx
}
Loading