aboutsummaryrefslogtreecommitdiff
path: root/server/rpc.go
blob: 2d022186de5051809f56212995cf5889229c8a7c (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package server

import (
	"log"
	"net"

	"golang.org/x/net/context"

	"golang.org/x/oauth2"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"

	"github.com/nsheridan/cashier/lib"
	"github.com/nsheridan/cashier/proto"
)

type rpcServer struct{}

type key int

const usernameKey key = 0

func (s *rpcServer) Sign(ctx context.Context, req *proto.SignRequest) (*proto.SignResponse, error) {
	username, ok := ctx.Value(usernameKey).(string)
	if !ok {
		return nil, grpc.Errorf(codes.InvalidArgument, "Error reading username")
	}
	cert, err := keysigner.SignUserKeyFromRPC(req, username)
	if err != nil {
		return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
	}
	if err := certstore.SetCert(cert); err != nil {
		log.Printf("Error recording cert: %v", err)
	}
	resp := &proto.SignResponse{
		Cert: lib.GetPublicKey(cert),
	}
	return resp, nil
}

func authInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok {
		return nil, grpc.Errorf(codes.Unauthenticated, "request not authenticated")
	}
	switch md["security"][0] {
	case "authorization":
		token := &oauth2.Token{
			AccessToken: md["payload"][0],
		}
		if !authprovider.Valid(token) {
			return nil, grpc.Errorf(codes.PermissionDenied, "access denied")
		}
		ctx = context.WithValue(ctx, usernameKey, authprovider.Username(token))
		authprovider.Revoke(token)
	default:
		return nil, grpc.Errorf(codes.InvalidArgument, "unknown argument")
	}
	return handler(ctx, req)
}

func runGRPCServer(l net.Listener) {
	serv := grpc.NewServer(grpc.UnaryInterceptor(authInterceptor))
	proto.RegisterSignerServer(serv, &rpcServer{})
	serv.Serve(l)
}