github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/auth/presharedkey_test.go (about)

     1  package auth
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/authzed/grpcutil"
     8  	metautils "github.com/grpc-ecosystem/go-grpc-middleware/v2/metadata"
     9  	"github.com/stretchr/testify/require"
    10  	"google.golang.org/grpc/codes"
    11  	"google.golang.org/grpc/metadata"
    12  )
    13  
    14  func TestPresharedKeys(t *testing.T) {
    15  	testcases := []struct {
    16  		name           string
    17  		presharedkeys  []string
    18  		withMetadata   bool
    19  		authzHeader    string
    20  		expectedStatus codes.Code
    21  	}{
    22  		{"valid request with the first key", []string{"one", "two"}, true, "bearer one", codes.OK},
    23  		{"valid request with the second key", []string{"one", "two"}, true, "bearer two", codes.OK},
    24  		{"denied due to unknown key", []string{"one", "two"}, true, "bearer three", codes.PermissionDenied},
    25  		{"unauthenticated due to missing key", []string{"one", "two"}, true, "bearer ", codes.Unauthenticated},
    26  		{"unauthenticated due to empty header", []string{"one", "two"}, true, "", codes.Unauthenticated},
    27  		{"unauthenticated due to missing metadata", []string{"one", "two"}, false, "", codes.Unauthenticated},
    28  	}
    29  
    30  	for _, testcase := range testcases {
    31  		testcase := testcase
    32  		t.Run(testcase.name, func(t *testing.T) {
    33  			f := MustRequirePresharedKey(testcase.presharedkeys)
    34  			ctx := context.Background()
    35  			if testcase.withMetadata {
    36  				ctx = withTokenMetadata(testcase.authzHeader)
    37  			}
    38  			_, err := f(ctx)
    39  			if testcase.expectedStatus != codes.OK {
    40  				require.Error(t, err)
    41  				grpcutil.RequireStatus(t, testcase.expectedStatus, err)
    42  			} else {
    43  				require.NoError(t, err)
    44  			}
    45  		})
    46  	}
    47  }
    48  
    49  func withTokenMetadata(authzHeader string) context.Context {
    50  	md := metadata.Pairs("authorization", authzHeader)
    51  	return metautils.MD(md).ToIncoming(context.Background())
    52  }