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

Added PerRPCCredentials for gRPC settings #1250

Merged
merged 4 commits into from
Jul 15, 2020
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
46 changes: 46 additions & 0 deletions config/configgrpc/bearer_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2020 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 configgrpc

import (
"context"
"fmt"

"google.golang.org/grpc/credentials"
)

var _ credentials.PerRPCCredentials = (*PerRPCAuth)(nil)

// PerRPCAuth is a gRPC credentials.PerRPCCredentials implementation that returns an 'authorization' header.
type PerRPCAuth struct {
metadata map[string]string
}

// BearerToken returns a new PerRPCAuth based on the given token.
func BearerToken(t string) *PerRPCAuth {
return &PerRPCAuth{
metadata: map[string]string{"authorization": fmt.Sprintf("Bearer %s", t)},
}
}

// GetRequestMetadata returns the request metadata to be used with the RPC.
func (c *PerRPCAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return c.metadata, nil
}

// RequireTransportSecurity always returns true for this implementation. Passing bearer tokens in plain-text connections is a bad idea.
func (c *PerRPCAuth) RequireTransportSecurity() bool {
return true
}
41 changes: 41 additions & 0 deletions config/configgrpc/bearer_token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// 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 configgrpc

import (
"context"
"testing"

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

func TestBearerToken(t *testing.T) {
// test
result := BearerToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
metadata, err := result.GetRequestMetadata(context.Background())
require.NoError(t, err)

// verify
assert.Equal(t, "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", metadata["authorization"])
}

func TestBearerTokenRequiresSecureTransport(t *testing.T) {
// test
token := BearerToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")

// verify
assert.True(t, token.RequireTransportSecurity())
}
24 changes: 24 additions & 0 deletions config/configgrpc/configgrpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import (
const (
CompressionUnsupported = ""
CompressionGzip = "gzip"

PerRPCAuthTypeBearer = "bearer"
)

var (
Expand Down Expand Up @@ -84,13 +86,25 @@ type GRPCClientSettings struct {

// The headers associated with gRPC requests.
Headers map[string]string `mapstructure:"headers"`

// PerRPCAuth parameter configures the client to send authentication data on a per-RPC basis.
PerRPCAuth *PerRPCAuthConfig `mapstructure:"per_rpc_auth"`
}

type KeepaliveServerConfig struct {
ServerParameters *KeepaliveServerParameters `mapstructure:"server_parameters,omitempty"`
EnforcementPolicy *KeepaliveEnforcementPolicy `mapstructure:"enforcement_policy,omitempty"`
}

// PerRPCAuthConfig specifies how the Per-RPC authentication data should be obtained.
type PerRPCAuthConfig struct {
// AuthType represents the authentication type to use. Currently, only 'bearer' is supported.
AuthType string `mapstructure:"type,omitempty"`

// BearerToken specifies the bearer token to use for every RPC.
BearerToken string `mapstructure:"bearer_token,omitempty"`
}

// KeepaliveServerParameters allow configuration of the keepalive.ServerParameters.
// The same default values as keepalive.ServerParameters are applicable and get applied by the server.
// See https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters for details.
Expand Down Expand Up @@ -176,6 +190,16 @@ func (gcs *GRPCClientSettings) ToDialOptions() ([]grpc.DialOption, error) {
opts = append(opts, keepAliveOption)
}

if gcs.PerRPCAuth != nil {
if strings.EqualFold(gcs.PerRPCAuth.AuthType, PerRPCAuthTypeBearer) {
sToken := gcs.PerRPCAuth.BearerToken
token := BearerToken(sToken)
opts = append(opts, grpc.WithPerRPCCredentials(token))
} else {
return nil, fmt.Errorf("unsupported per-RPC auth type %q", gcs.PerRPCAuth.AuthType)
}
jpkrohling marked this conversation as resolved.
Show resolved Hide resolved
}

return opts, nil
}

Expand Down
32 changes: 32 additions & 0 deletions config/configgrpc/configgrpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func TestAllGrpcClientSettings(t *testing.T) {
ReadBufferSize: 1024,
WriteBufferSize: 1024,
WaitForReady: true,
PerRPCAuth: nil,
}
opts, err := gcs.ToDialOptions()
assert.NoError(t, err)
Expand Down Expand Up @@ -158,6 +159,7 @@ func TestUseSecure(t *testing.T) {
Compression: "",
TLSSetting: configtls.TLSClientSetting{},
Keepalive: nil,
PerRPCAuth: nil,
}
dialOpts, err := gcs.ToDialOptions()
assert.NoError(t, err)
Expand Down Expand Up @@ -443,3 +445,33 @@ type grpcTraceServer struct{}
func (gts *grpcTraceServer) Export(context.Context, *otelcol.ExportTraceServiceRequest) (*otelcol.ExportTraceServiceResponse, error) {
return &otelcol.ExportTraceServiceResponse{}, nil
}

func TestWithPerRPCAuthBearerToken(t *testing.T) {
// prepare
// test
gcs := &GRPCClientSettings{
PerRPCAuth: &PerRPCAuthConfig{
AuthType: "bearer",
BearerToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
},
}
dialOpts, err := gcs.ToDialOptions()

// verify
assert.NoError(t, err)
assert.Len(t, dialOpts, 2) // WithInsecure and WithPerRPCCredentials
}

func TestWithPerRPCAuthInvalidAuthType(t *testing.T) {
// test
gcs := &GRPCClientSettings{
PerRPCAuth: &PerRPCAuthConfig{
AuthType: "non-existing",
},
}
dialOpts, err := gcs.ToDialOptions()

// verify
assert.Error(t, err)
assert.Nil(t, dialOpts)
}
4 changes: 4 additions & 0 deletions exporter/otlpexporter/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ func TestLoadConfig(t *testing.T) {
Timeout: 30 * time.Second,
},
WriteBufferSize: 512 * 1024,
PerRPCAuth: &configgrpc.PerRPCAuthConfig{
AuthType: "bearer",
BearerToken: "some-token",
},
},
})
}
3 changes: 3 additions & 0 deletions exporter/otlpexporter/testdata/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ exporters:
endpoint: "1.2.3.4:1234"
compression: "on"
ca_file: /var/lib/mycert.pem
per_rpc_auth:
type: bearer
bearer_token: some-token
headers:
"can you have a . here?": "F0000000-0000-0000-0000-000000000000"
header1: 234
Expand Down