-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathserver.go
213 lines (182 loc) · 5.28 KB
/
server.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
// gRPC server to be used only for automated integration testing.
package main
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/x509"
"flag"
"fmt"
"log"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"time"
"github.com/WICG/webpackage/go/signedexchange"
"github.com/WICG/webpackage/go/signedexchange/certurl"
pb "github.com/ampproject/amppackager/cmd/gateway_server/gateway"
"github.com/ampproject/amppackager/packager/rtv"
"github.com/ampproject/amppackager/packager/signer"
"github.com/ampproject/amppackager/packager/util"
"golang.org/x/crypto/ocsp"
"google.golang.org/grpc"
)
var (
port = flag.Int("port", 9000, "Gateway server port")
publisherServerPort = flag.Int("publisher_server_port", 10000,
"Publisher server port.")
)
type gatewayServer struct {
rtvCache *rtv.RTVCache
}
func shouldPackage() bool {
return true
}
func errorToSXGResponse(err error) *pb.SXGResponse {
response := &pb.SXGResponse{
Error: true,
ErrorDescription: err.Error(),
}
return response
}
func createOCSPResponse(cert *x509.Certificate, key crypto.Signer) ([]byte, error) {
thisUpdate := time.Now()
// Construct args to ocsp.CreateResponse.
template := ocsp.Response{
SerialNumber: cert.SerialNumber,
Status: ocsp.Good,
ThisUpdate: thisUpdate,
NextUpdate: thisUpdate.Add(time.Hour * 24 * 7),
IssuerHash: crypto.SHA256,
}
return ocsp.CreateResponse(cert /*issuer*/, cert /*responderCert*/, template, key)
}
func (s *gatewayServer) GenerateSXG(ctx context.Context, request *pb.SXGRequest) (*pb.SXGResponse, error) {
log.Println("Handling request with fetchUrl =", request.FetchUrl, "; signUrl =", request.SignUrl)
certs, err := signedexchange.ParseCertificates(request.PublicCert)
if err != nil {
return errorToSXGResponse(err), nil
}
privateKey, err := util.ParsePrivateKey(request.PrivateKey)
if err != nil {
return errorToSXGResponse(err), nil
}
signUrl, err := url.Parse(request.SignUrl)
if err != nil {
return errorToSXGResponse(err), nil
}
var dotStarPattern = ".*"
signUrlPattern := util.URLPattern{
Domain: signUrl.Host,
QueryRE: &dotStarPattern,
}
err = util.ValidateSignURLPattern(&signUrlPattern)
if err != nil {
return errorToSXGResponse(err), nil
}
fetchUrlPattern := util.URLPattern{
Scheme: []string{"http"},
Domain: fmt.Sprintf("localhost:%d", *publisherServerPort),
ErrorOnStatefulHeaders: false,
QueryRE: &dotStarPattern,
SamePath: new(bool),
}
*fetchUrlPattern.SamePath = false
err = util.ValidateFetchURLPattern(&fetchUrlPattern)
if err != nil {
return errorToSXGResponse(err), nil
}
urlSets := []util.URLSet{
{
Sign: &signUrlPattern,
Fetch: &fetchUrlPattern,
},
}
packager, err := signer.New(certs[0], privateKey, urlSets, s.rtvCache, shouldPackage, signUrl, false, []string{})
if err != nil {
return errorToSXGResponse(err), nil
}
if packager == nil {
return errorToSXGResponse(err), nil
}
baseUrl, err := url.Parse(fmt.Sprintf("http://localhost:%d", *port))
if err != nil {
return errorToSXGResponse(err), nil
}
q := baseUrl.Query()
q.Set("fetch", request.FetchUrl)
q.Set("sign", request.SignUrl)
baseUrl.RawQuery = q.Encode()
httpreq, err := http.NewRequest("GET", baseUrl.String(), nil)
httpresp := httptest.NewRecorder()
packager.ServeHTTP(httpresp, httpreq)
// TODO(amaltas): Capture error when signer returns unsigned document.
if httpresp.Code != 200 {
// TODO(amaltas): Add counter.
return &pb.SXGResponse{
Error: true,
ErrorDescription: "Packager error.",
}, nil
}
// Create cert-chain+cbor.
var ocspDer []byte
if len(certs) > 1 {
// Attach an OCSP response, signed with the second cert in the
// chain (assumed to be the issuer and using the same private
// key as the leaf cert).
var err error
ocspDer, err = createOCSPResponse(certs[1], privateKey.(*ecdsa.PrivateKey))
if err != nil {
return errorToSXGResponse(err), nil
}
} else {
// Make up an invalid OCSP response.
ocspDer = []byte("ocsp")
}
var sctList []byte
certChain, err := certurl.NewCertChain(certs, ocspDer, sctList)
if err != nil {
return errorToSXGResponse(err), nil
}
buf := &bytes.Buffer{}
err = certChain.Write(buf)
if err != nil {
return errorToSXGResponse(err), nil
}
// Record http headers from the packager.
http_headers := map[string]string{}
for header_key, header_value := range httpresp.Header() {
// Ignores multiple header values.
http_headers[strings.ToLower(header_key)] =
string(header_value[0])
}
return &pb.SXGResponse{
Sxg: httpresp.Body.Bytes(),
Cbor: buf.Bytes(),
HttpHeaders: http_headers}, nil
}
func main() {
flag.Parse()
if *port == -1 {
log.Fatalf("Set flag -port")
}
if *publisherServerPort == -1 {
log.Fatalf("Set flag -publisher-server-port")
}
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", *port))
if err != nil {
log.Fatalf("Failed to listen: %v", err)
}
rtvCache, err := rtv.New()
if err != nil {
log.Fatalf("Error initializing RTVCache: %v", err)
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
pb.RegisterGatewayServiceServer(grpcServer, &gatewayServer{rtvCache: rtvCache})
log.Println("Starting server on port: ", *port)
grpcServer.Serve(listener)
}