-
Notifications
You must be signed in to change notification settings - Fork 562
/
devicesvc.go
268 lines (246 loc) · 6.85 KB
/
devicesvc.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
258
259
260
261
262
263
264
265
266
267
268
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package devicestatetest
import (
"bytes"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"time"
. "gopkg.in/check.v1"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/snapdenv"
)
type DeviceServiceBehavior struct {
ReqID string
RequestIDURLPath string
SerialURLPath string
ExpectedCapabilities string
Head func(c *C, bhv *DeviceServiceBehavior, w http.ResponseWriter, r *http.Request)
PostPreflight func(c *C, bhv *DeviceServiceBehavior, w http.ResponseWriter, r *http.Request)
SignSerial func(c *C, bhv *DeviceServiceBehavior, headers map[string]interface{}, body []byte) (serial asserts.Assertion, ancillary []asserts.Assertion, err error)
}
// Request IDs for hard-coded behaviors.
const (
ReqIDFailID501 = "REQID-FAIL-ID-501"
ReqIDBadRequest = "REQID-BAD-REQ"
ReqIDPoll = "REQID-POLL"
ReqIDSerialWithBadModel = "REQID-SERIAL-W-BAD-MODEL"
)
const (
requestIDURLPath = "/api/v1/snaps/auth/request-id"
serialURLPath = "/api/v1/snaps/auth/devices"
)
func MockDeviceService(c *C, bhv *DeviceServiceBehavior) (mockServer *httptest.Server, extraPemEncodedCerts []byte) {
expectedUserAgent := snapdenv.UserAgent()
// default URL paths
if bhv.RequestIDURLPath == "" {
bhv.RequestIDURLPath = requestIDURLPath
bhv.SerialURLPath = serialURLPath
}
// currently supported
if bhv.ExpectedCapabilities == "" {
bhv.ExpectedCapabilities = "serial-stream"
}
var mu sync.Mutex
count := 0
// TODO: extract handler func
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check.Assert here will produce harder to understand failure
// modes
switch r.Method {
default:
c.Errorf("unexpected verb %q", r.Method)
w.WriteHeader(500)
return
case "HEAD":
if r.URL.Path != "/" {
c.Errorf("unexpected HEAD request %q", r.URL.String())
w.WriteHeader(500)
return
}
if bhv.Head != nil {
bhv.Head(c, bhv, w, r)
} else {
w.WriteHeader(200)
}
return
case "POST":
// carry on
}
if bhv.PostPreflight != nil {
bhv.PostPreflight(c, bhv, w, r)
}
switch r.URL.Path {
default:
c.Errorf("unexpected POST request %q", r.URL.String())
w.WriteHeader(500)
return
case bhv.RequestIDURLPath:
if bhv.ReqID == ReqIDFailID501 {
w.WriteHeader(501)
return
}
w.WriteHeader(200)
c.Check(r.Header.Get("User-Agent"), Equals, expectedUserAgent)
io.WriteString(w, fmt.Sprintf(`{"request-id": "%s"}`, bhv.ReqID))
case bhv.SerialURLPath:
c.Check(r.Header.Get("User-Agent"), Equals, expectedUserAgent)
c.Check(r.Header.Get("Snap-Device-Capabilities"), Equals, bhv.ExpectedCapabilities)
mu.Lock()
serialNum := 9999 + count
count++
mu.Unlock()
dec := asserts.NewDecoder(r.Body)
a, err := dec.Decode()
if err != nil {
w.WriteHeader(400)
return
}
serialReq, ok := a.(*asserts.SerialRequest)
if !ok {
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "expected serial-request"}]
}`))
return
}
extra := []asserts.Assertion{}
for {
a1, err := dec.Decode()
if err == io.EOF {
break
}
if err != nil {
w.WriteHeader(400)
return
}
extra = append(extra, a1)
}
err = asserts.SignatureCheck(serialReq, serialReq.DeviceKey())
c.Check(err, IsNil)
if err != nil {
// also return response to client
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "invalid serial-request self-signature"}]
}`))
return
}
brandID := serialReq.BrandID()
model := serialReq.Model()
reqID := serialReq.RequestID()
if reqID == ReqIDBadRequest {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "bad serial-request"}]
}`))
return
}
if reqID == ReqIDPoll && serialNum != 10002 {
w.WriteHeader(202)
return
}
serialStr := fmt.Sprintf("%d", serialNum)
if serialReq.Serial() != "" {
// use proposed serial
serialStr = serialReq.Serial()
}
if serialReq.HeaderString("original-model") != "" {
// re-registration
if len(extra) != 2 {
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "expected model and original serial"}]
}`))
return
}
_, ok := extra[0].(*asserts.Model)
if !ok {
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "expected model"}]
}`))
return
}
origSerial, ok := extra[1].(*asserts.Serial)
if !ok {
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "expected model"}]
}`))
}
c.Check(origSerial.DeviceKey(), DeepEquals, serialReq.DeviceKey())
// TODO: more checks once we have Original* accessors
} else {
mod, ok := extra[0].(*asserts.Model)
if !ok {
w.WriteHeader(400)
w.Write([]byte(`{
"error_list": [{"message": "expected model"}]
}`))
return
}
c.Check(mod.BrandID(), Equals, brandID)
c.Check(mod.Model(), Equals, model)
}
serial, ancillary, err := bhv.SignSerial(c, bhv, map[string]interface{}{
"authority-id": "canonical",
"brand-id": brandID,
"model": model,
"serial": serialStr,
"device-key": serialReq.HeaderString("device-key"),
"device-key-sha3-384": serialReq.SignKeyID(),
"timestamp": time.Now().Format(time.RFC3339),
}, serialReq.Body())
c.Check(err, IsNil)
if err != nil {
// also return response to client
w.WriteHeader(500)
return
}
w.Header().Set("Content-Type", asserts.MediaType)
w.WriteHeader(200)
if reqID == ReqIDSerialWithBadModel {
encoded := asserts.Encode(serial)
encoded = bytes.Replace(encoded, []byte("model: pc"), []byte("model: bad-model-foo"), 1)
w.Write(encoded)
return
}
enc := asserts.NewEncoder(w)
enc.Encode(serial)
for _, a := range ancillary {
enc.Encode(a)
}
}
}))
pemEncodedCerts := bytes.NewBuffer(nil)
for _, c1 := range server.TLS.Certificates {
block := &pem.Block{
Type: "CERTIFICATE",
Bytes: c1.Certificate[0],
}
err := pem.Encode(pemEncodedCerts, block)
c.Assert(err, IsNil)
}
return server, pemEncodedCerts.Bytes()
}