File: auth_test.go

package info (click to toggle)
vagrant 2.3.7%2Bgit20230731.5fc64cde%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 17,616 kB
  • sloc: ruby: 111,820; sh: 462; makefile: 123; ansic: 34; lisp: 1
file content (57 lines) | stat: -rw-r--r-- 1,168 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package server

import (
	"context"
	"testing"

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

type trivialAuth struct {
	method  string
	token   string
	effects []string
}

// Called before each RPC to authenticate it.
func (t *trivialAuth) Authenticate(ctx context.Context, token string, endpoint string, effects []string) error {
	t.method = endpoint
	t.token = token
	t.effects = effects
	return nil
}

func TestAuthUnaryInterceptor(t *testing.T) {
	require := require.New(t)

	var chk trivialAuth

	f := authUnaryInterceptor(&chk)

	ctx := context.Background()

	tokenVal := "this-is-a-token"

	ctx = metadata.NewIncomingContext(ctx, metadata.MD{
		"authorization": []string{tokenVal},
	})

	// Empty context
	called := false
	resp, err := f(ctx, nil, &grpc.UnaryServerInfo{FullMethod: "/foo/bar"},
		func(ctx context.Context, req interface{}) (interface{}, error) {
			called = true
			return "hello", nil
		},
	)

	require.True(called)
	require.Equal("hello", resp)
	require.NoError(err)

	require.Equal(tokenVal, chk.token)
	require.Equal("bar", chk.method)
	require.Equal(DefaultEffects, chk.effects)
}