-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathcodegen.go
executable file
·3905 lines (3280 loc) · 123 KB
/
codegen.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 shuffle
import (
"archive/zip"
"bytes"
"context"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"net/http"
"cloud.google.com/go/storage"
"github.com/frikky/kin-openapi/openapi3"
docker "github.com/docker/docker/client"
//"github.com/satori/go.uuid"
"gopkg.in/yaml.v2"
)
var downloadedImages = []string{}
var pythonAllowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
var pythonReplacements = map[string]string{
"[": "",
"]": "",
"{": "",
"}": "",
"(": "",
")": "",
"!": "",
"@": "",
"#": "",
"$": "",
"%": "",
"^": "",
"&": "",
":": "",
";": "",
"<": "",
">": "",
"'": "",
}
func CopyFile(fromfile, tofile string) error {
from, err := os.Open(fromfile)
if err != nil {
return err
}
defer from.Close()
to, err := os.OpenFile(tofile, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return err
}
defer to.Close()
_, err = io.Copy(to, from)
if err != nil {
return err
}
return nil
}
func GetCorrectActionName(parsed string) string {
if strings.HasPrefix(parsed, "post ") || strings.HasPrefix(parsed, "post_") {
parsed = parsed[5:]
} else if strings.HasPrefix(parsed, "get list") || strings.HasPrefix(parsed, "get_list") {
parsed = parsed[4:]
} else if strings.HasPrefix(parsed, "head ") || strings.HasPrefix(parsed, "head_") {
parsed = parsed[5:]
} else if strings.HasPrefix(parsed, "put ") || strings.HasPrefix(parsed, "put_") {
parsed = parsed[4:]
} else if strings.HasPrefix(parsed, "patch ") || strings.HasPrefix(parsed, "patch_") {
parsed = parsed[6:]
}
if strings.HasPrefix(parsed, "\"") {
parsed = parsed[1:]
}
if strings.HasSuffix(parsed, "\"") {
parsed = parsed[:len(parsed)-1]
}
return parsed
}
func FormatAppfile(filedata string) (string, string) {
lines := strings.Split(filedata, "\n")
newfile := []string{}
classname := ""
for _, line := range lines {
if strings.Contains(line, "walkoff_app_sdk") {
continue
}
// Remap logging. CBA this right now
// This issue also persists in onprem apps because of await thingies.. :(
// FIXME
if strings.Contains(line, "console_logger") && strings.Contains(line, "await") {
continue
//line = strings.Replace(line, "console_logger", "logger", -1)
//log.Println(line)
}
// Might not work with different import names
// Could be fucked up with spaces everywhere? Idk
if strings.Contains(line, "class") && strings.Contains(line, "(AppBase)") {
items := strings.Split(line, " ")
if len(items) > 0 && strings.Contains(items[1], "(AppBase)") {
classname = strings.Split(items[1], "(")[0]
} else {
// This could break something..
classname = "TMP"
}
}
if strings.Contains(line, "if __name__ ==") {
break
}
// asyncio.run(HelloWorld.run(), debug=True)
newfile = append(newfile, line)
}
filedata = strings.Join(newfile, "\n")
return classname, filedata
}
// Streams the data into a zip to be used for a cloud function
func StreamZipdata(ctx context.Context, identifier, pythoncode, requirements, bucketName string) (string, error) {
filename := fmt.Sprintf("generated_cloudfunctions/%s.zip", identifier)
buf := new(bytes.Buffer)
zipWriter := zip.NewWriter(buf)
if project.Environment == "cloud" {
client, err := storage.NewClient(ctx)
if err != nil {
log.Printf("Failed to create datastore client: %v", err)
return filename, err
}
bucket := client.Bucket(bucketName)
obj := bucket.Object(filename)
storageWriter := obj.NewWriter(ctx)
defer storageWriter.Close()
zipWriter = zip.NewWriter(storageWriter)
}
zipFile, err := zipWriter.Create("main.py")
if err != nil {
log.Printf("Packing failed to create zip file from bucket: %v", err)
return filename, err
}
// Have to use Fprintln otherwise it tries to parse all strings etc.
if _, err := fmt.Fprintln(zipFile, pythoncode); err != nil {
return filename, err
}
//log.Printf("Merging requirements: %s", requirements)
zipFile, err = zipWriter.Create("requirements.txt")
if err != nil {
log.Printf("Packing failed to create zip file from bucket: %v", err)
return filename, err
}
if _, err := fmt.Fprintln(zipFile, requirements); err != nil {
return filename, err
}
err = zipWriter.Close()
if err != nil {
log.Printf("Packing failed to close zip file writer from bucket: %v", err)
return filename, err
}
//src := client.Bucket(bucketName).Object(fmt.Sprintf("%s/baseline/%s", basePath, file))
//dst := client.Bucket(bucketName).Object(fmt.Sprintf("%s/%s", appPath, file))
//if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
// return "", err
//}
//log.Printf("Finished upload")
return filename, nil
}
func GetAppbase() ([]byte, []byte, error) {
// 1. Have baseline in bucket/generated_apps/baseline
// 2. Copy the baseline to a new folder with identifier name
appbase := "../app_sdk/app_base.py"
//static := "../app_sdk/static_baseline.py"
//staticData, err := ioutil.ReadFile(static)
//if err != nil {
// return []byte{}, []byte{}, err
//}
staticData := []byte{}
appbaseData, err := ioutil.ReadFile(appbase)
if err != nil {
return []byte{}, []byte{}, err
}
return appbaseData, staticData, nil
}
// Builds the structure for the new generated app in storage (copying baseline files)
func GetAppbaseGCP(ctx context.Context, client *storage.Client, bucketName string) ([]byte, []byte, error) {
// 1. Have baseline in bucket/generated_apps/baseline
// 2. Copy the baseline to a new folder with identifier name
basePath := "generated_apps/baseline"
appbase, err := client.Bucket(bucketName).Object(fmt.Sprintf("%s/app_base.py", basePath)).NewReader(ctx)
if err != nil {
return []byte{}, []byte{}, err
}
defer appbase.Close()
appbaseData, err := ioutil.ReadAll(appbase)
if err != nil {
return []byte{}, []byte{}, err
}
return appbaseData, []byte{}, nil
}
func FixAppbase(appbase []byte) []string {
record := true
validLines := []string{}
// Used to use static_baseline + app_base. Now it's only appbase :O
for _, line := range strings.Split(string(appbase), "\n") {
//if strings.Contains(line, "#STOPCOPY") {
// //log.Println("Stopping copy")
// break
//}
if record {
validLines = append(validLines, line)
}
//if strings.Contains(line, "#STARTCOPY") {
// //log.Println("Starting copy")
// record = true
//}
}
return validLines
}
// Builds the structure for the new generated app in storage (copying baseline files)
func BuildStructureGCP(ctx context.Context, client *storage.Client, identifier, bucketName string) (string, error) {
// 1. Have baseline in bucket/generated_apps/baseline
// 2. Copy the baseline to a new folder with identifier name
basePath := "generated_apps"
//identifier := fmt.Sprintf("%s-%s", swagger.Info.Title, curHash)
appPath := fmt.Sprintf("%s/%s", basePath, identifier)
fileNames := []string{"Dockerfile", "requirements.txt"}
for _, file := range fileNames {
src := client.Bucket(bucketName).Object(fmt.Sprintf("%s/baseline/%s", basePath, file))
dst := client.Bucket(bucketName).Object(fmt.Sprintf("%s/%s", appPath, file))
if _, err := dst.CopierFrom(src).Run(ctx); err != nil {
return "", err
}
}
return appPath, nil
}
// Builds the base structure for the app that we're making
// Returns error if anything goes wrong. This has to work if
// the python code is supposed to be generated
func BuildStructure(swagger *openapi3.Swagger, curHash string) (string, error) {
//log.Printf("%#v", swagger)
// adding md5 based on input data to not overwrite earlier data.
generatedPath := "generated"
subpath := "../app_gen/openapi/"
identifier := fmt.Sprintf("%s-%s", swagger.Info.Title, curHash)
appPath := fmt.Sprintf("%s/%s", generatedPath, identifier)
os.MkdirAll(appPath, os.ModePerm)
os.Mkdir(fmt.Sprintf("%s/src", appPath), os.ModePerm)
err := CopyFile(fmt.Sprintf("%sbaseline/Dockerfile", subpath), fmt.Sprintf("%s/%s", appPath, "Dockerfile"))
if err != nil {
log.Println("Failed to move Dockerfile")
return appPath, err
}
err = CopyFile(fmt.Sprintf("%sbaseline/requirements.txt", subpath), fmt.Sprintf("%s/%s", appPath, "requirements.txt"))
if err != nil {
log.Println("Failed to move requrements.txt")
return appPath, err
}
return appPath, nil
}
func TrimToNum(r int) bool {
if n := r - '0'; n >= 0 && n <= 9 {
return false
}
return true
}
// Returns fixed function names based on a list of strings
func GetValidParameters(parameters []string) []string {
numbers := "0123456789"
newParams := []string{}
for _, param := range parameters {
if param == "headers=\"\"" || param == "queries=\"\"" {
newParams = append(newParams, param)
continue
}
originalParam := param
// Something with dashes not working?
for key, val := range pythonReplacements {
param = strings.Replace(param, key, val, -1)
}
for _, char := range param {
if !strings.Contains(pythonAllowed, string(char)) {
param = strings.Replace(param, string(char), "", -1)
}
}
if len(param) > 0 && !ArrayContains(newParams, param) {
newParams = append(newParams, param)
} else {
// Find some name for it just for the code
h := md5.New()
io.WriteString(h, originalParam)
newName := strings.ToLower(fmt.Sprintf("%X", h.Sum(nil)))
// Fix leading numbers
newString := ""
shouldAdd := false
for _, char := range newName {
if !strings.Contains(numbers, string(char)) {
shouldAdd = true
}
if shouldAdd {
newString += string(char)
}
}
// Leading 0 not allowed
newParams = append(newParams, newString)
}
}
return newParams
}
// This function generates the python code that's being used.
// This is really meta when you program it. Handling parameters is hard here.
func MakePythoncode(swagger *openapi3.Swagger, name, url, method string, parameters, optionalQueries, headers []string, fileField string, api WorkflowApp, handleFile bool) (string, string) {
method = strings.ToLower(method)
queryString := ""
queryData := ""
extraHeaders := ""
extraQueries := ""
reservedKeys := []string{"BearerAuth", "ApiKeyAuth", "Oauth2", "BasicAuth", "JWT"}
if swagger.Components.SecuritySchemes != nil {
for key, value := range swagger.Components.SecuritySchemes {
if ArrayContains(reservedKeys, key) {
continue
}
//parsedKey := strings.Replace(key, "-", "_", -1)
parsedKey := FixFunctionName(key, "", true)
if value.Value.In == "header" {
queryString += fmt.Sprintf(", %s=\"\"", parsedKey)
if len(extraHeaders) > 0 {
extraHeaders += "\n "
}
extraHeaders += fmt.Sprintf(`if %s != " ": request_headers["%s"] = %s`, parsedKey, key, parsedKey)
} else if value.Value.In == "query" {
log.Printf("Handling extra queries for %#v", parsedKey)
if strings.Contains(parsedKey, "=") {
parsedKey = strings.Split(parsedKey, "=")[0]
}
queryString += fmt.Sprintf(", %s=\"\"", parsedKey)
if len(extraQueries) > 0 {
extraQueries += "\n "
}
extraQueries += fmt.Sprintf(`if %s != " ": params["%s"] = %s`, parsedKey, key, parsedKey)
} else {
//log.Printf("[WARNING] Can't handle type %s", value.Value.In)
}
}
}
// FIXME - this might break - need to check if ? or & should be set as query
parameterData := ""
if len(optionalQueries) > 0 {
//if len(queryString
queryString += ", "
for index, query := range optionalQueries {
// Check if it's a part of the URL already
parsedQuery := FixFunctionName(query, "", true)
newParams := GetValidParameters([]string{parsedQuery})
if len(newParams) > 0 {
parsedQuery = newParams[0]
}
queryString += fmt.Sprintf("%s=\"\"", parsedQuery)
if index != len(optionalQueries)-1 {
queryString += ", "
}
/*
queryData += fmt.Sprintf(`
if %s:
url += f"&%s={%s}"`, query, query, query)
*/
queryData += fmt.Sprintf(`
if %s:
if isinstance(%s, list) or isinstance(%s, dict):
try:
%s = json.dumps(%s)
except:
pass
params[requests.utils.quote("%s")] = requests.utils.quote(%s)`, parsedQuery, parsedQuery, parsedQuery, parsedQuery, parsedQuery, query, parsedQuery)
}
} else {
//log.Printf("No optional queries?")
}
// api.Authentication.Parameters[0].Value = "BearerAuth"
authenticationParameter := ""
authenticationSetup := ""
authenticationAddin := ""
// Python configuration code that should work :)
if swagger.Components.SecuritySchemes != nil {
if swagger.Components.SecuritySchemes["BearerAuth"] != nil {
authenticationParameter = ", apikey"
authenticationSetup = "if apikey != \" \" and not apikey.startswith(\"Bearer\"): request_headers[\"Authorization\"] = f\"Bearer {apikey}\""
} else if swagger.Components.SecuritySchemes["BasicAuth"] != nil {
authenticationParameter = ", username_basic, password_basic"
authenticationSetup = "auth=None\n if username_basic or password_basic:\n if \"Authorization\" not in headers and \"Basic\" not in headers and not \"Bearer\" in headers:\n auth = requests.auth.HTTPBasicAuth(username_basic, password_basic)"
//authenticationAddin = ", auth=(username_basic, password_basic)"
authenticationAddin = ", auth=auth"
} else if swagger.Components.SecuritySchemes["ApiKeyAuth"] != nil {
authenticationParameter = ", apikey"
//if len(securitySchemes["ApiKeyAuth"].Value.Description) > 0 {
// //log.Printf("UPDATING AUTH!")
// extraParam.Description = fmt.Sprintf("Start with %s", securitySchemes["ApiKeyAuth"].Value.Description)
if swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.In == "header" {
// This is a way to bypass apikeys by passing " "
authenticationSetup = fmt.Sprintf(`if apikey != " ": request_headers["%s"] = apikey`, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name)
// Fixes token prefixes (e.g. Token.. or SSWS..)
if len(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description) > 0 {
trimmedDescription := strings.Trim(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, " ")
authenticationSetup = fmt.Sprintf("if apikey != \" \":\n if apikey.startswith(\"%s\"):\n request_headers[\"%s\"] = apikey\n else:\n apikey = apikey.replace(\"%s\", \"\", -1).strip()\n request_headers[\"%s\"] = f\"%s{apikey}\"", trimmedDescription, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description)
}
} else if swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.In == "query" {
// This might suck lol
//authenticationSetup = fmt.Sprintf("if apikey != \" \": params[\"%s\"] = requests.utils.quote(apikey)", swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name)
trimmedDescription := strings.Trim(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, " ")
authenticationSetup = fmt.Sprintf("if apikey != \" \":\n if apikey.startswith(\"%s\"):\n params[\"%s\"] = requests.utils.quote(apikey)\n else:\n apikey = apikey.replace(\"%s\", \"\", -1).strip()\n params[\"%s\"] = requests.utils.quote(f\"%s{apikey}\")", trimmedDescription, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description)
}
} else if swagger.Components.SecuritySchemes["Oauth2"] != nil {
//log.Printf("[DEBUG] Appending Oauth2 code")
authenticationParameter = ", access_token"
authenticationSetup = fmt.Sprintf("if access_token != \" \": request_headers[\"Authorization\"] = f\"Bearer {access_token}\"\n #request_headers[\"Content-Type\"] = \"application/json\"")
} else if swagger.Components.SecuritySchemes["jwt"] != nil {
//log.Printf("[DEBUG] Appending Oauth2 code")
authenticationParameter = ", username_basic, password_basic"
//api.Authentication.TokenUri = securitySchemes["jwt"].Value.In
//authenticationSetup = fmt.Sprintf("authret = requests.get(f\"{url}%s\", headers=request_headers, auth=(username_basic, password_basic), verify=False)\n request_headers[\"Authorization\"] = f\"Bearer {authret.text}\"\n print(f\"{authret.text}\")", api.Authentication.TokenUri)
// Add: client_id and client_secret in body as JSON?
// ADD: accessToken = field
authenticationSetup = fmt.Sprintf("authret = requests.get(f\"{url}%s\", headers=request_headers, auth=(username_basic, password_basic), verify=False)\n if 'access_token' in authret.text:\n request_headers[\"Authorization\"] = f\"Bearer {authret.json()['access_token']}\"\n elif 'jwt' in authret.text:\n request_headers[\"Authorization\"] = f\"Bearer {authret.json()['jwt']}\"\n elif 'accessToken' in authret.text:\n request_headers[\"Authorization\"] = f\"Bearer {authret.json()['accessToken']}\"\n else:\n request_headers[\"Authorization\"] = f\"Bearer {authret.text}\"\n print(f\"Found Bearer auth: {authret.text}\")", api.Authentication.TokenUri)
//log.Printf("[DEBUG] Appending jwt code for authenticationSetup:\n %s", authenticationSetup)
}
}
urlSplit := strings.Split(url, "/")
if strings.HasPrefix(url, "http") && len(urlSplit) > 2 {
tmpUrl := strings.Join(urlSplit[3:len(urlSplit)], "/")
if len(tmpUrl) > 0 {
url = "/" + tmpUrl
} else {
if strings.HasSuffix(url, "/") {
url = "/"
} else {
url = ""
}
}
} else {
tmpUrl := ""
if len(urlSplit) > 2 {
tmpUrl = "/" + strings.Join(urlSplit[3:len(urlSplit)], "/")
}
if !strings.HasPrefix(url, "/") {
url = tmpUrl
}
}
urlParameter := ", url"
urlInline := "{url}"
// Specific check for SSL verification
// This is critical for onprem stuff.
// Added to_file as of July 2022
verifyParam := ", ssl_verify=False, to_file=False"
verifyWrapper := `ssl_verify = True if str(ssl_verify).lower() == "true" or ssl_verify == "1" else False`
verifyAddin := ", verify=ssl_verify"
// Codegen for headers
headerParserCode := ""
queryParserCode := ""
if len(parameters) > 0 {
parameters = GetValidParameters(parameters)
parameterData = fmt.Sprintf(", %s", strings.Join(parameters, ", "))
// This is gibberish :)
for _, param := range parameters {
if strings.Contains(param, "headers=") {
headerParserCode = "if len(headers) > 0:\n for header in headers.split(\"\\n\"):\n if ':' in header:\n headersplit=header.split(':')\n request_headers[headersplit[0].strip()] = ':'.join(headersplit[1:]).strip()\n elif '=' in header:\n headersplit=header.split('=')\n request_headers[headersplit[0].strip()] = '='.join(headersplit[1:]).strip()"
} else if strings.Contains(param, "queries=") {
queryParserCode = "\n if len(queries) > 0:\n if queries[0] == \"?\" or queries[0] == \"&\":\n queries = queries[1:len(queries)]\n if queries[len(queries)-1] == \"?\" or queries[len(queries)-1] == \"&\":\n queries = queries[0:-1]\n for query in queries.split(\"&\"):\n if isinstance(query, list) or isinstance(query, dict):\n try:\n query = json.dumps(query)\n except:\n pass\n if '=' in query:\n headersplit=query.split('=')\n params[requests.utils.quote(headersplit[0].strip())] = requests.utils.quote(headersplit[1].strip())\n else:\n params[requests.utils.quote(query.strip())] = None\n params = '&'.join([k if v is None else f\"{k}={v}\" for k, v in params.items()])"
} else {
if !strings.Contains(url, fmt.Sprintf("{%s}", param)) {
queryData += fmt.Sprintf(`
if %s:
if isinstance(%s, list) or isinstance(%s, dict):
try:
%s = json.dumps(%s)
except:
pass
params[requests.utils.quote("%s")] = requests.utils.quote(%s)`, param, param, param, param, param, param, param)
}
}
}
}
functionname := strings.ToLower(fmt.Sprintf("%s_%s", method, name))
if strings.Contains(strings.ToLower(name), strings.ToLower(method)) {
functionname = strings.ToLower(name)
}
bodyParameter := ""
bodyAddin := ""
bodyFormatter := ""
postParameters := []string{"post", "patch", "put", "delete"}
for _, item := range postParameters {
if method == item {
bodyParameter = ", body=\"\""
bodyAddin = ", data=body"
// FIXME: Does JSON data work?
bodyFormatter = "try:\n body = \" \".join(body.strip().split()).encode(\"utf-8\")\n except:\n pass"
}
}
preparedHeaders := "request_headers={}"
if len(headers) > 0 {
if method == "post" && len(fileField) > 0 {
} else {
preparedHeaders = "request_headers={"
for count, header := range headers {
headerSplit := strings.Split(header, "=")
added := false
if len(headerSplit) == 2 {
if strings.Contains(preparedHeaders, headerSplit[0]) {
continue
}
headerSplit[0] = strings.Replace(headerSplit[0], "\"", "", -1)
headerSplit[0] = strings.Replace(headerSplit[0], "'", "", -1)
headerSplit[1] = strings.Replace(headerSplit[1], "\"", "", -1)
headerSplit[1] = strings.Replace(headerSplit[1], "'", "", -1)
preparedHeaders += fmt.Sprintf(`"%s": "%s"`, headerSplit[0], headerSplit[1])
added = true
}
if count != len(headers)-1 && added {
preparedHeaders += ","
}
}
preparedHeaders += "}"
}
}
fileBalance := ""
fileAdder := ``
fileGrabber := ``
fileParameter := ``
contentTypeRemoval := "pass"
bodyParsing := "try:\n body = json.dumps(body)\n except:\n pass"
if method == "post" && len(fileField) > 0 {
fileParameter = ", file_id"
//fileGrabber = "filedata = self.get_file(file_id)\n print(f\"FILEDATA: {filedata}\")"
fileGrabber = "filedata = self.get_file(file_id)"
contentTypeRemoval = "del request_headers[contentType]"
// This indentation is confusing (but correct) ROFL
fileAdder = fmt.Sprintf(`if not filedata["success"]:
return {"success": False, "reason": f"{file_id} is not a valid File ID"}
files = {"%s": (filedata["filename"], filedata["data"])}`, fileField)
fileBalance = ", files=files"
bodyParsing = ""
}
// Removes duplicate file IDs
if strings.Contains(parameterData, `, file_id=""`) && strings.Contains(fileParameter, ", file_id") {
parameterData = strings.Replace(parameterData, `, file_id=""`, "", -1)
} else if strings.Contains(parameterData, `, file_id`) && strings.Contains(fileParameter, ", file_id") {
parameterData = strings.Replace(parameterData, ", file_id", "", -1)
}
// Extra param for url if it's changeable
// Extra param for authentication scheme(s)
// The last weird one is the body.. Tabs & spaces sucks.
parsedParameters := fmt.Sprintf("%s%s%s%s%s%s%s",
authenticationParameter,
urlParameter,
fileParameter,
parameterData,
queryString,
bodyParameter,
verifyParam,
)
// Handles default return value
handleFileString := "if not to_file:\n return self.prepare_response(ret)\n\n return ret.text"
parsedDataCurlParser := ""
if method == "post" || method == "patch" || method == "put" || method == "delete" {
parsedDataCurlParser = `parsed_curl_command += f""" -d '{body}'""" if isinstance(body, str) else f""" -d '{body.decode("utf-8")}'"""`
}
data := fmt.Sprintf(` def %s(self%s):
print(f"Started function %s")
params={}
%s
url=f"%s%s"
%s
%s
%s
%s
%s
%s
%s
%s
%s
%s
if str(to_file).lower() == "true":
to_file = True
else:
to_file = False
if "http:/" in url and not "http://" in url:
url = url.replace("http:/", "http://", -1)
if "https:/" in url and not "https://" in url:
url = url.replace("https:/", "https://", -1)
if "http:///" in url:
url = url.replace("http:///", "http://", -1)
if "https:///" in url:
url = url.replace("https:///", "https://", -1)
if not "http://" in url and not "http" in url:
url = f"http://{url}"
%s
found = False
contentType = ""
for key, value in request_headers.items():
if key.lower() == "user-agent":
found = True
if key.lower() == "content-type":
contentType = key
if len(contentType) > 0:
%s
if not found:
request_headers["User-Agent"] = "Shuffle Automation"
try:
#parsed_headers = [sys.stdout.write(f" -H \"{key}: {value}\"") for key, value in request_headers.items()]
parsed_headers = ""
parsed_curl_command = f"curl -X%s {url} {parsed_headers}"
%s
self.action["parameters"].append({
"name": "shuffle_request_url",
"value": f"{url}",
})
self.action["parameters"].append({
"name": "shuffle_request_curl",
"value": f"{parsed_curl_command}",
})
self.action["parameters"].append({
"name": "shuffle_request_headers",
"value": f"{json.dumps(parsed_headers)}",
})
self.action_result["action"] = self.action
print("[DEBUG] Updated values in self.action_result from OpenAPI app! (1)")
except Exception as e:
print(f"[WARNING] Something went wrong when adding extra returns (1). {e}")
session = requests.Session()
ret = session.%s(url, headers=request_headers, params=params%s%s%s%s)
try:
found = False
for item in self.action["parameters"]:
if item["name"] == "shuffle_response_status":
found = True
break
if not found:
self.action["parameters"].append({
"name": "shuffle_response_status",
"value": f"{ret.status_code}",
})
self.action["parameters"].append({
"name": "shuffle_response_length",
"value": f"{len(ret.text)}",
})
self.action["parameters"].append({
"name": "shuffle_request_cookies",
"value": f"{json.dumps(session.cookies.get_dict())}",
})
print("[DEBUG] Updated values in self.action_result from OpenAPI app! (2)")
except Exception as e:
print(f"[WARNING] Something went wrong when adding extra returns (2). {e}")
if to_file:
# If content encoding or transfer encoding is base64, decode it
if ("content-encoding" in ret.headers.keys() and "base64" in ret.headers["content-encoding"].lower()) or ("transfer-encoding" in ret.headers.keys() and "base64" in ret.headers["transfer-encoding"].lower()) or ("content-transfer-encoding" in ret.headers.keys() and "base64" in ret.headers["content-transfer-encoding"].lower()):
print("[DEBUG] Content encoding is base64, decoding it")
ret.content = base64.b64decode(ret.content)
filedata = {
"filename": "response",
"data": ret.content,
}
fileret = self.set_files([filedata])
if len(fileret) == 1:
return {"success": True, "file_id": fileret[0], "status": ret.status_code}
return fileret
%s
`,
functionname,
parsedParameters,
functionname,
preparedHeaders,
urlInline,
url,
verifyWrapper,
extraHeaders,
extraQueries,
authenticationSetup,
headerParserCode,
queryData,
queryParserCode,
bodyFormatter,
fileGrabber,
fileAdder,
bodyParsing,
contentTypeRemoval,
strings.ToUpper(method),
parsedDataCurlParser,
method,
authenticationAddin,
bodyAddin,
verifyAddin,
fileBalance,
handleFileString,
)
// Use lowercase when checking
//if strings.Contains(strings.ToLower(functionname), "upload_a_file") {
// log.Printf("\n%s", data)
//}
return functionname, data
}
func GetCustomActionCode(swagger *openapi3.Swagger, api WorkflowApp) string{
authenticationParameter := ""
authenticationSetup := ""
authenticationAddin := ""
if swagger.Components.SecuritySchemes != nil {
if swagger.Components.SecuritySchemes["BearerAuth"] != nil {
authenticationParameter = ", apikey"
authenticationSetup = "if apikey != \" \" and not apikey.startswith(\"Bearer\"): parsed_headers[\"Authorization\"] = f\"Bearer {apikey}\""
} else if swagger.Components.SecuritySchemes["BasicAuth"] != nil {
authenticationParameter = ", username_basic, password_basic"
authenticationSetup = "auth=None\n if username_basic or password_basic:\n if \"Authorization\" not in headers and \"Basic\" not in headers and not \"Bearer\" in headers:\n auth = requests.auth.HTTPBasicAuth(username_basic, password_basic)"
authenticationAddin = ", auth=auth"
} else if swagger.Components.SecuritySchemes["ApiKeyAuth"] != nil {
authenticationParameter = ", apikey"
if swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.In == "header" {
authenticationSetup = fmt.Sprintf(`if apikey != " ": parsed_headers["%s"] = apikey`, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name)
if len(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description) > 0 {
trimmedDescription := strings.Trim(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, " ")
authenticationSetup = fmt.Sprintf("if apikey != \" \":\n if apikey.startswith(\"%s\"):\n parsed_headers[\"%s\"] = apikey\n else:\n apikey = apikey.replace(\"%s\", \"\", -1).strip()\n parsed_headers[\"%s\"] = f\"%s{apikey}\"", trimmedDescription, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description)
}
} else if swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.In == "query" {
//authenticationSetup = fmt.Sprintf("if apikey != \" \": parsed_queries[\"%s\"] = requests.utils.quote(apikey)", swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name)
trimmedDescription := strings.Trim(swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, " ")
authenticationSetup = fmt.Sprintf("if apikey != \" \":\n if apikey.startswith(\"%s\"):\n parsed_queries[\"%s\"] = requests.utils.quote(apikey)\n else:\n apikey = apikey.replace(\"%s\", \"\", -1).strip()\n parsed_queries[\"%s\"] = requests.utils.quote(f\"%s{apikey}\")", trimmedDescription, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Name, swagger.Components.SecuritySchemes["ApiKeyAuth"].Value.Description)
}
} else if swagger.Components.SecuritySchemes["Oauth2"] != nil {
authenticationParameter = ", access_token"
authenticationSetup = fmt.Sprintf("if access_token != \" \": parsed_headers[\"Authorization\"] = f\"Bearer {access_token}\"\n #parsed_headers[\"Content-Type\"] = \"application/json\"")
} else if swagger.Components.SecuritySchemes["jwt"] != nil {
authenticationParameter = ", username_basic, password_basic"
authenticationSetup = fmt.Sprintf("authret = requests.get(f\"{url}%s\", headers=parsed_headers, auth=(username_basic, password_basic), verify=False)\n if 'access_token' in authret.text:\n parsed_headers[\"Authorization\"] = f\"Bearer {authret.json()['access_token']}\"\n elif 'jwt' in authret.text:\n parsed_headers[\"Authorization\"] = f\"Bearer {authret.json()['jwt']}\"\n elif 'accessToken' in authret.text:\n parsed_headers[\"Authorization\"] = f\"Bearer {authret.json()['accessToken']}\"\n else:\n parsed_headers[\"Authorization\"] = f\"Bearer {authret.text}\"\n print(f\"Found Bearer auth: {authret.text}\")", api.Authentication.TokenUri)
}
}
pythonCode := fmt.Sprintf(`
def fix_url(self, url, path=False):
if "hhttp" in url:
url = url.replace("hhttp", "http")
if url.startswith("http//"):
url = url.replace("http//", "http://")
if url.startswith("https//"):
url = url.replace("https//", "https://")
if "http:/" in url and not "http://" in url:
url = url.replace("http:/", "http://", -1)
if "https:/" in url and not "https://" in url:
url = url.replace("https:/", "https://", -1)
if "http:///" in url:
url = url.replace("http:///", "http://", -1)
if "https:///" in url:
url = url.replace("https:///", "https://", -1)
if not path and not "http://" in url and not "http" in url:
url = f"http://{url}"
return url
def checkverify(self, verify):
if str(verify).lower().strip() == "false":
return False
elif verify is None:
return False
elif verify:
return True
elif not verify:
return False
else:
return True
def is_valid_method(self, method):
valid_methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]
method = method.upper()
if method in valid_methods:
return method
else:
raise ValueError(f"Invalid HTTP method: {method}")
def parse_headers(self, headers):
parsed_headers = {}
if headers:
split_headers = headers.split("\n")
self.logger.info(split_headers)
for header in split_headers:
if ":" in header:
splititem = ":"
elif "=" in header:
splititem = "="
else:
continue
splitheader = header.split(splititem)
if len(splitheader) >= 2:
parsed_headers[splitheader[0].strip()] = splititem.join(
splitheader[1:]
).strip()
else:
continue
return parsed_headers
def parse_queries(self, queries):
parsed_queries = {}
if not queries:
return parsed_queries
cleaned_queries = queries.strip()
if not cleaned_queries:
return parsed_queries
cleaned_queries = " ".join(cleaned_queries.split())
splitted_queries = cleaned_queries.split("&")
self.logger.info(splitted_queries)
for query in splitted_queries:
if "=" not in query:
self.logger.info("Skipping as there is no = in the query")
continue
key, value = query.split("=")
if not key.strip() or not value.strip():
self.logger.info(
"Skipping because either key or value is not present in query"
)
continue
parsed_queries[key.strip()] = value.strip()
return parsed_queries
def prepare_response(self, request):
try:
parsedheaders = {}
for key, value in request.headers.items():
parsedheaders[key] = value
cookies = {}
if request.cookies: