This repository has been archived by the owner on Sep 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
grpc-auth.go
257 lines (218 loc) · 6.4 KB
/
grpc-auth.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package services
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
// "os"
"strconv"
"strings"
core "github.com/datawire/ambassador/go/apis/envoy/api/v2/core"
pb_legacy "github.com/datawire/ambassador/go/apis/envoy/service/auth/v2alpha"
pb "github.com/datawire/ambassador/go/apis/envoy/service/auth/v2"
envoy_type "github.com/datawire/ambassador/go/apis/envoy/type"
"github.com/gogo/googleapis/google/rpc"
gogo_type "github.com/gogo/protobuf/types"
"google.golang.org/grpc"
)
// GRPCAUTH server object (all fields are required).
type GRPCAUTH struct {
Port int16
Backend string
SecurePort int16
SecureBackend string
Cert string
Key string
}
// Start initializes the HTTP server.
func (g *GRPCAUTH) Start() <-chan bool {
log.Printf("GRPCAUTH: %s listening on %d/%d", g.Backend, g.Port, g.SecurePort)
exited := make(chan bool)
proto := "tcp"
go func() {
port := fmt.Sprintf(":%v", g.Port)
ln, err := net.Listen(proto, port)
if err != nil {
log.Fatal()
}
s := grpc.NewServer()
pb_legacy.RegisterAuthorizationServer(s, g)
s.Serve(ln)
defer ln.Close()
close(exited)
}()
go func() {
cer, err := tls.LoadX509KeyPair(g.Cert, g.Key)
if err != nil {
log.Fatal(err)
return
}
config := &tls.Config{Certificates: []tls.Certificate{cer}}
port := fmt.Sprintf(":%v", g.SecurePort)
ln, err := tls.Listen(proto, port, config)
if err != nil {
log.Fatal(err)
return
}
s := grpc.NewServer()
pb_legacy.RegisterAuthorizationServer(s, g)
s.Serve(ln)
defer ln.Close()
close(exited)
}()
log.Print("starting gRPC authorization service")
return exited
}
// Check checks the request object.
func (g *GRPCAUTH) Check(ctx context.Context, r *pb.CheckRequest) (*pb.CheckResponse, error) {
rs := &Response{}
rheader := r.GetAttributes().GetRequest().GetHttp().GetHeaders()
rbody := r.GetAttributes().GetRequest().GetHttp().GetBody()
if len(rbody) > 0 {
rheader["body"] = rbody
}
// Sets requested HTTP status.
rs.SetStatus(rheader["requested-status"])
// Sets requested headers.
for _, key := range strings.Split(rheader["requested-header"], ",") {
if val := rheader[key]; len(val) > 0 {
rs.AddHeader(false, key, val)
}
}
// Append requested headers.
for _, token := range strings.Split(rheader["x-grpc-auth-append"], ";") {
header := strings.Split(strings.TrimSpace(token), "=")
if len(header) > 1 {
log.Printf("appending header %s : %s", header[0], header[1])
rs.AddHeader(true, header[0], header[1])
}
}
// Sets requested Cookies.
for _, v := range strings.Split(rheader["requested-cookie"], ",") {
val := strings.Trim(v, " ")
rs.AddHeader(false, "Set-Cookie", fmt.Sprintf("%s=%s", val, val))
}
// Sets requested location.
if len(rheader["requested-location"]) > 0 {
rs.AddHeader(false, "Location", rheader["requested-location"])
}
// Parses request headers.
headers := make(map[string]interface{})
for k, v := range rheader {
headers[k] = strings.Split(v, ",")
}
// Parses request URL.
url := make(map[string]interface{})
url["fragment"] = r.GetAttributes().GetRequest().GetHttp().GetFragment()
url["host"] = r.GetAttributes().GetRequest().GetHttp().GetHost()
url["path"] = r.GetAttributes().GetRequest().GetHttp().GetPath()
url["query"] = r.GetAttributes().GetRequest().GetHttp().GetQuery()
url["scheme"] = r.GetAttributes().GetRequest().GetHttp().GetScheme()
// Parses TLS info.
tls := make(map[string]interface{})
tls["enabled"] = false
// Sets request portion of the results body.
request := make(map[string]interface{})
request["url"] = url
request["method"] = r.GetAttributes().GetRequest().GetHttp().GetMethod()
request["headers"] = headers
request["host"] = r.GetAttributes().GetRequest().GetHttp().GetHost()
request["tls"] = tls
// Sets results body.
results := make(map[string]interface{})
results["backend"] = g.Backend
results["status"] = rs.GetStatus()
if len(request) > 0 {
results["request"] = request
}
if rs.GetHTTPHeaderMap() != nil {
results["headers"] = *rs.GetHTTPHeaderMap()
}
body, err := json.MarshalIndent(results, "", " ")
if err != nil {
body = []byte(fmt.Sprintf("Error: %v", err))
}
// Sets response body.
log.Printf("setting response body: %s", string(body))
rs.SetBody(string(body))
return rs.GetResponse(), nil
}
// Response constructs an authorization response object.
type Response struct {
headers []*core.HeaderValueOption
body string
status uint32
}
// AddHeader adds a header to the response. When append param is true, Envoy will
// append the value to an existent request header instead of overriding it.
func (r *Response) AddHeader(a bool, k, v string) {
val := &core.HeaderValueOption{
Header: &core.HeaderValue{
Key: k,
Value: v,
},
Append: &gogo_type.BoolValue{Value: a},
}
r.headers = append(r.headers, val)
}
// GetHTTPHeaderMap returns HTTP header mapping of the response header-options.
func (r *Response) GetHTTPHeaderMap() *http.Header {
h := &http.Header{}
for _, v := range r.headers {
h.Add(v.Header.Key, v.Header.Value)
}
return h
}
// SetBody sets the authorization response message body.
func (r *Response) SetBody(s string) {
r.body = s
}
// SetStatus sets the authorization response HTTP status code.
func (r *Response) SetStatus(s string) {
if len(s) == 0 {
s = "200"
}
if val, err := strconv.Atoi(s); err == nil {
r.status = uint32(val)
r.AddHeader(false, "status", s)
log.Printf("setting HTTP status %v", r.status)
} else {
r.status = uint32(500)
r.AddHeader(false, "status", "500")
log.Printf("error setting HTTP status. Cannot parse string %s: %v.", s, err)
}
}
// GetStatus returns the authorization response HTTP status code.
func (r *Response) GetStatus() uint32 {
return r.status
}
// GetResponse returns the gRPC authorization response object.
func (r *Response) GetResponse() *pb.CheckResponse {
rs := &pb.CheckResponse{}
switch {
// Ok respose.
case r.status == 200 || r.status == 0:
rs.Status = &rpc.Status{Code: int32(0)}
rs.HttpResponse = &pb.CheckResponse_OkResponse{
OkResponse: &pb.OkHttpResponse{
Headers: r.headers,
},
}
// Denied response.
default:
rs.Status = &rpc.Status{Code: int32(16)}
rs.HttpResponse = &pb.CheckResponse_DeniedResponse{
DeniedResponse: &pb.DeniedHttpResponse{
Status: &envoy_type.HttpStatus{
Code: envoy_type.StatusCode(r.status),
},
Headers: r.headers,
Body: r.body,
},
}
}
return rs
}