-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathhandlers.go
1282 lines (1094 loc) · 44.8 KB
/
handlers.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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/cello-proj/cello/internal/requests"
"github.com/cello-proj/cello/internal/responses"
"github.com/cello-proj/cello/internal/types"
"github.com/cello-proj/cello/service/internal/credentials"
"github.com/cello-proj/cello/service/internal/db"
"github.com/cello-proj/cello/service/internal/env"
"github.com/cello-proj/cello/service/internal/git"
"github.com/cello-proj/cello/service/internal/workflow"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/gorilla/mux"
upper "github.com/upper/db/v4"
"gopkg.in/yaml.v2"
)
const (
numOfTokensLimit = 2
)
// Represents a JWT token.
type token struct {
Token string `json:"token"`
}
// Represents an error response.
type errorResponse struct {
ErrorMessage string `json:"error_message"`
}
// Generates error response JSON.
func generateErrorResponseJSON(message string) string {
er := errorResponse{
ErrorMessage: message,
}
// TODO swallowing error since this is only internally ever passed message
jsonData, _ := json.Marshal(er)
return string(jsonData)
}
// HTTP handler
type handler struct {
logger log.Logger
newCredentialsProvider func(a credentials.Authorization, env env.Vars, h http.Header, vaultConfig credentials.VaultConfigFn, fn credentials.VaultSvcFn) (credentials.Provider, error)
argo workflow.Workflow
argoCtx context.Context
config *Config
gitClient git.Client
env env.Vars
dbClient db.Client
}
// Service HealthCheck
func (h *handler) healthCheck(w http.ResponseWriter, r *http.Request) {
vaultEndpoint := fmt.Sprintf("%s/v1/sys/health", h.env.VaultAddress)
l := h.requestLogger(r, "op", "health-check", "vault-endpoint", vaultEndpoint)
// #nosec
response, err := http.Get(vaultEndpoint)
if err != nil {
level.Error(l).Log("message", "received error connecting to vault", "error", err)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "Health check failed")
return
}
// We don't care about the body but need to read it all and close it
// regardless.
// https://golang.org/pkg/net/http/#Client.Do
defer response.Body.Close()
_, err = io.ReadAll(response.Body)
if err != nil {
level.Warn(l).Log("message", "unable to read vault body; continuing", "error", err)
// Continue on and handle the actual response code from Vault accordingly.
}
if response.StatusCode != 200 && response.StatusCode != 429 {
level.Error(l).Log("message", fmt.Sprintf("received code %d which is not 200 (initialized, unsealed, and active) or 429 (unsealed and standby) when connecting to vault", response.StatusCode))
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "Health check failed")
return
}
if err = h.dbClient.Health(r.Context()); err != nil {
level.Error(l).Log("message", fmt.Sprintf("received code error %s when connecting to database", err.Error()))
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintln(w, "Health check failed")
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "Health check succeeded")
}
// Lists workflows
func (h handler) listWorkflows(w http.ResponseWriter, r *http.Request) {
// TODO authenticate user can list this workflow once auth figured out
// TODO fail if project / target does not exist or are not valid format
vars := mux.Vars(r)
projectName := vars["projectName"]
targetName := vars["targetName"]
l := h.requestLogger(r, "op", "list-workflows", "project", projectName, "target", targetName)
level.Debug(l).Log("message", "listing workflows")
workflowList, err := h.argo.ListStatus(h.argoCtx)
if err != nil {
level.Error(l).Log("message", "error listing workflows", "error", err)
h.errorResponse(w, "error listing workflows", http.StatusInternalServerError)
return
}
// Only return workflows the target project / target
workflows := make([]workflow.Status, 0)
prefix := fmt.Sprintf("%s-%s", projectName, targetName)
for _, wf := range workflowList {
if strings.HasPrefix(wf.Name, prefix) {
workflows = append(workflows, wf)
}
}
jsonData, err := json.Marshal(workflows)
if err != nil {
level.Error(l).Log("message", "error serializing workflow IDs", "error", err)
h.errorResponse(w, "error serializing workflow IDs", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, string(jsonData))
}
// Creates workflow init params by pulling manifest from given git repo, commit sha, and code path
func (h handler) loadCreateWorkflowRequestFromGit(repository, commitHash, path string) (requests.CreateWorkflow, error) {
level.Debug(h.logger).Log("message", fmt.Sprintf("retrieving manifest from repository %s at sha %s with path %s", repository, commitHash, path))
fileContents, err := h.gitClient.GetManifestFile(repository, commitHash, path)
if err != nil {
return requests.CreateWorkflow{}, err
}
var cwr requests.CreateWorkflow
err = yaml.Unmarshal(fileContents, &cwr)
return cwr, err
}
func (h handler) createWorkflowFromGit(w http.ResponseWriter, r *http.Request) {
l := h.requestLogger(r, "op", "create-workflow-from-git")
ctx := r.Context()
level.Debug(l).Log("message", "validating authorization header for create workflow from git")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
// TODO we need to ensure this _isn't an admin...
if err := a.Validate(); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "reading request body")
reqBody, err := io.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("message", "error reading request data", "error", err)
h.errorResponse(w, "error reading request data", http.StatusInternalServerError)
return
}
var cgwr requests.CreateGitWorkflow
err = json.Unmarshal(reqBody, &cgwr)
if err != nil {
level.Error(l).Log("message", "error deserializing request body", "error", err)
h.errorResponse(w, "error deserializing request body", http.StatusBadRequest)
return
}
if err := cgwr.Validate(); err != nil {
level.Error(l).Log("message", "error validating request", "error", err)
h.errorResponse(w, fmt.Sprintf("invalid request, %s", err), http.StatusBadRequest)
return
}
vars := mux.Vars(r)
projectName := vars["projectName"]
projectEntry, err := h.dbClient.ReadProjectEntry(ctx, projectName)
if err != nil {
level.Error(l).Log("message", "error reading project data", "error", err)
h.errorResponse(w, "error reading project data", http.StatusInternalServerError)
return
}
cwr, err := h.loadCreateWorkflowRequestFromGit(projectEntry.Repository, cgwr.CommitHash, cgwr.Path)
if err != nil {
level.Error(l).Log("message", "error loading workflow data from git", "error", err)
h.errorResponse(w, "error loading workflow data from git", http.StatusInternalServerError)
return
}
log.With(l, "project", cwr.ProjectName, "target", cwr.TargetName, "framework", cwr.Framework, "type", cwr.Type, "workflow-template", cwr.WorkflowTemplateName)
level.Debug(l).Log("message", "creating workflow")
h.createWorkflowFromRequest(ctx, w, r, a, cwr, l)
}
// Creates a workflow
func (h handler) createWorkflow(w http.ResponseWriter, r *http.Request) {
l := h.requestLogger(r, "op", "create-workflow")
ctx := r.Context()
level.Debug(l).Log("message", "validating authorization header for create workflow")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "reading request body")
var cwr requests.CreateWorkflow
reqBody, err := io.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("message", "error reading workflow request data", "error", err)
h.errorResponse(w, "error reading workflow request data", http.StatusInternalServerError)
return
}
if err := json.Unmarshal(reqBody, &cwr); err != nil {
level.Error(l).Log("message", "error deserializing workflow data", "error", err)
h.errorResponse(w, "error deserializing workflow data", http.StatusBadRequest)
return
}
log.With(l, "project", cwr.ProjectName, "target", cwr.TargetName, "framework", cwr.Framework, "type", cwr.Type, "workflow-template", cwr.WorkflowTemplateName)
level.Debug(l).Log("message", "creating workflow")
h.createWorkflowFromRequest(ctx, w, r, a, cwr, l)
}
// Creates a workflow
// Context is not currently used as Argo has its own and Vault doesn't
// currently support it.
func (h handler) createWorkflowFromRequest(_ context.Context, w http.ResponseWriter, r *http.Request, a *credentials.Authorization, cwr requests.CreateWorkflow, l log.Logger) {
types, err := h.config.listTypes(cwr.Framework)
if err != nil {
level.Error(l).Log("message", "error invalid framework", "error", err)
h.errorResponse(
w,
fmt.Sprintf("invalid request, framework must be one of '%s'", strings.Join(h.config.listFrameworks(), " ")),
http.StatusBadRequest,
)
return
}
level.Debug(l).Log("message", "validating workflow parameters")
if err := cwr.Validate(
cwr.ValidateType(types),
); err != nil {
level.Error(l).Log("message", "error validating request", "error", err)
h.errorResponse(w, fmt.Sprintf("error invalid request, %s", err), http.StatusBadRequest)
return
}
workflowFrom := fmt.Sprintf("workflowtemplate/%s", cwr.WorkflowTemplateName)
executeContainerImageURI := cwr.Parameters["execute_container_image_uri"]
environmentVariablesString := generateEnvVariablesString(cwr.EnvironmentVariables)
level.Debug(l).Log("message", "generating command to execute")
commandDefinition, err := h.config.getCommandDefinition(cwr.Framework, cwr.Type)
if err != nil {
level.Error(l).Log("message", "unable to get command definition", "error", err)
h.errorResponse(w, "unable to retrieve command definition", http.StatusInternalServerError)
return
}
executeCommand, err := generateExecuteCommand(commandDefinition, environmentVariablesString, cwr.Arguments)
if err != nil {
level.Error(l).Log("message", "unable to generate command", "error", err)
h.errorResponse(w, "unable to generate command", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "creating new credentials provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "bad or unknown credentials provider", "error", err)
h.errorResponse(w, "bad or unknown credentials provider", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "getting credentials provider token")
credentialsToken, err := cp.GetToken()
if err != nil {
level.Error(l).Log("message", "error getting credentials provider token", "error", err)
h.errorResponse(w, "error retrieving credentials provider token", http.StatusInternalServerError)
return
}
projectExists, err := cp.ProjectExists(cwr.ProjectName)
if err != nil {
level.Error(l).Log("message", "error checking project", "error", err)
h.errorResponse(w, "error checking project", http.StatusInternalServerError)
return
}
if !projectExists {
level.Error(l).Log("message", "project does not exist", "error", err)
h.errorResponse(w, "project does not exist", http.StatusBadRequest)
return
}
targetExists, err := cp.TargetExists(cwr.ProjectName, cwr.TargetName)
if err != nil {
level.Error(l).Log("message", "error retrieving target", "error", err)
h.errorResponse(w, "error retrieving target", http.StatusInternalServerError)
return
}
if !targetExists {
level.Error(l).Log("message", "target not found")
h.errorResponse(w, "target not found", http.StatusBadRequest)
return
}
level.Debug(l).Log("message", "creating workflow parameters")
parameters := workflow.NewParameters(environmentVariablesString, executeCommand, executeContainerImageURI, cwr.TargetName, cwr.ProjectName, cwr.Parameters, credentialsToken, cwr.Type)
workflowLabels := map[string]string{txIDHeader: r.Header.Get(txIDHeader)}
level.Debug(l).Log("message", "creating workflow")
workflowName, err := h.argo.Submit(h.argoCtx, workflowFrom, parameters, workflowLabels)
if err != nil {
level.Error(l).Log("message", "error creating workflow", "error", err)
h.errorResponse(w, "error creating workflow", http.StatusInternalServerError)
return
}
l = log.With(l, "workflow", workflowName)
level.Debug(l).Log("message", "workflow created")
tokenHead := credentialsToken[0:8]
level.Info(l).Log("message", fmt.Sprintf("Received token '%s...'", tokenHead))
var cwresp workflow.CreateWorkflowResponse
cwresp.WorkflowName = workflowName
jsonData, err := json.Marshal(cwresp)
if err != nil {
level.Error(l).Log("message", "error serializing workflow response", "error", err)
h.errorResponse(w, "error serializing workflow response", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, string(jsonData))
}
// Gets a workflow
func (h handler) getWorkflow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
workflowName := vars["workflowName"]
l := h.requestLogger(r, "op", "get-workflow", "workflow", workflowName)
level.Debug(l).Log("message", "getting workflow status")
status, err := h.argo.Status(h.argoCtx, workflowName)
if err != nil {
if strings.Contains(err.Error(), "code = NotFound") {
level.Error(l).Log("message", "error getting workflow", "error", err)
h.errorResponse(w, "workflow not found", http.StatusNotFound)
} else {
level.Error(l).Log("message", "error getting workflow", "error", err)
h.errorResponse(w, "error getting workflow", http.StatusInternalServerError)
}
return
}
level.Debug(l).Log("message", "decoding get workflow response")
jsonData, err := json.Marshal(status)
if err != nil {
level.Error(l).Log("message", "error serializing workflow", "error", err)
h.errorResponse(w, "error serializing workflow", http.StatusInternalServerError)
return
}
fmt.Fprint(w, string(jsonData))
}
// Gets a target
func (h handler) getTarget(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
targetName := vars["targetName"]
l := h.requestLogger(r, "op", "get-target", "project", projectName, "target", targetName)
level.Debug(l).Log("message", "validating authorization header for get target")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
targetExists, err := cp.TargetExists(projectName, targetName)
if err != nil {
level.Error(l).Log("message", "error retrieving target", "error", err)
h.errorResponse(w, "error retrieving target", http.StatusInternalServerError)
return
}
if !targetExists {
level.Error(l).Log("message", "target not found")
h.errorResponse(w, "target not found", http.StatusNotFound)
return
}
level.Debug(l).Log("message", "getting target information")
targetInfo, err := cp.GetTarget(projectName, targetName)
if err != nil {
level.Error(l).Log("message", "error retrieving target information", "error", err)
h.errorResponse(w, "error retrieving target information", http.StatusInternalServerError)
return
}
jsonResult, err := json.Marshal(targetInfo)
if err != nil {
level.Error(l).Log("message", "error serializing json target data", "error", err)
h.errorResponse(w, "error serializing json target data", http.StatusInternalServerError)
return
}
fmt.Fprint(w, string(jsonResult))
}
// Returns the logs for a workflow
func (h handler) getWorkflowLogs(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
workflowName := vars["workflowName"]
l := h.requestLogger(r, "op", "get-workflow-logs", "workflow", workflowName)
level.Debug(l).Log("message", "retrieving workflow logs")
argoWorkflowLogs, err := h.argo.Logs(h.argoCtx, workflowName)
if err != nil {
level.Error(l).Log("message", "error getting workflow logs", "error", err)
h.errorResponse(w, "error getting workflow logs", http.StatusInternalServerError)
return
}
jsonData, err := json.Marshal(argoWorkflowLogs)
if err != nil {
level.Error(l).Log("message", "error serializing workflow logs", "error", err)
h.errorResponse(w, "error serializing workflow logs", http.StatusInternalServerError)
return
}
fmt.Fprintln(w, string(jsonData))
}
// Streams workflow logs
func (h handler) getWorkflowLogStream(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("X-Accel-Buffering", "no")
vars := mux.Vars(r)
workflowName := vars["workflowName"]
l := h.requestLogger(r, "op", "get-workflow-log-stream", "workflow", workflowName)
level.Debug(l).Log("message", "retrieving workflow logs", "workflow", workflowName)
err := h.argo.LogStream(h.argoCtx, workflowName, w)
if err != nil {
level.Error(l).Log("message", "error getting workflow logstream", "error", err)
h.errorResponse(w, "error getting workflow logs", http.StatusInternalServerError)
return
}
}
// Returns a new Cello token
func newCelloToken(provider string, tok types.Token) *token {
return &token{
Token: fmt.Sprintf("%s:%s:%s", provider, tok.RoleID, tok.Secret),
}
}
// projectExists checks if a project exists using both the credential provider and database
func (h handler) projectExists(ctx context.Context, l log.Logger, cp credentials.Provider, w http.ResponseWriter, projectName string) (bool, error) {
// Checking credential provider
level.Debug(l).Log("message", "checking if project exists")
projectExists, err := cp.ProjectExists(projectName)
if err != nil {
level.Error(l).Log("message", "error checking credentials provider for project", "error", err)
h.errorResponse(w, "error retrieving project", http.StatusInternalServerError)
return false, err
}
if !projectExists {
level.Debug(l).Log("message", "project does not exist in credentials provider")
h.errorResponse(w, "project does not exist", http.StatusNotFound)
return false, err
}
// Checking database
_, err = h.dbClient.ReadProjectEntry(ctx, projectName)
if err != nil {
level.Error(l).Log("message", "error retrieving project from database", "error", err)
if errors.Is(err, upper.ErrNoMoreRows) {
h.errorResponse(w, "project does not exist", http.StatusNotFound)
} else {
h.errorResponse(w, "error retrieving project", http.StatusInternalServerError)
}
return false, err
}
return true, err
}
// Creates a project
func (h handler) createProject(w http.ResponseWriter, r *http.Request) {
l := h.requestLogger(r, "op", "create-project")
level.Debug(l).Log("message", "validating authorization header for create project")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
ctx := r.Context()
var capp requests.CreateProject
reqBody, err := io.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("message", "error reading request body", "error", err)
h.errorResponse(w, "error reading request body", http.StatusInternalServerError)
return
}
if err := json.Unmarshal(reqBody, &capp); err != nil {
level.Error(l).Log("message", "error decoding request", "error", err)
h.errorResponse(w, "error decoding request", http.StatusBadRequest)
return
}
if err := capp.Validate(); err != nil {
level.Error(l).Log("message", "error invalid request", "error", err)
h.errorResponse(w, fmt.Sprintf("invalid request, %s", err.Error()), http.StatusBadRequest)
return
}
l = log.With(l, "project", capp.Name)
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
projectExists, err := cp.ProjectExists(capp.Name)
if err != nil {
level.Error(l).Log("message", "error checking project", "error", err)
h.errorResponse(w, "error checking project", http.StatusInternalServerError)
return
}
if projectExists {
level.Error(l).Log("error", "project already exists")
h.errorResponse(w, "project already exists", http.StatusBadRequest)
return
}
level.Debug(l).Log("message", "inserting into db")
err = h.dbClient.CreateProjectEntry(ctx, db.ProjectEntry{
ProjectID: capp.Name,
Repository: capp.Repository,
})
if err != nil {
level.Error(l).Log("message", "error inserting project to db", "error", err)
h.errorResponse(w, "error creating project", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "creating project")
token, err := cp.CreateProject(capp.Name)
if err != nil {
level.Error(l).Log("message", "error creating project", "error", err)
h.errorResponse(w, "error creating project", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "inserting token into DB")
err = h.dbClient.CreateTokenEntry(ctx, token)
if err != nil {
level.Error(l).Log("message", "error inserting token into DB", "error", err)
h.errorResponse(w, "error creating token", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "retrieving Cello token")
celloToken := newCelloToken("vault", token)
resp := responses.CreateProject{
Token: celloToken.Token,
TokenID: token.ProjectToken.ID,
}
if err := json.NewEncoder(w).Encode(resp); err != nil {
level.Error(l).Log("message", "error serializing token", "error", err)
h.errorResponse(w, "error serializing token", http.StatusInternalServerError)
return
}
}
// Get a project
func (h handler) getProject(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
l := h.requestLogger(r, "op", "get-project", "project", projectName)
level.Debug(l).Log("message", "validating authorization header for get project")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "getting project from database")
ctx := r.Context()
projectEntry, err := h.dbClient.ReadProjectEntry(ctx, projectName)
if err != nil {
level.Error(l).Log("message", "error retrieving project", "error", err)
if errors.Is(err, upper.ErrNoMoreRows) {
h.errorResponse(w, "error retrieving project", http.StatusNotFound)
} else {
h.errorResponse(w, "error retrieving project", http.StatusInternalServerError)
}
return
}
resp := responses.GetProject{
Name: projectName,
Repository: projectEntry.Repository,
}
if err := json.NewEncoder(w).Encode(resp); err != nil {
level.Error(l).Log("message", "error creating response", "error", err)
h.errorResponse(w, "error creating response object", http.StatusInternalServerError)
return
}
}
// Delete a project
func (h handler) deleteProject(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
l := h.requestLogger(r, "op", "delete-project", "project", projectName)
level.Debug(l).Log("message", "validating authorization header for delete project")
ctx := r.Context()
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "checking if project exists")
projectExists, err := cp.ProjectExists(projectName)
if err != nil {
level.Error(l).Log("message", "error checking project", "error", err)
h.errorResponse(w, "error checking project", http.StatusInternalServerError)
return
}
if !projectExists {
level.Debug(l).Log("message", "no action required because project does not exist")
return
}
level.Debug(l).Log("message", "getting all targets in project")
targets, err := cp.ListTargets(projectName)
if err != nil {
level.Error(l).Log("message", "error getting all targets", "error", err)
h.errorResponse(w, "error getting all targets", http.StatusInternalServerError)
return
}
if len(targets) > 0 {
level.Error(l).Log("error", "project has existing targets, not deleting")
h.errorResponse(w, "project has existing targets, not deleting", http.StatusBadRequest)
return
}
level.Debug(l).Log("message", "deleting project")
err = cp.DeleteProject(projectName)
if err != nil {
level.Error(l).Log("message", "error deleting project", "error", err)
h.errorResponse(w, "error deleting project", http.StatusInternalServerError)
return
}
level.Debug(h.logger).Log("message", "deleting from db")
if err = h.dbClient.DeleteProjectEntry(ctx, projectName); err != nil {
level.Error(l).Log("message", "error deleting project in database", "error", err)
h.errorResponse(w, "error deleting project", http.StatusInternalServerError)
return
}
}
// Creates a target
func (h handler) createTarget(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
l := h.requestLogger(r, "op", "create-target", "project", projectName)
level.Debug(l).Log("message", "validating authorization header for create target")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "unauthorized", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "reading request body")
var ctr requests.CreateTarget
reqBody, err := io.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("message", "error reading request data", "error", err)
h.errorResponse(w, "error reading request data", http.StatusInternalServerError)
}
if err := json.Unmarshal(reqBody, &ctr); err != nil {
level.Error(l).Log("message", "error processing request", "error", err)
h.errorResponse(w, "error processing request", http.StatusBadRequest)
return
}
if err := types.Target(ctr).Validate(); err != nil {
level.Error(l).Log("message", "error invalid request", "error", err)
h.errorResponse(w, fmt.Sprintf("invalid request, %s", err), http.StatusBadRequest)
return
}
l = log.With(l, "target", ctr.Name)
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
projectExists, err := cp.ProjectExists(projectName)
if err != nil {
level.Error(l).Log("message", "error determining if project exists", "error", err)
}
// TODO Perhaps this should be 404
if !projectExists {
level.Error(l).Log("message", "project does not exist")
h.errorResponse(w, "project does not exist", http.StatusBadRequest)
return
}
targetExists, err := cp.TargetExists(projectName, ctr.Name)
if err != nil {
level.Error(l).Log("message", "error retrieving target", "error", err)
h.errorResponse(w, "error retrieving target", http.StatusInternalServerError)
return
}
if targetExists {
level.Error(l).Log("message", "target name must not already exist")
h.errorResponse(w, "target name must not already exist", http.StatusBadRequest)
return
}
level.Debug(l).Log("message", "creating target")
err = cp.CreateTarget(projectName, types.Target(ctr))
if err != nil {
level.Error(l).Log("message", "error creating target", "error", err)
h.errorResponse(w, "error creating target", http.StatusInternalServerError)
return
}
fmt.Fprint(w, "{}")
}
// Deletes a target
func (h handler) deleteTarget(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
targetName := vars["targetName"]
l := h.requestLogger(r, "op", "delete-target", "project", projectName, "target", targetName)
level.Debug(l).Log("message", "validating authorization header for delete target")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "deleting target")
err = cp.DeleteTarget(projectName, targetName)
if err != nil {
level.Error(l).Log("message", "error deleting target", "error", err)
h.errorResponse(w, "error deleting target", http.StatusInternalServerError)
return
}
}
// Lists the targets for a project
func (h handler) listTargets(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
l := h.requestLogger(r, "op", "list-targets", "project", projectName)
level.Debug(l).Log("message", "validating authorization header for target list")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header format", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
level.Debug(l).Log("message", "checking if project exists")
projectExists, err := cp.ProjectExists(projectName)
if err != nil {
level.Error(l).Log("message", "error checking project", "error", err)
h.errorResponse(w, "error checking project", http.StatusInternalServerError)
return
}
if !projectExists {
level.Debug(l).Log("message", "project does not exist")
h.errorResponse(w, "project does not exist", http.StatusNotFound)
return
}
targets, err := cp.ListTargets(projectName)
if err != nil {
level.Error(l).Log("message", "error listing targets", "error", err)
h.errorResponse(w, "error listing targets", http.StatusInternalServerError)
return
}
data, err := json.Marshal(targets)
if err != nil {
level.Error(l).Log("message", "error serializing targets", "error", err)
h.errorResponse(w, "error listing targets", http.StatusInternalServerError)
return
}
fmt.Fprint(w, string(data))
}
// Updates a target
func (h handler) updateTarget(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
projectName := vars["projectName"]
targetName := vars["targetName"]
l := h.requestLogger(r, "op", "update-target", "project", projectName, "target", targetName)
level.Debug(l).Log("message", "validating authorization header for update target")
ah := r.Header.Get("Authorization")
a, err := credentials.NewAuthorization(ah)
if err != nil {
h.errorResponse(w, "error unauthorized, invalid authorization header", http.StatusUnauthorized)
return
}
if err := a.Validate(a.ValidateAuthorizedAdmin(h.env.AdminSecret)); err != nil {
h.errorResponse(w, "unauthorized", http.StatusUnauthorized)
return
}
level.Debug(l).Log("message", "creating credential provider")
cp, err := h.newCredentialsProvider(*a, h.env, r.Header, credentials.NewVaultConfig, credentials.NewVaultSvc)
if err != nil {
level.Error(l).Log("message", "error creating credentials provider", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
projectExists, err := cp.ProjectExists(projectName)
if err != nil {
level.Error(l).Log("message", "error determining if project exists", "error", err)
h.errorResponse(w, "error creating credentials provider", http.StatusInternalServerError)
return
}
if !projectExists {
level.Error(l).Log("message", "project does not exist")
h.errorResponse(w, "project does not exist", http.StatusNotFound)
return
}
targetExists, err := cp.TargetExists(projectName, targetName)
if err != nil {
level.Error(l).Log("message", "error retrieving target", "error", err)
h.errorResponse(w, "error retrieving target", http.StatusInternalServerError)
return
}
if !targetExists {
level.Error(l).Log("message", "target not found")
h.errorResponse(w, "target not found", http.StatusNotFound)
return
}
target, err := cp.GetTarget(projectName, targetName)
if err != nil {
level.Error(l).Log("message", "error retrieving existing target")
h.errorResponse(w, "error retrieving target", http.StatusInternalServerError)
return
}
targetType := target.Type
level.Debug(l).Log("message", "reading request body")
reqBody, err := io.ReadAll(r.Body)
if err != nil {
level.Error(l).Log("message", "error reading request data", "error", err)
h.errorResponse(w, "error reading request data", http.StatusInternalServerError)
return