summaryrefslogtreecommitdiff
path: root/pkg/authz/server.go
blob: 24d6b0cf28723394534c2fca2548b9523a0f90d3 (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
package authz

import (
	"context"

	auth "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
	xcontext "github.com/xlgmokha/x/pkg/context"
	"github.com/xlgmokha/x/pkg/log"
	"github.com/xlgmokha/x/pkg/x"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var Connection xcontext.Key[*grpc.ClientConn] = xcontext.Key[*grpc.ClientConn]("grpc_client")

type Server struct {
	*grpc.Server
}

func New(ctx context.Context, options ...grpc.ServerOption) *Server {
	logger := log.From(ctx)

	server := grpc.NewServer(x.Prepend(
		options,
		grpc.UnaryInterceptor(pls.LogGRPC(logger)),
		grpc.StreamInterceptor(pls.LogGRPCStream(logger)),
	)...)

	connection := Connection.From(ctx)

	if x.IsZero(connection) {
		auth.RegisterAuthorizationServer(server, NewCheckService(nil))
	} else {
		pls.LogNow(ctx, log.Fields{"authzd": map[string]string{
			"target": connection.CanonicalTarget(),
			"state":  connection.GetState().String(),
		}})
		auth.RegisterAuthorizationServer(
			server,
			NewCheckService(
				auth.NewAuthorizationClient(connection),
			),
		)
	}
	reflection.Register(server)

	return &Server{
		Server: server,
	}
}