-
Notifications
You must be signed in to change notification settings - Fork 84
/
handler.go
906 lines (791 loc) · 30.2 KB
/
handler.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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//
// Copyright (c) 2018 Red Hat, Inc.
//
// 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 handler
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"os"
"strconv"
"strings"
yaml "gopkg.in/yaml.v1"
"github.com/automationbroker/bundle-lib/authorization"
k8sauthorization "github.com/automationbroker/bundle-lib/authorization/k8s"
"github.com/automationbroker/bundle-lib/bundle"
"github.com/automationbroker/bundle-lib/clients"
"github.com/automationbroker/config"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/openshift/ansible-service-broker/pkg/auth"
"github.com/openshift/ansible-service-broker/pkg/broker"
"github.com/openshift/ansible-service-broker/pkg/version"
"github.com/pborman/uuid"
log "github.com/sirupsen/logrus"
authv1 "k8s.io/api/authentication/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// RequestContextKey - keys that will be used in the request context
type RequestContextKey string
const (
// OriginatingIdentityHeader is the header for the originating identity
// or the user to check/impersonate
OriginatingIdentityHeader = "X-Broker-API-Originating-Identity"
// UserInfoContext - Broker.UserInfo retrieved from the
// originating identity header
UserInfoContext RequestContextKey = "userInfo"
)
type handler struct {
router mux.Router
broker broker.Broker
brokerConfig *config.Config
authorizer authorization.Authorizer
}
// authHandler - does the authentication for the routes
func authHandler(h http.Handler, providers []auth.Provider) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var principalFound error
for _, provider := range providers {
principal, err := provider.GetPrincipal(r)
if principal != nil {
log.Debug("We found one. HOORAY!")
// we found our principal, stop looking
break
}
if err != nil {
principalFound = err
}
}
// if we went through the providers and found no principals. We will
// have found an error
if principalFound != nil {
log.Debug("no principal found")
writeResponse(w, http.StatusUnauthorized, broker.ErrorResponse{Description: principalFound.Error()})
return
}
h.ServeHTTP(w, r)
})
}
func userInfoHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//Retrieve the UserInfo from request if available.
userJSONStr := r.Header.Get(OriginatingIdentityHeader)
if userJSONStr != "" {
userStr := strings.Split(userJSONStr, " ")
if len(userStr) != 2 {
//If we do not understand the user, but something was sent, we should return a 404.
log.Debugf("Not enough values in header "+
"for originating origin header - %v", userJSONStr)
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid User Info in Originating Identity Header",
})
return
}
userInfo := broker.UserInfo{}
uStr, err := base64.StdEncoding.DecodeString(userStr[1])
if err != nil {
//If we do not understand the user, but something was sent, we should return a 404.
log.Debugf("Unable to decode base64 encoding "+
"for originating origin header - %v", err)
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid User Info in Originating Identity Header",
})
return
}
err = json.Unmarshal(uStr, &userInfo)
if err != nil {
log.Debugf("Unable to marshal into object "+
"for originating origin header - %v", err)
//If we do not understand the user, but something was sent, we should return a 404.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid User Info in Originating Identity Header",
})
return
}
r = r.WithContext(context.WithValue(
r.Context(), UserInfoContext, userInfo),
)
} else {
log.Debugf("Unable to find originating origin header")
}
h.ServeHTTP(w, r)
})
}
// GorillaRouteHandler - gorilla route handler
// making the handler methods more testable by moving the reliance of mux.Vars()
// outside of the handlers themselves
type GorillaRouteHandler func(http.ResponseWriter, *http.Request)
// VarHandler - Variable route handler.
type VarHandler func(http.ResponseWriter, *http.Request, map[string]string)
func createVarHandler(r VarHandler) GorillaRouteHandler {
return func(writer http.ResponseWriter, request *http.Request) {
r(writer, request, mux.Vars(request))
}
}
// NewHandler - Create a new handler by attaching the routes and setting logger and broker.
func NewHandler(b broker.Broker, brokerConfig *config.Config, prefix string,
providers []auth.Provider, a authorization.Authorizer) http.Handler {
h := handler{
router: *mux.NewRouter(),
broker: b,
brokerConfig: brokerConfig,
authorizer: a,
}
var s *mux.Router
if prefix == "/" {
s = &h.router
} else {
s = h.router.PathPrefix(prefix).Subrouter()
}
s.HandleFunc("/v2/bootstrap", createVarHandler(h.bootstrap)).Methods("POST")
s.HandleFunc("/v2/catalog", createVarHandler(h.catalog)).Methods("GET")
s.HandleFunc("/v2/service_instances/{instance_uuid}", createVarHandler(h.getinstance)).Methods("GET")
s.HandleFunc("/v2/service_instances/{instance_uuid}", createVarHandler(h.provision)).Methods("PUT")
s.HandleFunc("/v2/service_instances/{instance_uuid}", createVarHandler(h.update)).Methods("PATCH")
s.HandleFunc("/v2/service_instances/{instance_uuid}", createVarHandler(h.deprovision)).Methods("DELETE")
s.HandleFunc("/v2/service_instances/{instance_uuid}/service_bindings/{binding_uuid}",
createVarHandler(h.getbind)).Methods("GET")
s.HandleFunc("/v2/service_instances/{instance_uuid}/service_bindings/{binding_uuid}",
createVarHandler(h.bind)).Methods("PUT")
s.HandleFunc("/v2/service_instances/{instance_uuid}/service_bindings/{binding_uuid}",
createVarHandler(h.unbind)).Methods("DELETE")
s.HandleFunc("/v2/service_instances/{instance_uuid}/last_operation",
createVarHandler(h.lastoperation)).Methods("GET")
s.HandleFunc("/v2/service_instances/{instance_uuid}/service_bindings/{binding_uuid}/last_operation",
createVarHandler(h.lastoperation)).Methods("GET")
if brokerConfig.GetBool("broker.dev_broker") {
s.HandleFunc("/v2/apb", createVarHandler(h.apbAddSpec)).Methods("POST")
s.HandleFunc("/v2/apb/{spec_id}", createVarHandler(h.apbRemoveSpec)).Methods("DELETE")
s.HandleFunc("/v2/apb", createVarHandler(h.apbRemoveSpecs)).Methods("DELETE")
}
return handlers.LoggingHandler(os.Stdout, userInfoHandler(authHandler(h, providers)))
}
func (h handler) bootstrap(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
go func() {
_, err := h.broker.Bootstrap()
if err != nil {
log.Errorf("Bootstrap failed because '%v'", err)
}
}()
resp := map[string]string{
"msg": "Bootstrap job started",
}
writeDefaultResponse(w, http.StatusOK, resp, nil)
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.router.ServeHTTP(w, r)
}
func (h handler) catalog(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
resp, err := h.broker.Catalog()
writeDefaultResponse(w, http.StatusOK, resp, err)
}
func (h handler) getinstance(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
// TODO: typically the methods on the broker return a response this
// was an old utility method that I'm re-purposing. I think we should
// make this consistent with the other methods in the broker.
si, err := h.broker.GetServiceInstance(instanceUUID)
if err != nil {
switch err {
case broker.ErrorNotFound: // return 404
writeResponse(w, http.StatusNotFound, broker.ErrorResponse{Description: err.Error()})
default: // return 422
writeResponse(w, http.StatusUnprocessableEntity, broker.ErrorResponse{Description: err.Error()})
}
return
}
// planParameterKey is unexported. Using the value here instead of
// refactoring the world. Besides with the above comment, this code
// would all live in the broker.go instead of here.
planID, ok := (*si.Parameters)["_apb_plan_id"].(string)
if !ok {
log.Warning("Could not retrieve the current plan name from parameters")
}
sir := broker.ServiceInstanceResponse{ServiceID: si.ID.String(), PlanID: planID, Parameters: *si.Parameters}
writeDefaultResponse(w, http.StatusOK, sir, err)
}
func (h handler) provision(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
// ignore the error, if async can't be parsed it will be false
async, _ := strconv.ParseBool(r.FormValue("accepts_incomplete"))
var req *broker.ProvisionRequest
err := readRequest(r, &req)
if err != nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "could not read request: " + err.Error()})
return
}
userInfo, ok := r.Context().Value(UserInfoContext).(broker.UserInfo)
if !h.brokerConfig.GetBool("broker.auto_escalate") {
if !ok {
log.Debugf("unable to retrieve user info from request context")
// if no user, we should error out with bad request.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid user info from originating origin header.",
})
return
}
if ok, status, err := h.validateUser(userInfo, req.Context.Namespace); !ok {
writeResponse(w, status, broker.ErrorResponse{Description: err.Error()})
return
}
} else {
log.Debugf("Auto Escalate has been set to true, we are escalating permissions")
}
// Ok let's provision this bad boy
resp, err := h.broker.Provision(instanceUUID, req, async, userInfo)
if err != nil {
log.Errorf("provision error %+v", err)
switch err {
case broker.ErrorDuplicate:
writeResponse(w, http.StatusConflict, broker.ProvisionResponse{})
case broker.ErrorProvisionInProgress:
writeResponse(w, http.StatusAccepted, resp)
case broker.ErrorAlreadyProvisioned:
writeResponse(w, http.StatusOK, resp)
case broker.ErrorNotFound:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
}
} else if async {
writeDefaultResponse(w, http.StatusAccepted, resp, err)
} else {
writeDefaultResponse(w, http.StatusCreated, resp, err)
}
}
func (h handler) update(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
var req *broker.UpdateRequest
if err := readRequest(r, &req); err != nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
return
}
// ignore the error, if async can't be parsed it will be false
async, _ := strconv.ParseBool(r.FormValue("accepts_incomplete"))
userInfo, ok := r.Context().Value(UserInfoContext).(broker.UserInfo)
if !h.brokerConfig.GetBool("broker.auto_escalate") {
if !ok {
log.Debugf("unable to retrieve user info from request context")
// if no user, we should error out with bad request.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid user info from originating origin header.",
})
return
}
if ok, status, err := h.validateUser(userInfo, req.Context.Namespace); !ok {
writeResponse(w, status, broker.ErrorResponse{Description: err.Error()})
return
}
} else {
log.Debugf("Auto Escalate has been set to true, we are escalating permissions")
}
resp, err := h.broker.Update(instanceUUID, req, async, userInfo)
if err != nil {
switch err {
case broker.ErrorUpdateInProgress:
writeResponse(w, http.StatusAccepted, resp)
case broker.ErrorNotFound:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
case broker.ErrorPlanNotFound,
broker.ErrorParameterNotUpdatable,
broker.ErrorParameterNotFound,
broker.ErrorParameterUnknownEnum,
broker.ErrorPlanUpdateNotPossible:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
} else if async {
writeDefaultResponse(w, http.StatusAccepted, resp, err)
} else {
writeDefaultResponse(w, http.StatusOK, resp, err)
}
}
func (h handler) deprovision(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
// ignore the error, if async can't be parsed it will be false
async, _ := strconv.ParseBool(r.FormValue("accepts_incomplete"))
planID := r.FormValue("plan_id")
if planID == "" {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "deprovision request missing plan_id query parameter"})
}
serviceInstance, err := h.broker.GetServiceInstance(instanceUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusGone, broker.DeprovisionResponse{})
return
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
return
}
}
nsDeleted, err := isNamespaceDeleted(serviceInstance.Context.Namespace)
if err != nil {
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
return
}
userInfo, ok := r.Context().Value(UserInfoContext).(broker.UserInfo)
if !h.brokerConfig.GetBool("broker.auto_escalate") {
if !ok {
log.Debugf("unable to retrieve user info from request context")
// if no user, we should error out with bad request.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid user info from originating origin header.",
})
return
}
if !nsDeleted {
ok, status, err := h.validateUser(userInfo, serviceInstance.Context.Namespace)
if !ok {
writeResponse(w, status, broker.ErrorResponse{Description: err.Error()})
return
}
}
} else {
log.Debugf("Auto Escalate has been set to true, we are escalating permissions")
}
resp, err := h.broker.Deprovision(serviceInstance, planID, nsDeleted, async, userInfo)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusGone, broker.DeprovisionResponse{})
return
case broker.ErrorBindingExists:
writeResponse(w, http.StatusBadRequest, broker.DeprovisionResponse{})
return
case broker.ErrorDeprovisionInProgress:
writeResponse(w, http.StatusAccepted, resp)
return
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
return
}
} else if async {
writeDefaultResponse(w, http.StatusAccepted, resp, err)
} else {
writeDefaultResponse(w, http.StatusCreated, resp, err)
}
}
func (h handler) getbind(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
// validate input uuids
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
bindingUUID := uuid.Parse(params["binding_uuid"])
if bindingUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid binding_uuid"})
return
}
if bytes.Compare(instanceUUID, bindingUUID) == 0 {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "instance_uuid and binding_uuid cannot be the same"})
return
}
serviceInstance, err := h.broker.GetServiceInstance(instanceUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
}
resp, err := h.broker.GetBind(serviceInstance, bindingUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusNotFound, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
}
return
}
log.Debug("handler: bind found")
writeDefaultResponse(w, http.StatusOK, resp, err)
}
func (h handler) bind(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
// validate input uuids
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
bindingUUID := uuid.Parse(params["binding_uuid"])
if bindingUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid binding_uuid"})
return
}
if bytes.Compare(instanceUUID, bindingUUID) == 0 {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "instance_uuid and binding_uuid cannot be the same"})
return
}
// ignore the error, if async can't be parsed it will be false
async, _ := strconv.ParseBool(r.FormValue("accepts_incomplete"))
if !async && h.brokerConfig.GetBool("broker.launch_apb_on_bind") {
log.Warning("launch_apb_on_bind is enabled, but accepts_incomplete is false, binding may fail")
}
var req *broker.BindRequest
if err := readRequest(r, &req); err != nil {
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
return
}
serviceInstance, err := h.broker.GetServiceInstance(instanceUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
return
}
userInfo, ok := r.Context().Value(UserInfoContext).(broker.UserInfo)
if !h.brokerConfig.GetBool("broker.auto_escalate") {
if !ok {
log.Debugf("unable to retrieve user info from request context")
// if no user, we should error out with bad request.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid user info from originating origin header.",
})
return
}
if ok, status, err := h.validateUser(userInfo, serviceInstance.Context.Namespace); !ok {
writeResponse(w, status, broker.ErrorResponse{Description: err.Error()})
return
}
} else {
log.Debugf("Auto Escalate has been set to true, we are escalating permissions")
}
// process binding request
resp, ranAsync, err := h.broker.Bind(serviceInstance, bindingUUID, req, async, userInfo)
if err != nil {
switch err {
case broker.ErrorDuplicate:
writeResponse(w, http.StatusConflict, broker.BindResponse{})
case broker.ErrorBindingExists:
writeResponse(w, http.StatusOK, resp)
case broker.ErrorNotFound:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
default:
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: err.Error()})
}
return
}
if ranAsync {
writeDefaultResponse(w, http.StatusAccepted, resp, err)
} else {
writeDefaultResponse(w, http.StatusCreated, resp, err)
}
}
func (h handler) unbind(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
bindingUUID := uuid.Parse(params["binding_uuid"])
if bindingUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid binding_uuid"})
return
}
if bytes.Compare(instanceUUID, bindingUUID) == 0 {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "instance_uuid and binding_uuid cannot be the same"})
return
}
planID := r.FormValue("plan_id")
if planID == "" {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "unbind request missing plan_id query parameter"})
}
// ignore the error, if async can't be parsed it will be false
async, _ := strconv.ParseBool(r.FormValue("accepts_incomplete"))
if !async && h.brokerConfig.GetBool("broker.launch_apb_on_bind") {
log.Warning("launch_apb_on_bind is enabled, but accepts_incomplete is false, unbinding may fail")
}
serviceInstance, err := h.broker.GetServiceInstance(instanceUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusGone, nil)
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
return
}
bindInstance, err := h.broker.GetBindInstance(bindingUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusGone, nil)
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
return
}
nsDeleted, err := isNamespaceDeleted(serviceInstance.Context.Namespace)
if err != nil {
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
return
}
userInfo, ok := r.Context().Value(UserInfoContext).(broker.UserInfo)
if !h.brokerConfig.GetBool("broker.auto_escalate") {
if !ok {
log.Debugf("unable to retrieve user info from request context")
// if no user, we should error out with bad request.
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{
Description: "Invalid user info from originating origin header.",
})
return
}
if !nsDeleted {
if ok, status, err := h.validateUser(userInfo, serviceInstance.Context.Namespace); !ok {
writeResponse(w, status, broker.ErrorResponse{Description: err.Error()})
return
}
}
} else {
log.Debugf("Auto Escalate has been set to true, we are escalating permissions")
}
resp, ranAsync, err := h.broker.Unbind(serviceInstance, bindInstance, planID, nsDeleted, async, userInfo)
switch {
case err == broker.ErrorNotFound: // return 404
log.Debugf("Binding not found.")
writeResponse(w, http.StatusNotFound, broker.ErrorResponse{Description: err.Error()})
case err == broker.ErrorUnbindingInProgress:
writeResponse(w, http.StatusAccepted, resp)
case err != nil: // return 500
log.Errorf("Unknown error: %v", err)
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
case ranAsync == true: // return 202
writeDefaultResponse(w, http.StatusAccepted, resp, err)
default: // return 200
writeDefaultResponse(w, http.StatusOK, resp, err)
}
return
}
func isNamespaceDeleted(name string) (bool, error) {
k8scli, err := clients.Kubernetes()
if err != nil {
return false, err
}
namespace, err := k8scli.Client.CoreV1().Namespaces().Get(name, metav1.GetOptions{})
if err != nil {
return false, err
}
return namespace == nil || namespace.Status.Phase == v1.NamespaceTerminating, nil
}
func (h handler) lastoperation(w http.ResponseWriter, r *http.Request, params map[string]string) {
defer r.Body.Close()
h.printRequest(r)
instanceUUID := uuid.Parse(params["instance_uuid"])
if instanceUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid instance_uuid"})
return
}
// we have a binding job
if strings.Index(r.URL.Path, "/service_bindings/") > 0 {
bindingUUID := uuid.Parse(params["binding_uuid"])
if bindingUUID == nil {
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "invalid binding_uuid"})
return
}
// let's see if the bindInstance exists or not. We don't need the
// actual instance, just need to know if it is there.
_, err := h.broker.GetBindInstance(bindingUUID)
if err != nil {
switch err {
case broker.ErrorNotFound:
writeResponse(w, http.StatusGone, make(map[string]interface{}, 1))
default:
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: err.Error()})
}
return
}
//
// Since we have a binding, let's use the binding id as the instance id
//
instanceUUID = bindingUUID
}
req := broker.LastOperationRequest{}
// operation is expected
if op := r.FormValue("operation"); op != "" {
req.Operation = op
} else {
errmsg := fmt.Sprintf("operation not supplied for a last_operation with instance_uuid [%s]", instanceUUID)
log.Error(errmsg)
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: errmsg})
return
}
// service_id is optional
if serviceID := r.FormValue("service_id"); serviceID != "" {
req.ServiceID = serviceID
}
// plan_id is optional
if planID := r.FormValue("plan_id"); planID != "" {
req.PlanID = planID
}
resp, err := h.broker.LastOperation(instanceUUID, &req)
if err == broker.ErrorNotFound { // return 404
writeResponse(w, http.StatusGone, broker.ErrorResponse{Description: "Job not found"})
return
}
writeDefaultResponse(w, http.StatusOK, resp, err)
}
// apbAddSpec - Development only route. Will be used by for local developers to add images to the catalog.
func (h handler) apbAddSpec(w http.ResponseWriter, r *http.Request, params map[string]string) {
log.Debug("handler::apbAddSpec")
// Read Request for an image name
// create helper method from MockRegistry
ansibleBroker, ok := h.broker.(broker.DevBroker)
if !ok {
log.Errorf("unable to use broker - %T as ansible service broker", h.broker)
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: "Internal server error"})
return
}
// Decode
spec64Yaml := r.FormValue("apbSpec")
if spec64Yaml == "" {
log.Errorf("Could not find form parameter apbSpec")
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "Could not parameter apbSpec"})
return
}
decodedSpecYaml, err := base64.StdEncoding.DecodeString(spec64Yaml)
if err != nil {
log.Errorf("Something went wrong decoding spec from encoded string - %v err -%v", spec64Yaml, err)
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "Invalid parameter encoding"})
return
}
log.Debug("Successfully decoded pushed spec:")
log.Debugf("%s", decodedSpecYaml)
var spec bundle.Spec
if err = yaml.Unmarshal([]byte(decodedSpecYaml), &spec); err != nil {
log.Errorf("Unable to decode yaml - %v to spec err - %v", decodedSpecYaml, err)
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "Invalid parameter yaml"})
return
}
log.Infof("Assuming pushed APB runtime version [%v]", version.MaxRuntimeVersion)
spec.Runtime = version.MaxRuntimeVersion
log.Debug("Unmarshalled into apb.Spec:")
log.Debugf("%+v", spec)
resp, err := ansibleBroker.AddSpec(spec)
if err != nil {
log.Errorf("An error occurred while trying to add a spec via apb push:")
log.Errorf("%s", err.Error())
writeResponse(w, http.StatusInternalServerError,
broker.ErrorResponse{Description: err.Error()})
return
}
writeDefaultResponse(w, http.StatusOK, resp, err)
}
func (h handler) apbRemoveSpec(w http.ResponseWriter, r *http.Request, params map[string]string) {
ansibleBroker, ok := h.broker.(broker.DevBroker)
if !ok {
log.Errorf("unable to use broker - %T as ansible service broker", h.broker)
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: "Internal server error"})
return
}
specID := params["spec_id"]
var err error
if specID != "" {
err = ansibleBroker.RemoveSpec(specID)
} else {
log.Errorf("Unable to find spec id in request")
writeResponse(w, http.StatusBadRequest, broker.ErrorResponse{Description: "No Spec/service id found."})
return
}
writeDefaultResponse(w, http.StatusNoContent, struct{}{}, err)
}
func (h handler) apbRemoveSpecs(w http.ResponseWriter, r *http.Request, params map[string]string) {
ansibleBroker, ok := h.broker.(broker.DevBroker)
if !ok {
log.Errorf("unable to use broker - %T as ansible service broker", h.broker)
writeResponse(w, http.StatusInternalServerError, broker.ErrorResponse{Description: "Internal server error"})
return
}
err := ansibleBroker.RemoveSpecs()
writeDefaultResponse(w, http.StatusNoContent, struct{}{}, err)
}
// printRequest - will print the request with the body.
func (h handler) printRequest(req *http.Request) {
if h.brokerConfig.GetBool("broker.output_request") {
b, err := httputil.DumpRequest(req, true)
if err != nil {
log.Errorf("unable to dump request to log: %v", err)
}
log.Infof("Request: %q", b)
}
}
// validateUser will use the cached cluster role's rules, and retrieve
// the rules for the user in the namespace to determine if the user's roles
// can cover the all of the cluster role's rules.
func (h handler) validateUser(userInfo broker.UserInfo, namespace string) (bool, int, error) {
u := k8sauthorization.AuthorizationUser{
UserInfo: authv1.UserInfo{
Username: userInfo.Username,
Extra: userInfo.Extra,
Groups: userInfo.Groups,
UID: userInfo.UID,
},
}
decision, err := h.authorizer.Authorize(&u, namespace)
log.Debugf("authorize decision: %v", decision)
if err != nil {
return false, http.StatusInternalServerError, fmt.Errorf("Unable to connect to the cluster")
}
if decision == authorization.DecisionAllowed {
return true, http.StatusOK, nil
}
return false, http.StatusForbidden, fmt.Errorf("User does not have sufficient permissions")
}