/
metadata_service.go
670 lines (541 loc) · 15.5 KB
/
metadata_service.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
// Copyright 2014 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"sync"
"syscall"
"github.com/appc/spec/schema"
"github.com/appc/spec/schema/types"
"github.com/coreos/rkt/common"
"github.com/gorilla/mux"
"github.com/hashicorp/errwrap"
"github.com/spf13/cobra"
)
var (
cmdMetadataService = &cobra.Command{
Use: "metadata-service [--listen-port=PORT]",
Short: "Run metadata service",
Long: `Provides a means for running apps to introspect their execution
environment and assert their identity.`,
Run: runWrapper(runMetadataService),
}
)
var (
hmacKey [sha512.Size]byte
pods = newPodStore()
errPodNotFound = errors.New("pod not found")
errAppNotFound = errors.New("app not found")
flagListenPort int
exitCh = make(chan os.Signal, 1)
)
const (
listenFdsStart = 3
)
func init() {
cmdRkt.AddCommand(cmdMetadataService)
cmdMetadataService.Flags().IntVar(&flagListenPort, "listen-port", common.MetadataServicePort, "listen port")
}
type mdsPod struct {
uuid types.UUID
token string
manifest *schema.PodManifest
apps map[string]*schema.ImageManifest
}
type podStore struct {
byToken map[string]*mdsPod
byUUID map[types.UUID]*mdsPod
mutex sync.Mutex
}
func newPodStore() *podStore {
return &podStore{
byToken: make(map[string]*mdsPod),
byUUID: make(map[types.UUID]*mdsPod),
}
}
func (ps *podStore) addPod(u *types.UUID, token string, manifest *schema.PodManifest) {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p := &mdsPod{
uuid: *u,
token: token,
manifest: manifest,
apps: make(map[string]*schema.ImageManifest),
}
ps.byUUID[*u] = p
ps.byToken[token] = p
}
func (ps *podStore) addApp(u *types.UUID, app string, manifest *schema.ImageManifest) error {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p, ok := ps.byUUID[*u]
if !ok {
return errPodNotFound
}
p.apps[app] = manifest
return nil
}
func (ps *podStore) remove(u *types.UUID) error {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p, ok := ps.byUUID[*u]
if !ok {
return errPodNotFound
}
delete(ps.byUUID, *u)
delete(ps.byToken, p.token)
return nil
}
func (ps *podStore) getUUID(token string) (*types.UUID, error) {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p, ok := ps.byToken[token]
if !ok {
return nil, errPodNotFound
}
return &p.uuid, nil
}
func (ps *podStore) getPodManifest(token string) (*schema.PodManifest, error) {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p, ok := ps.byToken[token]
if !ok {
return nil, errPodNotFound
}
return p.manifest, nil
}
func (ps *podStore) getManifests(token, an string) (*schema.PodManifest, *schema.ImageManifest, error) {
ps.mutex.Lock()
defer ps.mutex.Unlock()
p, ok := ps.byToken[token]
if !ok {
return nil, nil, errPodNotFound
}
im, ok := p.apps[an]
if !ok {
return nil, nil, errAppNotFound
}
return p.manifest, im, nil
}
func queryValue(u *url.URL, key string) string {
vals, ok := u.Query()[key]
if !ok || len(vals) != 1 {
return ""
}
return vals[0]
}
func handleRegisterPod(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "UUID is missing or malformed: %v", err)
return
}
token := queryValue(r.URL, "token")
if token == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "token missing")
return
}
pm := &schema.PodManifest{}
if err := json.NewDecoder(r.Body).Decode(pm); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "JSON-decoding failed: %v", err)
return
}
pods.addPod(uuid, token, pm)
w.WriteHeader(http.StatusOK)
}
func handleUnregisterPod(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "UUID is missing or malformed: %v", err)
return
}
if err := pods.remove(uuid); err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, err)
return
}
w.WriteHeader(http.StatusOK)
}
func handleRegisterApp(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "UUID is missing or malformed: %v", err)
return
}
an := mux.Vars(r)["app"]
if an == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "app missing")
return
}
im := &schema.ImageManifest{}
if err := json.NewDecoder(r.Body).Decode(im); err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "JSON-decoding failed: %v", err)
return
}
err = pods.addApp(uuid, an, im)
if err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Pod with given UUID not found")
return
}
w.WriteHeader(http.StatusOK)
}
func podGet(h func(http.ResponseWriter, *http.Request, *schema.PodManifest)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := mux.Vars(r)["token"]
pm, err := pods.getPodManifest(token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, err)
return
}
h(w, r, pm)
}
}
func appGet(h func(http.ResponseWriter, *http.Request, *schema.PodManifest, *schema.ImageManifest)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := mux.Vars(r)["token"]
an := mux.Vars(r)["app"]
if an == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "app missing")
return
}
pm, im, err := pods.getManifests(token, an)
switch {
case err == nil:
h(w, r, pm, im)
case err == errPodNotFound:
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, err)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintln(w, err)
}
}
}
func handlePodAnnotations(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest) {
defer r.Body.Close()
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
for k := range pm.Annotations {
fmt.Fprintln(w, k)
}
}
func handlePodAnnotation(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest) {
defer r.Body.Close()
n := mux.Vars(r)["name"]
k, err := types.NewACIdentifier(n)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Pod annotation %q is not a valid AC Identifier", n)
return
}
v, ok := pm.Annotations.Get(k.String())
if !ok {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Pod annotation %q not found", k)
return
}
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte(v))
}
func handlePodManifest(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest) {
defer r.Body.Close()
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(pm); err != nil {
stderr.Error(err)
}
}
func handlePodUUID(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
token := mux.Vars(r)["token"]
uuid, err := pods.getUUID(token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, err)
return
}
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte(uuid.String()))
}
func mergeAppAnnotations(im *schema.ImageManifest, pm *schema.PodManifest, appName *types.ACName) types.Annotations {
merged := types.Annotations{}
for _, annot := range im.Annotations {
merged.Set(annot.Name, annot.Value)
}
if app := pm.Apps.Get(*appName); app != nil {
for _, annot := range app.Annotations {
merged.Set(annot.Name, annot.Value)
}
}
return merged
}
func handleAppAnnotations(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest, im *schema.ImageManifest) {
defer r.Body.Close()
n := mux.Vars(r)["app"]
an, err := types.NewACName(n)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "App name %q is not a valid AC Name", n)
return
}
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
for _, annot := range mergeAppAnnotations(im, pm, an) {
fmt.Fprintln(w, string(annot.Name))
}
}
func handleAppAnnotation(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest, im *schema.ImageManifest) {
defer r.Body.Close()
n := mux.Vars(r)["name"]
k, err := types.NewACIdentifier(n)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "App annotation name %q is not a valid AC Identifier", n)
return
}
n = mux.Vars(r)["app"]
an, err := types.NewACName(n)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "App name %q is not a valid AC Name", n)
return
}
merged := mergeAppAnnotations(im, pm, an)
v, ok := merged.Get(k.String())
if !ok {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "App annotation %q not found", k)
return
}
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte(v))
}
func handleImageManifest(w http.ResponseWriter, r *http.Request, _ *schema.PodManifest, im *schema.ImageManifest) {
defer r.Body.Close()
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(*im); err != nil {
stderr.Error(err)
}
}
func handleAppID(w http.ResponseWriter, r *http.Request, pm *schema.PodManifest, im *schema.ImageManifest) {
defer r.Body.Close()
n := mux.Vars(r)["app"]
an, err := types.NewACName(n)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "App name %q is not a valid AC Name", n)
return
}
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
app := pm.Apps.Get(*an)
if app == nil {
// This is impossible as we have already checked that
// the image manifest is not nil in the parent function.
panic("could not find app in manifest!")
}
w.Write([]byte(app.Image.ID.String()))
}
func initCrypto() error {
if n, err := rand.Reader.Read(hmacKey[:]); err != nil || n != len(hmacKey) {
return fmt.Errorf("failed to generate HMAC Key")
}
return nil
}
func handlePodSign(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
token := mux.Vars(r)["token"]
uuid, err := pods.getUUID(token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, err)
return
}
content := r.FormValue("content")
if content == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "content form value not found")
return
}
// HMAC(UID:content)
h := hmac.New(sha512.New, hmacKey[:])
h.Write((*uuid)[:])
h.Write([]byte(content))
// Send back HMAC as the signature
w.Header().Add("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
enc := base64.NewEncoder(base64.StdEncoding, w)
enc.Write(h.Sum(nil))
enc.Close()
}
func handlePodVerify(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
uuid, err := types.NewUUID(r.FormValue("uuid"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "uuid field missing or malformed: %v", err)
return
}
content := r.FormValue("content")
if content == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "content field missing")
return
}
sig, err := base64.StdEncoding.DecodeString(r.FormValue("signature"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "signature field missing or corrupt: %v", err)
return
}
h := hmac.New(sha512.New, hmacKey[:])
h.Write((*uuid)[:])
h.Write([]byte(content))
if hmac.Equal(sig, h.Sum(nil)) {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
type httpResp struct {
writer http.ResponseWriter
status int
}
func (r *httpResp) Header() http.Header {
return r.writer.Header()
}
func (r *httpResp) Write(d []byte) (int, error) {
return r.writer.Write(d)
}
func (r *httpResp) WriteHeader(status int) {
r.status = status
r.writer.WriteHeader(status)
}
func logReq(h func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
resp := &httpResp{w, 0}
h(resp, r)
stderr.Printf("%v %v - %v", r.Method, r.RequestURI, resp.status)
}
}
// unixListener returns the listener used for registrations (over unix sock)
func unixListener() (net.Listener, error) {
s := os.Getenv("LISTEN_FDS")
if s != "" {
// socket activated
lfds, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return nil, errwrap.Wrap(errors.New("error parsing LISTEN_FDS env var"), err)
}
if lfds < 1 {
return nil, fmt.Errorf("LISTEN_FDS < 1")
}
return net.FileListener(os.NewFile(uintptr(listenFdsStart), "listen"))
} else {
dir := filepath.Dir(common.MetadataServiceRegSock)
err := os.MkdirAll(dir, 0755)
if err != nil {
return nil, errwrap.Wrap(fmt.Errorf("failed to create %v", dir), err)
}
return net.ListenUnix("unix", &net.UnixAddr{
Net: "unix",
Name: common.MetadataServiceRegSock,
})
}
}
func runRegistrationServer(l net.Listener) {
r := mux.NewRouter()
r.HandleFunc("/pods/{uuid}", logReq(handleRegisterPod)).Methods("PUT")
r.HandleFunc("/pods/{uuid}", logReq(handleUnregisterPod)).Methods("DELETE")
r.HandleFunc("/pods/{uuid}/{app:.*}", logReq(handleRegisterApp)).Methods("PUT")
if err := http.Serve(l, r); err != nil {
stderr.PrintE("error serving registration HTTP", err)
}
close(exitCh)
}
func runPublicServer(l net.Listener) {
r := mux.NewRouter().Headers("Metadata-Flavor", "AppContainer").
PathPrefix("/{token}/acMetadata/v1").Subrouter()
mr := r.Methods("GET").Subrouter()
mr.HandleFunc("/pod/annotations/", logReq(podGet(handlePodAnnotations)))
mr.HandleFunc("/pod/annotations/{name:.*}", logReq(podGet(handlePodAnnotation)))
mr.HandleFunc("/pod/manifest", logReq(podGet(handlePodManifest)))
mr.HandleFunc("/pod/uuid", logReq(handlePodUUID))
mr.HandleFunc("/apps/{app:.*}/annotations/", logReq(appGet(handleAppAnnotations)))
mr.HandleFunc("/apps/{app:.*}/annotations/{name:.*}", logReq(appGet(handleAppAnnotation)))
mr.HandleFunc("/apps/{app:.*}/image/manifest", logReq(appGet(handleImageManifest)))
mr.HandleFunc("/apps/{app:.*}/image/id", logReq(appGet(handleAppID)))
r.HandleFunc("/pod/hmac/sign", logReq(handlePodSign)).Methods("POST")
r.HandleFunc("/pod/hmac/verify", logReq(handlePodVerify)).Methods("POST")
if err := http.Serve(l, r); err != nil {
stderr.PrintE("error serving pod HTTP", err)
}
close(exitCh)
}
func runMetadataService(cmd *cobra.Command, args []string) (exit int) {
signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM)
stderr.Print("metadata service starting...")
unixl, err := unixListener()
if err != nil {
stderr.Error(err)
return 1
}
defer unixl.Close()
tcpl, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: flagListenPort})
if err != nil {
stderr.PrintE(fmt.Sprintf("error listening on port %v", flagListenPort), err)
return 1
}
defer tcpl.Close()
if err := initCrypto(); err != nil {
stderr.Error(err)
return 1
}
go runRegistrationServer(unixl)
go runPublicServer(tcpl)
stderr.Print("metadata service running...")
<-exitCh
stderr.Print("metadata service exiting...")
return
}