Skip to content

Commit ca921a5

Browse files
committed
Added stable execution injection in api requests, including Org-Id and 'normal' auth without apikey available
1 parent 8cb8322 commit ca921a5

1 file changed

Lines changed: 66 additions & 34 deletions

File tree

pkg/api.go

Lines changed: 66 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -370,17 +370,20 @@ func handleDirectTranslation(ctx context.Context, user shuffle.User, value shuff
370370
log.Printf("[ERROR] Singul - Failed unmarshaling schemaless output PRE datastore upload: %s", err)
371371
} else {
372372
// This is a hack to allow execution auth ((:
373+
curExecutionId := ""
373374
curOrg := user.ActiveOrg.Id
374375
newExecutionId := request.URL.Query().Get("execution_id")
375376
if len(newExecutionId) > 0 {
376-
curOrg = fmt.Sprintf("execution:%s", newExecutionId)
377+
//curOrg = fmt.Sprintf("execution:%s", newExecutionId)
378+
curExecutionId = newExecutionId
377379
}
378380

379381
log.Printf("\n\n\nSINGUL UPLOAD - %#v (2)\n\n\n", parsedTranslation)
380382
autoUploadSingulOutput(
381383
ctx,
382384
curOrg,
383385
authorization,
386+
curExecutionId,
384387
baseUrl,
385388
parsedTranslation,
386389
value,
@@ -400,7 +403,7 @@ func handleDirectTranslation(ctx context.Context, user shuffle.User, value shuff
400403
// Was made for a... weird format, so we are just continuing to use that
401404

402405
// orgId is SOMETIMES mapped to executionId in cases for execution auth
403-
func autoUploadSingulOutput(ctx context.Context, orgId string, curApikey string, curBackend string, parsedTranslation shuffle.SchemalessOutput, value shuffle.CategoryAction, secondAction shuffle.Action) {
406+
func autoUploadSingulOutput(ctx context.Context, orgId, curApikey, curExecutionId, curBackend string, parsedTranslation shuffle.SchemalessOutput, value shuffle.CategoryAction, secondAction shuffle.Action) {
404407
// Seems to work when authorization (curApikey) is NOT execution based
405408

406409
curOrg := orgId
@@ -485,7 +488,7 @@ func autoUploadSingulOutput(ctx context.Context, orgId string, curApikey string,
485488

486489
generatedItem := item.(map[string]interface{})
487490

488-
idKeys := []string{"id", "uid", "uuid", "identifier", "key"}
491+
idKeys := []string{"finding_uid", "uid", "uuid", "id", "identifier", "key"}
489492
foundIdentifier := ""
490493
foundIdentifierKey := ""
491494
for _, idKey := range idKeys {
@@ -520,7 +523,7 @@ func autoUploadSingulOutput(ctx context.Context, orgId string, curApikey string,
520523
// Generate an ID if we didn't find one
521524
if len(foundIdentifier) <= 4 {
522525
if debug {
523-
log.Printf("[DEBUG] Failed finding VALID ID key in item for label %s: ID Key: %s, Value: %s", value.Label, foundIdentifierKey, foundIdentifier)
526+
log.Printf("[DEBUG] Failed finding VALID ID key in item for label %s: ID Key: '%s', Value: '%s'", value.Label, foundIdentifierKey, foundIdentifier)
524527
}
525528

526529
marshalledItem, err := json.Marshal(generatedItem)
@@ -629,9 +632,9 @@ func autoUploadSingulOutput(ctx context.Context, orgId string, curApikey string,
629632
// v0.2: Send /api/v1/orgs/{org_id}/datastore/upload request
630633

631634
// Bulk request instead (shuffle 2.1.0 optimisation)
632-
err := sendDatastoreUploadRequest(ctx, allEntries, curApikey, curOrg, curBackend)
635+
err := sendDatastoreUploadRequest(ctx, allEntries, curApikey, curExecutionId, curOrg, curBackend)
633636
if err != nil {
634-
log.Printf("[WARNING] Failed sending datastore request (3) for item in schemaless output for label %s: %s", value.Label, err)
637+
//log.Printf("[ERROR] Failed sending datastore request (3) for item in schemaless output for label %s: %s", value.Label, err)
635638
} else {
636639
log.Printf("[INFO] Successfully stored %d items in schemaless/singul output for label %s in org %s", len(allEntries), value.Label, orgId)
637640
}
@@ -1687,6 +1690,13 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
16871690
}
16881691
}
16891692

1693+
if selectedApp.Name == "Shuffle_Datastore" {
1694+
if debug {
1695+
log.Printf("[DEBUG] Failing over to NO AUTH for shuffle datastore")
1696+
}
1697+
requiresAuth = false
1698+
}
1699+
16901700
if !requiresAuth {
16911701
//log.Printf("\n\n[ERROR] App '%s' doesn't require auth\n\n", selectedApp.Name)
16921702
} else {
@@ -1788,7 +1798,7 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
17881798
return jsonFormatted, nil
17891799
}
17901800

1791-
if !standalone && !value.SkipWorkflow {
1801+
if !standalone && value.KeepWorkflow {
17921802
log.Printf("\n\n[INFO] SHOULD add workflow %s\n\n", parentWorkflow.ID)
17931803
}
17941804

@@ -2173,8 +2183,8 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
21732183
}
21742184
}
21752185

2176-
// Handle it properly
2177-
if len(relevantValue) >= 4 {
2186+
// Handle it properly to force in missing data
2187+
if len(relevantValue) >= 2 {
21782188
found := false
21792189
for _, param := range secondAction.Parameters {
21802190
if strings.Contains(param.Value, relevantValue) {
@@ -2342,9 +2352,8 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
23422352
}
23432353
}
23442354

2345-
// Runs individual apps, one at a time
2346-
if value.SkipWorkflow {
2347-
2355+
// Runs individual apps, one at a time instead of building them as a workflow
2356+
if !value.KeepWorkflow {
23482357
if len(missingFields) > 0 && selectedAction.Name != "custom_action" {
23492358
log.Printf("[WARNING] Not all required fields were found in category action (2). Want: %#v in action %s", missingFields, selectedAction.Name)
23502359
//respBody = []byte(fmt.Sprintf(`{"success": false, "reason": "Not all required fields are set", "label": "%s", "missing_fields": "%s", "action": "%s", "api_debugger_url": "%s"}`, value.Label, strings.Join(missingFields, ","), selectedAction.Name, fmt.Sprintf("https://shuffler.io/apis/%s", selectedApp.ID)))
@@ -2899,6 +2908,15 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
28992908
baseUrl = strings.Join(baseurlSplit[0:3], "/")
29002909
}
29012910

2911+
if len(orgId) == 0 && len(user.ActiveOrg.Id) > 0 {
2912+
orgId = user.ActiveOrg.Id
2913+
}
2914+
2915+
// Map back to request apikey if nothing else is available
2916+
if len(authorization) == 0 && len(user.ApiKey) > 0 {
2917+
authorization = user.ApiKey
2918+
}
2919+
29022920
// No shuffler.io config for standalone runs
29032921
authConfig := fmt.Sprintf("false,%s,%s,%s,%s", baseUrl, authorization, orgId, optionalExecutionId)
29042922
if standalone {
@@ -2961,9 +2979,21 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
29612979
// This is just to FORCE it to work and be locally testable
29622980
foundLabelSplit := strings.Split(value.Label, "_")
29632981

2982+
curExecutionId := ""
29642983
curApikey := shuffleApiKey
29652984
curBackend := shuffleBackend
29662985
curOrg := shuffleOrg
2986+
if len(orgId) > 0 {
2987+
curOrg = user.ActiveOrg.Id
2988+
}
2989+
2990+
if len(authorization) > 0 {
2991+
curApikey = authorization
2992+
}
2993+
2994+
if len(baseUrl) > 0 {
2995+
curBackend = baseUrl
2996+
}
29672997

29682998
// Can we do this within the context of the current request IF it was a request?
29692999
// For cloud/self-hosted Shuffle:
@@ -2986,19 +3016,26 @@ func RunActionWrapper(ctx context.Context, user shuffle.User, value shuffle.Cate
29863016
// This is a hack to allow execution auth ((:
29873017
newExecutionId := request.URL.Query().Get("execution_id")
29883018
if len(newExecutionId) > 0 {
2989-
curOrg = fmt.Sprintf("execution:%s", newExecutionId)
3019+
curExecutionId = newExecutionId
29903020
}
29913021
}
29923022

3023+
// Fallback in case of execution auth instead of user auth
3024+
if len(curExecutionId) == 0 && len(optionalExecutionId) > 0 {
3025+
curExecutionId = optionalExecutionId
3026+
}
3027+
29933028
// Handles the actual uploading itself
29943029
if len(foundLabelSplit) > 1 && (strings.HasPrefix(value.Label, "list_") || strings.HasPrefix(value.Label, "get_") || strings.HasPrefix(value.Label, "search_")) && len(curApikey) > 0 && len(curOrg) > 0 {
29953030
if debug {
29963031
log.Printf("[DEBUG] Should upload Singul result for label '%s'", value.Label)
29973032
}
29983033

2999-
autoUploadSingulOutput(ctx, curOrg, curApikey, curBackend, parsedTranslation, value, secondAction)
3034+
autoUploadSingulOutput(ctx, curOrg, curApikey, curExecutionId, curBackend, parsedTranslation, value, secondAction)
30003035
} else {
3001-
log.Printf("\n\nNot uploading. Label: %#v\n\n", value.Label)
3036+
if debug {
3037+
log.Printf("[DEBUG] Singul: NOT uploading. Label: %#v. LabelSplit: %#v. Org: %#v\n\n", value.Label, foundLabelSplit, curOrg)
3038+
}
30023039
}
30033040
}
30043041

@@ -3414,13 +3451,6 @@ func GetTranslatedHttpAction(app shuffle.WorkflowApp, action shuffle.WorkflowApp
34143451
originalActionName = fmt.Sprintf("get_%s", originalActionName)
34153452
}
34163453

3417-
//if debug {
3418-
// log.Printf("[DEBUG] %s & %s", originalActionName, parsedSummary)
3419-
//}
3420-
//if strings.Contains(originalActionName, "messages_get") && strings.Contains(parsedSummary, "messages_get") {
3421-
//os.Exit(3)
3422-
//}
3423-
34243454
// Find exact match
34253455
if originalActionName == parsedSummary {
34263456
if customActionParam.Name == "method" {
@@ -3554,6 +3584,11 @@ func GetTranslatedHttpAction(app shuffle.WorkflowApp, action shuffle.WorkflowApp
35543584
}
35553585
}
35563586

3587+
// Just in case, e.g. to stay away from auth
3588+
if customActionParam.Configuration {
3589+
continue
3590+
}
3591+
35573592
if debug {
35583593
log.Printf("[DEBUG] Appending '%s' with value %#v (%s => custom_action)", customActionParam.Name, customActionParam.Value, originalActionName)
35593594
}
@@ -3749,9 +3784,7 @@ func GetUpdatedHttpValue(value shuffle.CategoryAction) shuffle.CategoryAction {
37493784
return value
37503785
}
37513786

3752-
func sendDatastoreUploadRequest(ctx context.Context, datastoreEntry []shuffle.CacheKeyData, apikey, orgId, backendUrl string) error {
3753-
3754-
3787+
func sendDatastoreUploadRequest(ctx context.Context, datastoreEntry []shuffle.CacheKeyData, apikey, curExecutionId, orgId, backendUrl string) error {
37553788
// Send a request to /api/v1/orgs/{org_id}/set_cache
37563789
if !strings.HasPrefix(backendUrl, "http") {
37573790
backendUrl = os.Getenv("BASE_URL")
@@ -3766,20 +3799,19 @@ func sendDatastoreUploadRequest(ctx context.Context, datastoreEntry []shuffle.Ca
37663799
}
37673800

37683801
url := fmt.Sprintf("%s/api/v2/datastore?bulk=true", backendUrl)
3769-
37703802
reqBody, err := json.Marshal(datastoreEntry)
37713803
if err != nil {
37723804
log.Printf("[ERROR] Failed marshalling cache item before send: %s", err)
37733805
return err
37743806
}
37753807

37763808
// Execution auth workaround
3777-
if strings.HasPrefix(orgId, "execution:") {
3778-
executionId := strings.TrimPrefix(orgId, "execution:")
3779-
url += fmt.Sprintf("%s&execution_id=%s&authorization=%s", url, executionId, apikey)
3780-
3781-
orgId = ""
3782-
apikey = ""
3809+
if len(curExecutionId) > 0 {
3810+
//executionId := strings.TrimPrefix(orgId, "execution:")
3811+
url = fmt.Sprintf("%s&execution_id=%s&authorization=%s", url, curExecutionId, apikey)
3812+
} else if len(apikey) > 0 {
3813+
} else {
3814+
log.Printf("[ERROR] No auth found for sendDatastoreUploadRequest in org %s", orgId)
37833815
}
37843816

37853817
// May need a fixed client here
@@ -3808,8 +3840,8 @@ func sendDatastoreUploadRequest(ctx context.Context, datastoreEntry []shuffle.Ca
38083840
}
38093841

38103842
if res.StatusCode != 200 {
3811-
log.Printf("[ERROR] Failed sending datastore request: %s. Status code: %d. Body: %s", err, res.StatusCode, string(body))
3812-
return errors.New(fmt.Sprintf("Failed sending datastore request (2): %s. Status code: %d. Body: %s", err, res.StatusCode, string(body)))
3843+
log.Printf("[ERROR] Failed sending datastore request (4): %s. Status code: %d. URL: %#v, Resp: %s", err, res.StatusCode, url, string(body))
3844+
return errors.New(fmt.Sprintf("Failed sending datastore request (4-2): %s. Status code: %d. Body: %s", err, res.StatusCode, string(body)))
38133845
}
38143846

38153847
//log.Printf("[DEBUG] Successfully sent datastore request for %d items

0 commit comments

Comments
 (0)