summaryrefslogtreecommitdiff
path: root/internal/stub/check.go
blob: 073b35bb51ee7a282e6b3d4dd328dddfd06a63ac (plain)
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
package stub

import (
	"context"
	"strings"
	"testing"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/authz"
	"google.golang.org/grpc"
)

type Check func(context.Context, *v1.CheckPermissionRequest) (*v1.CheckPermissionResponse, error)

func (m Check) CheckPermission(ctx context.Context, r *v1.CheckPermissionRequest, opts ...grpc.CallOption) (*v1.CheckPermissionResponse, error) {
	return m(ctx, r)
}

func AllowWith(t *testing.T, subject string, permission string, resource string) authz.CheckPermissionService {
	user := strings.SplitN(subject, ":", 2)
	model := strings.SplitN(resource, ":", 2)

	return Check(func(ctx context.Context, r *v1.CheckPermissionRequest) (*v1.CheckPermissionResponse, error) {
		require.Equal(t, user[0], r.Subject.Object.ObjectType)
		require.Equal(t, user[1], r.Subject.Object.ObjectId)

		require.Equal(t, permission, r.Permission)

		require.Equal(t, model[0], r.Resource.ObjectType)
		require.Equal(t, model[1], r.Resource.ObjectId)

		return &v1.CheckPermissionResponse{
			Permissionship: v1.CheckPermissionResponse_PERMISSIONSHIP_HAS_PERMISSION,
		}, nil
	})
}

func Allow() authz.CheckPermissionService {
	return Check(func(ctx context.Context, r *v1.CheckPermissionRequest) (*v1.CheckPermissionResponse, error) {
		return &v1.CheckPermissionResponse{
			Permissionship: v1.CheckPermissionResponse_PERMISSIONSHIP_HAS_PERMISSION,
		}, nil
	})
}

func Deny() authz.CheckPermissionService {
	return Check(func(ctx context.Context, r *v1.CheckPermissionRequest) (*v1.CheckPermissionResponse, error) {
		return &v1.CheckPermissionResponse{
			Permissionship: v1.CheckPermissionResponse_PERMISSIONSHIP_NO_PERMISSION,
		}, nil
	})
}