-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (78 loc) · 2.27 KB
/
main.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"log"
"net"
"strings"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
auth "github.com/envoyproxy/go-control-plane/envoy/service/auth/v2"
envoy_type "github.com/envoyproxy/go-control-plane/envoy/type"
"github.com/gogo/googleapis/google/rpc"
"google.golang.org/grpc"
)
// empty struct because this isn't a fancy example
type AuthorizationServer struct{}
// inject a header that can be used for future rate limiting
func (a *AuthorizationServer) Check(ctx context.Context, req *auth.CheckRequest) (*auth.CheckResponse, error) {
authHeader, ok := req.Attributes.Request.Http.Headers["authorization"]
var splitToken []string
if ok {
splitToken = strings.Split(authHeader, "Bearer ")
}
if len(splitToken) == 2 {
token := splitToken[1]
sha := sha256.New()
sha.Write([]byte(token))
tokenSha := base64.StdEncoding.EncodeToString(sha.Sum(nil))
// valid tokens have exactly 3 characters. #secure.
// Normally this is where you'd go check with the system that knows if it's a valid token.
if len(token) == 3 {
return &auth.CheckResponse{
Status: &rpc.Status{
Code: int32(rpc.OK),
},
HttpResponse: &auth.CheckResponse_OkResponse{
OkResponse: &auth.OkHttpResponse{
Headers: []*core.HeaderValueOption{
{
Header: &core.HeaderValue{
Key: "x-ext-auth-ratelimit",
Value: tokenSha,
},
},
},
},
},
}, nil
}
}
return &auth.CheckResponse{
Status: &rpc.Status{
Code: int32(rpc.UNAUTHENTICATED),
},
HttpResponse: &auth.CheckResponse_DeniedResponse{
DeniedResponse: &auth.DeniedHttpResponse{
Status: &envoy_type.HttpStatus{
Code: envoy_type.StatusCode_Unauthorized,
},
Body: "Need an Authorization Header with a 3 character bearer token! #secure",
},
},
}, nil
}
func main() {
// create a TCP listener on port 4000
lis, err := net.Listen("tcp", ":4000")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Printf("listening on %s", lis.Addr())
grpcServer := grpc.NewServer()
authServer := &AuthorizationServer{}
auth.RegisterAuthorizationServer(grpcServer, authServer)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}