From d86035991090ac1bedb6a0b740512b5a5818d1fe Mon Sep 17 00:00:00 2001 From: Kelley Loder Date: Thu, 25 Jun 2026 13:15:03 -0700 Subject: [PATCH 1/4] changes for multi-tenancy sat v2 --- adminapi/auth/permission_service.go | 382 ++++++++++++------ adminapi/auth/permission_service_test.go | 221 ++++++++++ adminapi/canary/canary_settings_handler.go | 12 +- .../canary/canary_settings_handler_test.go | 2 +- adminapi/change/change_handler.go | 24 +- adminapi/change/change_service.go | 35 +- adminapi/change/change_service_test.go | 10 +- .../permanent_telemetry_profile_service.go | 13 +- adminapi/change/telemetry_profile_handler.go | 18 +- .../change/telemetry_two_change_handler.go | 16 +- .../change/telemetry_two_change_service.go | 21 +- .../change/telemetry_two_profile_handler.go | 12 +- .../change/telemetry_two_profile_service.go | 14 +- adminapi/dcm/dcmformula_handler.go | 30 +- adminapi/dcm/device_settings_handler.go | 25 +- adminapi/dcm/logrepo_settings_handler.go | 26 +- adminapi/dcm/logrepo_settings_handler_test.go | 30 +- adminapi/dcm/logrepo_settings_service.go | 20 +- adminapi/dcm/logrepo_settings_service_test.go | 70 ++-- adminapi/dcm/logupload_settings_handler.go | 16 +- adminapi/dcm/vod_settings_handler.go | 18 +- .../firmware/firmware_test_page_controller.go | 2 +- .../lockdown/lockdown_settings_handler.go | 7 +- adminapi/queries/amv_handler.go | 20 +- adminapi/queries/common.go | 26 +- adminapi/queries/environment_handler.go | 8 +- adminapi/queries/feature_handler.go | 12 +- adminapi/queries/feature_rule_handler.go | 28 +- adminapi/queries/firmware_config_handler.go | 22 +- adminapi/queries/firmware_rule_handler.go | 18 +- .../firmware_rule_report_page_handler.go | 2 +- .../queries/firmware_rule_template_handler.go | 34 +- adminapi/queries/log_controller.go | 3 +- adminapi/queries/log_file_handler.go | 2 +- .../queries/log_upload_settings_handler.go | 2 +- adminapi/queries/model_handler.go | 12 +- adminapi/queries/namedspace_list_handler.go | 74 ++-- adminapi/queries/percentagebean_handler.go | 16 +- adminapi/queries/percentfilter_handler.go | 8 +- adminapi/queries/queries_handler.go | 116 +++--- adminapi/rfc/feature/feature_handler.go | 18 +- .../setting/setting_profile_controller.go | 20 +- adminapi/setting/setting_profile_service.go | 4 +- adminapi/setting/setting_rule_controller.go | 18 +- .../telemetry/telemetry_profile_controller.go | 14 +- adminapi/telemetry/telemetry_rule_handler.go | 16 +- .../telemetry/telemetry_v2_rule_handler.go | 16 +- .../recooking_lockdown_settings_handler.go | 4 +- config/sample_xconfadmin.conf | 5 +- http/auth.go | 67 ++- http/webconfig_server.go | 24 +- .../.openspec.yaml | 5 + .../sat-rbac-v2-tenant-enforcement/design.md | 75 ++++ .../proposal.md | 48 +++ .../sat-rbac-v2-tenant-enforcement/spec.md | 99 +++++ .../sat-rbac-v2-tenant-enforcement/tasks.md | 29 ++ openspec/specs/auth/auth-contract.md | 56 ++- taggingapi/tag/tag_handler.go | 19 +- taggingapi/tag/tag_member_handler.go | 59 ++- 59 files changed, 1415 insertions(+), 608 deletions(-) create mode 100644 adminapi/auth/permission_service_test.go create mode 100644 openspec/changes/sat-rbac-v2-tenant-enforcement/.openspec.yaml create mode 100644 openspec/changes/sat-rbac-v2-tenant-enforcement/design.md create mode 100644 openspec/changes/sat-rbac-v2-tenant-enforcement/proposal.md create mode 100644 openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md create mode 100644 openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md diff --git a/adminapi/auth/permission_service.go b/adminapi/auth/permission_service.go index 162c70b..427a4fb 100644 --- a/adminapi/auth/permission_service.go +++ b/adminapi/auth/permission_service.go @@ -90,6 +90,63 @@ const ( TELEMETRY_ENTITY string = "TelemetryEntity" ) +type SATv2Domain string + +const ( + DOMAIN_CORE SATv2Domain = "core" + DOMAIN_TAGGING SATv2Domain = "tagging" + DOMAIN_SYSTEM SATv2Domain = "system" + DOMAIN_METRICS SATv2Domain = "metrics" +) + +type RouteDomainMapping struct { + Prefix string + Domain SATv2Domain +} + +var satV2RouteMappings = []RouteDomainMapping{ + // system + {Prefix: "/queries/filters/downloadlocation", Domain: DOMAIN_SYSTEM}, + {Prefix: "/updates/filters/downloadlocation", Domain: DOMAIN_SYSTEM}, + {Prefix: "/roundrobinfilter", Domain: DOMAIN_SYSTEM}, + {Prefix: "/rfc/recooking", Domain: DOMAIN_SYSTEM}, + {Prefix: "/rfc/preprocess", Domain: DOMAIN_SYSTEM}, + {Prefix: "/appsettings", Domain: DOMAIN_SYSTEM}, + {Prefix: "/canarysettings", Domain: DOMAIN_SYSTEM}, + {Prefix: "/lockdownsettings", Domain: DOMAIN_SYSTEM}, + {Prefix: "/wakeuppool", Domain: DOMAIN_SYSTEM}, + + // core + {Prefix: "/dataservice", Domain: DOMAIN_CORE}, + {Prefix: "/estbfirmware", Domain: DOMAIN_CORE}, + {Prefix: "/queries", Domain: DOMAIN_CORE}, + {Prefix: "/updates", Domain: DOMAIN_CORE}, + {Prefix: "/delete", Domain: DOMAIN_CORE}, + {Prefix: "/model", Domain: DOMAIN_CORE}, + {Prefix: "/environment", Domain: DOMAIN_CORE}, + {Prefix: "/genericnamespacedlist", Domain: DOMAIN_CORE}, + {Prefix: "/firmwarerule", Domain: DOMAIN_CORE}, + {Prefix: "/firmwareruletemplate", Domain: DOMAIN_CORE}, + {Prefix: "/firmwareconfig", Domain: DOMAIN_CORE}, + {Prefix: "/percentfilter", Domain: DOMAIN_CORE}, + {Prefix: "/amv", Domain: DOMAIN_CORE}, + {Prefix: "/activationminimumversion", Domain: DOMAIN_CORE}, + {Prefix: "/settings", Domain: DOMAIN_CORE}, + {Prefix: "/setting", Domain: DOMAIN_CORE}, + {Prefix: "/featurerule", Domain: DOMAIN_CORE}, + {Prefix: "/feature", Domain: DOMAIN_CORE}, + {Prefix: "/rfc", Domain: DOMAIN_CORE}, + {Prefix: "/changelog", Domain: DOMAIN_CORE}, + {Prefix: "/log", Domain: DOMAIN_CORE}, + {Prefix: "/reportpage", Domain: DOMAIN_CORE}, + {Prefix: "/stats", Domain: DOMAIN_CORE}, + {Prefix: "/migration", Domain: DOMAIN_CORE}, + {Prefix: "/dcm", Domain: DOMAIN_CORE}, + {Prefix: "/telemetry", Domain: DOMAIN_CORE}, + {Prefix: "/change", Domain: DOMAIN_CORE}, + {Prefix: "/penetrationdata", Domain: DOMAIN_CORE}, +} + type EntityPermission struct { ReadAll string `json:"readAll,omitempty"` Read string `json:"read,omitempty"` @@ -140,7 +197,7 @@ func getEntityPermission(entityType string) *EntityPermission { return &CommonPermissions } if entityType == TOOL_ENTITY { - return &CommonPermissions + return &ToolPermissions } if entityType == CHANGE_ENTITY { return &ChangePermissions @@ -187,167 +244,256 @@ func getCurrentModule(r *http.Request, entityType string) string { return "" } -func HasReadPermissionForTool(r *http.Request) bool { - if !(owcommon.SatOn) { - return true +func hasSATv2ReadCapability(capabilities []string, domain SATv2Domain) bool { + readCap := "xconf:" + string(domain) + ":readonly" + writeCap := "xconf:" + string(domain) + ":readwrite" + + return util.Contains(capabilities, readCap) || util.Contains(capabilities, writeCap) +} + +func hasSATv2WriteCapability(capabilities []string, domain SATv2Domain) bool { + // metrics has no write capability + if domain == DOMAIN_METRICS { + return false } - // checked capabilities from SAT token if available - if capabilities := xhttp.GetCapabilitiesFromContext(r); len(capabilities) > 0 { - if util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_READ) { - return true - } - } else { - // checked permissions from Login token - permissions := GetPermissionsFunc(r) - if util.Contains(permissions, getEntityPermission(TOOL_ENTITY).ReadAll) { - return true - } + writeCap := "xconf:" + string(domain) + ":readwrite" + return util.Contains(capabilities, writeCap) +} + +func getTenantIdForSATv2(r *http.Request) string { + return xhttp.GetTenantIdFromHeader(r) +} + +func authorizeSATv2TenantScope(r *http.Request) error { + tenantId := getTenantIdForSATv2(r) + if util.IsBlank(tenantId) { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "Missing tenantId for SAT v2 authorization") } - return false + + allowedPartners := xhttp.GetAllowedPartnersFromContext(r) + if len(allowedPartners) == 0 { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "SAT token is missing allowed partners") + } + if !util.CaseInsensitiveContains(allowedPartners, tenantId) { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "SAT token is not allowed for tenant "+tenantId) + } + + return nil } -func HasWritePermissionForTool(r *http.Request) bool { - if !(owcommon.SatOn) { - return true +func CanReadSatV2(r *http.Request, capabilities []string, applicationType string) (string, error) { + domain, ok := classifySATv2Domain(r.URL.Path) + if !ok { + return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No SAT v2 read permission for unmapped route") } - // checked capabilities from SAT token if available - if capabilities := xhttp.GetCapabilitiesFromContext(r); len(capabilities) > 0 { - if util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_WRITE) { - return true - } - } else { - // checked permissions from Login token - permissions := GetPermissionsFunc(r) - if util.Contains(permissions, getEntityPermission(TOOL_ENTITY).WriteAll) { - return true - } + if !hasSATv2ReadCapability(capabilities, domain) { + requiredCap := "xconf:" + string(domain) + ":readonly" + return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, fmt.Sprintf("SAT v2 token is missing required capability: %s", requiredCap)) } - return false + if err := authorizeSATv2TenantScope(r); err != nil { + return "", err + } + + return applicationType, nil } -// CanWrite returns the applicationType the user has write permission for non-common entityType, -// otherwise returns error if applicationType is not specified in query parameter or cookie -func CanWrite(r *http.Request, entityType string, vargs ...string) (applicationType string, err error) { - tenantId := xwhttp.GetTenantId(r, "") +func CanWriteSatV2(r *http.Request, capabilities []string, applicationType string) (string, error) { + domain, ok := classifySATv2Domain(r.URL.Path) + if !ok { + return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No SAT v2 write permission for unmapped route") + } - if isLockdownMode(tenantId) { - lockdownModules := strings.Split(common.GetStringAppSetting(tenantId, common.PROP_LOCKDOWN_MODULES), ",") - if len(lockdownModules) != 0 { - if util.CaseInsensitiveContains(lockdownModules, getCurrentModule(r, entityType)) || strings.ToUpper(lockdownModules[0]) == common.DefaultLockdownModules { - return "", xwcommon.NewRemoteErrorAS(http.StatusLocked, "Modification not allowed in Lockdown mode") - } + if !hasSATv2WriteCapability(capabilities, domain) { + requiredCap := "xconf:" + string(domain) + ":readwrite" + return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, fmt.Sprintf("SAT v2 token is missing required capability: %s", requiredCap)) + } + if err := authorizeSATv2TenantScope(r); err != nil { + return "", err + } + + return applicationType, nil +} + +func resolveApplicationType(r *http.Request, entityType string, vargs ...string) (string, error) { + if entityType == COMMON_ENTITY || entityType == TOOL_ENTITY { + return "", nil + } + + applicationType := "" + if values, ok := r.URL.Query()[core.APPLICATION_TYPE]; ok { + applicationType = values[0] + } + if util.IsBlank(applicationType) { + applicationType = core.GetApplicationFromCookies(r) + } + if util.IsBlank(applicationType) { + if len(vargs) > 0 && vargs[0] != "" { + applicationType = vargs[0] + } else { + // work-around for backward compatibility + log.Debugf("applicationType not specified: auth_subject=%s path=%s", r.Header.Get(xhttp.AUTH_SUBJECT), r.URL.Path) + applicationType = core.STB } } - if entityType != COMMON_ENTITY && entityType != TOOL_ENTITY { - if values, ok := r.URL.Query()[core.APPLICATION_TYPE]; ok { - applicationType = values[0] + if err := core.ValidateApplicationType(applicationType); err != nil { + return "", err + } + + return applicationType, nil +} + +func authorizeWrite(r *http.Request, entityType string, applicationType string, authType interface{}) error { + if !(owcommon.SatOn) { + return nil + } + + if authType == xhttp.AUTH_TYPE_SAT_V2 || authType == xhttp.AUTH_TYPE_SAT_LEGACY { + // get capabilities from SAT token if available, return error if none found + capabilities := xhttp.GetCapabilitiesFromContext(r) + if len(capabilities) == 0 { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No capabilities found in SAT token") } - if util.IsBlank(applicationType) { - applicationType = core.GetApplicationFromCookies(r) + // if SAT is v2, do v2 check + if authType == xhttp.AUTH_TYPE_SAT_V2 { + _, err := CanWriteSatV2(r, capabilities, applicationType) + return err } - if util.IsBlank(applicationType) { - if len(vargs) > 0 && vargs[0] != "" { - applicationType = vargs[0] - } else { - // work-around for backward compatibility - log.Infof("applicationType not specified: auth_subject=%s path=%s", r.Header.Get(xhttp.AUTH_SUBJECT), r.URL.Path) - applicationType = core.STB - } + // else assume legacy SAT + if entityType == COMMON_ENTITY && util.Contains(capabilities, XCONF_WRITE_MACLIST) { + return nil } - if err := core.ValidateApplicationType(applicationType); err != nil { - return "", err + if !(util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_WRITE)) { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write capabilities") } + return nil + } + + // check permissions from Login token since SAT token is not available + permissions := GetPermissionsFunc(r) + if util.Contains(permissions, getEntityPermission(entityType).WriteAll) { + return nil + } + if util.Contains(common.ApplicationTypes, applicationType) && util.Contains(permissions, getEntityPermission(entityType).Write+applicationType) { + return nil + } + + // if we get here, it means user doesn't have required permissions, return error + if applicationType == "" { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write permission") } + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write permission for ApplicationType "+applicationType) +} - //TODO +func authorizeRead(r *http.Request, entityType string, applicationType string, authType interface{}) error { if !(owcommon.SatOn) { - return applicationType, nil + return nil } - // checked capabilities from SAT token if available - if capabilities := xhttp.GetCapabilitiesFromContext(r); len(capabilities) > 0 { - if entityType == COMMON_ENTITY && util.Contains(capabilities, XCONF_WRITE_MACLIST) { - return applicationType, nil + if authType == xhttp.AUTH_TYPE_SAT_V2 || authType == xhttp.AUTH_TYPE_SAT_LEGACY { + // get capabilities from SAT token if available, return error if none found + capabilities := xhttp.GetCapabilitiesFromContext(r) + if len(capabilities) == 0 { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No capabilities found in SAT token") } - if !(util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_WRITE)) { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write capabilities") + // if SAT is v2, do v2 check + if authType == xhttp.AUTH_TYPE_SAT_V2 { + _, err := CanReadSatV2(r, capabilities, applicationType) + return err } - return applicationType, nil - } else { - // checked permissions from Login token - permissions := GetPermissionsFunc(r) - if util.Contains(permissions, getEntityPermission(entityType).WriteAll) { - return applicationType, nil + // else assume legacy SAT + if entityType == COMMON_ENTITY && util.Contains(capabilities, XCONF_READ_MACLIST) { + return nil } - if util.Contains(common.ApplicationTypes, applicationType) && util.Contains(permissions, getEntityPermission(entityType).Write+applicationType) { - return applicationType, nil + if !(util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_READ)) { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read capabilities") } + return nil } + // check permissions from Login token since SAT token is not available + permissions := GetPermissionsFunc(r) + if util.Contains(permissions, getEntityPermission(entityType).ReadAll) { + return nil + } + + if util.Contains(common.ApplicationTypes, applicationType) && util.Contains(permissions, getEntityPermission(entityType).Read+applicationType) { + return nil + } + + // if we get here, it means user doesn't have required permissions, return error if applicationType == "" { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write permission") - } else { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No write permission for ApplicationType "+applicationType) + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission") } + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission for ApplicationType "+applicationType) } -// CanRead returns the applicationType the user has read permission for non-common entityType, +// CanWrite returns the applicationType the user has write permission for non-common entityType, // otherwise returns error if applicationType is not specified in query parameter or cookie -func CanRead(r *http.Request, entityType string, vargs ...string) (applicationType string, err error) { - if entityType != COMMON_ENTITY && entityType != TOOL_ENTITY { - if values, ok := r.URL.Query()[core.APPLICATION_TYPE]; ok { - applicationType = values[0] - } - if util.IsBlank(applicationType) { - applicationType = core.GetApplicationFromCookies(r) - } - if util.IsBlank(applicationType) { - if len(vargs) > 0 && vargs[0] != "" { - applicationType = vargs[0] - } else { - // work-around for backward compatibility - log.Infof("applicationType not specified: auth_subject=%s path=%s", r.Header.Get(xhttp.AUTH_SUBJECT), r.URL.Path) - applicationType = core.STB +func CanWrite(r *http.Request, entityType string, vargs ...string) (applicationType string, err error) { + authType := r.Context().Value(xhttp.CTX_KEY_AUTH_TYPE) + + applicationType, err = resolveApplicationType(r, entityType, vargs...) + if err != nil { + return "", err + } + + if err = authorizeWrite(r, entityType, applicationType, authType); err != nil { + return "", err + } + + // Lockdown check runs after authorization: unauthorized callers should receive + // 401/403, not a 423 that reveals operational system state. + tenantId := xhttp.GetTenantId(r.Context(), r) + if isLockdownMode(tenantId) { + lockdownModules := strings.Split(common.GetStringAppSetting(tenantId, common.PROP_LOCKDOWN_MODULES), ",") + if len(lockdownModules) != 0 { + if util.CaseInsensitiveContains(lockdownModules, getCurrentModule(r, entityType)) || strings.ToUpper(lockdownModules[0]) == common.DefaultLockdownModules { + return "", xwcommon.NewRemoteErrorAS(http.StatusLocked, "Modification not allowed in Lockdown mode") } } - if err := core.ValidateApplicationType(applicationType); err != nil { - return "", err - } } - if !(owcommon.SatOn) { - return applicationType, nil + return applicationType, nil +} + +// CanRead returns the applicationType the user has read permission for non-common entityType, +// otherwise returns error if applicationType is not specified in query parameter or cookie +func CanRead(r *http.Request, entityType string, vargs ...string) (applicationType string, err error) { + authType := r.Context().Value(xhttp.CTX_KEY_AUTH_TYPE) + + applicationType, err = resolveApplicationType(r, entityType, vargs...) + if err != nil { + return "", err } - // checked capabilities from SAT token if available - if capabilities := xhttp.GetCapabilitiesFromContext(r); len(capabilities) > 0 { - if entityType == COMMON_ENTITY && util.Contains(capabilities, XCONF_READ_MACLIST) { - return applicationType, nil - } - if !(util.Contains(capabilities, XCONF_ALL) || util.Contains(capabilities, XCONF_READ)) { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read capabilities") - } - return applicationType, nil - } else { - // checked permissions from Login token - permissions := GetPermissionsFunc(r) - if util.Contains(permissions, getEntityPermission(entityType).ReadAll) { - return applicationType, nil - } + if err = authorizeRead(r, entityType, applicationType, authType); err != nil { + return "", err + } - if util.Contains(common.ApplicationTypes, applicationType) && util.Contains(permissions, getEntityPermission(entityType).Read+applicationType) { - return applicationType, nil - } + return applicationType, nil +} + +func classifySATv2Domain(path string) (SATv2Domain, bool) { + path = strings.ToLower(strings.TrimSuffix(path, "/")) + + // tagging router is its own top-level domain + if strings.HasPrefix(path, "/taggingservice") { + return DOMAIN_TAGGING, true } - if applicationType == "" { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission") - } else { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission for ApplicationType "+applicationType) + // all other admin routes come through xconfAdminService + path = strings.TrimPrefix(path, "/xconfadminservice") + + for _, m := range satV2RouteMappings { + if strings.HasPrefix(path, m.Prefix) { + return m.Domain, true + } } + + return "", false } var GetPermissionsFunc = getPermissions diff --git a/adminapi/auth/permission_service_test.go b/adminapi/auth/permission_service_test.go new file mode 100644 index 0000000..a5ade80 --- /dev/null +++ b/adminapi/auth/permission_service_test.go @@ -0,0 +1,221 @@ +/** + * Copyright 2025 Comcast Cable Communications Management, LLC + * + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package auth + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + owcommon "github.com/rdkcentral/xconfadmin/common" + xhttp "github.com/rdkcentral/xconfadmin/http" + core "github.com/rdkcentral/xconfadmin/shared" +) + +func requestWithSAT(path string, queryApplicationType string, authType xhttp.AuthType, capabilities []string) *http.Request { + r := httptest.NewRequest("GET", path, nil) + r.Header.Set("tenantId", "comcast") + if queryApplicationType != "" { + q := r.URL.Query() + q.Set(core.APPLICATION_TYPE, queryApplicationType) + r.URL.RawQuery = q.Encode() + } + + ctx := context.WithValue(r.Context(), xhttp.CTX_KEY_AUTH_TYPE, authType) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_CAPABILITIES, capabilities) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_ALLOWED_PARTNERS, []string{"comcast"}) + return r.WithContext(ctx) +} + +func requestWithSATScope(path string, method string, tenantId string, authType xhttp.AuthType, capabilities []string, allowedPartners []string) *http.Request { + r := httptest.NewRequest(method, path, nil) + if tenantId != "" { + r.Header.Set("tenantId", tenantId) + } + + ctx := context.WithValue(r.Context(), xhttp.CTX_KEY_AUTH_TYPE, authType) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_CAPABILITIES, capabilities) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_ALLOWED_PARTNERS, allowedPartners) + return r.WithContext(ctx) +} + +func TestValidateReadSATv2MismatchedApplicationType(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + core.RDKCLOUD, + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + ) + + err := ValidateRead(r, core.STB, DCM_ENTITY) + if err == nil { + t.Fatalf("expected applicationType mismatch error") + } + if !strings.Contains(err.Error(), "doesn't match") { + t.Fatalf("expected mismatch error, got: %v", err) + } +} + +func TestValidateReadSATv2MatchingApplicationType(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + core.STB, + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + ) + + if err := ValidateRead(r, core.STB, DCM_ENTITY); err != nil { + t.Fatalf("expected success, got error: %v", err) + } +} + +func TestValidateWriteLegacySATMismatchedApplicationType(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + core.RDKCLOUD, + xhttp.AUTH_TYPE_SAT_LEGACY, + []string{XCONF_WRITE}, + ) + + err := ValidateWrite(r, core.STB, DCM_ENTITY) + if err == nil { + t.Fatalf("expected applicationType mismatch error") + } + if !strings.Contains(err.Error(), "doesn't match") { + t.Fatalf("expected mismatch error, got: %v", err) + } +} + +func TestValidateWriteLegacySATMatchingApplicationType(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + "", + xhttp.AUTH_TYPE_SAT_LEGACY, + []string{XCONF_WRITE}, + ) + + if err := ValidateWrite(r, core.STB, DCM_ENTITY); err != nil { + t.Fatalf("expected success, got error: %v", err) + } +} + +func TestCanReadSATv2CaseInsensitiveTenantMatch(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "COX", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + []string{"cox"}, + ) + + if _, err := CanRead(r, DCM_ENTITY); err != nil { + t.Fatalf("expected success for case-insensitive tenant match, got: %v", err) + } +} + +func TestCanReadSATv2FailsWhenTenantHeaderMissing(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + []string{"comcast"}, + ) + + _, err := CanRead(r, DCM_ENTITY) + if err == nil { + t.Fatalf("expected error for missing tenantId") + } + if !strings.Contains(err.Error(), "Missing tenantId") { + t.Fatalf("expected missing tenantId error, got: %v", err) + } +} + +func TestCanReadSATv2FailsWhenAllowedPartnersMissing(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + nil, + ) + + _, err := CanRead(r, DCM_ENTITY) + if err == nil { + t.Fatalf("expected error for missing allowed partners") + } + if !strings.Contains(err.Error(), "missing allowed partners") { + t.Fatalf("expected missing allowed partners error, got: %v", err) + } +} + +func TestCanWriteSATv2FailsWhenTenantNotAllowed(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodPost, + "cox", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readwrite"}, + []string{"comcast"}, + ) + + _, err := CanWrite(r, DCM_ENTITY, core.STB) + if err == nil { + t.Fatalf("expected error for tenant outside allowedPartners") + } + if !strings.Contains(err.Error(), "not allowed for tenant") { + t.Fatalf("expected tenant scope denial error, got: %v", err) + } +} diff --git a/adminapi/canary/canary_settings_handler.go b/adminapi/canary/canary_settings_handler.go index ad5afe7..8df88fd 100644 --- a/adminapi/canary/canary_settings_handler.go +++ b/adminapi/canary/canary_settings_handler.go @@ -30,8 +30,8 @@ import ( ) func PutCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { - if !auth.HasWritePermissionForTool(r) { - xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No write permission: tools") + if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { + xhttp.AdminError(w, err) return } @@ -48,7 +48,7 @@ func PutCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := SetCanarySetting(tenantId, &canarySettings) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -58,12 +58,12 @@ func PutCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { } func GetCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { - if !auth.HasReadPermissionForTool(r) { - xhttp.WriteAdminErrorResponse(w, http.StatusUnauthorized, "") + if _, err := auth.CanRead(r, auth.TOOL_ENTITY); err != nil { + xhttp.AdminError(w, err) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) canarySetting, err := GetCanarySettings(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/adminapi/canary/canary_settings_handler_test.go b/adminapi/canary/canary_settings_handler_test.go index fbe4a62..cb77307 100644 --- a/adminapi/canary/canary_settings_handler_test.go +++ b/adminapi/canary/canary_settings_handler_test.go @@ -72,5 +72,5 @@ func TestGetCanarySettingsHandler(t *testing.T) { common.SatOn = true req = httptest.NewRequest(http.MethodGet, testURL, nil) GetCanarySettingsHandler(w, req) - assert.Equal(t, http.StatusUnauthorized, w.Status()) + assert.Equal(t, http.StatusForbidden, w.Status()) } diff --git a/adminapi/change/change_handler.go b/adminapi/change/change_handler.go index d937d28..e56fc16 100644 --- a/adminapi/change/change_handler.go +++ b/adminapi/change/change_handler.go @@ -56,7 +56,8 @@ func GetProfileChangesHandler(w http.ResponseWriter, r *http.Request) { searchContext := make(map[string]string) searchContext[xwcommon.APPLICATION_TYPE] = applicationType - changes := FindByContextForChanges(searchContext) + tenantId := xhttp.GetTenantId(r.Context(), r) + changes := FindByContextForChanges(tenantId, searchContext) sort.Slice(changes, func(i, j int) bool { return changes[j].Updated < changes[i].Updated }) @@ -88,7 +89,7 @@ func ApproveChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) headerMap := createHeadersMap(tenantId, applicationType) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, nil) } @@ -113,7 +114,7 @@ func RevertChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) approveId, found := mux.Vars(r)[xcommon.APPROVE_ID] if !found || approveId == "" { @@ -137,7 +138,7 @@ func CancelChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changeId, found := mux.Vars(r)[xcommon.CHANGE_ID] if !found || changeId == "" { @@ -217,7 +218,7 @@ func GetGroupedChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changeList := xchange.GetChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[i].Updated < changeList[j].Updated @@ -264,7 +265,7 @@ func GetGroupedApprovedChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changeList := xchange.GetApprovedChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[j].Updated < changeList[i].Updated @@ -308,7 +309,8 @@ func ApprovedChangesGeneratePage(list []*xwchange.ApprovedChange, page int, page } func GetChangedEntityIdsHandler(w http.ResponseWriter, r *http.Request) { - entityIds := GetChangedEntityIds() + tenantId := xhttp.GetTenantId(r.Context(), r) + entityIds := GetChangedEntityIds(tenantId) response, err := util.JSONMarshal(entityIds) if err != nil { log.Error(fmt.Sprintf("json.Marshal entityIds error: %v", err)) @@ -323,7 +325,7 @@ func ApproveChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -432,7 +434,8 @@ func GetApprovedFilteredHandler(w http.ResponseWriter, r *http.Request) { if err != nil { log.Error(fmt.Sprintf("json.Marshal ApprovedChangesMap error: %v", err)) } - changeList := FindByContextForChanges(searchContext) + tenantId := xhttp.GetTenantId(r.Context(), r) + changeList := FindByContextForChanges(tenantId, searchContext) headerMap := createHeadersWithEntitySize(len(changeList), len(approvedChangeList)) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, response) } @@ -479,7 +482,8 @@ func GetChangesFilteredHandler(w http.ResponseWriter, r *http.Request) { } searchContext[xwcommon.APPLICATION_TYPE] = applicationType - changeList := FindByContextForChanges(searchContext) + tenantId := xhttp.GetTenantId(r.Context(), r) + changeList := FindByContextForChanges(tenantId, searchContext) sort.Slice(changeList, func(i, j int) bool { return changeList[j].Updated < changeList[i].Updated }) diff --git a/adminapi/change/change_service.go b/adminapi/change/change_service.go index a2f1409..72f1df1 100644 --- a/adminapi/change/change_service.go +++ b/adminapi/change/change_service.go @@ -27,12 +27,11 @@ import ( xcommon "github.com/rdkcentral/xconfadmin/common" "github.com/rdkcentral/xconfadmin/adminapi/auth" + xhttp "github.com/rdkcentral/xconfadmin/http" xshared "github.com/rdkcentral/xconfadmin/shared" xchange "github.com/rdkcentral/xconfadmin/shared/change" xutil "github.com/rdkcentral/xconfadmin/util" xwcommon "github.com/rdkcentral/xconfwebconfig/common" - "github.com/rdkcentral/xconfwebconfig/db" - xwhttp "github.com/rdkcentral/xconfwebconfig/http" "github.com/rdkcentral/xconfwebconfig/shared" xwshared "github.com/rdkcentral/xconfwebconfig/shared" xwchange "github.com/rdkcentral/xconfwebconfig/shared/change" @@ -43,7 +42,7 @@ import ( ) func GetApprovedAll(r *http.Request) ([]*xwchange.ApprovedChange, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) approvedChangesAll := xchange.GetApprovedChangeList(tenantId) approvedChanges := []*xwchange.ApprovedChange{} application, err := auth.CanRead(r, auth.CHANGE_ENTITY) @@ -87,7 +86,7 @@ func beforeSavingChange(r *http.Request, change *xwchange.Change) error { return err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) return validateAllChanges(tenantId, change) } @@ -164,7 +163,7 @@ func CreateApprovedChange(r *http.Request, change *xwchange.Change) (*xwchange.A return nil, err } - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r.Context(), r) approvedChange := xwchange.ApprovedChange(*change) xchange.SetOneApprovedChange(tenantId, &approvedChange) jsonBytes, _ := json.Marshal(change) @@ -176,7 +175,7 @@ func Revert(r *http.Request, approvedId string) error { if approvedId == "" { return xwcommon.NewRemoteErrorAS(http.StatusBadRequest, "Id is blank") } - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r.Context(), r) approvedChange := xchange.GetOneApprovedChange(tenantId, approvedId) if approvedChange == nil { return xwcommon.NewRemoteErrorAS(http.StatusNotFound, "ApprovedChange with "+approvedId+" id does not exist") @@ -193,13 +192,13 @@ func Revert(r *http.Request, approvedId string) error { func revertDelete(r *http.Request, id string, approvedChange *xwchange.ApprovedChange) *xwchange.ApprovedChange { CreatePermanentTelemetryProfile(r, approvedChange.OldEntity) - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r.Context(), r) xchange.DeleteOneApprovedChange(tenantId, id) return approvedChange } func revertCreateOrUpdateChange(r *http.Request, changeId string, entityId string, approvedChange *xwchange.ApprovedChange) *xwchange.ApprovedChange { - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r.Context(), r) entityToRevert := logupload.GetOnePermanentTelemetryProfile(tenantId, entityId) // in Java, equalPendingEntities(PermanentTelemetryProfile oldEntity, PermanentTelemetryProfile newEntity) always returns true //if (equalPendingEntities(approvedChange.getNewEntity(), entityToRevert)) { is being ignored @@ -213,7 +212,7 @@ func revertCreateOrUpdateChange(r *http.Request, changeId string, entityId strin } func CancelChange(r *http.Request, changeId string) error { - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r.Context(), r) canceledChange, err := Delete(tenantId, changeId) if err != nil { return err @@ -257,9 +256,8 @@ func groupApprovedChange(change *xwchange.ApprovedChange, groupedChanges map[str } } -func GetChangedEntityIds() *[]string { +func GetChangedEntityIds(tenantId string) *[]string { ids := []string{} - tenantId := db.GetDefaultTenantId() changeList := xchange.GetChangeList(tenantId) for _, change := range changeList { ids = append(ids, change.EntityID) @@ -297,7 +295,7 @@ func GetChangesByEntityId(tenantId, entityId string) []*xwchange.Change { } func Approve(r *http.Request, id string) (*xwchange.ApprovedChange, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) change := xchange.GetOneChange(tenantId, id) if change == nil { return nil, xwcommon.NewRemoteErrorAS(http.StatusNotFound, "Change with "+id+" id does not exist") @@ -340,7 +338,7 @@ func getChangeIds(changes []*xwchange.Change) []string { } func ApproveChanges(r *http.Request, changeIds *[]string) (map[string]string, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changesToApprove, err := GetChangesByEntityIds(tenantId, changeIds) if err != nil { return nil, err @@ -380,7 +378,7 @@ func ApproveChanges(r *http.Request, changeIds *[]string) (map[string]string, er } func SaveToApprovedAndCleanUpChange(r *http.Request, change *xwchange.Change) (*xwchange.ApprovedChange, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) userName := auth.GetUserNameOrUnknown(r) change.ApprovedUser = userName approvedChange, err := CreateApprovedChange(r, change) @@ -393,7 +391,7 @@ func SaveToApprovedAndCleanUpChange(r *http.Request, change *xwchange.Change) (* } func CancelApprovedChangesByEntityId(r *http.Request, entityIdsToByCancelChanges []string, changeIdsToBeExcluded []string) error { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entityId := range entityIdsToByCancelChanges { changes := GetChangesByEntityId(tenantId, entityId) for _, changeByEntityId := range changes { @@ -417,7 +415,7 @@ func logAndCollectChangeException(change *xwchange.Change, err error, errorMessa } func RevertChanges(r *http.Request, changeIds *[]string) (map[string]string, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changesToRevert := []*xwchange.ApprovedChange{} for _, changeId := range *changeIds { approvedChange := xchange.GetOneApprovedChange(tenantId, changeId) @@ -440,8 +438,7 @@ func RevertChanges(r *http.Request, changeIds *[]string) (map[string]string, err return errorMessages, nil } -func FindByContextForChanges(searchContext map[string]string) []*xwchange.Change { - tenantId := db.GetDefaultTenantId() +func FindByContextForChanges(tenantId string, searchContext map[string]string) []*xwchange.Change { changes := xchange.GetChangeList(tenantId) changesFound := []*xwchange.Change{} for _, change := range changes { @@ -479,7 +476,7 @@ func FindByContextForChanges(searchContext map[string]string) []*xwchange.Change } func FindByContextForApprovedChanges(r *http.Request, searchContext map[string]string) []*xwchange.ApprovedChange { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) approvedChanges := xchange.GetApprovedChangeList(tenantId) changesFound := []*xwchange.ApprovedChange{} for _, change := range approvedChanges { diff --git a/adminapi/change/change_service_test.go b/adminapi/change/change_service_test.go index 77fd486..37d146c 100644 --- a/adminapi/change/change_service_test.go +++ b/adminapi/change/change_service_test.go @@ -145,12 +145,12 @@ func TestFindByContextForChanges(t *testing.T) { t.Fatalf("setup: %v", err) } // filter by author substring - res := FindByContextForChanges(map[string]string{"author": "ali"}) + res := FindByContextForChanges(db.GetDefaultTenantId(), map[string]string{"author": "ali"}) if len(res) != 1 || res[0].Author != "alice" { t.Fatalf("expected filter by author matched alice only") } // filter by profile name substring - res = FindByContextForChanges(map[string]string{"entity": "beta"}) + res = FindByContextForChanges(db.GetDefaultTenantId(), map[string]string{"entity": "beta"}) if len(res) != 1 || res[0].NewEntity.Name != "telemetry-beta" { t.Fatalf("expected beta profile filter") } @@ -183,7 +183,7 @@ func TestGetChangedEntityIds(t *testing.T) { if err := xchange.CreateOneChange(db.GetDefaultTenantId(), c); err != nil { t.Fatalf("setup: %v", err) } - ids := GetChangedEntityIds() + ids := GetChangedEntityIds(db.GetDefaultTenantId()) if ids == nil || len(*ids) == 0 { t.Fatalf("expected at least one changed entity id") } @@ -397,7 +397,7 @@ func TestGetApprovedAll_WithResults(t *testing.T) { func TestFindByContextForChanges_EmptyContext(t *testing.T) { context := make(map[string]string) - result := FindByContextForChanges(context) + result := FindByContextForChanges(db.GetDefaultTenantId(), context) if result == nil { t.Fatalf("expected non-nil result") } @@ -418,7 +418,7 @@ func TestFindByContextForChanges_WithApplicationType(t *testing.T) { } context := map[string]string{"applicationType": shared.STB} - result := FindByContextForChanges(context) + result := FindByContextForChanges(db.GetDefaultTenantId(), context) if len(result) == 0 { t.Fatalf("expected results") } diff --git a/adminapi/change/permanent_telemetry_profile_service.go b/adminapi/change/permanent_telemetry_profile_service.go index 1df1ade..b0427ce 100644 --- a/adminapi/change/permanent_telemetry_profile_service.go +++ b/adminapi/change/permanent_telemetry_profile_service.go @@ -22,6 +22,7 @@ import ( "net/http" xcommon "github.com/rdkcentral/xconfadmin/common" + xhttp "github.com/rdkcentral/xconfadmin/http" xshared "github.com/rdkcentral/xconfadmin/shared" xwhttp "github.com/rdkcentral/xconfwebconfig/http" @@ -77,7 +78,7 @@ func UpdatePermanentTelemetryProfile(tenantId string, updatedProfile *logupload. func CreatePermanentTelemetryProfile(r *http.Request, profile *logupload.PermanentTelemetryProfile) (*logupload.PermanentTelemetryProfile, error) { normalizeOnSaveAfterApproving(profile) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err := beforeCreating(tenantId, profile) if err != nil { return nil, err @@ -89,7 +90,7 @@ func SavePermanentTelemetryProfile(r *http.Request, entity *logupload.PermanentT if err := auth.ValidateWrite(r, entity.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeSavingPermanentTelemetryProfile(tenantId, entity); err != nil { return nil, err } @@ -174,7 +175,7 @@ func DeletePermanentTelemetryProfile(r *http.Request, id string) (*logupload.Per if err != nil { return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile, err := beforeRemoving(tenantId, id, writeApplication) if err != nil { return nil, err @@ -246,7 +247,7 @@ func WriteCreateChange(r *http.Request, profile *logupload.PermanentTelemetryPro if err := auth.ValidateWrite(r, profile.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeCreating(tenantId, profile); err != nil { return nil, err } @@ -279,7 +280,7 @@ func WriteUpdateChangeOrSave(r *http.Request, newProfile *logupload.PermanentTel if err := auth.ValidateWrite(r, newProfile.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeUpdating(tenantId, newProfile); err != nil { return nil, err } @@ -317,7 +318,7 @@ func WriteDeleteChange(r *http.Request, profileId string) (*core_change.Change, if err != nil { return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile, err := beforeRemoving(tenantId, profileId, writeApplication) if err != nil { return nil, err diff --git a/adminapi/change/telemetry_profile_handler.go b/adminapi/change/telemetry_profile_handler.go index 678b736..23eac8a 100644 --- a/adminapi/change/telemetry_profile_handler.go +++ b/adminapi/change/telemetry_profile_handler.go @@ -58,7 +58,7 @@ func GetTelemetryProfileByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { errorStr := fmt.Sprintf("Entity with id %s does not exist", id) @@ -92,7 +92,7 @@ func GetTelemetryProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profiles := xlogupload.GetPermanentTelemetryProfileListByApplicationType(tenantId, application) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -203,7 +203,7 @@ func UpdateTelemetryProfileHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) updatedProfile, err := UpdatePermanentTelemetryProfile(tenantId, permTelemetryProfile) if err != nil { xhttp.AdminError(w, err) @@ -285,7 +285,7 @@ func CreateTelemetryIdsHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateTelemetryIds(tenantId) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -426,7 +426,7 @@ func PostTelemetryProfileFilteredHandler(w http.ResponseWriter, r *http.Request) } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) profiles := GetTelemetryProfilesByContext(contextMap) profilesPerPage := GeneratePageTelemetryProfiles(profiles, pageNumber, pageSize) @@ -477,7 +477,7 @@ func AddTelemetryProfileEntryHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -540,7 +540,7 @@ func AddTelemetryProfileEntryChangeHandler(w http.ResponseWriter, r *http.Reques return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -603,7 +603,7 @@ func RemoveTelemetryProfileEntryHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -667,7 +667,7 @@ func RemoveTelemetryProfileEntryChangeHandler(w http.ResponseWriter, r *http.Req return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) diff --git a/adminapi/change/telemetry_two_change_handler.go b/adminapi/change/telemetry_two_change_handler.go index 536f85f..2380f56 100644 --- a/adminapi/change/telemetry_two_change_handler.go +++ b/adminapi/change/telemetry_two_change_handler.go @@ -50,7 +50,7 @@ func GetTwoProfileChangesHandler(w http.ResponseWriter, r *http.Request) { searchContext := make(map[string]string) searchContext[xwcommon.APPLICATION_TYPE] = applicationType - searchContext[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + searchContext[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) changes := GetTelemetryTwoChangesByContext(searchContext) sort.Slice(changes, func(i, j int) bool { @@ -72,7 +72,7 @@ func GetApprovedTwoChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changes := xchange.GetApprovedTelemetryTwoChangesByApplicationType(tenantId, applicationType) res, err := xhttp.ReturnJsonResponse(changes, r) if err != nil { @@ -89,7 +89,7 @@ func GetTwoChangeEntityIdsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entityIds := GetTelemetryTwoChangeEntityIds(tenantId) res, err := xhttp.ReturnJsonResponse(entityIds, r) if err != nil { @@ -231,7 +231,7 @@ func CancelTwoChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := DeleteTelemetryTwoChange(tenantId, changeId); err != nil { xhttp.AdminError(w, err) return @@ -262,7 +262,7 @@ func GetGroupedTwoChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changes := xchange.GetAllTelemetryTwoChangeList(tenantId) changesPerPage := GeneratePageTelemetryTwoChanges(changes, pageNumber, pageSize) if err != nil { @@ -299,7 +299,7 @@ func GetGroupedApprovedTwoChangesHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changes := xchange.GetAllApprovedTelemetryTwoChangeList(tenantId) changesPerPage := GeneratePageApprovedTelemetryTwoChanges(changes, pageNumber, pageSize) if err != nil { @@ -354,7 +354,7 @@ func GetApprovedTwoChangesFilteredHandler(w http.ResponseWriter, r *http.Request } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) approvedChanges := GetApprovedTelemetryTwoChangesByContext(contextMap) approvedChangesPerPage := GeneratePageApprovedTelemetryTwoChanges(approvedChanges, pageNumber, pageSize) @@ -406,7 +406,7 @@ func GetTwoChangesFilteredHandler(w http.ResponseWriter, r *http.Request) { xutil.AddQueryParamsToContextMap(r, contextMap) } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) changes := GetTelemetryTwoChangesByContext(contextMap) changesPerPage := GeneratePageTelemetryTwoChanges(changes, pageNumber, pageSize) diff --git a/adminapi/change/telemetry_two_change_service.go b/adminapi/change/telemetry_two_change_service.go index bd2c079..3920a6b 100644 --- a/adminapi/change/telemetry_two_change_service.go +++ b/adminapi/change/telemetry_two_change_service.go @@ -26,6 +26,7 @@ import ( "github.com/rdkcentral/xconfadmin/adminapi/auth" xcommon "github.com/rdkcentral/xconfadmin/common" + xhttp "github.com/rdkcentral/xconfadmin/http" xchange "github.com/rdkcentral/xconfadmin/shared/change" xutil "github.com/rdkcentral/xconfadmin/util" @@ -137,7 +138,7 @@ func GetApprovedTelemetryTwoChangesByContext(searchContext map[string]string) [] } func ApproveTelemetryTwoChange(r *http.Request, changeId string) (*xwchange.ApprovedTelemetryTwoChange, error) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) change := xchange.GetOneTelemetryTwoChange(tenantId, changeId) if change == nil { return nil, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id %s does not exist", changeId)) @@ -172,7 +173,7 @@ func ApproveTelemetryTwoChanges(r *http.Request, changeIds []string) map[string] errorMessages := make(map[string]string) mergedUpdateChangesByEntityId := make(map[string]*logupload.TelemetryTwoProfile) entityToByCancelChange := []string{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) changesToApprove := GetTelemetryTwoChangesByIds(tenantId, changeIds) for _, change := range changesToApprove { var err error @@ -218,7 +219,7 @@ func SaveToApprovedApprovedTelemetryTwoChange(r *http.Request, change *xwchange. return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := xchange.SetOneApprovedTelemetryTwoChange(tenantId, approvedChange); err != nil { return nil, err } @@ -247,7 +248,7 @@ func DeleteApprovedTelemetryTwoChange(tenantId string, changeId string) error { } func RevertTelemetryTwoChange(r *http.Request, approvedId string) *xwhttp.ResponseEntity { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) approvedChange := xchange.GetOneApprovedTelemetryTwoChange(tenantId, approvedId) if approvedChange == nil { return xwhttp.NewResponseEntity(http.StatusNotFound, fmt.Errorf("ApprovedTelemetryTwoChange with %s id does not exist", approvedId), nil) @@ -267,7 +268,7 @@ func RevertTelemetryTwoChange(r *http.Request, approvedId string) *xwhttp.Respon func RevertTelemetryTwoChanges(r *http.Request, approvedIds []string) map[string]string { errorMessages := make(map[string]string) changesToRevert := make([]xwchange.ApprovedTelemetryTwoChange, 0, len(approvedIds)) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, approvedId := range approvedIds { approvedChange := xchange.GetOneApprovedTelemetryTwoChange(tenantId, approvedId) if approvedChange != nil { @@ -419,7 +420,7 @@ func revertDeleteApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwc return err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := DeleteApprovedTelemetryTwoChange(tenantId, approvedChange.ID); err != nil { return err } @@ -427,7 +428,7 @@ func revertDeleteApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwc } func revertCreateOrUpdateApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwchange.ApprovedTelemetryTwoChange) error { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entityToRevert := logupload.GetOneTelemetryTwoProfile(tenantId, approvedChange.EntityID) if entityToRevert == nil { return xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("TelemetryTwoProfile with id %s does not exist", approvedChange.EntityID)) @@ -485,7 +486,7 @@ func buildToDeleteTelemetryTwoChange(oldEntity *logupload.TelemetryTwoProfile, a func updateDeleteEntityTelemetryTwoChange(r *http.Request, change *xwchange.TelemetryTwoChange) (*xwchange.ApprovedTelemetryTwoChange, error) { currentEntity := change.OldEntity - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entityToChange := logupload.GetOneTelemetryTwoProfile(tenantId, change.EntityID) // in Java, equalPendingEntities(currentEntity, entityToChange) always return true //if (entityToChange != null && equalPendingEntities(currentEntity, entityToChange)) { @@ -540,7 +541,7 @@ func saveToApprovedAndCleanUpTelemetryTwoChange(r *http.Request, change *xwchang return err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := DeleteTelemetryTwoChange(tenantId, change.ID); err != nil { return err } @@ -550,7 +551,7 @@ func saveToApprovedAndCleanUpTelemetryTwoChange(r *http.Request, change *xwchang } func cancelApprovedTelemetryTwoChangesByEntityId(r *http.Request, entityIdsToByCancelChanges []string, changeIdsToBeExcluded []string) error { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entityId := range entityIdsToByCancelChanges { changes := GetTelemetryTwoChangesByEntityId(tenantId, entityId) for _, change := range changes { diff --git a/adminapi/change/telemetry_two_profile_handler.go b/adminapi/change/telemetry_two_profile_handler.go index 934d8e6..50c98cc 100644 --- a/adminapi/change/telemetry_two_profile_handler.go +++ b/adminapi/change/telemetry_two_profile_handler.go @@ -56,7 +56,7 @@ func GetTelemetryTwoProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profiles := xlogupload.GetTelemetryTwoProfileListByApplicationType(tenantId, applicationType) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -228,7 +228,7 @@ func GetTelemetryTwoProfileByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xlogupload.GetOneTelemetryTwoProfile(tenantId, id) if profile == nil { errorStr := fmt.Sprintf("Entity with id %s does not exist", id) @@ -276,7 +276,7 @@ func GetTelemetryTwoProfilePageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profiles := xlogupload.GetAllTelemetryTwoProfileList(tenantId, applicationType) profilesPerPage := GeneratePageTelemetryTwoProfiles(profiles, pageNumber, pageSize) if err != nil { @@ -313,7 +313,7 @@ func PostTelemetryTwoProfilesByIdListHandler(w http.ResponseWriter, r *http.Requ return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profiles := GetTelemetryTwoProfilesByIdList(tenantId, applicationType, idList) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -362,7 +362,7 @@ func PostTelemetryTwoProfileFilteredHandler(w http.ResponseWriter, r *http.Reque } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) profiles := GetTelemetryTwoProfilesByContext(contextMap) sort.SliceStable(profiles, func(i, j int) bool { @@ -485,7 +485,7 @@ func TelemetryTwoTestPageHandler(w http.ResponseWriter, r *http.Request) { } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) telemetryProfileService := telemetry.NewTelemetryProfileService() telemetryTwoRules := telemetryProfileService.ProcessTelemetryTwoRulesForAS(contextMap) diff --git a/adminapi/change/telemetry_two_profile_service.go b/adminapi/change/telemetry_two_profile_service.go index caf6c24..a72f0b5 100644 --- a/adminapi/change/telemetry_two_profile_service.go +++ b/adminapi/change/telemetry_two_profile_service.go @@ -30,11 +30,11 @@ import ( xcommon "github.com/rdkcentral/xconfadmin/common" "github.com/rdkcentral/xconfadmin/adminapi/auth" + xhttp "github.com/rdkcentral/xconfadmin/http" xchange "github.com/rdkcentral/xconfadmin/shared/change" xlogupload "github.com/rdkcentral/xconfadmin/shared/logupload" xwcommon "github.com/rdkcentral/xconfwebconfig/common" - xwhttp "github.com/rdkcentral/xconfwebconfig/http" "github.com/rdkcentral/xconfwebconfig/rulesengine" xwshared "github.com/rdkcentral/xconfwebconfig/shared" xwchange "github.com/rdkcentral/xconfwebconfig/shared/change" @@ -64,7 +64,7 @@ func WriteCreateChangeTelemetryTwoProfile(r *http.Request, profile *xwlogupload. return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeCreatingTelemetryTwoProfile(tenantId, profile, applicationType); err != nil { return nil, err @@ -94,7 +94,7 @@ func WriteUpdateChangeOrSaveTelemetryTwoProfile(r *http.Request, newProfile *xwl return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeUpdatingTelemetryTwoProfile(tenantId, newProfile, applicationType); err != nil { return nil, err @@ -132,7 +132,7 @@ func WriteDeleteChangeTelemetryTwoProfile(r *http.Request, id string) (*xwchange return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) deleteProfile, err := beforeRemovingTelemetryTwoProfile(tenantId, id, applicationType) if err != nil { @@ -195,7 +195,7 @@ func CreateTelemetryTwoProfile(r *http.Request, newProfile *xwlogupload.Telemetr return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeCreatingTelemetryTwoProfile(tenantId, newProfile, applicationType); err != nil { return nil, err @@ -215,7 +215,7 @@ func UpdateTelemetryTwoProfile(r *http.Request, profile *xwlogupload.TelemetryTw return nil, err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := beforeUpdatingTelemetryTwoProfile(tenantId, profile, applicationType); err != nil { return nil, err @@ -234,7 +234,7 @@ func DeleteTelemetryTwoProfile(r *http.Request, id string) error { if err != nil { return err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if _, err := beforeRemovingTelemetryTwoProfile(tenantId, id, applicationType); err != nil { return err } diff --git a/adminapi/dcm/dcmformula_handler.go b/adminapi/dcm/dcmformula_handler.go index 4fd30fb..6f63bb6 100644 --- a/adminapi/dcm/dcmformula_handler.go +++ b/adminapi/dcm/dcmformula_handler.go @@ -46,7 +46,7 @@ func GetDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allFormulas := GetDcmFormulaAll(tenantId) @@ -103,7 +103,7 @@ func GetDcmFormulaByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) formula := GetDcmFormula(tenantId, id) if formula == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -150,7 +150,7 @@ func GetDcmFormulaSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.DCMGenericRule{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetDcmFormulaAll(tenantId) for _, DcmRule := range result { if DcmRule.ApplicationType == appType { @@ -173,7 +173,7 @@ func GetDcmFormulaNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetDcmFormulaAll(tenantId) for _, DcmRule := range result { if DcmRule.ApplicationType == appType { @@ -205,7 +205,7 @@ func DeleteDcmFormulaByIdHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -253,7 +253,7 @@ func CreateDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -307,7 +307,7 @@ func UpdateDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -374,7 +374,7 @@ func DcmFormulaSettingsAvailabilitygHandler(w http.ResponseWriter, r *http.Reque return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dcmmap := make(map[string]map[string]bool) for _, id := range idlist { data := make(map[string]bool) @@ -418,7 +418,7 @@ func DcmFormulasAvailabilitygHandler(w http.ResponseWriter, r *http.Request) { } data := make(map[string]bool) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, id := range idlist { data[id] = getiFormulaAvail(tenantId, id) } @@ -453,7 +453,7 @@ func PostDcmFormulaFilteredWithParamsHandler(w http.ResponseWriter, r *http.Requ } requtil.AddQueryParamsToContextMap(r, contextMap) contextMap[core.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) dfrules := DcmFormulaFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(dfrules)) @@ -492,7 +492,7 @@ func DcmFormulaChangePriorityHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -575,7 +575,7 @@ func ImportDcmFormulaWithOverwriteHandler(w http.ResponseWriter, r *http.Request db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -634,7 +634,7 @@ func ImportDcmFormulasHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -698,7 +698,7 @@ func PostDcmFormulaListHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -748,7 +748,7 @@ func PutDcmFormulaListHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { diff --git a/adminapi/dcm/device_settings_handler.go b/adminapi/dcm/device_settings_handler.go index 669eb16..4c47c67 100644 --- a/adminapi/dcm/device_settings_handler.go +++ b/adminapi/dcm/device_settings_handler.go @@ -27,7 +27,6 @@ import ( xutil "github.com/rdkcentral/xconfadmin/util" - "github.com/rdkcentral/xconfwebconfig/db" xwutil "github.com/rdkcentral/xconfwebconfig/util" xhttp "github.com/rdkcentral/xconfadmin/http" @@ -76,7 +75,7 @@ func GetDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetDeviceSettingsAll(tenantId) appRules := []*logupload.DeviceSettings{} for _, rule := range result { @@ -106,7 +105,8 @@ func GetDeviceSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, errorStr) return } - devicesettings := GetDeviceSettings(db.GetDefaultTenantId(), id) + tenantId := xhttp.GetTenantId(r.Context(), r) + devicesettings := GetDeviceSettings(tenantId, id) if devicesettings == nil { errorStr := fmt.Sprintf("%v not found", id) xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, errorStr) @@ -133,7 +133,8 @@ func GetDeviceSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.DeviceSettings{} - result := GetDeviceSettingsAll(db.GetDefaultTenantId()) + tenantId := xhttp.GetTenantId(r.Context(), r) + result := GetDeviceSettingsAll(tenantId) for _, ds := range result { if ds.ApplicationType == appType { final = append(final, ds) @@ -155,7 +156,8 @@ func GetDeviceSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - result := GetDeviceSettingsAll(db.GetDefaultTenantId()) + tenantId := xhttp.GetTenantId(r.Context(), r) + result := GetDeviceSettingsAll(tenantId) for _, ds := range result { if ds.ApplicationType == appType { final = append(final, ds.Name) @@ -182,7 +184,8 @@ func DeleteDeviceSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, errorStr) return } - respEntity := DeleteDeviceSettingsbyId(db.GetDefaultTenantId(), id, applicationType) + tenantId := xhttp.GetTenantId(r.Context(), r) + respEntity := DeleteDeviceSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) return @@ -210,7 +213,8 @@ func CreateDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - respEntity := CreateDeviceSettings(db.GetDefaultTenantId(), &newds, applicationType) + tenantId := xhttp.GetTenantId(r.Context(), r) + respEntity := CreateDeviceSettings(tenantId, &newds, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) return @@ -244,7 +248,8 @@ func UpdateDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - respEntity := UpdateDeviceSettings(db.GetDefaultTenantId(), &newdsrule, applicationType) + tenantId := xhttp.GetTenantId(r.Context(), r) + respEntity := UpdateDeviceSettings(tenantId, &newdsrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) return @@ -281,7 +286,7 @@ func PostDeviceSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http. } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) dsrules := DeviceSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(dsrules)) @@ -305,7 +310,7 @@ func GetDeviceSettingsExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allFormulas := GetDcmFormulaAll(tenantId) dsList := []*logupload.DeviceSettings{} diff --git a/adminapi/dcm/logrepo_settings_handler.go b/adminapi/dcm/logrepo_settings_handler.go index c00a173..75de78b 100644 --- a/adminapi/dcm/logrepo_settings_handler.go +++ b/adminapi/dcm/logrepo_settings_handler.go @@ -40,7 +40,7 @@ func GetLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogRepoSettingsAll(tenantId) appRules := []*logupload.UploadRepository{} for _, rule := range result { @@ -79,7 +79,7 @@ func GetLogRepoSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) logreposettings := GetLogRepoSettings(tenantId, id) if logreposettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -121,7 +121,7 @@ func GetLogRepoSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.UploadRepository{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogRepoSettingsAll(tenantId) for _, lr := range result { if lr.ApplicationType == applicationType { @@ -144,7 +144,7 @@ func GetLogRepoSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogRepoSettingsAll(tenantId) for _, lr := range result { if lr.ApplicationType == applicationType { @@ -173,7 +173,7 @@ func DeleteLogRepoSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteLogRepoSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -202,7 +202,8 @@ func CreateLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - respEntity := CreateLogRepoSettings(&newlr, applicationType) + tenantId := xhttp.GetTenantId(r.Context(), r) + respEntity := CreateLogRepoSettingsForTenant(tenantId, &newlr, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) return @@ -237,7 +238,8 @@ func UpdateLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - respEntity := UpdateLogRepoSettings(&newlrrule, applicationType) + tenantId := xhttp.GetTenantId(r.Context(), r) + respEntity := UpdateLogRepoSettingsForTenant(tenantId, &newlrrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) return @@ -274,7 +276,7 @@ func PostLogRepoSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) lrrules := LogRepoSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(lrrules)) @@ -311,8 +313,9 @@ func PostLogRepoSettingsEntitiesHandler(w http.ResponseWriter, r *http.Request) return } entitiesMap := map[string]xhttp.EntityMessage{} + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { - respEntity := CreateLogRepoSettings(&entity, applicationType) + respEntity := CreateLogRepoSettingsForTenant(tenantId, &entity, applicationType) if respEntity.Error != nil { entitiesMap[entity.ID] = xhttp.EntityMessage{ Status: xcommon.ENTITY_STATUS_FAILURE, @@ -352,8 +355,9 @@ func PutLogRepoSettingsEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } entitiesMap := map[string]xhttp.EntityMessage{} + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { - respEntity := UpdateLogRepoSettings(&entity, applicationType) + respEntity := UpdateLogRepoSettingsForTenant(tenantId, &entity, applicationType) if respEntity.Error != nil { entitiesMap[entity.ID] = xhttp.EntityMessage{ Status: xcommon.ENTITY_STATUS_FAILURE, @@ -382,7 +386,7 @@ func GetLogRepoSettingsExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allFormulas := GetDcmFormulaAll(tenantId) lusList := []*logupload.LogUploadSettings{} diff --git a/adminapi/dcm/logrepo_settings_handler_test.go b/adminapi/dcm/logrepo_settings_handler_test.go index 6b2960c..3912617 100644 --- a/adminapi/dcm/logrepo_settings_handler_test.go +++ b/adminapi/dcm/logrepo_settings_handler_test.go @@ -107,7 +107,7 @@ func TestPostLogRepoSettingsEntitiesHandler_DuplicateEntity(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") // Try to create the same entity again entities := []logupload.UploadRepository{repo} @@ -141,7 +141,7 @@ func TestPostLogRepoSettingsEntitiesHandler_MixedSuccessAndFailure(t *testing.T) Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&existingRepo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &existingRepo, "stb") // Batch with one new and one duplicate entities := []logupload.UploadRepository{ @@ -195,8 +195,8 @@ func TestPutLogRepoSettingsEntitiesHandler_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo1, "stb") - CreateLogRepoSettings(&repo2, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo1, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo2, "stb") // Update both repositories updatedEntities := []logupload.UploadRepository{ @@ -298,7 +298,7 @@ func TestPutLogRepoSettingsEntitiesHandler_MixedSuccessAndFailure(t *testing.T) Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&existingRepo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &existingRepo, "stb") // Batch with one existing and one non-existent entities := []logupload.UploadRepository{ @@ -455,7 +455,7 @@ func TestGetLogRepoSettingsByIdHandler_ApplicationTypeMismatch(t *testing.T) { Protocol: "HTTP", ApplicationType: "xhome", } - CreateLogRepoSettings(&repo, "xhome") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "xhome") // Try to access with "stb" application type req, err := http.NewRequest("GET", "/xconfAdminService/dcm/uploadRepository/xhome-repo", nil) @@ -481,7 +481,7 @@ func TestGetLogRepoSettingsByIdHandler_WithExport(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") req, err := http.NewRequest("GET", "/xconfAdminService/dcm/uploadRepository/export-repo?export=true", nil) assert.NilError(t, err) @@ -541,8 +541,8 @@ func TestGetLogRepoSettingsHandler_WithExport(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo1, "stb") - CreateLogRepoSettings(&repo2, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo1, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo2, "stb") req, err := http.NewRequest("GET", "/xconfAdminService/dcm/uploadRepository?export=true", nil) assert.NilError(t, err) @@ -591,7 +591,7 @@ func TestGetLogRepoSettingsSizeHandler_NonZeroCount(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") } req, err := http.NewRequest("GET", "/xconfAdminService/dcm/uploadRepository/size", nil) @@ -642,7 +642,7 @@ func TestGetLogRepoSettingsNamesHandler_WithNames(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") } req, err := http.NewRequest("GET", "/xconfAdminService/dcm/uploadRepository/names", nil) @@ -704,7 +704,7 @@ func TestDeleteLogRepoSettingsByIdHandler_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") req, err := http.NewRequest("DELETE", "/xconfAdminService/dcm/uploadRepository/"+uniqueID, nil) assert.NilError(t, err) @@ -768,7 +768,7 @@ func TestCreateLogRepoSettingsHandler_DuplicateID(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") // Try to create another with same ID body, _ := json.Marshal(repo) @@ -837,7 +837,7 @@ func TestUpdateLogRepoSettingsHandler_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo, "stb") // Update it repo.Name = "Updated Name" @@ -910,7 +910,7 @@ func TestPostLogRepoSettingsFilteredWithParamsHandler_WithContext(t *testing.T) Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(&repo1, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), &repo1, "stb") contextMap := map[string]string{} body, _ := json.Marshal(contextMap) diff --git a/adminapi/dcm/logrepo_settings_service.go b/adminapi/dcm/logrepo_settings_service.go index 2c1d69b..6be3f1c 100644 --- a/adminapi/dcm/logrepo_settings_service.go +++ b/adminapi/dcm/logrepo_settings_service.go @@ -139,7 +139,7 @@ func DeleteOneLogRepoSettings(tenantId string, id string) error { return nil } -func LogRepoSettingsValidate(lr *logupload.UploadRepository) *xwhttp.ResponseEntity { +func LogRepoSettingsValidateForTenant(tenantId string, lr *logupload.UploadRepository) *xwhttp.ResponseEntity { if lr == nil { return xwhttp.NewResponseEntity(http.StatusBadRequest, fmt.Errorf("Log Repository Settings should be specified"), nil) } @@ -167,7 +167,7 @@ func LogRepoSettingsValidate(lr *logupload.UploadRepository) *xwhttp.ResponseEnt return xwhttp.NewResponseEntity(http.StatusBadRequest, fmt.Errorf("URL is InValid"), nil) } - lrrules := GetLogRepoSettingsAll(db.GetDefaultTenantId()) + lrrules := GetLogRepoSettingsAll(tenantId) for _, exlrrule := range lrrules { if exlrrule.ApplicationType != lr.ApplicationType { continue @@ -181,8 +181,8 @@ func LogRepoSettingsValidate(lr *logupload.UploadRepository) *xwhttp.ResponseEnt return xwhttp.NewResponseEntity(http.StatusCreated, nil, nil) } -func CreateLogRepoSettings(lr *logupload.UploadRepository, app string) *xwhttp.ResponseEntity { - _, err := db.GetCachedSimpleDao().GetOne(db.GetDefaultTenantId(), db.TABLE_UPLOAD_REPOSITORIES, lr.ID) +func CreateLogRepoSettingsForTenant(tenantId string, lr *logupload.UploadRepository, app string) *xwhttp.ResponseEntity { + _, err := db.GetCachedSimpleDao().GetOne(tenantId, db.TABLE_UPLOAD_REPOSITORIES, lr.ID) if err == nil { return xwhttp.NewResponseEntity(http.StatusConflict, errors.New(fmt.Sprintf("Entity with id %s already exists", lr.ID)), nil) } @@ -190,22 +190,22 @@ func CreateLogRepoSettings(lr *logupload.UploadRepository, app string) *xwhttp.R return xwhttp.NewResponseEntity(http.StatusConflict, errors.New(fmt.Sprintf("Entity with id %s ApplicationType doesn't match", lr.ID)), nil) } - respEntity := LogRepoSettingsValidate(lr) + respEntity := LogRepoSettingsValidateForTenant(tenantId, lr) if respEntity.Error != nil { return respEntity } lr.Updated = util.GetTimestamp() - if err = db.GetCachedSimpleDao().SetOne(db.GetDefaultTenantId(), db.TABLE_UPLOAD_REPOSITORIES, lr.ID, lr); err != nil { + if err = db.GetCachedSimpleDao().SetOne(tenantId, db.TABLE_UPLOAD_REPOSITORIES, lr.ID, lr); err != nil { return xwhttp.NewResponseEntity(http.StatusInternalServerError, err, nil) } return xwhttp.NewResponseEntity(http.StatusCreated, nil, lr) } -func UpdateLogRepoSettings(lr *logupload.UploadRepository, app string) *xwhttp.ResponseEntity { +func UpdateLogRepoSettingsForTenant(tenantId string, lr *logupload.UploadRepository, app string) *xwhttp.ResponseEntity { if util.IsBlank(lr.ID) { return xwhttp.NewResponseEntity(http.StatusBadRequest, errors.New(" ID is empty"), nil) } - inst, err := db.GetCachedSimpleDao().GetOne(db.GetDefaultTenantId(), db.TABLE_UPLOAD_REPOSITORIES, lr.ID) + inst, err := db.GetCachedSimpleDao().GetOne(tenantId, db.TABLE_UPLOAD_REPOSITORIES, lr.ID) if err != nil { return xwhttp.NewResponseEntity(http.StatusConflict, errors.New(fmt.Sprintf("Entity with id %s does not exists", lr.ID)), nil) } @@ -216,13 +216,13 @@ func UpdateLogRepoSettings(lr *logupload.UploadRepository, app string) *xwhttp.R if exlrrule.ApplicationType != lr.ApplicationType { return xwhttp.NewResponseEntity(http.StatusConflict, errors.New(fmt.Sprintf("ApplicationType can not be changed")), nil) } - respEntity := LogRepoSettingsValidate(lr) + respEntity := LogRepoSettingsValidateForTenant(tenantId, lr) if respEntity.Error != nil { return respEntity } lr.Updated = util.GetTimestamp() - if err = db.GetCachedSimpleDao().SetOne(db.GetDefaultTenantId(), db.TABLE_UPLOAD_REPOSITORIES, lr.ID, lr); err != nil { + if err = db.GetCachedSimpleDao().SetOne(tenantId, db.TABLE_UPLOAD_REPOSITORIES, lr.ID, lr); err != nil { return xwhttp.NewResponseEntity(http.StatusInternalServerError, err, nil) } diff --git a/adminapi/dcm/logrepo_settings_service_test.go b/adminapi/dcm/logrepo_settings_service_test.go index 127142c..092f2bf 100644 --- a/adminapi/dcm/logrepo_settings_service_test.go +++ b/adminapi/dcm/logrepo_settings_service_test.go @@ -53,7 +53,7 @@ func TestGetLogRepoSettings_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") result := GetLogRepoSettings(db.GetDefaultTenantId(), "test-repo-1") assert.Assert(t, result != nil) @@ -94,7 +94,7 @@ func TestGetLogRepoSettingsAll_WithRepositories(t *testing.T) { } for _, repo := range repos { - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") } result := GetLogRepoSettingsAll(db.GetDefaultTenantId()) @@ -108,7 +108,7 @@ func TestLogRepoSettingsValidate_NilInput(t *testing.T) { DeleteAllEntities() defer DeleteAllEntities() - respEntity := LogRepoSettingsValidate(nil) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), nil) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -128,7 +128,7 @@ func TestLogRepoSettingsValidate_EmptyApplicationType(t *testing.T) { ApplicationType: "", // Empty } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -148,7 +148,7 @@ func TestLogRepoSettingsValidate_EmptyName(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -168,7 +168,7 @@ func TestLogRepoSettingsValidate_EmptyURL(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -188,7 +188,7 @@ func TestLogRepoSettingsValidate_InvalidURL(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -207,7 +207,7 @@ func TestLogRepoSettingsValidate_EmptyProtocol(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -227,7 +227,7 @@ func TestLogRepoSettingsValidate_InvalidProtocol(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -247,7 +247,7 @@ func TestLogRepoSettingsValidate_DuplicateName(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo1, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo1, "stb") // Try to validate another with same name but different ID repo2 := &logupload.UploadRepository{ @@ -258,7 +258,7 @@ func TestLogRepoSettingsValidate_DuplicateName(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo2) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo2) assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -278,7 +278,7 @@ func TestLogRepoSettingsValidate_EmptyID(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusCreated, respEntity.Status) assert.Assert(t, respEntity.Error == nil) @@ -299,7 +299,7 @@ func TestLogRepoSettingsValidate_Success(t *testing.T) { ApplicationType: "stb", } - respEntity := LogRepoSettingsValidate(repo) + respEntity := LogRepoSettingsValidateForTenant(db.GetDefaultTenantId(), repo) assert.Equal(t, http.StatusCreated, respEntity.Status) assert.Assert(t, respEntity.Error == nil) @@ -319,10 +319,10 @@ func TestCreateLogRepoSettings_DuplicateID(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Try to create another with same ID - respEntity := CreateLogRepoSettings(repo, "stb") + respEntity := CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusConflict, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -342,7 +342,7 @@ func TestCreateLogRepoSettings_ApplicationTypeMismatch(t *testing.T) { } // Pass different app type - respEntity := CreateLogRepoSettings(repo, "stb") + respEntity := CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusConflict, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -361,7 +361,7 @@ func TestCreateLogRepoSettings_ValidationError(t *testing.T) { ApplicationType: "stb", } - respEntity := CreateLogRepoSettings(repo, "stb") + respEntity := CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -381,7 +381,7 @@ func TestCreateLogRepoSettings_Success(t *testing.T) { ApplicationType: "stb", } - respEntity := CreateLogRepoSettings(repo, "stb") + respEntity := CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusCreated, respEntity.Status) assert.Assert(t, respEntity.Error == nil) @@ -403,7 +403,7 @@ func TestUpdateLogRepoSettings_EmptyID(t *testing.T) { ApplicationType: "stb", } - respEntity := UpdateLogRepoSettings(repo, "stb") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -422,7 +422,7 @@ func TestUpdateLogRepoSettings_NonExistent(t *testing.T) { ApplicationType: "stb", } - respEntity := UpdateLogRepoSettings(repo, "stb") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusConflict, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -442,7 +442,7 @@ func TestUpdateLogRepoSettings_ApplicationTypeMismatch(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - createResp := CreateLogRepoSettings(repo, "stb") + createResp := CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusCreated, createResp.Status) // Try to update with different app type in parameter @@ -454,7 +454,7 @@ func TestUpdateLogRepoSettings_ApplicationTypeMismatch(t *testing.T) { Protocol: "HTTP", ApplicationType: "xhome", } - respEntity := UpdateLogRepoSettings(updateRepo, "xhome") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), updateRepo, "xhome") assert.Equal(t, http.StatusConflict, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -473,11 +473,11 @@ func TestUpdateLogRepoSettings_ChangeApplicationType(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Try to change ApplicationType repo.ApplicationType = "xhome" - respEntity := UpdateLogRepoSettings(repo, "stb") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusConflict, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -497,11 +497,11 @@ func TestUpdateLogRepoSettings_ValidationError(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Update with invalid data repo.Name = "" // Empty name - validation error - respEntity := UpdateLogRepoSettings(repo, "stb") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusBadRequest, respEntity.Status) assert.Assert(t, respEntity.Error != nil) @@ -521,11 +521,11 @@ func TestUpdateLogRepoSettings_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Update it repo.Name = "Updated Name" - respEntity := UpdateLogRepoSettings(repo, "stb") + respEntity := UpdateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") assert.Equal(t, http.StatusOK, respEntity.Status) assert.Assert(t, respEntity.Error == nil) @@ -562,7 +562,7 @@ func TestDeleteLogRepoSettingsbyId_ApplicationTypeMismatch(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Try to delete with different app type respEntity := DeleteLogRepoSettingsbyId(db.GetDefaultTenantId(), "test-id", "xhome") @@ -584,7 +584,7 @@ func TestDeleteLogRepoSettingsbyId_InUse(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Create a LogUploadSettings that references this repository // Note: This requires creating a DCM formula and LogUploadSettings @@ -615,7 +615,7 @@ func TestDeleteLogRepoSettingsbyId_Success(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") // Delete it respEntity := DeleteLogRepoSettingsbyId(db.GetDefaultTenantId(), uniqueID, "stb") @@ -790,7 +790,7 @@ func TestLogRepoSettingsFilterByContext_EmptyContext(t *testing.T) { } for _, repo := range repos { - CreateLogRepoSettings(repo, repo.ApplicationType) + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, repo.ApplicationType) } contextMap := map[string]string{ @@ -833,7 +833,7 @@ func TestLogRepoSettingsFilterByContext_FilterByApplicationType(t *testing.T) { } for _, repo := range repos { - CreateLogRepoSettings(repo, repo.ApplicationType) + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, repo.ApplicationType) } contextMap := map[string]string{ @@ -880,7 +880,7 @@ func TestLogRepoSettingsFilterByContext_FilterByName(t *testing.T) { } for _, repo := range repos { - CreateLogRepoSettings(repo, repo.ApplicationType) + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, repo.ApplicationType) } contextMap := map[string]string{ @@ -909,7 +909,7 @@ func TestLogRepoSettingsFilterByContext_NoMatches(t *testing.T) { Protocol: "HTTP", ApplicationType: "stb", } - CreateLogRepoSettings(repo, "stb") + CreateLogRepoSettingsForTenant(db.GetDefaultTenantId(), repo, "stb") contextMap := map[string]string{ common.APPLICATION_TYPE: "xhome", // Different type diff --git a/adminapi/dcm/logupload_settings_handler.go b/adminapi/dcm/logupload_settings_handler.go index 09729f2..ee1f78c 100644 --- a/adminapi/dcm/logupload_settings_handler.go +++ b/adminapi/dcm/logupload_settings_handler.go @@ -39,7 +39,7 @@ func GetLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogUploadSettingsList(tenantId) appRules := []*logupload.LogUploadSettings{} for _, rule := range result { @@ -70,7 +70,7 @@ func GetLogUploadSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) loguploadsettings := logupload.GetOneLogUploadSettings(tenantId, id) if loguploadsettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -98,7 +98,7 @@ func GetLogUploadSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.LogUploadSettings{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogUploadSettingsList(tenantId) for _, lu := range result { if lu.ApplicationType == applicationType { @@ -121,7 +121,7 @@ func GetLogUploadSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetLogUploadSettingsList(tenantId) for _, lu := range result { if lu.ApplicationType == applicationType { @@ -150,7 +150,7 @@ func DeleteLogUploadSettingsByIdHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteLogUploadSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -180,7 +180,7 @@ func CreateLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateLogUploadSettings(tenantId, &newlu, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -216,7 +216,7 @@ func UpdateLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateLogUploadSettings(tenantId, &newlurule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -254,7 +254,7 @@ func PostLogUploadSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *ht } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) lurules := LogUploadSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(lurules)) diff --git a/adminapi/dcm/vod_settings_handler.go b/adminapi/dcm/vod_settings_handler.go index 580ad8b..84f623a 100644 --- a/adminapi/dcm/vod_settings_handler.go +++ b/adminapi/dcm/vod_settings_handler.go @@ -42,7 +42,7 @@ func GetVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetVodSettingsAll(tenantId) appRules := []*logupload.VodSettings{} for _, rule := range result { @@ -69,7 +69,7 @@ func GetVodSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) vodsettings := GetVodSettings(tenantId, id) if vodsettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -93,7 +93,7 @@ func GetVodSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.VodSettings{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetVodSettingsAll(tenantId) for _, vs := range result { if vs.ApplicationType == applicationType { @@ -112,7 +112,7 @@ func GetVodSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetVodSettingsAll(tenantId) for _, vs := range result { if vs.ApplicationType == applicationType { @@ -137,7 +137,7 @@ func DeleteVodSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteVodSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -167,7 +167,7 @@ func CreateVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateVodSettings(tenantId, &newvs, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -203,7 +203,7 @@ func UpdateVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateVodSettings(tenantId, &newvsrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -241,7 +241,7 @@ func PostVodSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http.Req } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) vsrules := VodSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(vsrules)) @@ -261,7 +261,7 @@ func GetVodSettingExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allFormulas := GetDcmFormulaAll(tenantId) vodList := []*logupload.VodSettings{} diff --git a/adminapi/firmware/firmware_test_page_controller.go b/adminapi/firmware/firmware_test_page_controller.go index 62c436b..6c213c5 100644 --- a/adminapi/firmware/firmware_test_page_controller.go +++ b/adminapi/firmware/firmware_test_page_controller.go @@ -67,7 +67,7 @@ func GetFirmwareTestPageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) context[xwcommon.TENANT_ID] = tenantId // If input has any of these search-paramters, validate their values diff --git a/adminapi/lockdown/lockdown_settings_handler.go b/adminapi/lockdown/lockdown_settings_handler.go index 7500b1b..ddbf7bd 100644 --- a/adminapi/lockdown/lockdown_settings_handler.go +++ b/adminapi/lockdown/lockdown_settings_handler.go @@ -25,11 +25,10 @@ import ( "github.com/rdkcentral/xconfadmin/adminapi/auth" ccommon "github.com/rdkcentral/xconfadmin/common" xhttp "github.com/rdkcentral/xconfadmin/http" - xwhttp "github.com/rdkcentral/xconfwebconfig/http" ) func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { - if !auth.HasWritePermissionForTool(r) { + if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No write permission: tools") return } @@ -47,7 +46,7 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := SetLockdownSetting(tenantId, &lockdownSettings) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -58,7 +57,7 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { func GetLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { // No permission check needed - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) lockdownSetting, err := GetLockdownSettings(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/adminapi/queries/amv_handler.go b/adminapi/queries/amv_handler.go index 7ca1682..4cac616 100644 --- a/adminapi/queries/amv_handler.go +++ b/adminapi/queries/amv_handler.go @@ -46,7 +46,7 @@ func GetAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetAmvALL(tenantId) appRules := []*ActivationVersionResponse{} for _, rule := range result { @@ -87,7 +87,7 @@ func GetAmvByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) amv := GetAmv(tenantId, id) if amv == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -144,7 +144,7 @@ func PostAmvFilteredHandler(w http.ResponseWriter, r *http.Request) { } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) amvrules := AmvFilterByContext(contextMap) sort.Slice(amvrules, func(i, j int) bool { @@ -179,7 +179,7 @@ func DeleteAmvByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteAmvbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -196,7 +196,7 @@ func CreateAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateAmv(tenantId, &newAmv, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -245,7 +245,7 @@ func ImportAllAmvHandler(w http.ResponseWriter, r *http.Request) { determinedAppType = applicationType } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := importOrUpdateAllAmvs(tenantId, amvlist, determinedAppType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -267,7 +267,7 @@ func UpdateAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateAmv(tenantId, &newAmv, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -300,7 +300,7 @@ func PostAmvEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -344,7 +344,7 @@ func PutAmvEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -383,7 +383,7 @@ func GetAmvFilteredHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) amvrules := AmvFilterByContext(contextMap) sort.Slice(amvrules, func(i, j int) bool { diff --git a/adminapi/queries/common.go b/adminapi/queries/common.go index f362591..999fd22 100644 --- a/adminapi/queries/common.go +++ b/adminapi/queries/common.go @@ -90,7 +90,7 @@ func GetInfoTable(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -155,7 +155,7 @@ func GetInfoTableRowKey(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -247,7 +247,7 @@ func UpdateInfoTableRowKey(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -365,7 +365,7 @@ func GetStats(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) stats := db.GetCacheManager().GetStatistics(tenantId) response, _ := util.JSONMarshal(stats.TableStats) @@ -378,7 +378,7 @@ func GetInfoStatistics(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) stats := *db.GetCacheManager().GetStatistics(tenantId) response, _ := util.JSONMarshal(stats) @@ -387,12 +387,12 @@ func GetInfoStatistics(w http.ResponseWriter, r *http.Request) { func GetAppSettings(w http.ResponseWriter, r *http.Request) { // For retrieving app settings, tools permission is required - if !auth.HasReadPermissionForTool(r) { - xhttp.WriteAdminErrorResponse(w, http.StatusUnauthorized, "") + if _, err := auth.CanRead(r, auth.TOOL_ENTITY); err != nil { + xhttp.AdminError(w, err) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) settings, err := xcommon.GetAppSettings(tenantId) if err != nil { @@ -405,8 +405,8 @@ func GetAppSettings(w http.ResponseWriter, r *http.Request) { func UpdateAppSettings(w http.ResponseWriter, r *http.Request) { // For updating app settings, tools permission is required - if !auth.HasWritePermissionForTool(r) { - xhttp.WriteAdminErrorResponse(w, http.StatusUnauthorized, "") + if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { + xhttp.AdminError(w, err) return } @@ -424,7 +424,7 @@ func UpdateAppSettings(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for k, v := range settings { if !xcommon.IsValidAppSetting(k) { @@ -446,7 +446,7 @@ func GetInfoRefreshAllHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) failedToRefreshTables := db.GetCacheManager().RefreshAll(tenantId) if len(failedToRefreshTables) == 0 { @@ -464,7 +464,7 @@ func GetInfoRefreshHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] err := db.GetCacheManager().Refresh(tenantId, tableName) diff --git a/adminapi/queries/environment_handler.go b/adminapi/queries/environment_handler.go index c4b6ad4..38a080b 100644 --- a/adminapi/queries/environment_handler.go +++ b/adminapi/queries/environment_handler.go @@ -60,7 +60,7 @@ func UpdateEnvironmentHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateEnvironment(tenantId, &upEnv) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -96,7 +96,7 @@ func PostEnvironmentFilteredHandler(w http.ResponseWriter, r *http.Request) { } } xutil.AddQueryParamsToContextMap(r, contextMap) - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) evrules := EnvironmentFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(evrules)) @@ -132,7 +132,7 @@ func PostEnvironmentEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -175,7 +175,7 @@ func PutEnvironmentEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity diff --git a/adminapi/queries/feature_handler.go b/adminapi/queries/feature_handler.go index 37765f2..849d40f 100644 --- a/adminapi/queries/feature_handler.go +++ b/adminapi/queries/feature_handler.go @@ -44,7 +44,7 @@ func GetFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { } featureEntityList := []*rfc.FeatureEntity{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) features := GetAllFeatureEntity(tenantId) for _, rule := range features { if applicationType == rule.ApplicationType { @@ -65,7 +65,7 @@ func GetFeatureEntityFilteredHandler(w http.ResponseWriter, r *http.Request) { contextMap := map[string]string{} requtil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) featureList := GetFeatureEntityFiltered(contextMap) response, _ := util.XConfJSONMarshal(featureList, true) @@ -85,7 +85,7 @@ func GetFeatureEntityByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureEntity := GetFeatureEntityById(tenantId, id) if featureEntity == nil { xwhttp.WriteXconfResponse(w, http.StatusNotFound, []byte(fmt.Sprintf("\"Entity with id: %s does not exist\"", id))) @@ -133,7 +133,7 @@ func PostFeatureEntityImportAllHandler(w http.ResponseWriter, r *http.Request) { determinedAppType = applicationType } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureEntityMap := ImportOrUpdateAllFeatureEntity(tenantId, featureEntityList, determinedAppType) response, _ := util.XConfJSONMarshal(featureEntityMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) @@ -147,7 +147,7 @@ func PostFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xrfc.DoesFeatureExist(tenantId, featureEntity.ID) { xwhttp.WriteXconfResponse(w, http.StatusConflict, []byte(fmt.Sprintf("\"Entity with id: %s already exists\"", featureEntity.ID))) return @@ -184,7 +184,7 @@ func PutFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if !xrfc.DoesFeatureExist(tenantId, featureEntity.ID) { xwhttp.WriteXconfResponse(w, http.StatusNotFound, []byte(fmt.Sprintf("\"Entity with id: %s does not exist\"", featureEntity.ID))) return diff --git a/adminapi/queries/feature_rule_handler.go b/adminapi/queries/feature_rule_handler.go index 0e3989e..061c96b 100644 --- a/adminapi/queries/feature_rule_handler.go +++ b/adminapi/queries/feature_rule_handler.go @@ -64,7 +64,7 @@ func GetFeatureRulesFiltered(w http.ResponseWriter, r *http.Request) { } } contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) featureRules := FindFeatureRuleByContext(contextMap) response, err := util.JSONMarshal(featureRules) @@ -115,7 +115,7 @@ func GetFeatureRulesFilteredWithPage(w http.ResponseWriter, r *http.Request) { } } contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) featureRules := FindFeatureRuleByContext(contextMap) featureRuleList := FeatureRulesGeneratePage(featureRules, pageNumber, pageSize) @@ -158,7 +158,7 @@ func GetFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureRules := GetAllFeatureRulesByType(tenantId, applicationType) response, err := util.JSONMarshal(featureRules) if err != nil { @@ -174,7 +174,7 @@ func GetFeatureRulesExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureRules := GetAllFeatureRulesByType(tenantId, applicationType) sort.Slice(featureRules, func(i, j int) bool { return featureRules[j].Priority > featureRules[i].Priority @@ -205,7 +205,7 @@ func GetFeatureRuleOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureRule := xrfc.GetFeatureRule(tenantId, id) if featureRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -241,7 +241,7 @@ func GetFeatureRuleOne(w http.ResponseWriter, r *http.Request) { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("Id is blank")) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) featureRule := xrfc.GetFeatureRule(tenantId, id) if featureRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -272,7 +272,7 @@ func CreateFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -311,7 +311,7 @@ func UpdateFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -379,7 +379,7 @@ func ImportAllFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -413,7 +413,7 @@ func DeleteOneFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -505,7 +505,7 @@ func ChangeFeatureRulePrioritiesHandler(w http.ResponseWriter, r *http.Request) db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -546,7 +546,7 @@ func GetFeatureRulesSizeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) size := GetFeatureRulesSize(tenantId, applicationType) sizeString := strconv.Itoa(size) response, err := util.JSONMarshal(sizeString) @@ -596,7 +596,7 @@ func UpdateFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -660,7 +660,7 @@ func CreateFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { diff --git a/adminapi/queries/firmware_config_handler.go b/adminapi/queries/firmware_config_handler.go index 09f16d7..03acade 100644 --- a/adminapi/queries/firmware_config_handler.go +++ b/adminapi/queries/firmware_config_handler.go @@ -57,7 +57,7 @@ func PostFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { } status := http.StatusCreated - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateFirmwareConfigAS(tenantId, firmwareConfig, applicationType, true) data := respEntity.Data status = respEntity.Status @@ -88,7 +88,7 @@ func PutFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { } status := http.StatusOK - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateFirmwareConfigAS(tenantId, firmwareConfig, appType, true) data := respEntity.Data status = respEntity.Status @@ -161,7 +161,7 @@ func PutPostFirmwareConfigEntitiesHandler(w http.ResponseWriter, r *http.Request } descMap := make(map[string][]*estbfirmware.FirmwareConfig) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) list, err := estbfirmware.GetFirmwareConfigAsListDB(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -279,7 +279,7 @@ func PostFirmwareConfigBySupportedModelsHandler(w http.ResponseWriter, r *http.R return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetFirmwareConfigsByModelIdsAndApplication(tenantId, modelIds, appType) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -299,7 +299,7 @@ func GetFirmwareConfigFirmwareConfigMapHandler(w http.ResponseWriter, r *http.Re return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) configMap, err := estb.GetFirmwareConfigAsMapDB(tenantId, appType) if err != nil { xhttp.AdminError(w, err) @@ -341,7 +341,7 @@ func PostFirmwareConfigGetSortedFirmwareVersionsIfExistOrNotHandler(w http.Respo return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetSortedFirmwareVersionsIfDoesExistOrNot(tenantId, fcData, appType) response, err := xhttp.ReturnJsonResponse(result, r) @@ -405,7 +405,7 @@ func PostFirmwareConfigFilteredHandler(w http.ResponseWriter, r *http.Request) { } } filterContext[xcommon.APPLICATION_TYPE] = appType - filterContext[xcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + filterContext[xcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) // Get all entries and sort them entries, _ := estbfirmware.GetFirmwareConfigAsListDB(filterContext[xcommon.TENANT_ID]) @@ -454,7 +454,7 @@ func GetFirmwareConfigByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fc, _ := estbfirmware.GetFirmwareConfigOneDB(tenantId, id) if fc == nil { errorStr := fmt.Sprintf("Entity with id: %s does not exist", id) @@ -499,7 +499,7 @@ func GetFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { _, ok2 := queryParams[common.EXPORTALL] if ok1 || ok2 { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entries := GetFirmwareConfigsAS(tenantId, appType) res, err := xhttp.ReturnJsonResponse(entries, r) @@ -530,7 +530,7 @@ func GetSupportedConfigsByEnvModelRuleName(w http.ResponseWriter, r *http.Reques return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fwConfig := getSupportedConfigsByEnvModelRuleName(tenantId, ruleName, appType) if len(fwConfig) == 0 { errorStr := fmt.Sprintf("%s not found", ruleName) @@ -562,7 +562,7 @@ func GetFirmwareConfigByEnvModelRuleNameByRuleNameHandler(w http.ResponseWriter, return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fwConfig := getFirmwareConfigByEnvModelRuleName(tenantId, entry) if fwConfig != nil && fwConfig.ApplicationType != appType { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("Entity with id: %s aplicationType does not match", fwConfig.ID)) diff --git a/adminapi/queries/firmware_rule_handler.go b/adminapi/queries/firmware_rule_handler.go index 3b6b94a..e3226a4 100644 --- a/adminapi/queries/firmware_rule_handler.go +++ b/adminapi/queries/firmware_rule_handler.go @@ -48,7 +48,7 @@ func populateContext(w http.ResponseWriter, r *http.Request, isRead bool) (filte filterContext = map[string]string{} xutil.AddQueryParamsToContextMap(r, filterContext) - filterContext[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + filterContext[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) appType, found := filterContext[common.APPLICATION_TYPE] if !found || util.IsBlank(appType) { @@ -231,7 +231,7 @@ func PostFirmwareRuleImportAllHandler(w http.ResponseWriter, r *http.Request) { determinedAppType = appType } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := importOrUpdateAllFirmwareRules(tenantId, firmwareRules, determinedAppType, fields) response, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -253,7 +253,7 @@ func PostFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if util.IsBlank(firmwareRule.ID) { firmwareRule.ID = uuid.New().String() } else { @@ -285,7 +285,7 @@ func PostFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { func PutFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { firmwareRule := firmware.NewEmptyFirmwareRule() firmwareRule.ApplicationType = "" - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) appType, err := auth.ExtractBodyAndCheckPermissions(firmwareRule, w, r, auth.FIRMWARE_ENTITY) _, err = firmware.GetFirmwareRuleOneDB(tenantId, firmwareRule.ID) @@ -323,7 +323,7 @@ func DeleteFirmwareRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entityOnDb, err := firmware.GetFirmwareRuleOneDB(tenantId, id) if err == nil { if entityOnDb.ApplicationType != appType { @@ -358,7 +358,7 @@ func GetFirmwareRuleByTypeNamesHandler(w http.ResponseWriter, r *http.Request) { } nameMap := make(map[string]string) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := firmware.GetFirmwareRuleAllAsListDBForAdmin(tenantId) for _, v := range dbrules { if v.Type == givenType && appType == v.ApplicationType { @@ -611,7 +611,7 @@ func PostPutFirmwareRuleEntitiesHandler(w http.ResponseWriter, r *http.Request, nameMap := make(map[string][]*firmware.FirmwareRule) ruleMap := make(map[string][]*firmware.FirmwareRule) estbMap := make(map[string][]*firmware.FirmwareRule) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) list, err := firmware.GetFirmwareRuleAllAsListDBForAdmin(tenantId) if err != nil { @@ -753,7 +753,7 @@ func GetFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := xfirmware.GetFirmwareSortedRuleAllAsListDB(tenantId) filtRules := []*firmware.FirmwareRule{} @@ -799,7 +799,7 @@ func GetFirmwareRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fr, _ := firmware.GetFirmwareRuleOneDB(tenantId, id) if fr == nil { errorStr := fmt.Sprintf("%v not found", id) diff --git a/adminapi/queries/firmware_rule_report_page_handler.go b/adminapi/queries/firmware_rule_report_page_handler.go index 2c23dda..0ae12ac 100644 --- a/adminapi/queries/firmware_rule_report_page_handler.go +++ b/adminapi/queries/firmware_rule_report_page_handler.go @@ -56,7 +56,7 @@ func PostFirmwareRuleReportPageHandler(w http.ResponseWriter, r *http.Request) { header["Content-Disposition"] = "attachment; filename=filename=report.xls" header["Content-Type"] = "application/vnd.ms-excel" - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macRules, _ := db.GetSimpleDao().GetAllByKeys(tenantId, db.TABLE_FIRMWARE_RULES, macRuleIds) macIds := getMacAddresses(tenantId, macRules) reportBytes, err := doReport(tenantId, macIds) diff --git a/adminapi/queries/firmware_rule_template_handler.go b/adminapi/queries/firmware_rule_template_handler.go index 70a34c0..7269628 100644 --- a/adminapi/queries/firmware_rule_template_handler.go +++ b/adminapi/queries/firmware_rule_template_handler.go @@ -49,7 +49,7 @@ func GetFirmwareRuleTemplateFilteredHandler(w http.ResponseWriter, r *http.Reque util.AddQueryParamsToContextMap(r, filterContext) var err error - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allTemplates, err := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -110,7 +110,7 @@ func PostFirmwareRuleTemplateFilteredHandler(w http.ResponseWriter, r *http.Requ } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) allTemplates, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(allTemplates, func(i, j int) bool { return strings.Compare(strings.ToLower(allTemplates[i].ID), strings.ToLower(allTemplates[j].ID)) < 0 @@ -196,7 +196,7 @@ func PostFirmwareRuleTemplateImportAllHandler(w http.ResponseWriter, r *http.Req db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -260,7 +260,7 @@ func PostFirmwareRuleTemplateImportHandler(w http.ResponseWriter, r *http.Reques db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -330,7 +330,7 @@ func PostChangePriorityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) frt, err := corefw.GetFirmwareRuleTemplateOneDB(tenantId, templateId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("unable to find template with id %s", templateId)) @@ -410,7 +410,7 @@ func PostFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -467,7 +467,7 @@ func PutFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -512,7 +512,7 @@ func DeleteFirmwareRuleTemplateByIdHandler(w http.ResponseWriter, r *http.Reques return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) // Check for usage in FirmwareRule rules, err := corefw.GetFirmwareRuleAllAsListDBForAdmin(tenantId) @@ -611,7 +611,7 @@ func GetFirmwareRuleTemplateByIdHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) frt := GetFirmwareRuleTemplateById(tenantId, id) if frt == nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("unable to find FirmwareRuleTemplate with id : %v", id)) @@ -668,7 +668,7 @@ func PostFirmwareRuleTemplateEntitiesHandler(w http.ResponseWriter, r *http.Requ db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -744,7 +744,7 @@ func PutFirmwareRuleTemplateEntitiesHandler(w http.ResponseWriter, r *http.Reque db.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -795,7 +795,7 @@ func ObsoleteGetFirmwareRuleTemplatePageHandler(w http.ResponseWriter, r *http.R pageContext := map[string]string{} util.AddQueryParamsToContextMap(r, pageContext) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(dbrules, func(i, j int) bool { return strings.Compare(strings.ToLower(dbrules[i].ID), strings.ToLower(dbrules[j].ID)) < 0 @@ -821,7 +821,7 @@ func GetFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(dbrules, func(i, j int) bool { return strings.Compare(strings.ToLower(dbrules[i].ID), strings.ToLower(dbrules[j].ID)) < 0 @@ -855,7 +855,7 @@ func GetFirmwareRuleTemplateAllByTypeHandler(w http.ResponseWriter, r *http.Requ return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []corefw.FirmwareRuleTemplate{} for _, v := range dbrules { @@ -883,7 +883,7 @@ func GetFirmwareRuleTemplateIdsHandler(w http.ResponseWriter, r *http.Request) { applicableActionTypes, ok := queryParams[xcommon.TYPE] if ok { applicableActionType := applicableActionTypes[0] - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []string{} for _, v := range dbrules { @@ -925,7 +925,7 @@ func GetFirmwareRuleTemplateWithVarWithVarHandler(w http.ResponseWriter, r *http if editVar == "true" { editable = true } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []corefw.FirmwareRuleTemplate{} for _, v := range dbrules { @@ -951,7 +951,7 @@ func GetFirmwareRuleTemplateExportHandler(w http.ResponseWriter, r *http.Request } queryParams := r.URL.Query() actionTypes, ok := queryParams[xcommon.TYPE] - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if ok { actionType := actionTypes[0] entities, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") diff --git a/adminapi/queries/log_controller.go b/adminapi/queries/log_controller.go index 82d31bc..eb18824 100644 --- a/adminapi/queries/log_controller.go +++ b/adminapi/queries/log_controller.go @@ -25,7 +25,6 @@ import ( xhttp "github.com/rdkcentral/xconfadmin/http" "github.com/rdkcentral/xconfadmin/shared/estbfirmware" "github.com/rdkcentral/xconfadmin/util" - xwhttp "github.com/rdkcentral/xconfwebconfig/http" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" @@ -50,7 +49,7 @@ func GetLogs(w http.ResponseWriter, r *http.Request) { } result := make(map[string]interface{}, 2) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) last := estbfirmware.GetLastConfigLog(tenantId, macAddress) //*ConfigChangeLog if last != nil { configChangeLogList := estbfirmware.GetConfigChangeLogsOnly(tenantId, macAddress) //[]*ConfigChangeLog diff --git a/adminapi/queries/log_file_handler.go b/adminapi/queries/log_file_handler.go index 9fd26f9..38dedd5 100644 --- a/adminapi/queries/log_file_handler.go +++ b/adminapi/queries/log_file_handler.go @@ -59,7 +59,7 @@ func CreateLogFile(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if !isValidName(tenantId, logFile) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is already used") return diff --git a/adminapi/queries/log_upload_settings_handler.go b/adminapi/queries/log_upload_settings_handler.go index 3273972..1788cde 100644 --- a/adminapi/queries/log_upload_settings_handler.go +++ b/adminapi/queries/log_upload_settings_handler.go @@ -119,7 +119,7 @@ func SaveLogUploadSettings(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) nameErrorMessage := validateName(tenantId, &logUploadSettings) if nameErrorMessage != "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, nameErrorMessage) diff --git a/adminapi/queries/model_handler.go b/adminapi/queries/model_handler.go index 4573f9f..af2dbe7 100644 --- a/adminapi/queries/model_handler.go +++ b/adminapi/queries/model_handler.go @@ -57,7 +57,7 @@ func PostModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -99,7 +99,7 @@ func PutModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, response) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -125,7 +125,7 @@ func PutModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { } func ObsoleteGetModelPageHandler(w http.ResponseWriter, r *http.Request) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entries := shared.GetAllModelList(tenantId) sort.Slice(entries, func(i, j int) bool { return strings.Compare(strings.ToLower(entries[i].ID), strings.ToLower(entries[j].ID)) < 0 @@ -179,7 +179,7 @@ func PostModelFilteredHandler(w http.ResponseWriter, r *http.Request) { } // Get all entries and sort them - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entries := shared.GetAllModelList(tenantId) sort.Slice(entries, func(i, j int) bool { return strings.Compare(strings.ToLower(entries[i].ID), strings.ToLower(entries[j].ID)) < 0 @@ -224,7 +224,7 @@ func GetModelByIdHandler(w http.ResponseWriter, r *http.Request) { return } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) model := shared.GetOneModel(tenantId, id) if model == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -261,7 +261,7 @@ func GetModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) models := shared.GetAllModelList(tenantId) sort.Slice(models, func(i, j int) bool { return strings.Compare(strings.ToLower(models[i].ID), strings.ToLower(models[j].ID)) < 0 diff --git a/adminapi/queries/namedspace_list_handler.go b/adminapi/queries/namedspace_list_handler.go index d1a2e02..9a558fc 100644 --- a/adminapi/queries/namedspace_list_handler.go +++ b/adminapi/queries/namedspace_list_handler.go @@ -45,7 +45,7 @@ func GetQueriesIpAddressGroups(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetIpAddressGroups(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -73,7 +73,7 @@ func GetQueriesIpAddressGroupsByIp(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetIpAddressGroupsByIp(tenantId, ipAddress) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -97,7 +97,7 @@ func GetQueriesIpAddressGroupsByName(w http.ResponseWriter, r *http.Request) { } result := []*shared.IpAddressGroup{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipAddrGrp := GetIpAddressGroupByName(tenantId, name) if ipAddrGrp == nil { values, ok := r.URL.Query()[xwcommon.VERSION] @@ -141,7 +141,7 @@ func CreateIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateIpAddressGroup(tenantId, &newIpAddressGroup) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -183,7 +183,7 @@ func AddDataIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -241,7 +241,7 @@ func RemoveDataIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -279,7 +279,7 @@ func DeleteIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -314,7 +314,7 @@ func GetQueriesIpAddressGroupsV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetNamespacedListsByType(tenantId, shared.IP_LIST) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -342,7 +342,7 @@ func GetQueriesIpAddressGroupsByIpV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetNamespacedListsByIp(tenantId, ipAddress) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -365,7 +365,7 @@ func GetQueriesIpAddressGroupsByNameV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipAddrGrp := GetNamespacedListByIdAndType(tenantId, id, shared.IP_LIST) if ipAddrGrp == nil { errorStr := fmt.Sprintf("IpAddressGroup with name %s does not exist", id) @@ -402,7 +402,7 @@ func CreateIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newIpList.ID); err != nil { @@ -454,7 +454,7 @@ func UpdateIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newIpList.ID); err != nil { @@ -498,7 +498,7 @@ func DeleteIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -529,7 +529,7 @@ func GetQueriesMacLists(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetNamespacedListsByType(tenantId, shared.MAC_LIST) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -552,7 +552,7 @@ func GetQueriesMacListsById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macList := GetNamespacedListByIdAndType(tenantId, id, shared.MAC_LIST) if macList == nil { values, ok := r.URL.Query()[xwcommon.VERSION] @@ -582,7 +582,7 @@ func GetQueriesMacListsByMacPart(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) mac := mux.Vars(r)[xwcommon.MAC] result := GetMacListsByMacPart(tenantId, mac) res, err := xhttp.ReturnJsonResponse(result, r) @@ -613,7 +613,7 @@ func SaveMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -665,7 +665,7 @@ func CreateMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -716,7 +716,7 @@ func UpdateMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -774,7 +774,7 @@ func AddDataMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -832,7 +832,7 @@ func RemoveDataMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -875,7 +875,7 @@ func DeleteMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -917,7 +917,7 @@ func GetQueriesMacListsByIdV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macList := GetNamespacedListByIdAndType(tenantId, id, shared.MAC_LIST) if macList == nil { errorStr := fmt.Sprintf("MacList with id %s does not exist", id) @@ -946,7 +946,7 @@ func DeleteMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -984,7 +984,7 @@ func GetNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) nsList, err := shared.GetGenericNamedListOneByTypeNonCached(tenantId, id, "") if err != nil { errorStr := fmt.Sprintf("List with id %s does not exist", id) @@ -1017,7 +1017,7 @@ func GetNamespacedListIdsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ids := GetNamespacedListIdsByType(tenantId, "") res, err := xhttp.ReturnJsonResponse(ids, r) @@ -1041,7 +1041,7 @@ func GetNamespacedListIdsByTypeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ids := GetNamespacedListIdsByType(tenantId, typeName) sortedById := func(i, j int) bool { return strings.ToLower(ids[i]) < strings.ToLower(ids[j]) @@ -1062,7 +1062,7 @@ func GetNamespacedListsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetNamespacedListsByType(tenantId, "") sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToLower(result[i].ID), strings.ToLower(result[j].ID)) < 0 @@ -1095,7 +1095,7 @@ func GetNamespacedListsByTypeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetNamespacedListsByType(tenantId, typeName) sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToLower(result[i].ID), strings.ToLower(result[j].ID)) < 0 @@ -1121,7 +1121,7 @@ func GetIpAddressGroupsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) nsLists := GetNamespacedListsByType(tenantId, shared.IP_LIST) result := covt.ConvertToListOfIpAddressGroups(nsLists) res, err := xhttp.ReturnJsonResponse(result, r) @@ -1153,7 +1153,7 @@ func CreateNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newNamespacedListList.ID); err != nil { @@ -1205,7 +1205,7 @@ func UpdateNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, namespacedListList.ID); err != nil { @@ -1264,7 +1264,7 @@ func RenameNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -1308,7 +1308,7 @@ func DeleteNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -1368,7 +1368,7 @@ func PostNamespacedListFilteredHandler(w http.ResponseWriter, r *http.Request) { } } util.AddQueryParamsToContextMap(r, contextMap) - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) nsLists := GetNamespacedListsByContext(contextMap) sort.Slice(nsLists, func(i, j int) bool { @@ -1407,7 +1407,7 @@ func PostNamespacedListEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) owner := auth.GetDistributedLockOwner(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, e := range entities { @@ -1472,7 +1472,7 @@ func PutNamespacedListEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) owner := auth.GetDistributedLockOwner(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, e := range entities { diff --git a/adminapi/queries/percentagebean_handler.go b/adminapi/queries/percentagebean_handler.go index cedd893..1b21a08 100644 --- a/adminapi/queries/percentagebean_handler.go +++ b/adminapi/queries/percentagebean_handler.go @@ -58,7 +58,7 @@ func GetPercentageBeanAllHandler(w http.ResponseWriter, r *http.Request) { var result interface{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err = GetAllPercentageBeansFromDB(tenantId, applicationType, true, false) if err != nil { @@ -102,7 +102,7 @@ func GetPercentageBeanByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) bean, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Entity with id: "+id+" does not exist") @@ -151,7 +151,7 @@ func GetAllPercentageBeanAsRule(w http.ResponseWriter, r *http.Request) { var result []*firmware.FirmwareRule - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err = GetAllGlobalPercentageBeansAsRuleFromDB(tenantId, applicationType, true) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -186,7 +186,7 @@ func GetPercentageBeanAsRuleById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fwRule, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "\"

404 NOT FOUND

\"") @@ -232,7 +232,7 @@ func PostPercentageBeanEntitiesHandler(w http.ResponseWriter, r *http.Request) { fields := xw.Audit() entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity respEntity := CreatePercentageBean(tenantId, &entity, applicationType, fields) @@ -277,7 +277,7 @@ func PutPercentageBeanEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity respEntity := UpdatePercentageBean(tenantId, &entity, applicationType, fields) @@ -323,7 +323,7 @@ func PostPercentageBeanFilteredWithParamsHandler(w http.ResponseWriter, r *http. } util.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) pbrules := PercentageBeanFilterByContext(contextMap, applicationType) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(pbrules)) @@ -368,7 +368,7 @@ func CreateWakeupPoolHandler(w http.ResponseWriter, r *http.Request) { log.WithFields(fields).Infof("Received request to create wakeup pool. force=%v", force) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err := CreateWakeupPoolList(tenantId, shared.STB, force, fields) if err != nil { xhttp.WriteXconfErrorResponse(w, err) diff --git a/adminapi/queries/percentfilter_handler.go b/adminapi/queries/percentfilter_handler.go index c43cdac..0d0193c 100644 --- a/adminapi/queries/percentfilter_handler.go +++ b/adminapi/queries/percentfilter_handler.go @@ -110,7 +110,7 @@ func UpdatePercentFilterGlobalHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdatePercentFilterGlobal(tenantId, applicationType, globalPercentage) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -148,7 +148,7 @@ func GetPercentFilterGlobalHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) globalpercent, err := GetPercentFilterGlobal(tenantId, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("unable to get globalpercent reponse. error: %v", err)) @@ -209,7 +209,7 @@ func GetGlobalPercentFilterHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) globalpercent, err := GetGlobalPercentFilter(tenantId, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("unable to get globalpercent reponse. error: %v", err)) @@ -295,7 +295,7 @@ func GetGlobalPercentFilterAsRuleHandler(w http.ResponseWriter, r *http.Request) contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) globalpercentasrule, err := GetGlobalPercentFilterAsRule(tenantId, applicationType) if err != nil { globalPercentage := coreef.NewGlobalPercentage() diff --git a/adminapi/queries/queries_handler.go b/adminapi/queries/queries_handler.go index be4fb0b..d66a565 100644 --- a/adminapi/queries/queries_handler.go +++ b/adminapi/queries/queries_handler.go @@ -61,7 +61,7 @@ func GetQueriesPercentageBean(w http.ResponseWriter, r *http.Request) { var result interface{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fieldName, found := contextMap[xcommon.FIELD] if found { result, err = GetPercentageBeanFilterFieldValues(tenantId, fieldName, applicationType) @@ -109,7 +109,7 @@ func GetQueriesPercentageBeanById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) bean, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Entity with id: "+id+" does not exist") @@ -154,7 +154,7 @@ func CreatePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { percentageBean.ApplicationType = applicationType } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreatePercentageBean(tenantId, percentageBean, applicationType, fields) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -191,7 +191,7 @@ func UpdatePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdatePercentageBean(tenantId, percentageBean, applicationType, fields) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -225,7 +225,7 @@ func DeletePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeletePercentageBean(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -240,7 +240,7 @@ func GetQueriesEnvironments(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := shared.GetAllEnvironmentList(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -272,7 +272,7 @@ func GetQueriesEnvironmentsById(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) env := GetEnvironment(tenantId, id) if env == nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Environment does not exist") @@ -322,7 +322,7 @@ func CreateEnvironmentHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateEnvironment(tenantId, &newEnv) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -351,7 +351,7 @@ func DeleteEnvironmentHandler(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteEnvironment(tenantId, id) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -366,7 +366,7 @@ func GetQueriesModels(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetModels(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -390,7 +390,7 @@ func GetQueriesModelsById(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) model := GetModel(tenantId, id) if model == nil { values, ok := r.URL.Query()[xcommon.VERSION] @@ -433,7 +433,7 @@ func CreateModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateModel(tenantId, &newModel) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -468,7 +468,7 @@ func UpdateModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateModel(tenantId, &newModel) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -497,7 +497,7 @@ func DeleteModelHandler(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteModel(tenantId, id) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -507,7 +507,7 @@ func DeleteModelHandler(w http.ResponseWriter, r *http.Request) { } func getQueriesFirmwareConfigsASFlavor(w http.ResponseWriter, r *http.Request, app string) { - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result := GetFirmwareConfigsAS(tenantId, app) sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToUpper(result[i].Description), strings.ToUpper(result[j].Description)) < 0 @@ -535,7 +535,7 @@ func GetQueriesFirmwareConfigsById(w http.ResponseWriter, r *http.Request) { } errorStr := fmt.Sprintf("\"FirmwareConfig with id %s does not exist\"", id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fc := GetFirmwareConfigByIdAS(tenantId, id) if fc == nil { values, ok := r.URL.Query()[xcommon.VERSION] @@ -579,7 +579,7 @@ func GetQueriesFirmwareConfigsByIdASFlavor(w http.ResponseWriter, r *http.Reques return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) firmwareConfig := GetFirmwareConfigByIdAS(tenantId, id) if firmwareConfig != nil { res, err := xhttp.ReturnJsonResponse(firmwareConfig, r) @@ -621,7 +621,7 @@ func GetQueriesFirmwareConfigsByModelId(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) model := shared.GetOneModel(tenantId, modelId) if model == nil { errorStr := fmt.Sprintf("%v not found", modelId) @@ -652,7 +652,7 @@ func GetQueriesFirmwareConfigsByModelIdASFlavor(w http.ResponseWriter, r *http.R return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) model := shared.GetOneModel(tenantId, modelId) if model == nil { errorStr := fmt.Sprintf("%v not found", modelId) @@ -695,7 +695,7 @@ func CreateFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateFirmwareConfig(tenantId, firmwareConfig, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -736,7 +736,7 @@ func UpdateFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateFirmwareConfig(tenantId, firmwareConfig, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -762,7 +762,7 @@ func DeleteFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteFirmwareConfig(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -784,7 +784,7 @@ func DeleteFirmwareConfigHandlerASFlavor(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteFirmwareConfig(tenantId, id, appType) status := respEntity.Status err = respEntity.Error @@ -804,7 +804,7 @@ func GetQueriesRulesIps(w http.ResponseWriter, r *http.Request) { } ipRuleService := daef.IpRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) ipRuleBeansResponse := []*IpRuleBeanResponse{} for _, ipRuleBean := range ipRuleBeans { @@ -834,7 +834,7 @@ func GetQueriesRulesMacs(w http.ResponseWriter, r *http.Request) { } macRuleService := daef.MacRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macRuleBeans := macRuleService.GetRulesWithMacCondition(tenantId, applicationType) macRuleBeansResponse := []*MacRuleBeanResponse{} for _, macRuleBean := range macRuleBeans { @@ -861,7 +861,7 @@ func GetQueriesRulesEnvModels(w http.ResponseWriter, r *http.Request) { } emRuleService := daef.EnvModelRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) envModelRulesResponse := []*EnvModelRuleBeanResponse{} for _, emRuleBean := range emRuleBeans { @@ -886,7 +886,7 @@ func GetQueriesFiltersDownloadLocation(w http.ResponseWriter, r *http.Request) { id := xcoreef.GetRoundRobinIdByApplication(applicationType) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) singletonFilterValue, err := coreef.GetDownloadLocationRoundRobinFilterValOneDB(tenantId, id) if err != nil { log.Errorf("unable to get singleton filter value. error: %+v", err) @@ -911,7 +911,7 @@ func UpdateDownloadLocationFilterHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateDownloadLocationRoundRobinFilter(tenantId, applicationType, locationRoundRobinFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -933,7 +933,7 @@ func GetQueriesFiltersIps(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.IpFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -960,7 +960,7 @@ func GetQueriesFiltersIpsByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.IpFilterByName(tenantId, name, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1000,7 +1000,7 @@ func UpdateIpsFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateIpFilter(tenantId, applicationType, ipFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1028,7 +1028,7 @@ func DeleteIpsFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteIpsFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1044,7 +1044,7 @@ func GetQueriesFiltersTime(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.TimeFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1071,7 +1071,7 @@ func GetQueriesFiltersTimeByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.TimeFilterByName(tenantId, name, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1106,7 +1106,7 @@ func UpdateTimeFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateTimeFilter(tenantId, applicationType, timeFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1134,7 +1134,7 @@ func DeleteTimeFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteTimeFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1150,7 +1150,7 @@ func GetQueriesFiltersLocation(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.DownloadLocationFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1177,7 +1177,7 @@ func GetQueriesFiltersLocationByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.DownloadLocationFiltersByName(tenantId, applicationType, name) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1225,7 +1225,7 @@ func UpdateLocationFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateLocationFilter(tenantId, applicationType, &locationFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1253,7 +1253,7 @@ func DeleteLocationFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteLocationFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1273,7 +1273,7 @@ func GetQueriesFiltersPercent(w http.ResponseWriter, r *http.Request) { xutil.AddQueryParamsToContextMap(r, contextMap) var result interface{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) fieldName, found := contextMap[xcommon.FIELD] if found { result, err = GetPercentFilterFieldValues(tenantId, fieldName, applicationType) @@ -1323,7 +1323,7 @@ func UpdatePercentFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdatePercentFilter(tenantId, applicationType, percentFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1345,7 +1345,7 @@ func GetQueriesFiltersRebootImmediately(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := coreef.RebootImmediatelyFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get reboot immediately filter value. error: %+v", err) @@ -1372,7 +1372,7 @@ func GetQueriesFiltersRebootImmediatelyByName(w http.ResponseWriter, r *http.Req return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) result, err := xcoreef.RebootImmediatelyFiltersByName(tenantId, applicationType, name) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1407,7 +1407,7 @@ func UpdateRebootImmediatelyHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateRebootImmediatelyFilter(tenantId, applicationType, rebootFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1435,7 +1435,7 @@ func DeleteRebootImmediatelyHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteRebootImmediatelyFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1453,7 +1453,7 @@ func GetRoundRobinFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) id := xcoreef.GetRoundRobinIdByApplication(applicationType) singletonFilterValue, err := coreef.GetDownloadLocationRoundRobinFilterValOneDB(tenantId, id) if err != nil { @@ -1506,7 +1506,7 @@ func GetIpRuleById(w http.ResponseWriter, r *http.Request) { var ipRuleBean *coreef.IpRuleBean ipRuleService := daef.IpRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.Name == ruleName { @@ -1552,7 +1552,7 @@ func GetIpRuleByIpAddressGroup(w http.ResponseWriter, r *http.Request) { ipRules := []*IpRuleBeanResponse{} ipRuleService := daef.IpRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.IpAddressGroup != nil && ipAddressGroupName == bean.IpAddressGroup.Name { @@ -1591,7 +1591,7 @@ func UpdateIpRule(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipRuleBean_origin := ipRuleBean if ipRuleBean.Name == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is empty") @@ -1711,7 +1711,7 @@ func GetMACRuleByName(w http.ResponseWriter, r *http.Request) { var macRuleBean *coreef.MacRuleBean macRuleService := daef.MacRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macRuleBeans := macRuleService.GetRulesWithMacCondition(tenantId, applicationType) for _, mrBean := range macRuleBeans { if mrBean.Name == ruleName { @@ -1759,7 +1759,7 @@ func GetMACRulesByMAC(w http.ResponseWriter, r *http.Request) { result := []*coreef.MacRuleBeanResponse{} if util.IsValidMacAddress(macAddress) { macRuleService := daef.MacRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macRuleBeans := macRuleService.SearchMacRules(tenantId, macAddress, applicationType) for _, macRule := range macRuleBeans { macRule = wrap(tenantId, macRule, apiVersion) @@ -1826,7 +1826,7 @@ func SaveMACRule(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "MAC address list is empty or blank") return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if err := corefw.ValidateRuleName(tenantId, macRule.Id, macRule.Name, applicationType); err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -1954,7 +1954,7 @@ func DeleteMACRule(w http.ResponseWriter, r *http.Request) { var macRuleBean *coreef.MacRuleBean macRuleService := daef.MacRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) macRuleBeans := macRuleService.GetByApplicationType(tenantId, applicationType) for _, mrBean := range macRuleBeans { if mrBean.Name == name { @@ -1991,7 +1991,7 @@ func GetEnvModelRuleByNameHandler(w http.ResponseWriter, r *http.Request) { var envModelRule *coreef.EnvModelBean emRuleService := daef.EnvModelRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) for _, emRuleBean := range emRuleBeans { if strings.EqualFold(emRuleBean.Name, name) { @@ -2043,7 +2043,7 @@ func UpdateEnvModelRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if envModelRuleBean.Name == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is empty") return @@ -2133,7 +2133,7 @@ func DeleteEnvModelRuleBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) emRuleService := daef.EnvModelRuleService{} emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) for _, emRuleBean := range emRuleBeans { @@ -2169,7 +2169,7 @@ func DeleteIpRule(w http.ResponseWriter, r *http.Request) { var ipRuleBean *coreef.IpRuleBean ipRuleService := daef.IpRuleService{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.Name == name { diff --git a/adminapi/rfc/feature/feature_handler.go b/adminapi/rfc/feature/feature_handler.go index dfcba50..9eda2d2 100644 --- a/adminapi/rfc/feature/feature_handler.go +++ b/adminapi/rfc/feature/feature_handler.go @@ -52,7 +52,7 @@ func GetFeaturesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) _, isExport := r.URL.Query()["export"] if isExport { featureEntityList := GetFeatureEntityListByApplicationTypeSorted(tenantId, applicationType) @@ -80,7 +80,7 @@ func GetFeatureByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) _, isExport := r.URL.Query()["export"] if isExport { featureEntity := GetFeatureEntityById(tenantId, id) @@ -125,7 +125,7 @@ func DeleteFeatureByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) if !xrfc.DoesFeatureExistWithApplicationType(tenantId, id, applicationType) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id)) return @@ -159,7 +159,7 @@ func PutFeatureEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := ImportFeatureEntities(tenantId, featureEntityList, true, applicationType) response, _ := util.XConfJSONMarshal(entitiesMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) @@ -185,7 +185,7 @@ func PostFeatureEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := ImportFeatureEntities(tenantId, featureEntityList, false, applicationType) response, _ := util.XConfJSONMarshal(entitiesMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) @@ -210,7 +210,7 @@ func PostFeatureHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) feature := featureEntity.CreateFeature() if xrfc.DoesFeatureExist(tenantId, feature.ID) { @@ -260,7 +260,7 @@ func PutFeatureHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) feature := featureEntity.CreateFeature() if feature.ID == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Entity id is empty") @@ -326,7 +326,7 @@ func GetFeaturesFilteredHandler(w http.ResponseWriter, r *http.Request) { } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) features := GetFeatureFiltered(contextMap) sort.SliceStable(features, func(i, j int) bool { @@ -357,7 +357,7 @@ func GetFeaturesByIdListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) features := GetFeaturesByIdList(tenantId, featureIdList) response, _ := util.JSONMarshal(features) xwhttp.WriteXconfResponse(w, http.StatusOK, response) diff --git a/adminapi/setting/setting_profile_controller.go b/adminapi/setting/setting_profile_controller.go index 0d6a819..2f74696 100644 --- a/adminapi/setting/setting_profile_controller.go +++ b/adminapi/setting/setting_profile_controller.go @@ -54,7 +54,8 @@ func GetSettingProfilesAllExport(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - all := GetAll() + tenantId := xhttp.GetTenantId(r.Context(), r) + all := GetAllForTenant(tenantId) settingProfiles := []*logupload.SettingProfiles{} for _, entity := range all { if entity.ApplicationType == applicationType { @@ -86,7 +87,7 @@ func GetSettingProfileOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) settingProfile, _ := GetOne(tenantId, id) if settingProfile == nil { invalid := "Entity with id: " + id + " does not exist" @@ -135,7 +136,8 @@ func GetAllSettingProfilesWithPage(w http.ResponseWriter, r *http.Request) { return } } - settingProfiles := GetAll() + tenantId := xhttp.GetTenantId(r.Context(), r) + settingProfiles := GetAllForTenant(tenantId) featureRuleList := SettingProfilesGeneratePage(settingProfiles, pageNumber, pageSize) response, err := util.JSONMarshal(featureRuleList) if err != nil { @@ -168,7 +170,7 @@ func DeleteOneSettingProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) _, err = Delete(tenantId, id, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -218,7 +220,7 @@ func GetSettingProfilesFilteredWithPage(w http.ResponseWriter, r *http.Request) } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) settingProfiles := FindByContext(contextMap) sort.Slice(settingProfiles, func(i, j int) bool { @@ -256,7 +258,7 @@ func CreateSettingProfileHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = Create(tenantId, &settingProfiles, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -291,7 +293,7 @@ func CreateSettingProfilesPackageHandler(w http.ResponseWriter, r *http.Request) } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -338,7 +340,7 @@ func UpdateSettingProfilesHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = Update(tenantId, &settingProfiles, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -370,7 +372,7 @@ func UpdateSettingProfilesPackageHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity diff --git a/adminapi/setting/setting_profile_service.go b/adminapi/setting/setting_profile_service.go index 58de314..2ed227d 100644 --- a/adminapi/setting/setting_profile_service.go +++ b/adminapi/setting/setting_profile_service.go @@ -36,8 +36,8 @@ import ( log "github.com/sirupsen/logrus" ) -func GetAll() []*xwlogupload.SettingProfiles { - SettingProfiles := GetSettingProfileList(db.GetDefaultTenantId()) +func GetAllForTenant(tenantId string) []*xwlogupload.SettingProfiles { + SettingProfiles := GetSettingProfileList(tenantId) sort.Slice(SettingProfiles, func(i, j int) bool { return strings.ToLower(SettingProfiles[i].SettingProfileID) < strings.ToLower(SettingProfiles[j].SettingProfileID) }) diff --git a/adminapi/setting/setting_rule_controller.go b/adminapi/setting/setting_rule_controller.go index eb41c6e..4820e3a 100644 --- a/adminapi/setting/setting_rule_controller.go +++ b/adminapi/setting/setting_rule_controller.go @@ -50,7 +50,7 @@ func GetSettingRulesAllExport(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) all := GetAllSettingRules(tenantId) settingRules := []*logupload.SettingRule{} for _, entity := range all { @@ -82,7 +82,7 @@ func GetSettingRuleOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) settingRule, _ := GetOneSettingRule(tenantId, id) if settingRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -121,7 +121,7 @@ func DeleteOneSettingRulesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) _, err = DeleteSettingRule(tenantId, id, applicationType) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) @@ -170,7 +170,7 @@ func GetSettingRulesFilteredWithPage(w http.ResponseWriter, r *http.Request) { } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) settingRules := FindByContextSettingRule(contextMap) sort.Slice(settingRules, func(i, j int) bool { @@ -207,7 +207,7 @@ func CreateSettingRuleHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = CreateSettingRule(tenantId, applicationType, &settingRules) if err != nil { xhttp.AdminError(w, err) @@ -239,7 +239,7 @@ func CreateSettingRulesPackageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -285,7 +285,7 @@ func UpdateSettingRulesHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = UpdateSettingRule(tenantId, applicationType, &settingRules) if err != nil { xhttp.AdminError(w, err) @@ -316,7 +316,7 @@ func UpdateSettingRulesPackageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -384,7 +384,7 @@ func SettingTestPageHandler(w http.ResponseWriter, r *http.Request) { return } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) result := make(map[string]interface{}) result["result"] = GetSettingRulesWithConfig(settingTypes, contextMap) diff --git a/adminapi/telemetry/telemetry_profile_controller.go b/adminapi/telemetry/telemetry_profile_controller.go index 7284c1a..1501b3c 100644 --- a/adminapi/telemetry/telemetry_profile_controller.go +++ b/adminapi/telemetry/telemetry_profile_controller.go @@ -94,7 +94,7 @@ func CreateTelemetryEntryFor(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) timestampedRule := CreateTelemetryProfile(tenantId, contextAttributeName, expectedValue, &telemetryProfile) response, err := util.JSONMarshal(timestampedRule) if err != nil { @@ -120,7 +120,7 @@ func DropTelemetryEntryFor(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) telemetryProfileList := DropTelemetryFor(tenantId, contextAttributeName, expectedValue) response, err := util.JSONMarshal(telemetryProfileList) if err != nil { @@ -144,7 +144,7 @@ func GetDescriptors(w http.ResponseWriter, r *http.Request) { } applicationType, _ := contextMap[xwcommon.APPLICATION_TYPE] - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) descriptors := GetAvailableDescriptors(tenantId, applicationType) response, err := util.JSONMarshal(descriptors) if err != nil { @@ -168,7 +168,7 @@ func GetTelemetryDescriptors(w http.ResponseWriter, r *http.Request) { } applicationType, _ := contextMap[xwcommon.APPLICATION_TYPE] - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) descriptors := GetAvailableProfileDescriptors(tenantId, applicationType) response, err := util.JSONMarshal(descriptors) if err != nil { @@ -213,7 +213,7 @@ func TempAddToPermanentRule(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) telemetryRule := xlogupload.GetOneTelemetryRule(tenantId, ruleId) //*TelemetryRule if telemetryRule == nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("no rule found for ruleId")) @@ -281,7 +281,7 @@ func BindToTelemetry(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) profile := xlogupload.GetOnePermanentTelemetryProfile(tenantId, telemetryId) //*PermanentTelemetryProfile if profile == nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("no rule found for ID "+telemetryId+" provided")) @@ -330,7 +330,7 @@ func TelemetryTestPageHandler(w http.ResponseWriter, r *http.Request) { } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) result := make(map[string]interface{}) result["context"] = contextMap diff --git a/adminapi/telemetry/telemetry_rule_handler.go b/adminapi/telemetry/telemetry_rule_handler.go index 69a7108..79b7f91 100644 --- a/adminapi/telemetry/telemetry_rule_handler.go +++ b/adminapi/telemetry/telemetry_rule_handler.go @@ -46,7 +46,7 @@ func GetTelemetryRulesHandler(w http.ResponseWriter, r *http.Request) { } result := []*xwlogupload.TelemetryRule{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) ruleList := xwlogupload.GetTelemetryRuleListForAs(tenantId) for _, teleRule := range ruleList { if teleRule.ApplicationType != applicationType { @@ -83,7 +83,7 @@ func GetTelemetryRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) teleRule := xlogupload.GetOneTelemetryRule(tenantId, id) if teleRule == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -131,7 +131,7 @@ func DeleteTelmetryRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := DeleteTelemetryRulebyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -161,7 +161,7 @@ func CreateTelemetryRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := CreateTelemetryRule(tenantId, &newtmrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -198,7 +198,7 @@ func UpdateTelemetryRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) respEntity := UpdateTelemetryRule(tenantId, &newtmrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -234,7 +234,7 @@ func PostTelemtryRuleEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity respEntity := CreateTelemetryRule(tenantId, &entity, applicationType) @@ -278,7 +278,7 @@ func PutTelemetryRuleEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity respEntity := UpdateTelemetryRule(tenantId, &entity, applicationType) @@ -325,7 +325,7 @@ func PostTelemetryRuleFilteredWithParamsHandler(w http.ResponseWriter, r *http.R } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) tmrules := TelemetryRuleFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(tmrules)) diff --git a/adminapi/telemetry/telemetry_v2_rule_handler.go b/adminapi/telemetry/telemetry_v2_rule_handler.go index 392db75..8ba7310 100644 --- a/adminapi/telemetry/telemetry_v2_rule_handler.go +++ b/adminapi/telemetry/telemetry_v2_rule_handler.go @@ -53,7 +53,7 @@ func GetTelemetryTwoRulesAllExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) all := GetAll(tenantId) telemetryTwoRules := []*xwlogupload.TelemetryTwoRule{} for _, entity := range all { @@ -88,7 +88,7 @@ func GetTelemetryTwoRuleById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) telemetryTwoRule := logupload.GetOneTelemetryTwoRule(tenantId, id) if telemetryTwoRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -138,7 +138,7 @@ func DeleteOneTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) _, err = Delete(tenantId, id) if err != nil { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) @@ -189,7 +189,7 @@ func GetTelemetryTwoRulesFilteredWithPage(w http.ResponseWriter, r *http.Request } } contextMap[core.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xwhttp.GetTenantId(r, "") + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) telemetryTwoRules := findByContext(contextMap) sort.SliceStable(telemetryTwoRules, func(i, j int) bool { @@ -225,7 +225,7 @@ func CreateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = Create(tenantId, &telemetry2Rule, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -258,7 +258,7 @@ func CreateTelemetryTwoRulesPackageHandler(w http.ResponseWriter, r *http.Reques } entitiesMap := map[string]common.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity err := Create(tenantId, &entity, applicationType) @@ -301,7 +301,7 @@ func UpdateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) err = Update(tenantId, &telemetryTwoRule, writeApplication) if err != nil { xhttp.AdminError(w, err) @@ -334,7 +334,7 @@ func UpdateTelemetryTwoRulesPackageHandler(w http.ResponseWriter, r *http.Reques } entitiesMap := map[string]common.EntityMessage{} - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) for _, entity := range entities { entity := entity err := Update(tenantId, &entity, writeApplication) diff --git a/adminapi/xcrp/recooking_lockdown_settings_handler.go b/adminapi/xcrp/recooking_lockdown_settings_handler.go index a22df66..ff632ef 100644 --- a/adminapi/xcrp/recooking_lockdown_settings_handler.go +++ b/adminapi/xcrp/recooking_lockdown_settings_handler.go @@ -24,7 +24,7 @@ func GetXcrpConnector() *xhttp.XcrpConnector { } func PostRecookingLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { - if !auth.HasWritePermissionForTool(r) { + if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No write permission: tools") return } @@ -53,7 +53,7 @@ func PostRecookingLockdownSettingsHandler(w http.ResponseWriter, r *http.Request dao.GetCacheManager().ForceSyncChanges() - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) var lockdownSettingFromDB *common.LockdownSettings lockdownSettingFromDB, err = lockdown.GetLockdownSettings(tenantId) if err != nil { diff --git a/config/sample_xconfadmin.conf b/config/sample_xconfadmin.conf index cdc0128..18d39b5 100644 --- a/config/sample_xconfadmin.conf +++ b/config/sample_xconfadmin.conf @@ -387,8 +387,9 @@ xconfwebconfig { hosts = [ // Cassandra cluster hosts "127.0.0.1" // Primary Cassandra host (add more for cluster) ] - keyspace = "ApplicationsDiscoveryDataService" // Primary keyspace name - test_keyspace = "test_appds" // Test keyspace for unit/integration tests + keyspace = "xconf" + test_keyspace = "test_appds" + adds_keyspace = "ApplicationsDiscoveryDataService" xpc_keyspace = "xpc" xpc_test_keyspace = "xpc_test_keyspace" xpc_precook_table_name = "reference_document" // table name of preprocessed data diff --git a/http/auth.go b/http/auth.go index e8e386e..0ba1f48 100644 --- a/http/auth.go +++ b/http/auth.go @@ -16,6 +16,7 @@ package http import ( + "context" "crypto/rsa" "encoding/base64" "errors" @@ -26,6 +27,7 @@ import ( "strings" "github.com/rdkcentral/xconfadmin/common" + "github.com/rdkcentral/xconfwebconfig/db" "github.com/golang-jwt/jwt/v4" log "github.com/sirupsen/logrus" @@ -46,10 +48,20 @@ func (c AuthCtxKey) String() string { return string(c) } +type AuthType string + const ( - CTX_KEY_TOKEN AuthCtxKey = "Token" - CTX_KEY_PERMISSIONS AuthCtxKey = "Permissions" - CTX_KEY_CAPABILITIES AuthCtxKey = "Capabilities" + AUTH_TYPE_SAT_V2 AuthType = "SAT_V2" + AUTH_TYPE_SAT_LEGACY AuthType = "SAT_LEGACY" + AUTH_TYPE_LOGIN_TOKEN AuthType = "LOGIN_TOKEN" +) + +const ( + CTX_KEY_TOKEN AuthCtxKey = "Token" + CTX_KEY_PERMISSIONS AuthCtxKey = "Permissions" + CTX_KEY_CAPABILITIES AuthCtxKey = "Capabilities" + CTX_KEY_ALLOWED_PARTNERS AuthCtxKey = "AllowedPartners" + CTX_KEY_AUTH_TYPE AuthCtxKey = "AuthType" ) type LoginToken struct { @@ -156,6 +168,31 @@ func GetCapabilitiesFromContext(r *http.Request) []string { return capabilities.([]string) } +func GetAllowedPartnersFromContext(r *http.Request) []string { + allowedPartners := r.Context().Value(CTX_KEY_ALLOWED_PARTNERS) + if allowedPartners == nil { + log.Debug("allowed partners not found in context") + return []string{} + } + return allowedPartners.([]string) +} + +func GetTenantId(ctx context.Context, r *http.Request) string { + if ctx != nil { + authType := ctx.Value(CTX_KEY_AUTH_TYPE) + if authType != nil { + if authType == AUTH_TYPE_SAT_V2 { + return strings.ToUpper(GetTenantIdFromHeader(r)) + } + } + } + return strings.ToUpper(db.GetDefaultTenantId()) +} + +func GetTenantIdFromHeader(r *http.Request) string { + return strings.TrimSpace(r.Header.Get("tenantId")) +} + func ValidateAndGetLoginToken(authToken string) (*LoginToken, error) { if authToken == "" { return nil, errors.New("auth token is empty") @@ -279,11 +316,21 @@ func NewLoginToken(claims jwt.MapClaims) *LoginToken { return LoginToken } -// Get SAT V2 token +// Get SAT token func getSatTokenFromRequest(r *http.Request) string { return r.Header.Get(AUTHORIZATION) } +// SAT v2 for capabilities starting with "xconf:" rather than "x1:coast" +func isSATv2(capabilities []string) bool { + for _, c := range capabilities { + if strings.HasPrefix(c, "xconf:") { + return true + } + } + return false +} + func getLoginTokenFromRequest(r *http.Request) string { authToken := r.Header.Get(AUTH_TOKEN) if authToken == "" { @@ -312,7 +359,7 @@ func getWebValidator() *WebValidator { } } -func getSubjectAndCapabilitiesFromSatToken(token string, verifyStageHost bool) (string, []string, error) { +func getSubjectAndCapabilitiesFromSatToken(token string, verifyStageHost bool) (string, []string, []string, error) { var webValidator *WebValidator var claims *Claims @@ -327,7 +374,7 @@ func getSubjectAndCapabilitiesFromSatToken(token string, verifyStageHost bool) ( token = fragments[1] } if strings.TrimSpace(token) == "" { - return "", nil, errors.New("unable to extract required sat token") + return "", nil, nil, errors.New("unable to extract required sat token") } // 2 Validate Sat Token @@ -336,7 +383,7 @@ func getSubjectAndCapabilitiesFromSatToken(token string, verifyStageHost bool) ( claims, err = webValidator.Validate(token) if err != nil { log.Error("Validation failed with staging host") - return "", nil, errors.New("unable to validate sat token with staging host") + return "", nil, nil, errors.New("unable to validate sat token with staging host") } } else { // Validate with sat service host if flag is disabled. @@ -349,15 +396,15 @@ func getSubjectAndCapabilitiesFromSatToken(token string, verifyStageHost bool) ( claims, err = webValidator.Validate(token) if err != nil { log.Error("Validation failed with prod host") - return "", nil, errors.New("unable to validate sat token with prod host") + return "", nil, nil, errors.New("unable to validate sat token with prod host") } } // get capabilities capabilities := claims.Capabilities if len(capabilities) == 0 { - return "", nil, errors.New("unable to extract capabilities from sat token") + return "", nil, nil, errors.New("unable to extract capabilities from sat token") } - return claims.Subject, capabilities, nil + return claims.Subject, capabilities, claims.AllowedResources.AllowedPartners, nil } func getJsonWebKey(header map[string]interface{}) *JsonWebKey { diff --git a/http/webconfig_server.go b/http/webconfig_server.go index 7af9005..c61a3bb 100644 --- a/http/webconfig_server.go +++ b/http/webconfig_server.go @@ -277,9 +277,9 @@ func (s *WebconfigServer) AuthValidationMiddleware(next http.Handler) http.Handl ctx := r.Context() - // Check for SAT V2 token + // Check for SAT token if satToken := getSatTokenFromRequest(r); satToken != "" { - if subject, capabilities, err := getSubjectAndCapabilitiesFromSatToken(satToken, s.VerifyStageHost); err != nil { + if subject, capabilities, allowedPartners, err := getSubjectAndCapabilitiesFromSatToken(satToken, s.VerifyStageHost); err != nil { log.Error(err.Error()) http.Error(w, "invalid SAT token", http.StatusUnauthorized) return @@ -288,12 +288,19 @@ func (s *WebconfigServer) AuthValidationMiddleware(next http.Handler) http.Handl // Add capabilities to request context ctx = context.WithValue(ctx, CTX_KEY_CAPABILITIES, capabilities) + ctx = context.WithValue(ctx, CTX_KEY_ALLOWED_PARTNERS, allowedPartners) + + // check if SAT is legacy SAT or SAT v2 based on capabilities and set auth type in context + if isSATv2(capabilities) { + ctx = context.WithValue(ctx, CTX_KEY_AUTH_TYPE, AUTH_TYPE_SAT_V2) + } else { + ctx = context.WithValue(ctx, CTX_KEY_AUTH_TYPE, AUTH_TYPE_SAT_LEGACY) + } } } else if authToken := getLoginTokenFromRequest(r); authToken != "" { if LoginToken, err := ValidateAndGetLoginToken(authToken); err != nil { log.Error(err.Error()) http.Error(w, "invalid auth token", http.StatusUnauthorized) - ctx = context.WithValue(ctx, CTX_KEY_TOKEN, LoginToken) return } else { // THIS IS LOGIN TOKEN SUCCESS CASE @@ -303,6 +310,7 @@ func (s *WebconfigServer) AuthValidationMiddleware(next http.Handler) http.Handl ctx = context.WithValue(ctx, CTX_KEY_TOKEN, LoginToken) permissions := getPermissionsFromLoginToken(LoginToken) ctx = context.WithValue(ctx, CTX_KEY_PERMISSIONS, permissions) + ctx = context.WithValue(ctx, CTX_KEY_AUTH_TYPE, AUTH_TYPE_LOGIN_TOKEN) } } else if r.Header.Get(RequestID) != "adminui" && !xcommon.SatOn { //allowing api request without sat_token if sat is off @@ -405,6 +413,11 @@ func (s *WebconfigServer) logRequestStarts(w http.ResponseWriter, r *http.Reques "xpc_trace": xpcTrace, } + // add field to distinguish between SAT v2, legacy SAT and login token in logs for better analysis of auth types in use + if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(string); ok { + fields["authType"] = authType + } + xwriter := xhttp.NewXResponseWriter(w, time.Now(), token, fields) if r.Method == "POST" || r.Method == "PUT" { @@ -448,6 +461,11 @@ func (s *WebconfigServer) logRequestEnds(xw *xhttp.XResponseWriter, r *http.Requ statusCode := xw.Status() fields := xw.Audit() + // add field to distinguish between SAT v2, legacy SAT and login token in logs for better analysis of auth types in use + if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(string); ok { + fields["authType"] = authType + } + fields["status"] = statusCode fields["duration"] = duration fields["response_header"] = getHeadersForLogAsMap(xw.Header(), s.notLoggedHeaders) diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/.openspec.yaml b/openspec/changes/sat-rbac-v2-tenant-enforcement/.openspec.yaml new file mode 100644 index 0000000..0d48b92 --- /dev/null +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/.openspec.yaml @@ -0,0 +1,5 @@ +schema: spec-driven +created: 2026-06-22 +status: proposed +applies_to: + - openspec/specs/auth/auth-contract.md diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md new file mode 100644 index 0000000..c8fcd61 --- /dev/null +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md @@ -0,0 +1,75 @@ +# SAT RBAC v2 Tenant Enforcement Design + +## Overview + +This document defines tenant-aware SAT authorization for xconfadmin as a follow-on phase to SAT RBAC v2 capability authorization. The goal is to enforce partner/tenant scope for SAT-authenticated requests in multi-tenant deployments. + +Capability authorization remains the first gate. Tenant enforcement is a second gate that runs only after SAT RBAC v2 capability checks succeed. + +## Design Principles + +1. Keep credential-path routing unchanged. +2. Keep SAT RBAC v2 capability names and capability matching unchanged. +3. Enforce tenant scope only for all SAT RBAC v2 requests. +4. Deny with `403 Forbidden` for all tenant-enforcement failures. +5. Preserve legacy SAT and login-token behavior. + +## Authorization Flow + +1. Choose auth path +- If `Authorization` header is present, select SAT path. +- Else, if login token (`token` header/cookie) is present, select login/Xerxes path. +- Else, return `401 Unauthorized`. + +2. Validate credentials +- SAT path: validate SAT token. +- Login/Xerxes path: validate login token as currently implemented. + +3. Detect SAT mode on SAT path +- If SAT includes at least one capability with prefix `xconf:`, classify request as SAT RBAC v2. +- Otherwise, use legacy SAT behavior unchanged and stop this design flow. + +4. Perform SAT RBAC v2 capability authorization +- Classify request to `(domain, access)`. +- Evaluate SAT capabilities. +- If capability authorization fails, return `403 Forbidden`. + +5. Enforce SAT tenant scope (new phase) +- For SAT RBAC v2 requests requiring tenant enforcement: + - Read request tenant from header `tenantId`. + - Read allowed partner list from SAT claim `allowedResources.allowedPartners`. + - Allow only when `allowedPartners` contains `tenantId`. + +6. Complete request +- If tenant scope check passes, continue to handler. +- If tenant scope check fails, return `403 Forbidden` and terminate. + +## Tenant Enforcement Decision Table + +| Condition | Result | +|---|---| +| `tenantId` header missing | `403 Forbidden` | +| `allowedResources.allowedPartners` missing | `403 Forbidden` | +| `allowedResources.allowedPartners` empty | `403 Forbidden` | +| `tenantId` not found in `allowedPartners` | `403 Forbidden` | +| `tenantId` found in `allowedPartners` | Allow | + +## Error Semantics + +- `401 Unauthorized` remains only for missing/invalid authentication. +- `403 Forbidden` is used for authenticated authorization failures, including: + - SAT capability denials + - SAT tenant-scope denials + +## Compatibility + +- SAT RBAC v2 capability checks remain unchanged and execute first. +- Legacy SAT behavior remains unchanged. +- Login token / IDP service behavior remains unchanged. +- Capability strings remain unchanged; tenant enforcement uses `tenantId` plus SAT claim values. + +## Implementation Notes + +- Tenant enforcement should be implemented in SAT RBAC v2 authorization flow after capability success and before handler execution. +- Tenant enforcement logic should be isolated and reusable to minimize risk to existing capability validation code paths. +- Failure responses for tenant checks should be explicit authorization failures (`403`) and should keep fail-fast behavior. diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/proposal.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/proposal.md new file mode 100644 index 0000000..7a8202b --- /dev/null +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/proposal.md @@ -0,0 +1,48 @@ +Status: Proposed +Applied to: openspec/specs/auth/auth-contract.md + +## Why + +xconfadmin now supports SAT RBAC v2 capability authorization, but capability checks alone are not sufficient for multi-tenant protection. A SAT token may have the correct domain/access capability while still being scoped only to specific partners. Without tenant-aware enforcement, a SAT-authenticated request can be authorized at capability level without proving access to the request tenant. + +This change introduces tenant-aware SAT authorization as a separate phase after the base SAT RBAC v2 rollout. It adds explicit enforcement using request header tenantId and SAT token claim allowedResources.allowedPartners. + +## What Changes + +- Define tenant source for SAT tenant enforcement: + - Request header `tenantId` +- Define SAT partner scope source: + - SAT claim `allowedResources.allowedPartners` +- Define SAT tenant authorization rule (applies after SAT RBAC v2 capability success): + - Read `tenantId` from request header. + - Read partner allowlist from `allowedResources.allowedPartners`. + - Allow only when `allowedPartners` contains `tenantId`. +- Define SAT tenant failure behavior: + - If `tenantId` is missing when tenant-scoped SAT authorization is required, return `403 Forbidden`. + - If `allowedResources.allowedPartners` is missing or empty for a SAT request that requires tenant enforcement, return `403 Forbidden`. + - If `allowedPartners` does not contain `tenantId`, return `403 Forbidden`. +- Clarify compatibility and sequencing: + - Existing SAT RBAC v2 capability checks remain unchanged and still run first. + - Tenant enforcement runs only after capability authorization succeeds. + - Legacy SAT behavior remains unchanged. + - Login token / IDP service behavior remains unchanged. + - Capability strings remain unchanged. + +## Non-Goals + +- No changes to SAT RBAC v2 capability names or capability detection. +- No changes to legacy SAT authorization behavior. +- No changes to Xerxes/login-token/IDP service behavior. +- No endpoint contract changes beyond documented `403` authorization outcomes for tenant-scope denials. + +## Capabilities + +### Modified Capabilities +- `auth`: Adds SAT RBAC v2 tenant-aware authorization enforcement using request header `tenantId` and SAT claim `allowedResources.allowedPartners` after capability authorization succeeds. + +## Impact + +- Affected specs: openspec/specs/auth/auth-contract.md. +- Affected implementation areas (future apply phase): SAT authorization middleware and SAT claim extraction/validation flow. +- API behavior impact: SAT RBAC v2 requests now return `403 Forbidden` when tenant scope checks fail. +- Compatibility impact: legacy SAT and login token flows are unchanged. diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md new file mode 100644 index 0000000..e2f3e9e --- /dev/null +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md @@ -0,0 +1,99 @@ +# SAT RBAC v2 Tenant Enforcement Specification + +## Spec Delta Summary + +This change updates openspec/specs/auth/auth-contract.md with the following normative clauses: + +- SAT RBAC v2 capability authorization remains unchanged and runs first. +- For all SAT RBAC v2 requests, enforce tenant authorization using: + - request header `tenantId` + - SAT claim `allowedResources.allowedPartners` +- Authorization SHALL allow only when `allowedPartners` contains `tenantId`. +- Authorization SHALL deny with `403 Forbidden` when: + - `tenantId` is missing + - `allowedResources.allowedPartners` is missing + - `allowedResources.allowedPartners` is empty + - `allowedPartners` does not contain `tenantId` +- Legacy SAT behavior and login token/IDP behavior remain unchanged. +- Capability strings remain unchanged. + +## Definitions + +### Request Tenant +The request tenant is the value of HTTP header `tenantId`. + +### Allowed Partners Claim +The SAT partner scope claim is `allowedResources.allowedPartners`, represented as a list of tenant/partner identifiers. + +Example: + +{ + "allowedResources": { + "allowedPartners": ["comcast"] + } +} + +### Tenant-Scoped SAT Authorization +Tenant-scoped SAT authorization is an authorization gate evaluated after SAT RBAC v2 capability authorization succeeds. + +## Normative Behavior + +### SAT Authorization Sequence + +For SAT RBAC v2 requests, authorization SHALL execute in this order: + +1. SAT authentication and SAT RBAC v2 capability authorization. +2. Tenant-scope authorization (this change). + +If step 1 fails, deny according to existing SAT RBAC v2 rules. +If step 1 succeeds but step 2 fails, deny with `403 Forbidden`. + +### Tenant-Scope Authorization Rule + +For all SAT RBAC v2 requests: + +1. Read `tenantId` from request header. +2. Read `allowedResources.allowedPartners` from SAT token. +3. Allow only when `allowedPartners` contains the `tenantId` value. + +For this phase, the `tenantId` request header value SHALL be compared directly against the values in `allowedResources.allowedPartners` using exact membership matching. No separate tenant-to-partner translation is performed. + +### Tenant-Scope Failure Outcomes + +For all SAT RBAC v2 requests, the system SHALL return `403 Forbidden` when any of the following is true: + +- `tenantId` header is missing. +- `allowedResources.allowedPartners` is missing. +- `allowedResources.allowedPartners` is present but empty. +- `allowedResources.allowedPartners` does not contain `tenantId`. + +## Compatibility + +- SAT RBAC v2 capability checks remain unchanged and run before tenant checks. +- Legacy SAT authorization behavior remains unchanged; token validation + does not enforce tenant or partner claims. Request processing still + supports multi-tenancy, and in this phase resolves `tenantId` to the + default tenant. +- Login token / IDP service behavior remains unchanged; token validation + does not enforce tenant or partner claims. Request processing still + supports multi-tenancy, and in this phase resolves `tenantId` to the + default tenant. +- Capability names remain unchanged; tenant enforcement does not add or modify capability strings. +- Multi-tenant authorization guarantees in this change apply only to + SAT RBAC v2 requests. + +## HTTP Status Semantics + +- `401 Unauthorized` is reserved for missing or invalid authentication. +- `403 Forbidden` is used for authenticated authorization denials, including tenant-scope enforcement failures. + +## Validation Scenarios + +| SAT RBAC v2 capability check | tenantId header | allowedPartners claim | Contains tenantId | Result | +|---|---|---|---|---| +| Fail | Any | Any | Any | Existing deny behavior | +| Pass | Missing | Present | N/A | `403 Forbidden` | +| Pass | Present | Missing | N/A | `403 Forbidden` | +| Pass | Present | Empty | N/A | `403 Forbidden` | +| Pass | Present | Present | No | `403 Forbidden` | +| Pass | Present | Present | Yes | Allow | diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md new file mode 100644 index 0000000..ea3d8fd --- /dev/null +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md @@ -0,0 +1,29 @@ +## 1. OpenSpec Artifacts +- [x] 1.1 Create proposal for SAT RBAC v2 tenant enforcement phase. +- [x] 1.2 Create design describing auth flow and tenant-scope gate ordering. +- [x] 1.3 Create spec delta for tenantId and allowedPartners enforcement. +- [x] 1.4 Define implementation and validation task plan. + +## 2. Contract Update +- [x] 2.1 Update openspec/specs/auth/auth-contract.md with SAT tenant-scope enforcement requirements. +- [x] 2.2 Add tenant source definition (`tenantId` header). +- [x] 2.3 Add SAT partner scope source definition (`allowedResources.allowedPartners`). +- [x] 2.4 Add mandatory `403 Forbidden` outcomes for missing/empty/mismatch tenant scope. +- [x] 2.5 Clarify ordering: capability checks first, tenant checks second. + +## 3. Implementation +- [ ] 3.1 Add SAT tenant-enforcement step in SAT RBAC v2 auth flow after capability success. +- [ ] 3.2 Read and validate request header `tenantId`. +- [ ] 3.3 Read and validate SAT claim `allowedResources.allowedPartners`. +- [ ] 3.4 Enforce membership check (`tenantId` in `allowedPartners`). +- [ ] 3.5 Return `403 Forbidden` for tenant authorization failures with fail-fast behavior. +- [ ] 3.6 Keep legacy SAT and login-token/IDP flows unchanged. + +## 4. Validation +- [ ] 4.1 Add tests for tenantId missing -> `403` (SAT tenant-enforced route). +- [ ] 4.2 Add tests for allowedPartners missing -> `403`. +- [ ] 4.3 Add tests for allowedPartners empty -> `403`. +- [ ] 4.4 Add tests for tenant mismatch -> `403`. +- [ ] 4.5 Add tests for tenant match -> allow. +- [ ] 4.6 Add tests confirming capability failure still evaluated first. +- [ ] 4.7 Add tests confirming legacy SAT and login-token paths are unchanged. diff --git a/openspec/specs/auth/auth-contract.md b/openspec/specs/auth/auth-contract.md index ea670e7..771f2f8 100644 --- a/openspec/specs/auth/auth-contract.md +++ b/openspec/specs/auth/auth-contract.md @@ -15,7 +15,7 @@ This specification describes: This specification does not describe: - business-specific policy enforcement -- tenant or partner enforcement policy +- downstream tenant or partner enforcement policy outside SAT RBAC v2 - downstream extensions or constraints ## Guarantees @@ -94,6 +94,57 @@ Normative behavior: - Endpoints that use `POST` for read behavior (such as filtered searches) MUST be explicitly treated as `readonly` via the route override. +### SAT RBAC v2 Tenant Scope Enforcement + +For SAT RBAC v2 authorization, tenant scope enforcement SHALL be applied +after SAT capability authorization succeeds. + +Tenant scope sources: + +- Request tenant: header `tenantId`. +- SAT partner scope: claim `allowedResources.allowedPartners`. + +Normative behavior for SAT RBAC v2 requests requiring tenant scope: + +- The system SHALL read tenant from request header `tenantId`. +- The system SHALL read allowed partner scope from + `allowedResources.allowedPartners`. +- The request SHALL be authorized only when `allowedPartners` contains + the request `tenantId` value. +- If `tenantId` is missing, authorization SHALL be denied with + `403 Forbidden`. +- If `allowedResources.allowedPartners` is missing or empty, + authorization SHALL be denied with `403 Forbidden`. +- If `allowedPartners` does not contain `tenantId`, authorization SHALL + be denied with `403 Forbidden`. + +SAT RBAC v2 tenant scope enforcement SHALL NOT modify SAT capability +strings and SHALL use request metadata plus SAT claims only. + +### Tenant Resolution By Auth Path + +Tenant resolution SHALL be path-specific in this phase: + +- SAT RBAC v2 path: + - The request tenant SHALL be read from header `tenantId`. + - Authorization SHALL enforce membership against SAT claim + `allowedResources.allowedPartners`. +- Legacy SAT path: + - Legacy SAT authorization semantics remain unchanged. + - Token validation SHALL NOT enforce tenant or partner claims. + - Request processing SHALL continue to support multi-tenancy. + - In this phase, request processing SHALL resolve `tenantId` + to the default tenant. +- Login-token/Xerxes path: + - Login-token/Xerxes authorization semantics remain unchanged. + - Token validation SHALL NOT enforce tenant or partner claims. + - Request processing SHALL continue to support multi-tenancy. + - In this phase, request processing SHALL resolve `tenantId` + to the default tenant. + +In this phase, multi-tenant authorization guarantees apply only to +SAT RBAC v2 requests. + ### SAT RBAC v2 Deny-By-Default If a SAT RBAC v2 request cannot be classified into `(domain, access)` @@ -113,7 +164,8 @@ The system SHALL use: - `401 Unauthorized` only for missing or invalid authentication. - `403 Forbidden` for authenticated-but-not-authorized requests, - including SAT RBAC v2 classification or capability denials. + including SAT RBAC v2 classification, capability, or tenant scope + denials. ### Fail-Fast Termination diff --git a/taggingapi/tag/tag_handler.go b/taggingapi/tag/tag_handler.go index 71a1ed8..013595d 100644 --- a/taggingapi/tag/tag_handler.go +++ b/taggingapi/tag/tag_handler.go @@ -6,10 +6,9 @@ import ( "net/http" "github.com/gorilla/mux" + "github.com/rdkcentral/xconfadmin/adminapi/auth" "github.com/rdkcentral/xconfadmin/common" xhttp "github.com/rdkcentral/xconfadmin/http" - - xwhttp "github.com/rdkcentral/xconfwebconfig/http" ) const ( @@ -24,13 +23,19 @@ const ( ) func GetTagsByMemberHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + member, found := mux.Vars(r)[common.Member] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Member))) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tags, err := GetTagsByMember(tenantId, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) @@ -46,13 +51,19 @@ func GetTagsByMemberHandler(w http.ResponseWriter, r *http.Request) { } func GetTagsWithValuesByMemberHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + member, found := mux.Vars(r)[common.Member] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Member))) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) tags, err := GetTagsWithValuesByMember(tenantId, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) diff --git a/taggingapi/tag/tag_member_handler.go b/taggingapi/tag/tag_member_handler.go index 0ab739c..dee2b95 100644 --- a/taggingapi/tag/tag_member_handler.go +++ b/taggingapi/tag/tag_member_handler.go @@ -7,6 +7,7 @@ import ( "net/http" "strconv" + "github.com/rdkcentral/xconfadmin/adminapi/auth" "github.com/rdkcentral/xconfadmin/common" xhttp "github.com/rdkcentral/xconfadmin/http" @@ -51,13 +52,19 @@ func parsePaginationParams(r *http.Request) (*PaginationParams, error) { // Non-paginated mode (V1 compatible): Returns []string with up to 100k members, HTTP 206 if truncated // Paginated mode: Returns paginated envelope when limit/cursor params are present func GetTagMembersHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + id, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) query := r.URL.Query() isPaginatedRequest := query.Has("limit") || query.Has("cursor") @@ -106,6 +113,12 @@ func GetTagMembersHandler(w http.ResponseWriter, r *http.Request) { // AddMembersToTagHandler - Updated with bucketed implementation func AddMembersToTagHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + tagId, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) @@ -113,7 +126,7 @@ func AddMembersToTagHandler(w http.ResponseWriter, r *http.Request) { } tagValue := getTagValueFromRequest(r) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -169,13 +182,19 @@ func getTagValueFromRequest(r *http.Request) string { // RemoveMembersFromTagHandler - Updated with bucketed implementation func RemoveMembersFromTagHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanWrite(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + id, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) var members []string body, err := io.ReadAll(r.Body) @@ -221,6 +240,12 @@ func RemoveMembersFromTagHandler(w http.ResponseWriter, r *http.Request) { // RemoveMemberFromTagHandler - Updated with bucketed implementation func RemoveMemberFromTagHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanWrite(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + id, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) @@ -233,8 +258,8 @@ func RemoveMemberFromTagHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") - err := RemoveMemberWithXdas(tenantId, id, member) + tenantId := xhttp.GetTenantId(r.Context(), r) + err = RemoveMemberWithXdas(tenantId, id, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) return @@ -245,7 +270,13 @@ func RemoveMemberFromTagHandler(w http.ResponseWriter, r *http.Request) { // GetAllTagsHandler returns all tag IDs from V2 storage func GetAllTagsHandler(w http.ResponseWriter, r *http.Request) { - tenantId := xwhttp.GetTenantId(r, "") + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + + tenantId := xhttp.GetTenantId(r.Context(), r) tagIds, err := GetAllTagIds(tenantId) if err != nil { xhttp.WriteXconfErrorResponse(w, err) @@ -263,13 +294,19 @@ func GetAllTagsHandler(w http.ResponseWriter, r *http.Request) { // GetTagByIdHandler retrieves a single tag with its members from V2 storage func GetTagByIdHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + id, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) members, wasTruncated, err := GetTagById(tenantId, id) if err != nil { // Check if tag not found @@ -307,6 +344,12 @@ func GetTagByIdHandler(w http.ResponseWriter, r *http.Request) { // DeleteTagHandler deletes a tag and all its members from V2 storage asynchronously func DeleteTagHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanWrite(r, auth.COMMON_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + id, found := mux.Vars(r)[common.Tag] if !found { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf(NotSpecifiedErrorMsg, common.Tag))) @@ -319,7 +362,7 @@ func DeleteTagHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r.Context(), r) populatedBuckets, err := getPopulatedBuckets(tenantId, id) if err != nil { xhttp.WriteXconfErrorResponse(w, err) From 9416b83369232408c223a392db3b017f04e40d50 Mon Sep 17 00:00:00 2001 From: Kelley Loder Date: Thu, 25 Jun 2026 16:18:44 -0700 Subject: [PATCH 2/4] addressed PR review comments --- adminapi/xcrp/recooking_lockdown_settings_handler.go | 2 +- http/webconfig_server.go | 8 ++++---- openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md | 2 +- taggingapi/tag/tag_member_handler.go | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/adminapi/xcrp/recooking_lockdown_settings_handler.go b/adminapi/xcrp/recooking_lockdown_settings_handler.go index ff632ef..e853536 100644 --- a/adminapi/xcrp/recooking_lockdown_settings_handler.go +++ b/adminapi/xcrp/recooking_lockdown_settings_handler.go @@ -25,7 +25,7 @@ func GetXcrpConnector() *xhttp.XcrpConnector { func PostRecookingLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { - xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No write permission: tools") + xhttp.AdminError(w, err) return } xw, ok := w.(*xwhttp.XResponseWriter) diff --git a/http/webconfig_server.go b/http/webconfig_server.go index c61a3bb..93885fc 100644 --- a/http/webconfig_server.go +++ b/http/webconfig_server.go @@ -414,8 +414,8 @@ func (s *WebconfigServer) logRequestStarts(w http.ResponseWriter, r *http.Reques } // add field to distinguish between SAT v2, legacy SAT and login token in logs for better analysis of auth types in use - if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(string); ok { - fields["authType"] = authType + if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(AuthType); ok { + fields["authType"] = string(authType) } xwriter := xhttp.NewXResponseWriter(w, time.Now(), token, fields) @@ -462,8 +462,8 @@ func (s *WebconfigServer) logRequestEnds(xw *xhttp.XResponseWriter, r *http.Requ fields := xw.Audit() // add field to distinguish between SAT v2, legacy SAT and login token in logs for better analysis of auth types in use - if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(string); ok { - fields["authType"] = authType + if authType, ok := r.Context().Value(CTX_KEY_AUTH_TYPE).(AuthType); ok { + fields["authType"] = string(authType) } fields["status"] = statusCode diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md index e2f3e9e..ce5fd99 100644 --- a/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md @@ -56,7 +56,7 @@ For all SAT RBAC v2 requests: 2. Read `allowedResources.allowedPartners` from SAT token. 3. Allow only when `allowedPartners` contains the `tenantId` value. -For this phase, the `tenantId` request header value SHALL be compared directly against the values in `allowedResources.allowedPartners` using exact membership matching. No separate tenant-to-partner translation is performed. +For this phase, the `tenantId` request header value SHALL be compared against the values in `allowedResources.allowedPartners` using case-insensitive membership matching. No separate tenant-to-partner translation is performed. ### Tenant-Scope Failure Outcomes diff --git a/taggingapi/tag/tag_member_handler.go b/taggingapi/tag/tag_member_handler.go index dee2b95..194920d 100644 --- a/taggingapi/tag/tag_member_handler.go +++ b/taggingapi/tag/tag_member_handler.go @@ -113,7 +113,7 @@ func GetTagMembersHandler(w http.ResponseWriter, r *http.Request) { // AddMembersToTagHandler - Updated with bucketed implementation func AddMembersToTagHandler(w http.ResponseWriter, r *http.Request) { - _, err := auth.CanRead(r, auth.COMMON_ENTITY) + _, err := auth.CanWrite(r, auth.COMMON_ENTITY) if err != nil { xhttp.AdminError(w, err) return From 72781defd3602834ffb0a30fc1b0016aa16371e7 Mon Sep 17 00:00:00 2001 From: Kelley Loder Date: Fri, 26 Jun 2026 13:47:02 -0700 Subject: [PATCH 3/4] PR review comment changes --- adminapi/auth/permission_service.go | 31 +- adminapi/auth/permission_service_test.go | 456 ++++++++++++++++++ adminapi/change/change_handler.go | 16 +- adminapi/change/change_service.go | 9 +- adminapi/change/change_service_test.go | 6 +- .../firmware/firmware_test_page_controller.go | 15 +- .../lockdown/lockdown_settings_handler.go | 5 +- adminapi/queries/model_handler.go | 4 + .../changes/sat-rbac-capabilities-v2/tasks.md | 46 +- .../sat-rbac-v2-tenant-enforcement/design.md | 4 +- .../sat-rbac-v2-tenant-enforcement/tasks.md | 26 +- 11 files changed, 557 insertions(+), 61 deletions(-) diff --git a/adminapi/auth/permission_service.go b/adminapi/auth/permission_service.go index 427a4fb..c52842f 100644 --- a/adminapi/auth/permission_service.go +++ b/adminapi/auth/permission_service.go @@ -105,6 +105,12 @@ type RouteDomainMapping struct { } var satV2RouteMappings = []RouteDomainMapping{ + // tagging (own top-level router, must appear before xconfAdminService stripping) + {Prefix: "/taggingservice", Domain: DOMAIN_TAGGING}, + + // metrics + {Prefix: "/metrics", Domain: DOMAIN_METRICS}, + // system {Prefix: "/queries/filters/downloadlocation", Domain: DOMAIN_SYSTEM}, {Prefix: "/updates/filters/downloadlocation", Domain: DOMAIN_SYSTEM}, @@ -246,8 +252,13 @@ func getCurrentModule(r *http.Request, entityType string) string { func hasSATv2ReadCapability(capabilities []string, domain SATv2Domain) bool { readCap := "xconf:" + string(domain) + ":readonly" - writeCap := "xconf:" + string(domain) + ":readwrite" + // metrics has no readwrite capability; only xconf:metrics:readonly is valid + if domain == DOMAIN_METRICS { + return util.Contains(capabilities, readCap) + } + + writeCap := "xconf:" + string(domain) + ":readwrite" return util.Contains(capabilities, readCap) || util.Contains(capabilities, writeCap) } @@ -479,16 +490,22 @@ func CanRead(r *http.Request, entityType string, vargs ...string) (applicationTy func classifySATv2Domain(path string) (SATv2Domain, bool) { path = strings.ToLower(strings.TrimSuffix(path, "/")) - // tagging router is its own top-level domain - if strings.HasPrefix(path, "/taggingservice") { - return DOMAIN_TAGGING, true + // tagging paths are not under xconfAdminService; check registry before stripping prefix + for _, m := range satV2RouteMappings { + if strings.HasPrefix(path, m.Prefix) { + return m.Domain, true + } } - // all other admin routes come through xconfAdminService - path = strings.TrimPrefix(path, "/xconfadminservice") + // strip the xconfAdminService prefix and re-check for admin routes + adminPath := strings.TrimPrefix(path, "/xconfadminservice") + if adminPath == path { + // no prefix was stripped; no match found above + return "", false + } for _, m := range satV2RouteMappings { - if strings.HasPrefix(path, m.Prefix) { + if strings.HasPrefix(adminPath, m.Prefix) { return m.Domain, true } } diff --git a/adminapi/auth/permission_service_test.go b/adminapi/auth/permission_service_test.go index a5ade80..90976a4 100644 --- a/adminapi/auth/permission_service_test.go +++ b/adminapi/auth/permission_service_test.go @@ -219,3 +219,459 @@ func TestCanWriteSATv2FailsWhenTenantNotAllowed(t *testing.T) { t.Fatalf("expected tenant scope denial error, got: %v", err) } } + +// 4.3 – SAT_V2 with correct capability and tenantId present, but allowedPartners is an empty slice. +func TestCanReadSATv2FailsWhenAllowedPartnersEmpty(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + []string{}, // empty slice, not nil + ) + + _, err := CanRead(r, DCM_ENTITY) + if err == nil { + t.Fatalf("expected error for empty allowedPartners slice") + } + if !strings.Contains(err.Error(), "missing allowed partners") { + t.Fatalf("expected missing allowed partners error, got: %v", err) + } +} + +// 4.6 – SAT_V2 with wrong/missing capability and invalid allowedPartners: capability failure +// must be returned before tenant scope failure. +func TestCanReadSATv2CapabilityCheckedBeforeTenantScope(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + // Wrong capability (write-only token on a read path) + empty allowedPartners. + // If capability is evaluated first, we get a capability error, not a tenant error. + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readwrite"}, // write cap; readonly required for CanRead + []string{}, // empty allowedPartners – would be tenant error if reached + ) + + // Force a capability miss: use a path that maps to a different domain so the + // read capability check fails before tenant scope is evaluated. + r2 := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{}, // no capabilities at all + []string{}, // also no allowed partners + ) + + _, err := CanRead(r2, DCM_ENTITY) + if err == nil { + t.Fatalf("expected capability error") + } + // Error must be about capabilities, not about tenant/allowedPartners. + if strings.Contains(err.Error(), "allowed partners") || strings.Contains(err.Error(), "tenantId") { + t.Fatalf("expected capability error before tenant check, got: %v", err) + } + _ = r // suppress unused warning +} + +// 4.7a – SAT_LEGACY with legacy read capability succeeds without tenantId or allowedPartners. +func TestCanReadLegacySATSucceedsWithoutTenantScope(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := httptest.NewRequest(http.MethodGet, "/xconfadminservice/dcm?applicationType=stb", nil) + // No tenantId header, no allowedPartners in context. + ctx := context.WithValue(r.Context(), xhttp.CTX_KEY_AUTH_TYPE, xhttp.AUTH_TYPE_SAT_LEGACY) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_CAPABILITIES, []string{XCONF_READ}) + r = r.WithContext(ctx) + + if _, err := CanRead(r, DCM_ENTITY); err != nil { + t.Fatalf("expected legacy SAT read to succeed without tenant scope, got: %v", err) + } +} + +// 4.7b – LOGIN_TOKEN path succeeds with permissions and without tenantId or allowedPartners. +func TestCanReadLoginTokenSucceedsWithoutTenantScope(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + entityPerm := getEntityPermission(DCM_ENTITY) + + r := httptest.NewRequest(http.MethodGet, "/xconfadminservice/dcm?applicationType=stb", nil) + // No tenantId header, no allowedPartners – login token path uses permissions only. + ctx := context.WithValue(r.Context(), xhttp.CTX_KEY_AUTH_TYPE, xhttp.AUTH_TYPE_LOGIN_TOKEN) + ctx = context.WithValue(ctx, xhttp.CTX_KEY_PERMISSIONS, []string{entityPerm.ReadAll}) + r = r.WithContext(ctx) + + if _, err := CanRead(r, DCM_ENTITY); err != nil { + t.Fatalf("expected login token read to succeed without tenant scope, got: %v", err) + } +} + +// Metrics readonly-only behavior (3.4) + +// xconf:metrics:readonly is the only valid metrics capability; read is allowed. +func TestCanReadSATv2MetricsReadonlyCapabilityAllowed(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/metrics", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:metrics:readonly"}, + []string{"comcast"}, + ) + + if _, err := CanRead(r, COMMON_ENTITY); err != nil { + t.Fatalf("expected metrics read with xconf:metrics:readonly to be allowed, got: %v", err) + } +} + +// xconf:metrics:readwrite is not a defined capability; read must be denied. +func TestCanReadSATv2MetricsReadwriteCapabilityDenied(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/metrics", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:metrics:readwrite"}, + []string{"comcast"}, + ) + + _, err := CanRead(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected metrics read with xconf:metrics:readwrite to be denied") + } + if !strings.Contains(err.Error(), "403") && !strings.Contains(err.Error(), "capability") && !strings.Contains(err.Error(), "permission") { + t.Fatalf("expected 403 capability denial, got: %v", err) + } +} + +// Write to metrics with xconf:metrics:readonly must be denied. +func TestCanWriteSATv2MetricsReadonlyCapabilityDenied(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/metrics", + http.MethodPost, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:metrics:readonly"}, + []string{"comcast"}, + ) + + _, err := CanWrite(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected metrics write with xconf:metrics:readonly to be denied") + } + if !strings.Contains(err.Error(), "403") && !strings.Contains(err.Error(), "capability") && !strings.Contains(err.Error(), "permission") { + t.Fatalf("expected 403 capability denial, got: %v", err) + } +} + +// Write to metrics with xconf:metrics:readwrite must also be denied (capability does not exist). +func TestCanWriteSATv2MetricsReadwriteCapabilityDenied(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/metrics", + http.MethodPost, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:metrics:readwrite"}, + []string{"comcast"}, + ) + + _, err := CanWrite(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected metrics write with xconf:metrics:readwrite to be denied") + } + if !strings.Contains(err.Error(), "403") && !strings.Contains(err.Error(), "capability") && !strings.Contains(err.Error(), "permission") { + t.Fatalf("expected 403 capability denial, got: %v", err) + } +} + +// SAT v2 Detection (5.2) + +// Capabilities with at least one xconf: prefix are detected as SAT v2 and follow v2 auth logic. +func TestSATv2DetectionWithXconfCapabilities(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + core.STB, + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + ) + + // SAT v2 logic: xconf:core:readonly is accepted for read + if _, err := CanRead(r, DCM_ENTITY); err != nil { + t.Fatalf("expected SAT v2 with xconf: prefix to use v2 auth logic, got error: %v", err) + } +} + +// Capabilities without any xconf: prefix are treated as legacy SAT and follow legacy auth logic. +func TestLegacySATDetectionWithoutXconfCapabilities(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + "", + xhttp.AUTH_TYPE_SAT_LEGACY, + []string{XCONF_READ}, // legacy capability, no xconf: prefix + ) + + // Legacy SAT logic: XCONF_READ is accepted for read + if _, err := CanRead(r, DCM_ENTITY); err != nil { + t.Fatalf("expected legacy SAT without xconf: prefix to use legacy auth logic, got error: %v", err) + } +} + +// Empty capabilities list is not SAT v2; treated as legacy SAT. +func TestLegacySATDetectionWithEmptyCapabilities(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSAT( + "/xconfadminservice/dcm", + "", + xhttp.AUTH_TYPE_SAT_LEGACY, + []string{}, // empty capabilities + ) + + // Empty capabilities with legacy SAT type should fail (no XCONF_READ) + _, err := CanRead(r, DCM_ENTITY) + if err == nil { + t.Fatalf("expected empty legacy SAT capabilities to be denied") + } + if !strings.Contains(err.Error(), "capabilities") && !strings.Contains(err.Error(), "403") { + t.Fatalf("expected read permission denial, got: %v", err) + } +} + +// Route-to-Domain Classification (5.3) + +// /taggingService/tags should map to tagging domain +func TestClassifySATv2DomainTaggingService(t *testing.T) { + domain, found := classifySATv2Domain("/taggingService/tags") + if !found { + t.Fatalf("expected /taggingService/tags to be classified") + } + if domain != DOMAIN_TAGGING { + t.Fatalf("expected tagging domain for /taggingService/tags, got: %s", domain) + } +} + +// /xconfAdminService/dcm should map to core domain +func TestClassifySATv2DomainDcmCore(t *testing.T) { + domain, found := classifySATv2Domain("/xconfAdminService/dcm") + if !found { + t.Fatalf("expected /xconfAdminService/dcm to be classified") + } + if domain != DOMAIN_CORE { + t.Fatalf("expected core domain for /xconfAdminService/dcm, got: %s", domain) + } +} + +// /xconfAdminService/lockdownsettings should map to system domain +func TestClassifySATv2DomainLockdownSystem(t *testing.T) { + domain, found := classifySATv2Domain("/xconfAdminService/lockdownsettings") + if !found { + t.Fatalf("expected /xconfAdminService/lockdownsettings to be classified") + } + if domain != DOMAIN_SYSTEM { + t.Fatalf("expected system domain for /xconfAdminService/lockdownsettings, got: %s", domain) + } +} + +// /metrics should map to metrics domain +func TestClassifySATv2DomainMetrics(t *testing.T) { + domain, found := classifySATv2Domain("/metrics") + if !found { + t.Fatalf("expected /metrics to be classified") + } + if domain != DOMAIN_METRICS { + t.Fatalf("expected metrics domain for /metrics, got: %s", domain) + } +} + +// First-match-wins: /xconfAdminService/rfc/recooking should match system before /rfc matches core +func TestClassifySATv2DomainFirstMatchWinsRfcRecooking(t *testing.T) { + domain, found := classifySATv2Domain("/xconfAdminService/rfc/recooking") + if !found { + t.Fatalf("expected /xconfAdminService/rfc/recooking to be classified") + } + if domain != DOMAIN_SYSTEM { + t.Fatalf("expected system domain for /xconfAdminService/rfc/recooking (first-match /rfc/recooking), got: %s", domain) + } +} + +// First-match-wins: /xconfAdminService/queries/filters/downloadlocation should match system before /queries matches core +func TestClassifySATv2DomainFirstMatchWinsQueriesFilters(t *testing.T) { + domain, found := classifySATv2Domain("/xconfAdminService/queries/filters/downloadlocation") + if !found { + t.Fatalf("expected /xconfAdminService/queries/filters/downloadlocation to be classified") + } + if domain != DOMAIN_SYSTEM { + t.Fatalf("expected system domain for /xconfAdminService/queries/filters/downloadlocation (first-match /queries/filters/downloadlocation), got: %s", domain) + } +} + +// Path normalization: case insensitivity and trailing slash handling +func TestClassifySATv2DomainCaseInsensitive(t *testing.T) { + domain, found := classifySATv2Domain("/XconfAdminService/DCM") + if !found { + t.Fatalf("expected /XconfAdminService/DCM (mixed case) to be classified") + } + if domain != DOMAIN_CORE { + t.Fatalf("expected core domain for mixed case path, got: %s", domain) + } +} + +// Path normalization: trailing slash should be stripped +func TestClassifySATv2DomainTrailingSlashStripped(t *testing.T) { + domain, found := classifySATv2Domain("/xconfadminservice/dcm/") + if !found { + t.Fatalf("expected /xconfadminservice/dcm/ (with trailing slash) to be classified") + } + if domain != DOMAIN_CORE { + t.Fatalf("expected core domain after stripping trailing slash, got: %s", domain) + } +} + +// Deny-by-default on Unclassified Routes (5.5) + +// SAT v2 with valid capability on unmapped route should be denied (403). +func TestCanReadSATv2UnmappedRouteDeniedByDefault(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/unknown-api", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, // valid SAT v2 capability + []string{"comcast"}, // tenant allowed + ) + + _, err := CanRead(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected unmapped route to be denied by default (deny-by-default)") + } + if !strings.Contains(err.Error(), "permission") && !strings.Contains(err.Error(), "403") { + t.Fatalf("expected authorization denial for unmapped route, got: %v", err) + } +} + +// SAT v2 with valid capability on unmapped route CanWrite should also be denied (403). +func TestCanWriteSATv2UnmappedRouteDeniedByDefault(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + r := requestWithSATScope( + "/xconfadminservice/unknown-api", + http.MethodPost, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readwrite"}, // valid SAT v2 capability for write + []string{"comcast"}, // tenant allowed + ) + + _, err := CanWrite(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected unmapped route to be denied by default (deny-by-default)") + } + if !strings.Contains(err.Error(), "permission") && !strings.Contains(err.Error(), "403") { + t.Fatalf("expected authorization denial for unmapped route, got: %v", err) + } +} + +// HTTP Status Semantics: 401 vs 403 (5.7) + +// 403 Forbidden: Valid SAT v2 auth but insufficient capability +// 403 Forbidden: Valid SAT v2 auth but insufficient capability (wrong domain) +func TestSATv2InsufficientCapabilityReturns403(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + // Valid SAT v2 auth but with tagging capability trying to read core resource + r := requestWithSATScope( + "/xconfadminservice/dcm", + http.MethodGet, // read operation + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:tagging:readonly"}, // wrong domain capability + []string{"comcast"}, + ) + + _, err := CanRead(r, DCM_ENTITY) + if err == nil { + t.Fatalf("expected insufficient capability to be denied") + } + + // Error should indicate authorization failure (403), not authentication failure (401) + errMsg := err.Error() + if !strings.Contains(errMsg, "403") && !strings.Contains(errMsg, "capability") && !strings.Contains(errMsg, "permission") { + t.Fatalf("expected 403 authorization denial for insufficient capability, got: %v", err) + } +} + +// 403 Forbidden: Valid SAT v2 auth but unclassified route +func TestSATv2UnclassifiedRouteReturns403(t *testing.T) { + oldSatOn := owcommon.SatOn + owcommon.SatOn = true + defer func() { owcommon.SatOn = oldSatOn }() + + // Valid SAT v2 auth on unmapped route + r := requestWithSATScope( + "/xconfadminservice/unknown-endpoint", + http.MethodGet, + "comcast", + xhttp.AUTH_TYPE_SAT_V2, + []string{"xconf:core:readonly"}, + []string{"comcast"}, + ) + + _, err := CanRead(r, COMMON_ENTITY) + if err == nil { + t.Fatalf("expected unclassified route to be denied") + } + + // Error should indicate authorization failure (403), not authentication failure (401) + errMsg := err.Error() + if !strings.Contains(errMsg, "403") && !strings.Contains(errMsg, "permission") { + t.Fatalf("expected 403 authorization denial for unclassified route, got: %v", err) + } +} diff --git a/adminapi/change/change_handler.go b/adminapi/change/change_handler.go index e56fc16..54f8317 100644 --- a/adminapi/change/change_handler.go +++ b/adminapi/change/change_handler.go @@ -95,7 +95,14 @@ func ApproveChangeHandler(w http.ResponseWriter, r *http.Request) { } func GetApprovedHandler(w http.ResponseWriter, r *http.Request) { - approvedChange, err := GetApprovedAll(r) + applicationType, err := auth.CanRead(r, auth.CHANGE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + + tenantId := xhttp.GetTenantId(r.Context(), r) + approvedChange, err := GetApprovedAll(tenantId, applicationType) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) return @@ -217,7 +224,7 @@ func GetGroupedChangesHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - + tenantId := xhttp.GetTenantId(r.Context(), r) changeList := xchange.GetChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { @@ -309,6 +316,11 @@ func ApprovedChangesGeneratePage(list []*xwchange.ApprovedChange, page int, page } func GetChangedEntityIdsHandler(w http.ResponseWriter, r *http.Request) { + _, err := auth.CanRead(r, auth.CHANGE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } tenantId := xhttp.GetTenantId(r.Context(), r) entityIds := GetChangedEntityIds(tenantId) response, err := util.JSONMarshal(entityIds) diff --git a/adminapi/change/change_service.go b/adminapi/change/change_service.go index 72f1df1..a602b94 100644 --- a/adminapi/change/change_service.go +++ b/adminapi/change/change_service.go @@ -41,16 +41,11 @@ import ( log "github.com/sirupsen/logrus" ) -func GetApprovedAll(r *http.Request) ([]*xwchange.ApprovedChange, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) +func GetApprovedAll(tenantId string, applicationType string) ([]*xwchange.ApprovedChange, error) { approvedChangesAll := xchange.GetApprovedChangeList(tenantId) approvedChanges := []*xwchange.ApprovedChange{} - application, err := auth.CanRead(r, auth.CHANGE_ENTITY) - if err != nil { - return nil, err - } for _, approvedChange := range approvedChangesAll { - if xshared.ApplicationTypeEquals(application, approvedChange.ApplicationType) || xshared.ApplicationTypeEquals(application, xwshared.ALL) { + if xshared.ApplicationTypeEquals(applicationType, approvedChange.ApplicationType) || xshared.ApplicationTypeEquals(applicationType, xwshared.ALL) { approvedChanges = append(approvedChanges, approvedChange) } } diff --git a/adminapi/change/change_service_test.go b/adminapi/change/change_service_test.go index 37d146c..d8cedd3 100644 --- a/adminapi/change/change_service_test.go +++ b/adminapi/change/change_service_test.go @@ -359,8 +359,7 @@ func TestGetApprovedAll_EmptyResult(t *testing.T) { xchange.DeleteOneApprovedChange(db.GetDefaultTenantId(), ac.ID) } - r := httptest.NewRequest(http.MethodGet, "/?applicationType=stb", nil) - result, err := GetApprovedAll(r) + result, err := GetApprovedAll(db.GetDefaultTenantId(), shared.STB) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -385,8 +384,7 @@ func TestGetApprovedAll_WithResults(t *testing.T) { t.Fatalf("failed to create approved change: %v", err) } - r := httptest.NewRequest(http.MethodGet, "/?applicationType=stb", nil) - result, err := GetApprovedAll(r) + result, err := GetApprovedAll(db.GetDefaultTenantId(), shared.STB) if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/adminapi/firmware/firmware_test_page_controller.go b/adminapi/firmware/firmware_test_page_controller.go index 6c213c5..1439b9c 100644 --- a/adminapi/firmware/firmware_test_page_controller.go +++ b/adminapi/firmware/firmware_test_page_controller.go @@ -58,6 +58,14 @@ func writeErrorResponse(w http.ResponseWriter, r *http.Request, errorMsg string, } func GetFirmwareTestPageHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + + tenantId := xhttp.GetTenantId(r.Context(), r) + // Extract the search parameters from query params context := make(map[string]string) xutil.AddQueryParamsToContextMap(r, context) @@ -67,7 +75,6 @@ func GetFirmwareTestPageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) context[xwcommon.TENANT_ID] = tenantId // If input has any of these search-paramters, validate their values @@ -114,12 +121,6 @@ func GetFirmwareTestPageHandler(w http.ResponseWriter, r *http.Request) { convertedContext := coreef.GetContextConverted(context) // Evaluate rule - applicationType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) - if err != nil { - xhttp.AdminError(w, err) - return - } - eval, err := ruleBase.Eval(context, convertedContext, applicationType, log.Fields{}) if err != nil { errMsg := fmt.Sprintf("Rule Evaluation Error: %v", err) diff --git a/adminapi/lockdown/lockdown_settings_handler.go b/adminapi/lockdown/lockdown_settings_handler.go index ddbf7bd..1db6dd2 100644 --- a/adminapi/lockdown/lockdown_settings_handler.go +++ b/adminapi/lockdown/lockdown_settings_handler.go @@ -56,7 +56,10 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { } func GetLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { - // No permission check needed + if _, err := auth.CanRead(r, auth.TOOL_ENTITY); err != nil { + xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No read permission: tools") + return + } tenantId := xhttp.GetTenantId(r.Context(), r) lockdownSetting, err := GetLockdownSettings(tenantId) if err != nil { diff --git a/adminapi/queries/model_handler.go b/adminapi/queries/model_handler.go index af2dbe7..61e7d45 100644 --- a/adminapi/queries/model_handler.go +++ b/adminapi/queries/model_handler.go @@ -125,6 +125,10 @@ func PutModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { } func ObsoleteGetModelPageHandler(w http.ResponseWriter, r *http.Request) { + if _, err := auth.CanRead(r, auth.COMMON_ENTITY); err != nil { + xhttp.AdminError(w, err) + return + } tenantId := xhttp.GetTenantId(r.Context(), r) entries := shared.GetAllModelList(tenantId) sort.Slice(entries, func(i, j int) bool { diff --git a/openspec/changes/sat-rbac-capabilities-v2/tasks.md b/openspec/changes/sat-rbac-capabilities-v2/tasks.md index e4937ff..79bf0bf 100644 --- a/openspec/changes/sat-rbac-capabilities-v2/tasks.md +++ b/openspec/changes/sat-rbac-capabilities-v2/tasks.md @@ -9,29 +9,39 @@ - [x] 1.8 Add metrics domain constraint (readonly only; no `xconf:metrics:readwrite`). ## 2. Mapping Registry And Classification -- [ ] 2.1 Implement a central route-to-domain mapping registry used by SAT v2 authorization. -- [ ] 2.2 Ensure mapping evaluation is ordered and first-match-wins. -- [ ] 2.3 Seed registry with representative patterns for `core`, `tagging`, `system`, `metrics`. -- [ ] 2.4 Add explicit readonly override patterns for POST-based read endpoints (including `/filtered`). +- [x] 2.1 Implement a central route-to-domain mapping registry used by SAT v2 authorization. +- [x] 2.2 Ensure mapping evaluation is ordered and first-match-wins. +- [x] 2.3 Seed registry with representative patterns for `core`, `tagging`, `system`, `metrics`. +- [x] 2.4 Verify POST-based read endpoints (e.g. `/filtered`) use read authorization paths. + - Audited all POST `/filtered` handlers. + - All matched handlers use `auth.CanRead`. + - No POST `/filtered` handlers use `auth.CanWrite`. + - No POST `/filtered` handlers are missing auth checks. + - No separate readonly override registry needed at this time because access semantics are already determined by handler auth method. + ## 3. Authorization Flow Integration -- [ ] 3.1 Integrate routing-based selection in auth middleware: Authorization header selects SAT path; otherwise Xerxes path. -- [ ] 3.2 Add SAT v2 detection logic based on any capability prefixed with `xconf:`. -- [ ] 3.3 Ensure SAT v2 deny-by-default on unclassifiable `(domain, access)` requests. -- [ ] 3.4 Enforce metrics as readonly-only during SAT v2 capability checks. -- [ ] 3.5 Preserve legacy SAT behavior unchanged when SAT v2 is not detected. +- [x] 3.1 Integrate routing-based selection in auth middleware: Authorization header selects SAT path; otherwise Xerxes path. +- [x] 3.2 Add SAT v2 detection logic based on any capability prefixed with `xconf:`. +- [x] 3.3 Ensure SAT v2 deny-by-default on unclassifiable `(domain, access)` requests. +- [x] 3.4 Enforce metrics as readonly-only during SAT v2 capability checks. +- [x] 3.5 Preserve legacy SAT behavior unchanged when SAT v2 is not detected. ## 4. HTTP Semantics And Error Handling -- [ ] 4.1 Ensure `401` is returned only for missing/invalid authentication. -- [ ] 4.2 Ensure `403` is returned for authenticated-but-not-authorized requests. -- [ ] 4.3 Ensure SAT v2 classification and capability failures consistently return `403`. -- [ ] 4.4 Verify fail-fast termination remains enforced after `401`/`403` responses. +- [x] 4.1 Ensure `401` is returned only for missing/invalid authentication. +- [x] 4.2 Ensure `403` is returned for authenticated-but-not-authorized requests. +- [x] 4.3 Ensure SAT v2 classification and capability failures consistently return `403`. +- [x] 4.4 Verify fail-fast termination remains enforced after `401`/`403` responses. ## 5. Validation - [ ] 5.1 Add tests for routing behavior (Authorization header selects SAT path; SAT v2 vs legacy SAT selection on SAT path; Xerxes path only when Authorization is absent). -- [ ] 5.2 Add tests for SAT v2 detection by `xconf:` prefix presence. -- [ ] 5.3 Add tests for ordered route classification and first-match behavior. -- [ ] 5.4 Add tests for access classification (`/filtered` override and method-based fallback). -- [ ] 5.5 Add tests for deny-by-default on unclassified SAT v2 routes. -- [ ] 5.6 Add tests for metrics readonly-only behavior and no readwrite functionality. + - Deferred: requires SAT/login-token middleware test harness with local JWT/key validation or test seams. +- [x] 5.2 Add tests for SAT v2 detection by `xconf:` prefix presence. +- [x] 5.3 Add tests for ordered route classification and first-match behavior. +- [x] 5.4 Verify POST /filtered endpoints use read authorization (`CanRead`) rather than write authorization. +- [x] 5.5 Add tests for deny-by-default on unclassified SAT v2 routes. +- [x] 5.6 Add tests for metrics readonly-only behavior and no readwrite functionality. - [ ] 5.7 Add tests for `401` vs `403` semantics across auth/authz scenarios. + - 403 authorization semantics covered by permission_service tests. + - 401 middleware-level coverage deferred with 5.1 pending middleware test harness. + diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md index c8fcd61..9ea940a 100644 --- a/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md @@ -10,7 +10,7 @@ Capability authorization remains the first gate. Tenant enforcement is a second 1. Keep credential-path routing unchanged. 2. Keep SAT RBAC v2 capability names and capability matching unchanged. -3. Enforce tenant scope only for all SAT RBAC v2 requests. +3. Enforce tenant scope for all SAT RBAC v2 requests. 4. Deny with `403 Forbidden` for all tenant-enforcement failures. 5. Preserve legacy SAT and login-token behavior. @@ -35,7 +35,7 @@ Capability authorization remains the first gate. Tenant enforcement is a second - If capability authorization fails, return `403 Forbidden`. 5. Enforce SAT tenant scope (new phase) -- For SAT RBAC v2 requests requiring tenant enforcement: +- For all SAT RBAC v2 requests: - Read request tenant from header `tenantId`. - Read allowed partner list from SAT claim `allowedResources.allowedPartners`. - Allow only when `allowedPartners` contains `tenantId`. diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md index ea3d8fd..94b8ab4 100644 --- a/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/tasks.md @@ -12,18 +12,18 @@ - [x] 2.5 Clarify ordering: capability checks first, tenant checks second. ## 3. Implementation -- [ ] 3.1 Add SAT tenant-enforcement step in SAT RBAC v2 auth flow after capability success. -- [ ] 3.2 Read and validate request header `tenantId`. -- [ ] 3.3 Read and validate SAT claim `allowedResources.allowedPartners`. -- [ ] 3.4 Enforce membership check (`tenantId` in `allowedPartners`). -- [ ] 3.5 Return `403 Forbidden` for tenant authorization failures with fail-fast behavior. -- [ ] 3.6 Keep legacy SAT and login-token/IDP flows unchanged. +- [x] 3.1 Add SAT tenant-enforcement step in SAT RBAC v2 auth flow after capability success. +- [x] 3.2 Read and validate request header `tenantId`. +- [x] 3.3 Read and validate SAT claim `allowedResources.allowedPartners`. +- [x] 3.4 Enforce membership check (`tenantId` in `allowedPartners`). +- [x] 3.5 Return `403 Forbidden` for tenant authorization failures with fail-fast behavior. +- [x] 3.6 Keep legacy SAT and login-token/IDP flows unchanged. ## 4. Validation -- [ ] 4.1 Add tests for tenantId missing -> `403` (SAT tenant-enforced route). -- [ ] 4.2 Add tests for allowedPartners missing -> `403`. -- [ ] 4.3 Add tests for allowedPartners empty -> `403`. -- [ ] 4.4 Add tests for tenant mismatch -> `403`. -- [ ] 4.5 Add tests for tenant match -> allow. -- [ ] 4.6 Add tests confirming capability failure still evaluated first. -- [ ] 4.7 Add tests confirming legacy SAT and login-token paths are unchanged. +- [x] 4.1 Add tests for tenantId missing -> `403` (SAT tenant-enforced route). +- [x] 4.2 Add tests for allowedPartners missing -> `403`. +- [x] 4.3 Add tests for allowedPartners empty -> `403`. +- [x] 4.4 Add tests for tenant mismatch -> `403`. +- [x] 4.5 Add tests for tenant match -> allow. +- [x] 4.6 Add tests confirming capability failure still evaluated first. +- [x] 4.7 Add tests confirming legacy SAT and login-token paths are unchanged. From 0c481f465b4279d1bf7fb30f5dcdb4d8bbabb63b Mon Sep 17 00:00:00 2001 From: Kelley Loder Date: Tue, 30 Jun 2026 10:23:17 -0700 Subject: [PATCH 4/4] changes for PR comments --- adminapi/auth/permission_service.go | 11 +- adminapi/canary/canary_settings_handler.go | 4 +- adminapi/change/change_handler.go | 22 +-- adminapi/change/change_service.go | 24 ++-- .../permanent_telemetry_profile_service.go | 12 +- adminapi/change/telemetry_profile_handler.go | 18 +-- .../change/telemetry_two_change_handler.go | 16 +-- .../change/telemetry_two_change_service.go | 20 +-- .../change/telemetry_two_profile_handler.go | 14 +- .../change/telemetry_two_profile_service.go | 12 +- adminapi/dcm/dcmformula_handler.go | 30 ++--- adminapi/dcm/device_settings_handler.go | 18 +-- adminapi/dcm/logrepo_settings_handler.go | 22 +-- adminapi/dcm/logupload_settings_handler.go | 16 +-- adminapi/dcm/vod_settings_handler.go | 18 +-- .../firmware/firmware_test_page_controller.go | 2 +- .../lockdown/lockdown_settings_handler.go | 11 +- adminapi/queries/amv_handler.go | 38 +++--- adminapi/queries/amv_test.go | 12 +- adminapi/queries/common.go | 18 +-- adminapi/queries/environment_handler.go | 8 +- adminapi/queries/feature_handler.go | 35 +++-- adminapi/queries/feature_rule_handler.go | 48 +++---- adminapi/queries/firmware_config_handler.go | 22 +-- adminapi/queries/firmware_rule_handler.go | 127 ++++++++---------- .../firmware_rule_report_page_handler.go | 2 +- .../queries/firmware_rule_template_handler.go | 34 ++--- adminapi/queries/log_controller.go | 2 +- adminapi/queries/log_file_handler.go | 2 +- .../queries/log_upload_settings_handler.go | 2 +- adminapi/queries/model_handler.go | 12 +- adminapi/queries/namedspace_list_handler.go | 74 +++++----- adminapi/queries/percentagebean_handler.go | 24 ++-- adminapi/queries/percentfilter_handler.go | 8 +- adminapi/queries/queries_handler.go | 116 ++++++++-------- adminapi/rfc/feature/feature_handler.go | 18 +-- .../setting/setting_profile_controller.go | 18 +-- adminapi/setting/setting_rule_controller.go | 18 +-- .../telemetry/telemetry_profile_controller.go | 28 ++-- adminapi/telemetry/telemetry_rule_handler.go | 16 +-- .../telemetry/telemetry_v2_rule_handler.go | 41 +++--- .../recooking_lockdown_settings_handler.go | 2 +- http/auth.go | 14 +- .../changes/sat-rbac-capabilities-v2/spec.md | 1 + .../sat-rbac-v2-tenant-enforcement/design.md | 2 + .../sat-rbac-v2-tenant-enforcement/spec.md | 10 +- openspec/specs/auth/auth-contract.md | 29 +++- taggingapi/tag/tag_handler.go | 4 +- taggingapi/tag/tag_member_handler.go | 14 +- 49 files changed, 529 insertions(+), 540 deletions(-) diff --git a/adminapi/auth/permission_service.go b/adminapi/auth/permission_service.go index c52842f..4640118 100644 --- a/adminapi/auth/permission_service.go +++ b/adminapi/auth/permission_service.go @@ -457,7 +457,7 @@ func CanWrite(r *http.Request, entityType string, vargs ...string) (applicationT // Lockdown check runs after authorization: unauthorized callers should receive // 401/403, not a 423 that reveals operational system state. - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if isLockdownMode(tenantId) { lockdownModules := strings.Split(common.GetStringAppSetting(tenantId, common.PROP_LOCKDOWN_MODULES), ",") if len(lockdownModules) != 0 { @@ -630,6 +630,10 @@ func GetDistributedLockOwner(r *http.Request) (owner string) { } func ExtractBodyAndCheckPermissions(obj owcommon.ApplicationTypeAware, w http.ResponseWriter, r *http.Request, entityType string) (applicationType string, err error) { + applicationType, err = CanWrite(r, entityType, obj.GetApplicationType()) + if err != nil { + return "", err + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { return "", xwcommon.NewRemoteErrorAS(http.StatusBadRequest, "responsewriter cast error") @@ -640,11 +644,6 @@ func ExtractBodyAndCheckPermissions(obj owcommon.ApplicationTypeAware, w http.Re return "", xwcommon.NewRemoteErrorAS(http.StatusBadRequest, err.Error()) } - applicationType, err = CanWrite(r, entityType, obj.GetApplicationType()) - if err != nil { - return "", err - } - if obj.GetApplicationType() == "" { obj.SetApplicationType(applicationType) } else if obj.GetApplicationType() != applicationType { diff --git a/adminapi/canary/canary_settings_handler.go b/adminapi/canary/canary_settings_handler.go index 8df88fd..724d929 100644 --- a/adminapi/canary/canary_settings_handler.go +++ b/adminapi/canary/canary_settings_handler.go @@ -48,7 +48,7 @@ func PutCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := SetCanarySetting(tenantId, &canarySettings) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -63,7 +63,7 @@ func GetCanarySettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) canarySetting, err := GetCanarySettings(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/adminapi/change/change_handler.go b/adminapi/change/change_handler.go index 54f8317..dce7931 100644 --- a/adminapi/change/change_handler.go +++ b/adminapi/change/change_handler.go @@ -56,7 +56,7 @@ func GetProfileChangesHandler(w http.ResponseWriter, r *http.Request) { searchContext := make(map[string]string) searchContext[xwcommon.APPLICATION_TYPE] = applicationType - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changes := FindByContextForChanges(tenantId, searchContext) sort.Slice(changes, func(i, j int) bool { return changes[j].Updated < changes[i].Updated @@ -89,7 +89,7 @@ func ApproveChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) headerMap := createHeadersMap(tenantId, applicationType) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, nil) } @@ -101,7 +101,7 @@ func GetApprovedHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approvedChange, err := GetApprovedAll(tenantId, applicationType) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) @@ -121,7 +121,7 @@ func RevertChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approveId, found := mux.Vars(r)[xcommon.APPROVE_ID] if !found || approveId == "" { @@ -145,7 +145,7 @@ func CancelChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changeId, found := mux.Vars(r)[xcommon.CHANGE_ID] if !found || changeId == "" { @@ -225,7 +225,7 @@ func GetGroupedChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changeList := xchange.GetChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[i].Updated < changeList[j].Updated @@ -272,7 +272,7 @@ func GetGroupedApprovedChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changeList := xchange.GetApprovedChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[j].Updated < changeList[i].Updated @@ -321,7 +321,7 @@ func GetChangedEntityIdsHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityIds := GetChangedEntityIds(tenantId) response, err := util.JSONMarshal(entityIds) if err != nil { @@ -337,7 +337,7 @@ func ApproveChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -446,7 +446,7 @@ func GetApprovedFilteredHandler(w http.ResponseWriter, r *http.Request) { if err != nil { log.Error(fmt.Sprintf("json.Marshal ApprovedChangesMap error: %v", err)) } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changeList := FindByContextForChanges(tenantId, searchContext) headerMap := createHeadersWithEntitySize(len(changeList), len(approvedChangeList)) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, response) @@ -494,7 +494,7 @@ func GetChangesFilteredHandler(w http.ResponseWriter, r *http.Request) { } searchContext[xwcommon.APPLICATION_TYPE] = applicationType - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changeList := FindByContextForChanges(tenantId, searchContext) sort.Slice(changeList, func(i, j int) bool { return changeList[j].Updated < changeList[i].Updated diff --git a/adminapi/change/change_service.go b/adminapi/change/change_service.go index a602b94..a3c77bf 100644 --- a/adminapi/change/change_service.go +++ b/adminapi/change/change_service.go @@ -81,7 +81,7 @@ func beforeSavingChange(r *http.Request, change *xwchange.Change) error { return err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) return validateAllChanges(tenantId, change) } @@ -158,7 +158,7 @@ func CreateApprovedChange(r *http.Request, change *xwchange.Change) (*xwchange.A return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approvedChange := xwchange.ApprovedChange(*change) xchange.SetOneApprovedChange(tenantId, &approvedChange) jsonBytes, _ := json.Marshal(change) @@ -170,7 +170,7 @@ func Revert(r *http.Request, approvedId string) error { if approvedId == "" { return xwcommon.NewRemoteErrorAS(http.StatusBadRequest, "Id is blank") } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approvedChange := xchange.GetOneApprovedChange(tenantId, approvedId) if approvedChange == nil { return xwcommon.NewRemoteErrorAS(http.StatusNotFound, "ApprovedChange with "+approvedId+" id does not exist") @@ -187,13 +187,13 @@ func Revert(r *http.Request, approvedId string) error { func revertDelete(r *http.Request, id string, approvedChange *xwchange.ApprovedChange) *xwchange.ApprovedChange { CreatePermanentTelemetryProfile(r, approvedChange.OldEntity) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) xchange.DeleteOneApprovedChange(tenantId, id) return approvedChange } func revertCreateOrUpdateChange(r *http.Request, changeId string, entityId string, approvedChange *xwchange.ApprovedChange) *xwchange.ApprovedChange { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityToRevert := logupload.GetOnePermanentTelemetryProfile(tenantId, entityId) // in Java, equalPendingEntities(PermanentTelemetryProfile oldEntity, PermanentTelemetryProfile newEntity) always returns true //if (equalPendingEntities(approvedChange.getNewEntity(), entityToRevert)) { is being ignored @@ -207,7 +207,7 @@ func revertCreateOrUpdateChange(r *http.Request, changeId string, entityId strin } func CancelChange(r *http.Request, changeId string) error { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) canceledChange, err := Delete(tenantId, changeId) if err != nil { return err @@ -290,7 +290,7 @@ func GetChangesByEntityId(tenantId, entityId string) []*xwchange.Change { } func Approve(r *http.Request, id string) (*xwchange.ApprovedChange, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) change := xchange.GetOneChange(tenantId, id) if change == nil { return nil, xwcommon.NewRemoteErrorAS(http.StatusNotFound, "Change with "+id+" id does not exist") @@ -333,7 +333,7 @@ func getChangeIds(changes []*xwchange.Change) []string { } func ApproveChanges(r *http.Request, changeIds *[]string) (map[string]string, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changesToApprove, err := GetChangesByEntityIds(tenantId, changeIds) if err != nil { return nil, err @@ -373,7 +373,7 @@ func ApproveChanges(r *http.Request, changeIds *[]string) (map[string]string, er } func SaveToApprovedAndCleanUpChange(r *http.Request, change *xwchange.Change) (*xwchange.ApprovedChange, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) userName := auth.GetUserNameOrUnknown(r) change.ApprovedUser = userName approvedChange, err := CreateApprovedChange(r, change) @@ -386,7 +386,7 @@ func SaveToApprovedAndCleanUpChange(r *http.Request, change *xwchange.Change) (* } func CancelApprovedChangesByEntityId(r *http.Request, entityIdsToByCancelChanges []string, changeIdsToBeExcluded []string) error { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entityId := range entityIdsToByCancelChanges { changes := GetChangesByEntityId(tenantId, entityId) for _, changeByEntityId := range changes { @@ -410,7 +410,7 @@ func logAndCollectChangeException(change *xwchange.Change, err error, errorMessa } func RevertChanges(r *http.Request, changeIds *[]string) (map[string]string, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changesToRevert := []*xwchange.ApprovedChange{} for _, changeId := range *changeIds { approvedChange := xchange.GetOneApprovedChange(tenantId, changeId) @@ -471,7 +471,7 @@ func FindByContextForChanges(tenantId string, searchContext map[string]string) [ } func FindByContextForApprovedChanges(r *http.Request, searchContext map[string]string) []*xwchange.ApprovedChange { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approvedChanges := xchange.GetApprovedChangeList(tenantId) changesFound := []*xwchange.ApprovedChange{} for _, change := range approvedChanges { diff --git a/adminapi/change/permanent_telemetry_profile_service.go b/adminapi/change/permanent_telemetry_profile_service.go index b0427ce..1429b75 100644 --- a/adminapi/change/permanent_telemetry_profile_service.go +++ b/adminapi/change/permanent_telemetry_profile_service.go @@ -78,7 +78,7 @@ func UpdatePermanentTelemetryProfile(tenantId string, updatedProfile *logupload. func CreatePermanentTelemetryProfile(r *http.Request, profile *logupload.PermanentTelemetryProfile) (*logupload.PermanentTelemetryProfile, error) { normalizeOnSaveAfterApproving(profile) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err := beforeCreating(tenantId, profile) if err != nil { return nil, err @@ -90,7 +90,7 @@ func SavePermanentTelemetryProfile(r *http.Request, entity *logupload.PermanentT if err := auth.ValidateWrite(r, entity.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeSavingPermanentTelemetryProfile(tenantId, entity); err != nil { return nil, err } @@ -175,7 +175,7 @@ func DeletePermanentTelemetryProfile(r *http.Request, id string) (*logupload.Per if err != nil { return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile, err := beforeRemoving(tenantId, id, writeApplication) if err != nil { return nil, err @@ -247,7 +247,7 @@ func WriteCreateChange(r *http.Request, profile *logupload.PermanentTelemetryPro if err := auth.ValidateWrite(r, profile.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeCreating(tenantId, profile); err != nil { return nil, err } @@ -280,7 +280,7 @@ func WriteUpdateChangeOrSave(r *http.Request, newProfile *logupload.PermanentTel if err := auth.ValidateWrite(r, newProfile.ApplicationType, auth.TELEMETRY_ENTITY); err != nil { return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeUpdating(tenantId, newProfile); err != nil { return nil, err } @@ -318,7 +318,7 @@ func WriteDeleteChange(r *http.Request, profileId string) (*core_change.Change, if err != nil { return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile, err := beforeRemoving(tenantId, profileId, writeApplication) if err != nil { return nil, err diff --git a/adminapi/change/telemetry_profile_handler.go b/adminapi/change/telemetry_profile_handler.go index 23eac8a..3fd13f1 100644 --- a/adminapi/change/telemetry_profile_handler.go +++ b/adminapi/change/telemetry_profile_handler.go @@ -58,7 +58,7 @@ func GetTelemetryProfileByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { errorStr := fmt.Sprintf("Entity with id %s does not exist", id) @@ -92,7 +92,7 @@ func GetTelemetryProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profiles := xlogupload.GetPermanentTelemetryProfileListByApplicationType(tenantId, application) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -203,7 +203,7 @@ func UpdateTelemetryProfileHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) updatedProfile, err := UpdatePermanentTelemetryProfile(tenantId, permTelemetryProfile) if err != nil { xhttp.AdminError(w, err) @@ -285,7 +285,7 @@ func CreateTelemetryIdsHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateTelemetryIds(tenantId) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -426,7 +426,7 @@ func PostTelemetryProfileFilteredHandler(w http.ResponseWriter, r *http.Request) } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) profiles := GetTelemetryProfilesByContext(contextMap) profilesPerPage := GeneratePageTelemetryProfiles(profiles, pageNumber, pageSize) @@ -477,7 +477,7 @@ func AddTelemetryProfileEntryHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -540,7 +540,7 @@ func AddTelemetryProfileEntryChangeHandler(w http.ResponseWriter, r *http.Reques return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -603,7 +603,7 @@ func RemoveTelemetryProfileEntryHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) @@ -667,7 +667,7 @@ func RemoveTelemetryProfileEntryChangeHandler(w http.ResponseWriter, r *http.Req return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xwlogupload.GetOnePermanentTelemetryProfile(tenantId, id) if profile == nil { xhttp.AdminError(w, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id))) diff --git a/adminapi/change/telemetry_two_change_handler.go b/adminapi/change/telemetry_two_change_handler.go index 2380f56..61a9ae2 100644 --- a/adminapi/change/telemetry_two_change_handler.go +++ b/adminapi/change/telemetry_two_change_handler.go @@ -50,7 +50,7 @@ func GetTwoProfileChangesHandler(w http.ResponseWriter, r *http.Request) { searchContext := make(map[string]string) searchContext[xwcommon.APPLICATION_TYPE] = applicationType - searchContext[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + searchContext[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) changes := GetTelemetryTwoChangesByContext(searchContext) sort.Slice(changes, func(i, j int) bool { @@ -72,7 +72,7 @@ func GetApprovedTwoChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changes := xchange.GetApprovedTelemetryTwoChangesByApplicationType(tenantId, applicationType) res, err := xhttp.ReturnJsonResponse(changes, r) if err != nil { @@ -89,7 +89,7 @@ func GetTwoChangeEntityIdsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityIds := GetTelemetryTwoChangeEntityIds(tenantId) res, err := xhttp.ReturnJsonResponse(entityIds, r) if err != nil { @@ -231,7 +231,7 @@ func CancelTwoChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := DeleteTelemetryTwoChange(tenantId, changeId); err != nil { xhttp.AdminError(w, err) return @@ -262,7 +262,7 @@ func GetGroupedTwoChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changes := xchange.GetAllTelemetryTwoChangeList(tenantId) changesPerPage := GeneratePageTelemetryTwoChanges(changes, pageNumber, pageSize) if err != nil { @@ -299,7 +299,7 @@ func GetGroupedApprovedTwoChangesHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changes := xchange.GetAllApprovedTelemetryTwoChangeList(tenantId) changesPerPage := GeneratePageApprovedTelemetryTwoChanges(changes, pageNumber, pageSize) if err != nil { @@ -354,7 +354,7 @@ func GetApprovedTwoChangesFilteredHandler(w http.ResponseWriter, r *http.Request } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) approvedChanges := GetApprovedTelemetryTwoChangesByContext(contextMap) approvedChangesPerPage := GeneratePageApprovedTelemetryTwoChanges(approvedChanges, pageNumber, pageSize) @@ -406,7 +406,7 @@ func GetTwoChangesFilteredHandler(w http.ResponseWriter, r *http.Request) { xutil.AddQueryParamsToContextMap(r, contextMap) } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) changes := GetTelemetryTwoChangesByContext(contextMap) changesPerPage := GeneratePageTelemetryTwoChanges(changes, pageNumber, pageSize) diff --git a/adminapi/change/telemetry_two_change_service.go b/adminapi/change/telemetry_two_change_service.go index 3920a6b..e50147d 100644 --- a/adminapi/change/telemetry_two_change_service.go +++ b/adminapi/change/telemetry_two_change_service.go @@ -138,7 +138,7 @@ func GetApprovedTelemetryTwoChangesByContext(searchContext map[string]string) [] } func ApproveTelemetryTwoChange(r *http.Request, changeId string) (*xwchange.ApprovedTelemetryTwoChange, error) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) change := xchange.GetOneTelemetryTwoChange(tenantId, changeId) if change == nil { return nil, xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("Entity with id %s does not exist", changeId)) @@ -173,7 +173,7 @@ func ApproveTelemetryTwoChanges(r *http.Request, changeIds []string) map[string] errorMessages := make(map[string]string) mergedUpdateChangesByEntityId := make(map[string]*logupload.TelemetryTwoProfile) entityToByCancelChange := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) changesToApprove := GetTelemetryTwoChangesByIds(tenantId, changeIds) for _, change := range changesToApprove { var err error @@ -219,7 +219,7 @@ func SaveToApprovedApprovedTelemetryTwoChange(r *http.Request, change *xwchange. return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := xchange.SetOneApprovedTelemetryTwoChange(tenantId, approvedChange); err != nil { return nil, err } @@ -248,7 +248,7 @@ func DeleteApprovedTelemetryTwoChange(tenantId string, changeId string) error { } func RevertTelemetryTwoChange(r *http.Request, approvedId string) *xwhttp.ResponseEntity { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) approvedChange := xchange.GetOneApprovedTelemetryTwoChange(tenantId, approvedId) if approvedChange == nil { return xwhttp.NewResponseEntity(http.StatusNotFound, fmt.Errorf("ApprovedTelemetryTwoChange with %s id does not exist", approvedId), nil) @@ -268,7 +268,7 @@ func RevertTelemetryTwoChange(r *http.Request, approvedId string) *xwhttp.Respon func RevertTelemetryTwoChanges(r *http.Request, approvedIds []string) map[string]string { errorMessages := make(map[string]string) changesToRevert := make([]xwchange.ApprovedTelemetryTwoChange, 0, len(approvedIds)) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, approvedId := range approvedIds { approvedChange := xchange.GetOneApprovedTelemetryTwoChange(tenantId, approvedId) if approvedChange != nil { @@ -420,7 +420,7 @@ func revertDeleteApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwc return err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := DeleteApprovedTelemetryTwoChange(tenantId, approvedChange.ID); err != nil { return err } @@ -428,7 +428,7 @@ func revertDeleteApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwc } func revertCreateOrUpdateApprovedTelemetryTwoChange(r *http.Request, approvedChange *xwchange.ApprovedTelemetryTwoChange) error { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityToRevert := logupload.GetOneTelemetryTwoProfile(tenantId, approvedChange.EntityID) if entityToRevert == nil { return xwcommon.NewRemoteErrorAS(http.StatusNotFound, fmt.Sprintf("TelemetryTwoProfile with id %s does not exist", approvedChange.EntityID)) @@ -486,7 +486,7 @@ func buildToDeleteTelemetryTwoChange(oldEntity *logupload.TelemetryTwoProfile, a func updateDeleteEntityTelemetryTwoChange(r *http.Request, change *xwchange.TelemetryTwoChange) (*xwchange.ApprovedTelemetryTwoChange, error) { currentEntity := change.OldEntity - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityToChange := logupload.GetOneTelemetryTwoProfile(tenantId, change.EntityID) // in Java, equalPendingEntities(currentEntity, entityToChange) always return true //if (entityToChange != null && equalPendingEntities(currentEntity, entityToChange)) { @@ -541,7 +541,7 @@ func saveToApprovedAndCleanUpTelemetryTwoChange(r *http.Request, change *xwchang return err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := DeleteTelemetryTwoChange(tenantId, change.ID); err != nil { return err } @@ -551,7 +551,7 @@ func saveToApprovedAndCleanUpTelemetryTwoChange(r *http.Request, change *xwchang } func cancelApprovedTelemetryTwoChangesByEntityId(r *http.Request, entityIdsToByCancelChanges []string, changeIdsToBeExcluded []string) error { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entityId := range entityIdsToByCancelChanges { changes := GetTelemetryTwoChangesByEntityId(tenantId, entityId) for _, change := range changes { diff --git a/adminapi/change/telemetry_two_profile_handler.go b/adminapi/change/telemetry_two_profile_handler.go index 50c98cc..64aaa29 100644 --- a/adminapi/change/telemetry_two_profile_handler.go +++ b/adminapi/change/telemetry_two_profile_handler.go @@ -56,7 +56,7 @@ func GetTelemetryTwoProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profiles := xlogupload.GetTelemetryTwoProfileListByApplicationType(tenantId, applicationType) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -228,7 +228,7 @@ func GetTelemetryTwoProfileByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xlogupload.GetOneTelemetryTwoProfile(tenantId, id) if profile == nil { errorStr := fmt.Sprintf("Entity with id %s does not exist", id) @@ -276,7 +276,7 @@ func GetTelemetryTwoProfilePageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profiles := xlogupload.GetAllTelemetryTwoProfileList(tenantId, applicationType) profilesPerPage := GeneratePageTelemetryTwoProfiles(profiles, pageNumber, pageSize) if err != nil { @@ -313,7 +313,7 @@ func PostTelemetryTwoProfilesByIdListHandler(w http.ResponseWriter, r *http.Requ return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profiles := GetTelemetryTwoProfilesByIdList(tenantId, applicationType, idList) res, err := xhttp.ReturnJsonResponse(profiles, r) @@ -362,7 +362,7 @@ func PostTelemetryTwoProfileFilteredHandler(w http.ResponseWriter, r *http.Reque } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) profiles := GetTelemetryTwoProfilesByContext(contextMap) sort.SliceStable(profiles, func(i, j int) bool { @@ -462,7 +462,7 @@ func PutTelemetryTwoProfileEntitiesHandler(w http.ResponseWriter, r *http.Reques func TelemetryTwoTestPageHandler(w http.ResponseWriter, r *http.Request) { applicationType, err := auth.CanRead(r, auth.TELEMETRY_ENTITY) if err != nil { - xhttp.WriteAdminErrorResponse(w, err.(xcommon.XconfError).StatusCode, err.Error()) + xhttp.AdminError(w, err) return } @@ -485,7 +485,7 @@ func TelemetryTwoTestPageHandler(w http.ResponseWriter, r *http.Request) { } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) telemetryProfileService := telemetry.NewTelemetryProfileService() telemetryTwoRules := telemetryProfileService.ProcessTelemetryTwoRulesForAS(contextMap) diff --git a/adminapi/change/telemetry_two_profile_service.go b/adminapi/change/telemetry_two_profile_service.go index a72f0b5..db740d4 100644 --- a/adminapi/change/telemetry_two_profile_service.go +++ b/adminapi/change/telemetry_two_profile_service.go @@ -64,7 +64,7 @@ func WriteCreateChangeTelemetryTwoProfile(r *http.Request, profile *xwlogupload. return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeCreatingTelemetryTwoProfile(tenantId, profile, applicationType); err != nil { return nil, err @@ -94,7 +94,7 @@ func WriteUpdateChangeOrSaveTelemetryTwoProfile(r *http.Request, newProfile *xwl return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeUpdatingTelemetryTwoProfile(tenantId, newProfile, applicationType); err != nil { return nil, err @@ -132,7 +132,7 @@ func WriteDeleteChangeTelemetryTwoProfile(r *http.Request, id string) (*xwchange return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) deleteProfile, err := beforeRemovingTelemetryTwoProfile(tenantId, id, applicationType) if err != nil { @@ -195,7 +195,7 @@ func CreateTelemetryTwoProfile(r *http.Request, newProfile *xwlogupload.Telemetr return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeCreatingTelemetryTwoProfile(tenantId, newProfile, applicationType); err != nil { return nil, err @@ -215,7 +215,7 @@ func UpdateTelemetryTwoProfile(r *http.Request, profile *xwlogupload.TelemetryTw return nil, err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := beforeUpdatingTelemetryTwoProfile(tenantId, profile, applicationType); err != nil { return nil, err @@ -234,7 +234,7 @@ func DeleteTelemetryTwoProfile(r *http.Request, id string) error { if err != nil { return err } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if _, err := beforeRemovingTelemetryTwoProfile(tenantId, id, applicationType); err != nil { return err } diff --git a/adminapi/dcm/dcmformula_handler.go b/adminapi/dcm/dcmformula_handler.go index 6f63bb6..def03dc 100644 --- a/adminapi/dcm/dcmformula_handler.go +++ b/adminapi/dcm/dcmformula_handler.go @@ -46,7 +46,7 @@ func GetDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allFormulas := GetDcmFormulaAll(tenantId) @@ -103,7 +103,7 @@ func GetDcmFormulaByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) formula := GetDcmFormula(tenantId, id) if formula == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -150,7 +150,7 @@ func GetDcmFormulaSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.DCMGenericRule{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetDcmFormulaAll(tenantId) for _, DcmRule := range result { if DcmRule.ApplicationType == appType { @@ -173,7 +173,7 @@ func GetDcmFormulaNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetDcmFormulaAll(tenantId) for _, DcmRule := range result { if DcmRule.ApplicationType == appType { @@ -205,7 +205,7 @@ func DeleteDcmFormulaByIdHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -253,7 +253,7 @@ func CreateDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -307,7 +307,7 @@ func UpdateDcmFormulaHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -374,7 +374,7 @@ func DcmFormulaSettingsAvailabilitygHandler(w http.ResponseWriter, r *http.Reque return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dcmmap := make(map[string]map[string]bool) for _, id := range idlist { data := make(map[string]bool) @@ -418,7 +418,7 @@ func DcmFormulasAvailabilitygHandler(w http.ResponseWriter, r *http.Request) { } data := make(map[string]bool) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, id := range idlist { data[id] = getiFormulaAvail(tenantId, id) } @@ -453,7 +453,7 @@ func PostDcmFormulaFilteredWithParamsHandler(w http.ResponseWriter, r *http.Requ } requtil.AddQueryParamsToContextMap(r, contextMap) contextMap[core.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) dfrules := DcmFormulaFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(dfrules)) @@ -492,7 +492,7 @@ func DcmFormulaChangePriorityHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -575,7 +575,7 @@ func ImportDcmFormulaWithOverwriteHandler(w http.ResponseWriter, r *http.Request db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -634,7 +634,7 @@ func ImportDcmFormulasHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -698,7 +698,7 @@ func PostDcmFormulaListHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { @@ -748,7 +748,7 @@ func PutDcmFormulaListHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := dcmRuleTableLock.Lock(tenantId, owner); err != nil { diff --git a/adminapi/dcm/device_settings_handler.go b/adminapi/dcm/device_settings_handler.go index 4c47c67..73db5f0 100644 --- a/adminapi/dcm/device_settings_handler.go +++ b/adminapi/dcm/device_settings_handler.go @@ -75,7 +75,7 @@ func GetDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetDeviceSettingsAll(tenantId) appRules := []*logupload.DeviceSettings{} for _, rule := range result { @@ -105,7 +105,7 @@ func GetDeviceSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, errorStr) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) devicesettings := GetDeviceSettings(tenantId, id) if devicesettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -133,7 +133,7 @@ func GetDeviceSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.DeviceSettings{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetDeviceSettingsAll(tenantId) for _, ds := range result { if ds.ApplicationType == appType { @@ -156,7 +156,7 @@ func GetDeviceSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetDeviceSettingsAll(tenantId) for _, ds := range result { if ds.ApplicationType == appType { @@ -184,7 +184,7 @@ func DeleteDeviceSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, errorStr) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteDeviceSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -213,7 +213,7 @@ func CreateDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateDeviceSettings(tenantId, &newds, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -248,7 +248,7 @@ func UpdateDeviceSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateDeviceSettings(tenantId, &newdsrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -286,7 +286,7 @@ func PostDeviceSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http. } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) dsrules := DeviceSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(dsrules)) @@ -310,7 +310,7 @@ func GetDeviceSettingsExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allFormulas := GetDcmFormulaAll(tenantId) dsList := []*logupload.DeviceSettings{} diff --git a/adminapi/dcm/logrepo_settings_handler.go b/adminapi/dcm/logrepo_settings_handler.go index 75de78b..699f466 100644 --- a/adminapi/dcm/logrepo_settings_handler.go +++ b/adminapi/dcm/logrepo_settings_handler.go @@ -40,7 +40,7 @@ func GetLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogRepoSettingsAll(tenantId) appRules := []*logupload.UploadRepository{} for _, rule := range result { @@ -79,7 +79,7 @@ func GetLogRepoSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) logreposettings := GetLogRepoSettings(tenantId, id) if logreposettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -121,7 +121,7 @@ func GetLogRepoSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.UploadRepository{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogRepoSettingsAll(tenantId) for _, lr := range result { if lr.ApplicationType == applicationType { @@ -144,7 +144,7 @@ func GetLogRepoSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogRepoSettingsAll(tenantId) for _, lr := range result { if lr.ApplicationType == applicationType { @@ -173,7 +173,7 @@ func DeleteLogRepoSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteLogRepoSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -202,7 +202,7 @@ func CreateLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateLogRepoSettingsForTenant(tenantId, &newlr, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -238,7 +238,7 @@ func UpdateLogRepoSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateLogRepoSettingsForTenant(tenantId, &newlrrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -276,7 +276,7 @@ func PostLogRepoSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) lrrules := LogRepoSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(lrrules)) @@ -313,7 +313,7 @@ func PostLogRepoSettingsEntitiesHandler(w http.ResponseWriter, r *http.Request) return } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { respEntity := CreateLogRepoSettingsForTenant(tenantId, &entity, applicationType) if respEntity.Error != nil { @@ -355,7 +355,7 @@ func PutLogRepoSettingsEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { respEntity := UpdateLogRepoSettingsForTenant(tenantId, &entity, applicationType) if respEntity.Error != nil { @@ -386,7 +386,7 @@ func GetLogRepoSettingsExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allFormulas := GetDcmFormulaAll(tenantId) lusList := []*logupload.LogUploadSettings{} diff --git a/adminapi/dcm/logupload_settings_handler.go b/adminapi/dcm/logupload_settings_handler.go index ee1f78c..5a0b9d2 100644 --- a/adminapi/dcm/logupload_settings_handler.go +++ b/adminapi/dcm/logupload_settings_handler.go @@ -39,7 +39,7 @@ func GetLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogUploadSettingsList(tenantId) appRules := []*logupload.LogUploadSettings{} for _, rule := range result { @@ -70,7 +70,7 @@ func GetLogUploadSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) loguploadsettings := logupload.GetOneLogUploadSettings(tenantId, id) if loguploadsettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -98,7 +98,7 @@ func GetLogUploadSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.LogUploadSettings{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogUploadSettingsList(tenantId) for _, lu := range result { if lu.ApplicationType == applicationType { @@ -121,7 +121,7 @@ func GetLogUploadSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetLogUploadSettingsList(tenantId) for _, lu := range result { if lu.ApplicationType == applicationType { @@ -150,7 +150,7 @@ func DeleteLogUploadSettingsByIdHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteLogUploadSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -180,7 +180,7 @@ func CreateLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateLogUploadSettings(tenantId, &newlu, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -216,7 +216,7 @@ func UpdateLogUploadSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateLogUploadSettings(tenantId, &newlurule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -254,7 +254,7 @@ func PostLogUploadSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *ht } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) lurules := LogUploadSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(lurules)) diff --git a/adminapi/dcm/vod_settings_handler.go b/adminapi/dcm/vod_settings_handler.go index 84f623a..eb24613 100644 --- a/adminapi/dcm/vod_settings_handler.go +++ b/adminapi/dcm/vod_settings_handler.go @@ -42,7 +42,7 @@ func GetVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetVodSettingsAll(tenantId) appRules := []*logupload.VodSettings{} for _, rule := range result { @@ -69,7 +69,7 @@ func GetVodSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) vodsettings := GetVodSettings(tenantId, id) if vodsettings == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -93,7 +93,7 @@ func GetVodSettingsSizeHandler(w http.ResponseWriter, r *http.Request) { } final := []*logupload.VodSettings{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetVodSettingsAll(tenantId) for _, vs := range result { if vs.ApplicationType == applicationType { @@ -112,7 +112,7 @@ func GetVodSettingsNamesHandler(w http.ResponseWriter, r *http.Request) { } final := []string{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetVodSettingsAll(tenantId) for _, vs := range result { if vs.ApplicationType == applicationType { @@ -137,7 +137,7 @@ func DeleteVodSettingsByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteVodSettingsbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -167,7 +167,7 @@ func CreateVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateVodSettings(tenantId, &newvs, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -203,7 +203,7 @@ func UpdateVodSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateVodSettings(tenantId, &newvsrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -241,7 +241,7 @@ func PostVodSettingsFilteredWithParamsHandler(w http.ResponseWriter, r *http.Req } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) vsrules := VodSettingsFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(vsrules)) @@ -261,7 +261,7 @@ func GetVodSettingExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allFormulas := GetDcmFormulaAll(tenantId) vodList := []*logupload.VodSettings{} diff --git a/adminapi/firmware/firmware_test_page_controller.go b/adminapi/firmware/firmware_test_page_controller.go index 1439b9c..c7c8e20 100644 --- a/adminapi/firmware/firmware_test_page_controller.go +++ b/adminapi/firmware/firmware_test_page_controller.go @@ -64,7 +64,7 @@ func GetFirmwareTestPageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) // Extract the search parameters from query params context := make(map[string]string) diff --git a/adminapi/lockdown/lockdown_settings_handler.go b/adminapi/lockdown/lockdown_settings_handler.go index 1db6dd2..23cf988 100644 --- a/adminapi/lockdown/lockdown_settings_handler.go +++ b/adminapi/lockdown/lockdown_settings_handler.go @@ -25,15 +25,16 @@ import ( "github.com/rdkcentral/xconfadmin/adminapi/auth" ccommon "github.com/rdkcentral/xconfadmin/common" xhttp "github.com/rdkcentral/xconfadmin/http" + xwhttp "github.com/rdkcentral/xconfwebconfig/http" ) func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { if _, err := auth.CanWrite(r, auth.TOOL_ENTITY); err != nil { - xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No write permission: tools") + xhttp.AdminError(w, err) return } - xw, ok := w.(*xhttp.XResponseWriter) + xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "responsewriter cast error") return @@ -46,7 +47,7 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := SetLockdownSetting(tenantId, &lockdownSettings) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -57,10 +58,10 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { func GetLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { if _, err := auth.CanRead(r, auth.TOOL_ENTITY); err != nil { - xhttp.WriteAdminErrorResponse(w, http.StatusForbidden, "No read permission: tools") + xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) lockdownSetting, err := GetLockdownSettings(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) diff --git a/adminapi/queries/amv_handler.go b/adminapi/queries/amv_handler.go index 4cac616..5d3fd12 100644 --- a/adminapi/queries/amv_handler.go +++ b/adminapi/queries/amv_handler.go @@ -46,7 +46,7 @@ func GetAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetAmvALL(tenantId) appRules := []*ActivationVersionResponse{} for _, rule := range result { @@ -87,7 +87,7 @@ func GetAmvByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) amv := GetAmv(tenantId, id) if amv == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -144,7 +144,7 @@ func PostAmvFilteredHandler(w http.ResponseWriter, r *http.Request) { } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) amvrules := AmvFilterByContext(contextMap) sort.Slice(amvrules, func(i, j int) bool { @@ -179,7 +179,7 @@ func DeleteAmvByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteAmvbyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -196,7 +196,7 @@ func CreateAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateAmv(tenantId, &newAmv, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -212,6 +212,11 @@ func CreateAmvHandler(w http.ResponseWriter, r *http.Request) { } func ImportAllAmvHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { response := "Unable to extract Body" @@ -225,28 +230,17 @@ func ImportAllAmvHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, response) return } - determinedAppType := "" for i := range amvlist { - applicationType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY, amvlist[i].ApplicationType) - if err != nil { - xhttp.AdminError(w, err) - return - } - if determinedAppType != "" && determinedAppType != applicationType { - xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType mixing not allowed") - return - } if amvlist[i].ApplicationType == "" { amvlist[i].ApplicationType = applicationType } else if amvlist[i].ApplicationType != applicationType { xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType Conflict") return } - determinedAppType = applicationType } - tenantId := xhttp.GetTenantId(r.Context(), r) - result, err := importOrUpdateAllAmvs(tenantId, amvlist, determinedAppType) + tenantId := xhttp.GetTenantId(r) + result, err := importOrUpdateAllAmvs(tenantId, amvlist, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -267,7 +261,7 @@ func UpdateAmvHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateAmv(tenantId, &newAmv, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -300,7 +294,7 @@ func PostAmvEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -344,7 +338,7 @@ func PutAmvEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -383,7 +377,7 @@ func GetAmvFilteredHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) amvrules := AmvFilterByContext(contextMap) sort.Slice(amvrules, func(i, j int) bool { diff --git a/adminapi/queries/amv_test.go b/adminapi/queries/amv_test.go index c3ca6ca..146487b 100644 --- a/adminapi/queries/amv_test.go +++ b/adminapi/queries/amv_test.go @@ -142,7 +142,7 @@ func TestAmvAllApi(t *testing.T) { // config := GetTestConfig() // _, router := GetTestWebConfigServer(config) - //Badrequest + // Badrequest req, err := http.NewRequest("POST", AMV_URL, bytes.NewBuffer(jsonAmvCreateData)) req.Header.Set("Content-Type", "application/json: charset=UTF-8") req.Header.Set("Accept", "application/json") @@ -251,16 +251,16 @@ func TestAmvAllApi(t *testing.T) { assert.Equal(t, len(bodyMap["NOT_IMPORTED"]) > 0, true) } - //update ImportALL error + // update ImportALL error - applicationType mismatch should return 409 conflict req, err = http.NewRequest("POST", urlimport, bytes.NewBuffer(jsonAmvImportupdateErrData)) req.Header.Set("Content-Type", "application/json: charset=UTF-8") req.Header.Set("Accept", "application/json") assert.NilError(t, err) res = ExecuteRequest(req, router).Result() defer res.Body.Close() - assert.Equal(t, res.StatusCode, http.StatusBadRequest) + assert.Equal(t, res.StatusCode, http.StatusConflict) - //update ImportALL + // update ImportALL req, err = http.NewRequest("POST", urlimport, bytes.NewBuffer(jsonAmvImportupdateData)) req.Header.Set("Content-Type", "application/json: charset=UTF-8") req.Header.Set("Accept", "application/json") @@ -487,6 +487,6 @@ func TestAmv_ImportAll_MixingApplicationTypes(t *testing.T) { assert.NilError(t, err) res := ExecuteRequest(req, router).Result() defer res.Body.Close() - // observed status is 400 due to validation of applicationType wrong - assert.Equal(t, res.StatusCode, http.StatusBadRequest) + // observed status is 409 due to validation of applicationType wrong + assert.Equal(t, res.StatusCode, http.StatusConflict) } diff --git a/adminapi/queries/common.go b/adminapi/queries/common.go index 999fd22..a9b6f6d 100644 --- a/adminapi/queries/common.go +++ b/adminapi/queries/common.go @@ -90,7 +90,7 @@ func GetInfoTable(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -155,7 +155,7 @@ func GetInfoTableRowKey(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -247,7 +247,7 @@ func UpdateInfoTableRowKey(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] tableInfo, _ := db.GetTableInfo(tableName) @@ -365,7 +365,7 @@ func GetStats(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) stats := db.GetCacheManager().GetStatistics(tenantId) response, _ := util.JSONMarshal(stats.TableStats) @@ -378,7 +378,7 @@ func GetInfoStatistics(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) stats := *db.GetCacheManager().GetStatistics(tenantId) response, _ := util.JSONMarshal(stats) @@ -392,7 +392,7 @@ func GetAppSettings(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) settings, err := xcommon.GetAppSettings(tenantId) if err != nil { @@ -424,7 +424,7 @@ func UpdateAppSettings(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for k, v := range settings { if !xcommon.IsValidAppSetting(k) { @@ -446,7 +446,7 @@ func GetInfoRefreshAllHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) failedToRefreshTables := db.GetCacheManager().RefreshAll(tenantId) if len(failedToRefreshTables) == 0 { @@ -464,7 +464,7 @@ func GetInfoRefreshHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tableName := mux.Vars(r)[xcommon.TABLE_NAME] err := db.GetCacheManager().Refresh(tenantId, tableName) diff --git a/adminapi/queries/environment_handler.go b/adminapi/queries/environment_handler.go index 38a080b..2fb2ea8 100644 --- a/adminapi/queries/environment_handler.go +++ b/adminapi/queries/environment_handler.go @@ -60,7 +60,7 @@ func UpdateEnvironmentHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateEnvironment(tenantId, &upEnv) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -96,7 +96,7 @@ func PostEnvironmentFilteredHandler(w http.ResponseWriter, r *http.Request) { } } xutil.AddQueryParamsToContextMap(r, contextMap) - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) evrules := EnvironmentFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(evrules)) @@ -132,7 +132,7 @@ func PostEnvironmentEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -175,7 +175,7 @@ func PutEnvironmentEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity diff --git a/adminapi/queries/feature_handler.go b/adminapi/queries/feature_handler.go index 849d40f..b116554 100644 --- a/adminapi/queries/feature_handler.go +++ b/adminapi/queries/feature_handler.go @@ -44,7 +44,7 @@ func GetFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { } featureEntityList := []*rfc.FeatureEntity{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) features := GetAllFeatureEntity(tenantId) for _, rule := range features { if applicationType == rule.ApplicationType { @@ -65,7 +65,7 @@ func GetFeatureEntityFilteredHandler(w http.ResponseWriter, r *http.Request) { contextMap := map[string]string{} requtil.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) featureList := GetFeatureEntityFiltered(contextMap) response, _ := util.XConfJSONMarshal(featureList, true) @@ -85,7 +85,7 @@ func GetFeatureEntityByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) featureEntity := GetFeatureEntityById(tenantId, id) if featureEntity == nil { xwhttp.WriteXconfResponse(w, http.StatusNotFound, []byte(fmt.Sprintf("\"Entity with id: %s does not exist\"", id))) @@ -101,6 +101,11 @@ func GetFeatureEntityByIdHandler(w http.ResponseWriter, r *http.Request) { } func PostFeatureEntityImportAllHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.DCM_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xwhttp.WriteXconfResponse(w, http.StatusInternalServerError, []byte("responsewriter cast error")) @@ -108,33 +113,23 @@ func PostFeatureEntityImportAllHandler(w http.ResponseWriter, r *http.Request) { } body := xw.Body() var featureEntityList []*rfc.FeatureEntity - err := json.Unmarshal([]byte(body), &featureEntityList) + err = json.Unmarshal([]byte(body), &featureEntityList) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(fmt.Sprintf("\"%s\"", err.Error()))) return } - determinedAppType := "" - for i, _ := range featureEntityList { - applicationType, err := auth.CanWrite(r, auth.DCM_ENTITY, featureEntityList[i].ApplicationType) - if err != nil { - xhttp.AdminError(w, err) - return - } - if determinedAppType != "" && determinedAppType != applicationType { - xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType mixing not allowed") - return - } + for i := range featureEntityList { + if featureEntityList[i].ApplicationType == "" { featureEntityList[i].ApplicationType = applicationType } else if featureEntityList[i].ApplicationType != applicationType { xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType Conflict") return } - determinedAppType = applicationType } - tenantId := xhttp.GetTenantId(r.Context(), r) - featureEntityMap := ImportOrUpdateAllFeatureEntity(tenantId, featureEntityList, determinedAppType) + tenantId := xhttp.GetTenantId(r) + featureEntityMap := ImportOrUpdateAllFeatureEntity(tenantId, featureEntityList, applicationType) response, _ := util.XConfJSONMarshal(featureEntityMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) } @@ -147,7 +142,7 @@ func PostFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xrfc.DoesFeatureExist(tenantId, featureEntity.ID) { xwhttp.WriteXconfResponse(w, http.StatusConflict, []byte(fmt.Sprintf("\"Entity with id: %s already exists\"", featureEntity.ID))) return @@ -184,7 +179,7 @@ func PutFeatureEntityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if !xrfc.DoesFeatureExist(tenantId, featureEntity.ID) { xwhttp.WriteXconfResponse(w, http.StatusNotFound, []byte(fmt.Sprintf("\"Entity with id: %s does not exist\"", featureEntity.ID))) return diff --git a/adminapi/queries/feature_rule_handler.go b/adminapi/queries/feature_rule_handler.go index 061c96b..e65d6a4 100644 --- a/adminapi/queries/feature_rule_handler.go +++ b/adminapi/queries/feature_rule_handler.go @@ -64,7 +64,7 @@ func GetFeatureRulesFiltered(w http.ResponseWriter, r *http.Request) { } } contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) featureRules := FindFeatureRuleByContext(contextMap) response, err := util.JSONMarshal(featureRules) @@ -115,7 +115,7 @@ func GetFeatureRulesFilteredWithPage(w http.ResponseWriter, r *http.Request) { } } contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) featureRules := FindFeatureRuleByContext(contextMap) featureRuleList := FeatureRulesGeneratePage(featureRules, pageNumber, pageSize) @@ -158,7 +158,7 @@ func GetFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) featureRules := GetAllFeatureRulesByType(tenantId, applicationType) response, err := util.JSONMarshal(featureRules) if err != nil { @@ -174,7 +174,7 @@ func GetFeatureRulesExportHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) featureRules := GetAllFeatureRulesByType(tenantId, applicationType) sort.Slice(featureRules, func(i, j int) bool { return featureRules[j].Priority > featureRules[i].Priority @@ -205,7 +205,7 @@ func GetFeatureRuleOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) featureRule := xrfc.GetFeatureRule(tenantId, id) if featureRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -241,7 +241,7 @@ func GetFeatureRuleOne(w http.ResponseWriter, r *http.Request) { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("Id is blank")) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) featureRule := xrfc.GetFeatureRule(tenantId, id) if featureRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -272,7 +272,7 @@ func CreateFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -311,7 +311,7 @@ func UpdateFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -341,6 +341,11 @@ func UpdateFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { } func ImportAllFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xwhttp.Error(w, http.StatusInternalServerError, xwcommon.NewRemoteErrorAS(http.StatusInternalServerError, "responsewriter cast error")) @@ -353,24 +358,13 @@ func ImportAllFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { return } - determinedAppType := "" - for i, _ := range featureRules { - applicationType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY, featureRules[i].ApplicationType) - if err != nil { - xhttp.AdminError(w, err) - return - } - if determinedAppType != "" && determinedAppType != applicationType { - xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType mixing not allowed") - return - } + for i := range featureRules { if featureRules[i].ApplicationType == "" { featureRules[i].ApplicationType = applicationType } else if featureRules[i].ApplicationType != applicationType { xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType Conflict") return } - determinedAppType = applicationType } sort.Slice(featureRules, func(i, j int) bool { @@ -379,7 +373,7 @@ func ImportAllFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -396,7 +390,7 @@ func ImportAllFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { defer featureRuleTableMutex.Unlock() } - importResult := importOrUpdateAllFeatureRule(tenantId, featureRules, determinedAppType) + importResult := importOrUpdateAllFeatureRule(tenantId, featureRules, applicationType) response, err := util.JSONMarshal(importResult) if err != nil { log.Error(fmt.Sprintf("json.Marshal featureRuleNew error: %v", err)) @@ -413,7 +407,7 @@ func DeleteOneFeatureRuleHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -505,7 +499,7 @@ func ChangeFeatureRulePrioritiesHandler(w http.ResponseWriter, r *http.Request) db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -546,7 +540,7 @@ func GetFeatureRulesSizeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) size := GetFeatureRulesSize(tenantId, applicationType) sizeString := strconv.Itoa(size) response, err := util.JSONMarshal(sizeString) @@ -596,7 +590,7 @@ func UpdateFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { @@ -660,7 +654,7 @@ func CreateFeatureRulesHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := featureRuleTableLock.Lock(tenantId, owner); err != nil { diff --git a/adminapi/queries/firmware_config_handler.go b/adminapi/queries/firmware_config_handler.go index 03acade..60c1037 100644 --- a/adminapi/queries/firmware_config_handler.go +++ b/adminapi/queries/firmware_config_handler.go @@ -57,7 +57,7 @@ func PostFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { } status := http.StatusCreated - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateFirmwareConfigAS(tenantId, firmwareConfig, applicationType, true) data := respEntity.Data status = respEntity.Status @@ -88,7 +88,7 @@ func PutFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { } status := http.StatusOK - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateFirmwareConfigAS(tenantId, firmwareConfig, appType, true) data := respEntity.Data status = respEntity.Status @@ -161,7 +161,7 @@ func PutPostFirmwareConfigEntitiesHandler(w http.ResponseWriter, r *http.Request } descMap := make(map[string][]*estbfirmware.FirmwareConfig) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) list, err := estbfirmware.GetFirmwareConfigAsListDB(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -279,7 +279,7 @@ func PostFirmwareConfigBySupportedModelsHandler(w http.ResponseWriter, r *http.R return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetFirmwareConfigsByModelIdsAndApplication(tenantId, modelIds, appType) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -299,7 +299,7 @@ func GetFirmwareConfigFirmwareConfigMapHandler(w http.ResponseWriter, r *http.Re return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) configMap, err := estb.GetFirmwareConfigAsMapDB(tenantId, appType) if err != nil { xhttp.AdminError(w, err) @@ -341,7 +341,7 @@ func PostFirmwareConfigGetSortedFirmwareVersionsIfExistOrNotHandler(w http.Respo return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetSortedFirmwareVersionsIfDoesExistOrNot(tenantId, fcData, appType) response, err := xhttp.ReturnJsonResponse(result, r) @@ -405,7 +405,7 @@ func PostFirmwareConfigFilteredHandler(w http.ResponseWriter, r *http.Request) { } } filterContext[xcommon.APPLICATION_TYPE] = appType - filterContext[xcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + filterContext[xcommon.TENANT_ID] = xhttp.GetTenantId(r) // Get all entries and sort them entries, _ := estbfirmware.GetFirmwareConfigAsListDB(filterContext[xcommon.TENANT_ID]) @@ -454,7 +454,7 @@ func GetFirmwareConfigByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fc, _ := estbfirmware.GetFirmwareConfigOneDB(tenantId, id) if fc == nil { errorStr := fmt.Sprintf("Entity with id: %s does not exist", id) @@ -499,7 +499,7 @@ func GetFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { _, ok2 := queryParams[common.EXPORTALL] if ok1 || ok2 { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entries := GetFirmwareConfigsAS(tenantId, appType) res, err := xhttp.ReturnJsonResponse(entries, r) @@ -530,7 +530,7 @@ func GetSupportedConfigsByEnvModelRuleName(w http.ResponseWriter, r *http.Reques return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fwConfig := getSupportedConfigsByEnvModelRuleName(tenantId, ruleName, appType) if len(fwConfig) == 0 { errorStr := fmt.Sprintf("%s not found", ruleName) @@ -562,7 +562,7 @@ func GetFirmwareConfigByEnvModelRuleNameByRuleNameHandler(w http.ResponseWriter, return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fwConfig := getFirmwareConfigByEnvModelRuleName(tenantId, entry) if fwConfig != nil && fwConfig.ApplicationType != appType { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("Entity with id: %s aplicationType does not match", fwConfig.ID)) diff --git a/adminapi/queries/firmware_rule_handler.go b/adminapi/queries/firmware_rule_handler.go index e3226a4..54cb772 100644 --- a/adminapi/queries/firmware_rule_handler.go +++ b/adminapi/queries/firmware_rule_handler.go @@ -44,22 +44,15 @@ import ( re "github.com/rdkcentral/xconfwebconfig/rulesengine" ) -func populateContext(w http.ResponseWriter, r *http.Request, isRead bool) (filterContext map[string]string, err error) { - filterContext = map[string]string{} +func populateContext(r *http.Request, tenantId string, applicationType string) map[string]string { + filterContext := map[string]string{} xutil.AddQueryParamsToContextMap(r, filterContext) - filterContext[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + filterContext[common.TENANT_ID] = tenantId - appType, found := filterContext[common.APPLICATION_TYPE] - if !found || util.IsBlank(appType) { - if isRead { - filterContext[common.APPLICATION_TYPE], err = auth.CanRead(r, auth.FIRMWARE_ENTITY) - } else { - filterContext[common.APPLICATION_TYPE], err = auth.CanWrite(r, auth.FIRMWARE_ENTITY) - } - } + filterContext[common.APPLICATION_TYPE] = applicationType - return filterContext, err + return filterContext } // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 @@ -69,13 +62,8 @@ func GetFirmwareRuleFilteredHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - - filterContext, err := populateContext(w, r, true) - if err != nil { - xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - filterContext[common.APPLICATION_TYPE] = appType + tenantId := xhttp.GetTenantId(r) + filterContext := populateContext(r, tenantId, appType) for k, v := range filterContext { if strings.ToUpper(k) == "KEY" { @@ -118,12 +106,9 @@ func PostFirmwareRuleFilteredHandler(w http.ResponseWriter, r *http.Request) { return } + tenantId := xhttp.GetTenantId(r) // Build the pageContext from query params - pageContext, err := populateContext(w, r, false) - if err != nil { - xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } + pageContext := populateContext(r, tenantId, applicationType) // Build the filterContext from Body filterContext := make(map[string]string) @@ -192,6 +177,11 @@ func PostFirmwareRuleFilteredHandler(w http.ResponseWriter, r *http.Request) { // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 func PostFirmwareRuleImportAllHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Unable to extract Body") @@ -211,28 +201,17 @@ func PostFirmwareRuleImportAllHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, response) return } - determinedAppType := "" - for i, _ := range firmwareRules { - appType, err := auth.CanWrite(r, auth.FIRMWARE_ENTITY, firmwareRules[i].ApplicationType) - if err != nil { - xhttp.AdminError(w, err) - return - } - if determinedAppType != "" && determinedAppType != appType { - xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType mixing not allowed") - return - } + for i := range firmwareRules { if firmwareRules[i].ApplicationType == "" { - firmwareRules[i].ApplicationType = appType - } else if firmwareRules[i].ApplicationType != appType { + firmwareRules[i].ApplicationType = applicationType + } else if firmwareRules[i].ApplicationType != applicationType { xhttp.WriteAdminErrorResponse(w, http.StatusConflict, "ApplicationType Conflict") return } - determinedAppType = appType } - tenantId := xhttp.GetTenantId(r.Context(), r) - result := importOrUpdateAllFirmwareRules(tenantId, firmwareRules, determinedAppType, fields) + tenantId := xhttp.GetTenantId(r) + result := importOrUpdateAllFirmwareRules(tenantId, firmwareRules, applicationType, fields) response, err := xhttp.ReturnJsonResponse(result, r) if err != nil { xhttp.AdminError(w, err) @@ -253,7 +232,7 @@ func PostFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if util.IsBlank(firmwareRule.ID) { firmwareRule.ID = uuid.New().String() } else { @@ -285,9 +264,15 @@ func PostFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { func PutFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { firmwareRule := firmware.NewEmptyFirmwareRule() firmwareRule.ApplicationType = "" - tenantId := xhttp.GetTenantId(r.Context(), r) appType, err := auth.ExtractBodyAndCheckPermissions(firmwareRule, w, r, auth.FIRMWARE_ENTITY) + + if err != nil { + xhttp.AdminError(w, err) + return + } + tenantId := xhttp.GetTenantId(r) + _, err = firmware.GetFirmwareRuleOneDB(tenantId, firmwareRule.ID) if err == nil { err = updateFirmwareRule(tenantId, *firmwareRule, appType, true) @@ -323,7 +308,7 @@ func DeleteFirmwareRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entityOnDb, err := firmware.GetFirmwareRuleOneDB(tenantId, id) if err == nil { if entityOnDb.ApplicationType != appType { @@ -358,7 +343,7 @@ func GetFirmwareRuleByTypeNamesHandler(w http.ResponseWriter, r *http.Request) { } nameMap := make(map[string]string) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := firmware.GetFirmwareRuleAllAsListDBForAdmin(tenantId) for _, v := range dbrules { if v.Type == givenType && appType == v.ApplicationType { @@ -382,6 +367,11 @@ func GetFirmwareRuleByTemplateNamesHandler(w http.ResponseWriter, r *http.Reques // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 func GetFirmwareRuleByTemplateByTemplateIdNamesHandler(w http.ResponseWriter, r *http.Request) { + appType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } muxVarTemplateId := "templateId" templateId, found := mux.Vars(r)[muxVarTemplateId] if !found { @@ -389,12 +379,9 @@ func GetFirmwareRuleByTemplateByTemplateIdNamesHandler(w http.ResponseWriter, r xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, errorStr) return } + tenantId := xhttp.GetTenantId(r) - filterContext, err := populateContext(w, r, true) - if err != nil { - xhttp.AdminError(w, err) - return - } + filterContext := populateContext(r, tenantId, appType) dbrules, err := firmware.GetFirmwareRuleAllAsListDBForAdmin(filterContext[common.TENANT_ID]) if err != nil { @@ -421,6 +408,12 @@ func GetFirmwareRuleByTemplateByTemplateIdNamesHandler(w http.ResponseWriter, r // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 // /firmwarerule/export/byType?exportAll&type=applicableActionType func GetFirmwareRuleExportByTypeHandler(w http.ResponseWriter, r *http.Request) { + appType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + tenantId := xhttp.GetTenantId(r) queryParams := r.URL.Query() _, ok := queryParams[xcommon.EXPORTALL] if ok { @@ -433,18 +426,12 @@ func GetFirmwareRuleExportByTypeHandler(w http.ResponseWriter, r *http.Request) xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Missing type param") return } - filterContext, err := populateContext(w, r, true) - if err != nil { - xhttp.AdminError(w, err) - return - } - appType := filterContext[common.APPLICATION_TYPE] - frs, _ := firmware.GetFirmwareRuleAllAsListByApplicationTypeForAS(filterContext[common.TENANT_ID], appType) + frs, _ := firmware.GetFirmwareRuleAllAsListByApplicationTypeForAS(tenantId, appType) dbrules := []*firmware.FirmwareRule{} for _, rules := range frs { - rules = firmwareRuleFilterByActionType(filterContext[common.TENANT_ID], rules, actionType) + rules = firmwareRuleFilterByActionType(tenantId, rules, actionType) dbrules = append(dbrules, rules...) } @@ -466,19 +453,21 @@ func GetFirmwareRuleExportByTypeHandler(w http.ResponseWriter, r *http.Request) // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 func GetFirmwareRuleExportAllTypesHandler(w http.ResponseWriter, r *http.Request) { + appType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + tenantId := xhttp.GetTenantId(r) queryParams := r.URL.Query() if queryParams[xcommon.EXPORTALL] == nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Missing exportAll param") return } - filterContext, err := populateContext(w, r, true) - if err != nil { - xhttp.AdminError(w, err) - return - } + filterContext := populateContext(r, tenantId, appType) - dbrules, err := firmware.GetFirmwareRuleAllAsListDBForAdmin(filterContext[common.TENANT_ID]) + dbrules, err := firmware.GetFirmwareRuleAllAsListDBForAdmin(tenantId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -490,7 +479,7 @@ func GetFirmwareRuleExportAllTypesHandler(w http.ResponseWriter, r *http.Request xhttp.AdminError(w, err) return } - appType := filterContext[common.APPLICATION_TYPE] + headers := xhttp.CreateContentDispositionHeader(xcommon.ExportFileNames_ALL_FIRMWARE_RULES + "_" + appType) xwhttp.WriteXconfResponseWithHeaders(w, headers, http.StatusOK, res) } @@ -611,7 +600,7 @@ func PostPutFirmwareRuleEntitiesHandler(w http.ResponseWriter, r *http.Request, nameMap := make(map[string][]*firmware.FirmwareRule) ruleMap := make(map[string][]*firmware.FirmwareRule) estbMap := make(map[string][]*firmware.FirmwareRule) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) list, err := firmware.GetFirmwareRuleAllAsListDBForAdmin(tenantId) if err != nil { @@ -712,11 +701,13 @@ func PostPutFirmwareRuleEntitiesHandler(w http.ResponseWriter, r *http.Request, // Zero Usage pattern from green splunk for 4 weeks ending 23rd Oct 2021 func ObsoleteGetFirmwareRulePageHandler(w http.ResponseWriter, r *http.Request) { - filterContext, err := populateContext(w, r, true) + appType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) if err != nil { xhttp.AdminError(w, err) return } + tenantId := xhttp.GetTenantId(r) + filterContext := populateContext(r, tenantId, appType) // Get all sorted rules dbrules, err := firmware.GetFirmwareSortedRuleAllAsListDB(filterContext[common.TENANT_ID]) @@ -753,7 +744,7 @@ func GetFirmwareRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := xfirmware.GetFirmwareSortedRuleAllAsListDB(tenantId) filtRules := []*firmware.FirmwareRule{} @@ -799,7 +790,7 @@ func GetFirmwareRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fr, _ := firmware.GetFirmwareRuleOneDB(tenantId, id) if fr == nil { errorStr := fmt.Sprintf("%v not found", id) diff --git a/adminapi/queries/firmware_rule_report_page_handler.go b/adminapi/queries/firmware_rule_report_page_handler.go index 0ae12ac..e149a9c 100644 --- a/adminapi/queries/firmware_rule_report_page_handler.go +++ b/adminapi/queries/firmware_rule_report_page_handler.go @@ -56,7 +56,7 @@ func PostFirmwareRuleReportPageHandler(w http.ResponseWriter, r *http.Request) { header["Content-Disposition"] = "attachment; filename=filename=report.xls" header["Content-Type"] = "application/vnd.ms-excel" - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macRules, _ := db.GetSimpleDao().GetAllByKeys(tenantId, db.TABLE_FIRMWARE_RULES, macRuleIds) macIds := getMacAddresses(tenantId, macRules) reportBytes, err := doReport(tenantId, macIds) diff --git a/adminapi/queries/firmware_rule_template_handler.go b/adminapi/queries/firmware_rule_template_handler.go index 7269628..8a6b443 100644 --- a/adminapi/queries/firmware_rule_template_handler.go +++ b/adminapi/queries/firmware_rule_template_handler.go @@ -49,7 +49,7 @@ func GetFirmwareRuleTemplateFilteredHandler(w http.ResponseWriter, r *http.Reque util.AddQueryParamsToContextMap(r, filterContext) var err error - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allTemplates, err := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -110,7 +110,7 @@ func PostFirmwareRuleTemplateFilteredHandler(w http.ResponseWriter, r *http.Requ } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) allTemplates, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(allTemplates, func(i, j int) bool { return strings.Compare(strings.ToLower(allTemplates[i].ID), strings.ToLower(allTemplates[j].ID)) < 0 @@ -196,7 +196,7 @@ func PostFirmwareRuleTemplateImportAllHandler(w http.ResponseWriter, r *http.Req db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -260,7 +260,7 @@ func PostFirmwareRuleTemplateImportHandler(w http.ResponseWriter, r *http.Reques db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -330,7 +330,7 @@ func PostChangePriorityHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) frt, err := corefw.GetFirmwareRuleTemplateOneDB(tenantId, templateId) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("unable to find template with id %s", templateId)) @@ -410,7 +410,7 @@ func PostFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -467,7 +467,7 @@ func PutFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -512,7 +512,7 @@ func DeleteFirmwareRuleTemplateByIdHandler(w http.ResponseWriter, r *http.Reques return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) // Check for usage in FirmwareRule rules, err := corefw.GetFirmwareRuleAllAsListDBForAdmin(tenantId) @@ -611,7 +611,7 @@ func GetFirmwareRuleTemplateByIdHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) frt := GetFirmwareRuleTemplateById(tenantId, id) if frt == nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("unable to find FirmwareRuleTemplate with id : %v", id)) @@ -668,7 +668,7 @@ func PostFirmwareRuleTemplateEntitiesHandler(w http.ResponseWriter, r *http.Requ db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -744,7 +744,7 @@ func PutFirmwareRuleTemplateEntitiesHandler(w http.ResponseWriter, r *http.Reque db.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := fwRuleTemplateTableLock.Lock(tenantId, owner); err != nil { @@ -795,7 +795,7 @@ func ObsoleteGetFirmwareRuleTemplatePageHandler(w http.ResponseWriter, r *http.R pageContext := map[string]string{} util.AddQueryParamsToContextMap(r, pageContext) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(dbrules, func(i, j int) bool { return strings.Compare(strings.ToLower(dbrules[i].ID), strings.ToLower(dbrules[j].ID)) < 0 @@ -821,7 +821,7 @@ func GetFirmwareRuleTemplateHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") sort.Slice(dbrules, func(i, j int) bool { return strings.Compare(strings.ToLower(dbrules[i].ID), strings.ToLower(dbrules[j].ID)) < 0 @@ -855,7 +855,7 @@ func GetFirmwareRuleTemplateAllByTypeHandler(w http.ResponseWriter, r *http.Requ return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []corefw.FirmwareRuleTemplate{} for _, v := range dbrules { @@ -883,7 +883,7 @@ func GetFirmwareRuleTemplateIdsHandler(w http.ResponseWriter, r *http.Request) { applicableActionTypes, ok := queryParams[xcommon.TYPE] if ok { applicableActionType := applicableActionTypes[0] - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []string{} for _, v := range dbrules { @@ -925,7 +925,7 @@ func GetFirmwareRuleTemplateWithVarWithVarHandler(w http.ResponseWriter, r *http if editVar == "true" { editable = true } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) dbrules, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") tempIds := []corefw.FirmwareRuleTemplate{} for _, v := range dbrules { @@ -951,7 +951,7 @@ func GetFirmwareRuleTemplateExportHandler(w http.ResponseWriter, r *http.Request } queryParams := r.URL.Query() actionTypes, ok := queryParams[xcommon.TYPE] - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if ok { actionType := actionTypes[0] entities, _ := corefw.GetFirmwareRuleTemplateAllAsListDBForAS(tenantId, "") diff --git a/adminapi/queries/log_controller.go b/adminapi/queries/log_controller.go index eb18824..c22fd4b 100644 --- a/adminapi/queries/log_controller.go +++ b/adminapi/queries/log_controller.go @@ -49,7 +49,7 @@ func GetLogs(w http.ResponseWriter, r *http.Request) { } result := make(map[string]interface{}, 2) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) last := estbfirmware.GetLastConfigLog(tenantId, macAddress) //*ConfigChangeLog if last != nil { configChangeLogList := estbfirmware.GetConfigChangeLogsOnly(tenantId, macAddress) //[]*ConfigChangeLog diff --git a/adminapi/queries/log_file_handler.go b/adminapi/queries/log_file_handler.go index 38dedd5..723ebc4 100644 --- a/adminapi/queries/log_file_handler.go +++ b/adminapi/queries/log_file_handler.go @@ -59,7 +59,7 @@ func CreateLogFile(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if !isValidName(tenantId, logFile) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is already used") return diff --git a/adminapi/queries/log_upload_settings_handler.go b/adminapi/queries/log_upload_settings_handler.go index 1788cde..db88bac 100644 --- a/adminapi/queries/log_upload_settings_handler.go +++ b/adminapi/queries/log_upload_settings_handler.go @@ -119,7 +119,7 @@ func SaveLogUploadSettings(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) nameErrorMessage := validateName(tenantId, &logUploadSettings) if nameErrorMessage != "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, nameErrorMessage) diff --git a/adminapi/queries/model_handler.go b/adminapi/queries/model_handler.go index 61e7d45..9170209 100644 --- a/adminapi/queries/model_handler.go +++ b/adminapi/queries/model_handler.go @@ -57,7 +57,7 @@ func PostModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -99,7 +99,7 @@ func PutModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, response) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -129,7 +129,7 @@ func ObsoleteGetModelPageHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entries := shared.GetAllModelList(tenantId) sort.Slice(entries, func(i, j int) bool { return strings.Compare(strings.ToLower(entries[i].ID), strings.ToLower(entries[j].ID)) < 0 @@ -183,7 +183,7 @@ func PostModelFilteredHandler(w http.ResponseWriter, r *http.Request) { } // Get all entries and sort them - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entries := shared.GetAllModelList(tenantId) sort.Slice(entries, func(i, j int) bool { return strings.Compare(strings.ToLower(entries[i].ID), strings.ToLower(entries[j].ID)) < 0 @@ -228,7 +228,7 @@ func GetModelByIdHandler(w http.ResponseWriter, r *http.Request) { return } id = strings.ToUpper(id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) model := shared.GetOneModel(tenantId, id) if model == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -265,7 +265,7 @@ func GetModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) models := shared.GetAllModelList(tenantId) sort.Slice(models, func(i, j int) bool { return strings.Compare(strings.ToLower(models[i].ID), strings.ToLower(models[j].ID)) < 0 diff --git a/adminapi/queries/namedspace_list_handler.go b/adminapi/queries/namedspace_list_handler.go index 9a558fc..d415bd6 100644 --- a/adminapi/queries/namedspace_list_handler.go +++ b/adminapi/queries/namedspace_list_handler.go @@ -45,7 +45,7 @@ func GetQueriesIpAddressGroups(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetIpAddressGroups(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -73,7 +73,7 @@ func GetQueriesIpAddressGroupsByIp(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetIpAddressGroupsByIp(tenantId, ipAddress) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -97,7 +97,7 @@ func GetQueriesIpAddressGroupsByName(w http.ResponseWriter, r *http.Request) { } result := []*shared.IpAddressGroup{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipAddrGrp := GetIpAddressGroupByName(tenantId, name) if ipAddrGrp == nil { values, ok := r.URL.Query()[xwcommon.VERSION] @@ -141,7 +141,7 @@ func CreateIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateIpAddressGroup(tenantId, &newIpAddressGroup) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -183,7 +183,7 @@ func AddDataIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -241,7 +241,7 @@ func RemoveDataIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -279,7 +279,7 @@ func DeleteIpAddressGroupHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -314,7 +314,7 @@ func GetQueriesIpAddressGroupsV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetNamespacedListsByType(tenantId, shared.IP_LIST) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -342,7 +342,7 @@ func GetQueriesIpAddressGroupsByIpV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetNamespacedListsByIp(tenantId, ipAddress) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -365,7 +365,7 @@ func GetQueriesIpAddressGroupsByNameV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipAddrGrp := GetNamespacedListByIdAndType(tenantId, id, shared.IP_LIST) if ipAddrGrp == nil { errorStr := fmt.Sprintf("IpAddressGroup with name %s does not exist", id) @@ -402,7 +402,7 @@ func CreateIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newIpList.ID); err != nil { @@ -454,7 +454,7 @@ func UpdateIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newIpList.ID); err != nil { @@ -498,7 +498,7 @@ func DeleteIpAddressGroupHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -529,7 +529,7 @@ func GetQueriesMacLists(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetNamespacedListsByType(tenantId, shared.MAC_LIST) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -552,7 +552,7 @@ func GetQueriesMacListsById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macList := GetNamespacedListByIdAndType(tenantId, id, shared.MAC_LIST) if macList == nil { values, ok := r.URL.Query()[xwcommon.VERSION] @@ -582,7 +582,7 @@ func GetQueriesMacListsByMacPart(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) mac := mux.Vars(r)[xwcommon.MAC] result := GetMacListsByMacPart(tenantId, mac) res, err := xhttp.ReturnJsonResponse(result, r) @@ -613,7 +613,7 @@ func SaveMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -665,7 +665,7 @@ func CreateMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -716,7 +716,7 @@ func UpdateMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newMacList.ID); err != nil { @@ -774,7 +774,7 @@ func AddDataMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -832,7 +832,7 @@ func RemoveDataMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, listId); err != nil { @@ -875,7 +875,7 @@ func DeleteMacListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -917,7 +917,7 @@ func GetQueriesMacListsByIdV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macList := GetNamespacedListByIdAndType(tenantId, id, shared.MAC_LIST) if macList == nil { errorStr := fmt.Sprintf("MacList with id %s does not exist", id) @@ -946,7 +946,7 @@ func DeleteMacListHandlerV2(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -984,7 +984,7 @@ func GetNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) nsList, err := shared.GetGenericNamedListOneByTypeNonCached(tenantId, id, "") if err != nil { errorStr := fmt.Sprintf("List with id %s does not exist", id) @@ -1017,7 +1017,7 @@ func GetNamespacedListIdsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ids := GetNamespacedListIdsByType(tenantId, "") res, err := xhttp.ReturnJsonResponse(ids, r) @@ -1041,7 +1041,7 @@ func GetNamespacedListIdsByTypeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ids := GetNamespacedListIdsByType(tenantId, typeName) sortedById := func(i, j int) bool { return strings.ToLower(ids[i]) < strings.ToLower(ids[j]) @@ -1062,7 +1062,7 @@ func GetNamespacedListsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetNamespacedListsByType(tenantId, "") sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToLower(result[i].ID), strings.ToLower(result[j].ID)) < 0 @@ -1095,7 +1095,7 @@ func GetNamespacedListsByTypeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetNamespacedListsByType(tenantId, typeName) sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToLower(result[i].ID), strings.ToLower(result[j].ID)) < 0 @@ -1121,7 +1121,7 @@ func GetIpAddressGroupsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) nsLists := GetNamespacedListsByType(tenantId, shared.IP_LIST) result := covt.ConvertToListOfIpAddressGroups(nsLists) res, err := xhttp.ReturnJsonResponse(result, r) @@ -1153,7 +1153,7 @@ func CreateNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, newNamespacedListList.ID); err != nil { @@ -1205,7 +1205,7 @@ func UpdateNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, namespacedListList.ID); err != nil { @@ -1264,7 +1264,7 @@ func RenameNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -1308,7 +1308,7 @@ func DeleteNamespacedListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if xhttp.WebConfServer.DistributedLockConfig.Enabled { owner := auth.GetDistributedLockOwner(r) if err := namedListTableLock.LockRow(tenantId, owner, id); err != nil { @@ -1368,7 +1368,7 @@ func PostNamespacedListFilteredHandler(w http.ResponseWriter, r *http.Request) { } } util.AddQueryParamsToContextMap(r, contextMap) - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) nsLists := GetNamespacedListsByContext(contextMap) sort.Slice(nsLists, func(i, j int) bool { @@ -1407,7 +1407,7 @@ func PostNamespacedListEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) owner := auth.GetDistributedLockOwner(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, e := range entities { @@ -1472,7 +1472,7 @@ func PutNamespacedListEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) owner := auth.GetDistributedLockOwner(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, e := range entities { diff --git a/adminapi/queries/percentagebean_handler.go b/adminapi/queries/percentagebean_handler.go index 1b21a08..fd7be2a 100644 --- a/adminapi/queries/percentagebean_handler.go +++ b/adminapi/queries/percentagebean_handler.go @@ -47,18 +47,19 @@ const ( ) func GetPercentageBeanAllHandler(w http.ResponseWriter, r *http.Request) { - contextMap := make(map[string]string) - applicationType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) if err != nil { xhttp.AdminError(w, err) return } + + contextMap := make(map[string]string) + util.AddQueryParamsToContextMap(r, contextMap) var result interface{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err = GetAllPercentageBeansFromDB(tenantId, applicationType, true, false) if err != nil { @@ -102,7 +103,7 @@ func GetPercentageBeanByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) bean, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Entity with id: "+id+" does not exist") @@ -141,17 +142,18 @@ func DeletePercentageBeanByIdHandler(w http.ResponseWriter, r *http.Request) { } func GetAllPercentageBeanAsRule(w http.ResponseWriter, r *http.Request) { - contextMap := make(map[string]string) applicationType, err := auth.CanRead(r, auth.FIRMWARE_ENTITY) if err != nil { xhttp.AdminError(w, err) return } + contextMap := make(map[string]string) + util.AddQueryParamsToContextMap(r, contextMap) var result []*firmware.FirmwareRule - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err = GetAllGlobalPercentageBeansAsRuleFromDB(tenantId, applicationType, true) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, err.Error()) @@ -186,7 +188,7 @@ func GetPercentageBeanAsRuleById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fwRule, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "\"

404 NOT FOUND

\"") @@ -232,7 +234,7 @@ func PostPercentageBeanEntitiesHandler(w http.ResponseWriter, r *http.Request) { fields := xw.Audit() entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity respEntity := CreatePercentageBean(tenantId, &entity, applicationType, fields) @@ -277,7 +279,7 @@ func PutPercentageBeanEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity respEntity := UpdatePercentageBean(tenantId, &entity, applicationType, fields) @@ -323,7 +325,7 @@ func PostPercentageBeanFilteredWithParamsHandler(w http.ResponseWriter, r *http. } util.AddQueryParamsToContextMap(r, contextMap) contextMap[common.APPLICATION_TYPE] = applicationType - contextMap[common.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[common.TENANT_ID] = xhttp.GetTenantId(r) pbrules := PercentageBeanFilterByContext(contextMap, applicationType) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(pbrules)) @@ -368,7 +370,7 @@ func CreateWakeupPoolHandler(w http.ResponseWriter, r *http.Request) { log.WithFields(fields).Infof("Received request to create wakeup pool. force=%v", force) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err := CreateWakeupPoolList(tenantId, shared.STB, force, fields) if err != nil { xhttp.WriteXconfErrorResponse(w, err) diff --git a/adminapi/queries/percentfilter_handler.go b/adminapi/queries/percentfilter_handler.go index 0d0193c..c0339e8 100644 --- a/adminapi/queries/percentfilter_handler.go +++ b/adminapi/queries/percentfilter_handler.go @@ -110,7 +110,7 @@ func UpdatePercentFilterGlobalHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdatePercentFilterGlobal(tenantId, applicationType, globalPercentage) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -148,7 +148,7 @@ func GetPercentFilterGlobalHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) globalpercent, err := GetPercentFilterGlobal(tenantId, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("unable to get globalpercent reponse. error: %v", err)) @@ -209,7 +209,7 @@ func GetGlobalPercentFilterHandler(w http.ResponseWriter, r *http.Request) { contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) globalpercent, err := GetGlobalPercentFilter(tenantId, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("unable to get globalpercent reponse. error: %v", err)) @@ -295,7 +295,7 @@ func GetGlobalPercentFilterAsRuleHandler(w http.ResponseWriter, r *http.Request) contextMap := make(map[string]string) xutil.AddQueryParamsToContextMap(r, contextMap) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) globalpercentasrule, err := GetGlobalPercentFilterAsRule(tenantId, applicationType) if err != nil { globalPercentage := coreef.NewGlobalPercentage() diff --git a/adminapi/queries/queries_handler.go b/adminapi/queries/queries_handler.go index d66a565..003b7e8 100644 --- a/adminapi/queries/queries_handler.go +++ b/adminapi/queries/queries_handler.go @@ -61,7 +61,7 @@ func GetQueriesPercentageBean(w http.ResponseWriter, r *http.Request) { var result interface{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fieldName, found := contextMap[xcommon.FIELD] if found { result, err = GetPercentageBeanFilterFieldValues(tenantId, fieldName, applicationType) @@ -109,7 +109,7 @@ func GetQueriesPercentageBeanById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) bean, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Entity with id: "+id+" does not exist") @@ -154,7 +154,7 @@ func CreatePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { percentageBean.ApplicationType = applicationType } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreatePercentageBean(tenantId, percentageBean, applicationType, fields) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -191,7 +191,7 @@ func UpdatePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdatePercentageBean(tenantId, percentageBean, applicationType, fields) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -225,7 +225,7 @@ func DeletePercentageBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeletePercentageBean(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -240,7 +240,7 @@ func GetQueriesEnvironments(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := shared.GetAllEnvironmentList(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -272,7 +272,7 @@ func GetQueriesEnvironmentsById(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) env := GetEnvironment(tenantId, id) if env == nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "Environment does not exist") @@ -322,7 +322,7 @@ func CreateEnvironmentHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateEnvironment(tenantId, &newEnv) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -351,7 +351,7 @@ func DeleteEnvironmentHandler(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteEnvironment(tenantId, id) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -366,7 +366,7 @@ func GetQueriesModels(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetModels(tenantId) res, err := xhttp.ReturnJsonResponse(result, r) if err != nil { @@ -390,7 +390,7 @@ func GetQueriesModelsById(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) model := GetModel(tenantId, id) if model == nil { values, ok := r.URL.Query()[xcommon.VERSION] @@ -433,7 +433,7 @@ func CreateModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateModel(tenantId, &newModel) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -468,7 +468,7 @@ func UpdateModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateModel(tenantId, &newModel) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -497,7 +497,7 @@ func DeleteModelHandler(w http.ResponseWriter, r *http.Request) { } id = strings.ToUpper(id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteModel(tenantId, id) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -507,7 +507,7 @@ func DeleteModelHandler(w http.ResponseWriter, r *http.Request) { } func getQueriesFirmwareConfigsASFlavor(w http.ResponseWriter, r *http.Request, app string) { - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result := GetFirmwareConfigsAS(tenantId, app) sort.Slice(result, func(i, j int) bool { return strings.Compare(strings.ToUpper(result[i].Description), strings.ToUpper(result[j].Description)) < 0 @@ -535,7 +535,7 @@ func GetQueriesFirmwareConfigsById(w http.ResponseWriter, r *http.Request) { } errorStr := fmt.Sprintf("\"FirmwareConfig with id %s does not exist\"", id) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fc := GetFirmwareConfigByIdAS(tenantId, id) if fc == nil { values, ok := r.URL.Query()[xcommon.VERSION] @@ -579,7 +579,7 @@ func GetQueriesFirmwareConfigsByIdASFlavor(w http.ResponseWriter, r *http.Reques return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) firmwareConfig := GetFirmwareConfigByIdAS(tenantId, id) if firmwareConfig != nil { res, err := xhttp.ReturnJsonResponse(firmwareConfig, r) @@ -621,7 +621,7 @@ func GetQueriesFirmwareConfigsByModelId(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) model := shared.GetOneModel(tenantId, modelId) if model == nil { errorStr := fmt.Sprintf("%v not found", modelId) @@ -652,7 +652,7 @@ func GetQueriesFirmwareConfigsByModelIdASFlavor(w http.ResponseWriter, r *http.R return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) model := shared.GetOneModel(tenantId, modelId) if model == nil { errorStr := fmt.Sprintf("%v not found", modelId) @@ -695,7 +695,7 @@ func CreateFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateFirmwareConfig(tenantId, firmwareConfig, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -736,7 +736,7 @@ func UpdateFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateFirmwareConfig(tenantId, firmwareConfig, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -762,7 +762,7 @@ func DeleteFirmwareConfigHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteFirmwareConfig(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -784,7 +784,7 @@ func DeleteFirmwareConfigHandlerASFlavor(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteFirmwareConfig(tenantId, id, appType) status := respEntity.Status err = respEntity.Error @@ -804,7 +804,7 @@ func GetQueriesRulesIps(w http.ResponseWriter, r *http.Request) { } ipRuleService := daef.IpRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) ipRuleBeansResponse := []*IpRuleBeanResponse{} for _, ipRuleBean := range ipRuleBeans { @@ -834,7 +834,7 @@ func GetQueriesRulesMacs(w http.ResponseWriter, r *http.Request) { } macRuleService := daef.MacRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macRuleBeans := macRuleService.GetRulesWithMacCondition(tenantId, applicationType) macRuleBeansResponse := []*MacRuleBeanResponse{} for _, macRuleBean := range macRuleBeans { @@ -861,7 +861,7 @@ func GetQueriesRulesEnvModels(w http.ResponseWriter, r *http.Request) { } emRuleService := daef.EnvModelRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) envModelRulesResponse := []*EnvModelRuleBeanResponse{} for _, emRuleBean := range emRuleBeans { @@ -886,7 +886,7 @@ func GetQueriesFiltersDownloadLocation(w http.ResponseWriter, r *http.Request) { id := xcoreef.GetRoundRobinIdByApplication(applicationType) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) singletonFilterValue, err := coreef.GetDownloadLocationRoundRobinFilterValOneDB(tenantId, id) if err != nil { log.Errorf("unable to get singleton filter value. error: %+v", err) @@ -911,7 +911,7 @@ func UpdateDownloadLocationFilterHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateDownloadLocationRoundRobinFilter(tenantId, applicationType, locationRoundRobinFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -933,7 +933,7 @@ func GetQueriesFiltersIps(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.IpFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -960,7 +960,7 @@ func GetQueriesFiltersIpsByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.IpFilterByName(tenantId, name, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1000,7 +1000,7 @@ func UpdateIpsFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateIpFilter(tenantId, applicationType, ipFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1028,7 +1028,7 @@ func DeleteIpsFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteIpsFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1044,7 +1044,7 @@ func GetQueriesFiltersTime(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.TimeFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1071,7 +1071,7 @@ func GetQueriesFiltersTimeByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.TimeFilterByName(tenantId, name, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1106,7 +1106,7 @@ func UpdateTimeFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateTimeFilter(tenantId, applicationType, timeFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1134,7 +1134,7 @@ func DeleteTimeFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteTimeFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1150,7 +1150,7 @@ func GetQueriesFiltersLocation(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.DownloadLocationFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1177,7 +1177,7 @@ func GetQueriesFiltersLocationByName(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.DownloadLocationFiltersByName(tenantId, applicationType, name) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1225,7 +1225,7 @@ func UpdateLocationFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateLocationFilter(tenantId, applicationType, &locationFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1253,7 +1253,7 @@ func DeleteLocationFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteLocationFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1273,7 +1273,7 @@ func GetQueriesFiltersPercent(w http.ResponseWriter, r *http.Request) { xutil.AddQueryParamsToContextMap(r, contextMap) var result interface{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) fieldName, found := contextMap[xcommon.FIELD] if found { result, err = GetPercentFilterFieldValues(tenantId, fieldName, applicationType) @@ -1323,7 +1323,7 @@ func UpdatePercentFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdatePercentFilter(tenantId, applicationType, percentFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1345,7 +1345,7 @@ func GetQueriesFiltersRebootImmediately(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := coreef.RebootImmediatelyFiltersByApplicationType(tenantId, applicationType) if err != nil { log.Errorf("unable to get reboot immediately filter value. error: %+v", err) @@ -1372,7 +1372,7 @@ func GetQueriesFiltersRebootImmediatelyByName(w http.ResponseWriter, r *http.Req return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) result, err := xcoreef.RebootImmediatelyFiltersByName(tenantId, applicationType, name) if err != nil { log.Errorf("unable to get ip filter value. error: %+v", err) @@ -1407,7 +1407,7 @@ func UpdateRebootImmediatelyHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateRebootImmediatelyFilter(tenantId, applicationType, rebootFilter) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1435,7 +1435,7 @@ func DeleteRebootImmediatelyHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteRebootImmediatelyFilter(tenantId, name, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -1453,7 +1453,7 @@ func GetRoundRobinFilterHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) id := xcoreef.GetRoundRobinIdByApplication(applicationType) singletonFilterValue, err := coreef.GetDownloadLocationRoundRobinFilterValOneDB(tenantId, id) if err != nil { @@ -1506,7 +1506,7 @@ func GetIpRuleById(w http.ResponseWriter, r *http.Request) { var ipRuleBean *coreef.IpRuleBean ipRuleService := daef.IpRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.Name == ruleName { @@ -1552,7 +1552,7 @@ func GetIpRuleByIpAddressGroup(w http.ResponseWriter, r *http.Request) { ipRules := []*IpRuleBeanResponse{} ipRuleService := daef.IpRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.IpAddressGroup != nil && ipAddressGroupName == bean.IpAddressGroup.Name { @@ -1591,7 +1591,7 @@ func UpdateIpRule(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipRuleBean_origin := ipRuleBean if ipRuleBean.Name == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is empty") @@ -1711,7 +1711,7 @@ func GetMACRuleByName(w http.ResponseWriter, r *http.Request) { var macRuleBean *coreef.MacRuleBean macRuleService := daef.MacRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macRuleBeans := macRuleService.GetRulesWithMacCondition(tenantId, applicationType) for _, mrBean := range macRuleBeans { if mrBean.Name == ruleName { @@ -1759,7 +1759,7 @@ func GetMACRulesByMAC(w http.ResponseWriter, r *http.Request) { result := []*coreef.MacRuleBeanResponse{} if util.IsValidMacAddress(macAddress) { macRuleService := daef.MacRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macRuleBeans := macRuleService.SearchMacRules(tenantId, macAddress, applicationType) for _, macRule := range macRuleBeans { macRule = wrap(tenantId, macRule, apiVersion) @@ -1826,7 +1826,7 @@ func SaveMACRule(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "MAC address list is empty or blank") return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if err := corefw.ValidateRuleName(tenantId, macRule.Id, macRule.Name, applicationType); err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -1954,7 +1954,7 @@ func DeleteMACRule(w http.ResponseWriter, r *http.Request) { var macRuleBean *coreef.MacRuleBean macRuleService := daef.MacRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) macRuleBeans := macRuleService.GetByApplicationType(tenantId, applicationType) for _, mrBean := range macRuleBeans { if mrBean.Name == name { @@ -1991,7 +1991,7 @@ func GetEnvModelRuleByNameHandler(w http.ResponseWriter, r *http.Request) { var envModelRule *coreef.EnvModelBean emRuleService := daef.EnvModelRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) for _, emRuleBean := range emRuleBeans { if strings.EqualFold(emRuleBean.Name, name) { @@ -2043,7 +2043,7 @@ func UpdateEnvModelRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if envModelRuleBean.Name == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Name is empty") return @@ -2133,7 +2133,7 @@ func DeleteEnvModelRuleBeanHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) emRuleService := daef.EnvModelRuleService{} emRuleBeans := emRuleService.GetByApplicationType(tenantId, applicationType) for _, emRuleBean := range emRuleBeans { @@ -2169,7 +2169,7 @@ func DeleteIpRule(w http.ResponseWriter, r *http.Request) { var ipRuleBean *coreef.IpRuleBean ipRuleService := daef.IpRuleService{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ipRuleBeans := ipRuleService.GetByApplicationType(tenantId, applicationType) for _, bean := range ipRuleBeans { if bean.Name == name { diff --git a/adminapi/rfc/feature/feature_handler.go b/adminapi/rfc/feature/feature_handler.go index 9eda2d2..95dd49f 100644 --- a/adminapi/rfc/feature/feature_handler.go +++ b/adminapi/rfc/feature/feature_handler.go @@ -52,7 +52,7 @@ func GetFeaturesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) _, isExport := r.URL.Query()["export"] if isExport { featureEntityList := GetFeatureEntityListByApplicationTypeSorted(tenantId, applicationType) @@ -80,7 +80,7 @@ func GetFeatureByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) _, isExport := r.URL.Query()["export"] if isExport { featureEntity := GetFeatureEntityById(tenantId, id) @@ -125,7 +125,7 @@ func DeleteFeatureByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) if !xrfc.DoesFeatureExistWithApplicationType(tenantId, id, applicationType) { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, fmt.Sprintf("Entity with id: %s does not exist", id)) return @@ -159,7 +159,7 @@ func PutFeatureEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := ImportFeatureEntities(tenantId, featureEntityList, true, applicationType) response, _ := util.XConfJSONMarshal(entitiesMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) @@ -185,7 +185,7 @@ func PostFeatureEntitiesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := ImportFeatureEntities(tenantId, featureEntityList, false, applicationType) response, _ := util.XConfJSONMarshal(entitiesMap, true) xwhttp.WriteXconfResponse(w, http.StatusOK, []byte(response)) @@ -210,7 +210,7 @@ func PostFeatureHandler(w http.ResponseWriter, r *http.Request) { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) feature := featureEntity.CreateFeature() if xrfc.DoesFeatureExist(tenantId, feature.ID) { @@ -260,7 +260,7 @@ func PutFeatureHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) feature := featureEntity.CreateFeature() if feature.ID == "" { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "Entity id is empty") @@ -326,7 +326,7 @@ func GetFeaturesFilteredHandler(w http.ResponseWriter, r *http.Request) { } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) features := GetFeatureFiltered(contextMap) sort.SliceStable(features, func(i, j int) bool { @@ -357,7 +357,7 @@ func GetFeaturesByIdListHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) features := GetFeaturesByIdList(tenantId, featureIdList) response, _ := util.JSONMarshal(features) xwhttp.WriteXconfResponse(w, http.StatusOK, response) diff --git a/adminapi/setting/setting_profile_controller.go b/adminapi/setting/setting_profile_controller.go index 2f74696..67fa5e8 100644 --- a/adminapi/setting/setting_profile_controller.go +++ b/adminapi/setting/setting_profile_controller.go @@ -54,7 +54,7 @@ func GetSettingProfilesAllExport(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) all := GetAllForTenant(tenantId) settingProfiles := []*logupload.SettingProfiles{} for _, entity := range all { @@ -87,7 +87,7 @@ func GetSettingProfileOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) settingProfile, _ := GetOne(tenantId, id) if settingProfile == nil { invalid := "Entity with id: " + id + " does not exist" @@ -136,7 +136,7 @@ func GetAllSettingProfilesWithPage(w http.ResponseWriter, r *http.Request) { return } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) settingProfiles := GetAllForTenant(tenantId) featureRuleList := SettingProfilesGeneratePage(settingProfiles, pageNumber, pageSize) response, err := util.JSONMarshal(featureRuleList) @@ -170,7 +170,7 @@ func DeleteOneSettingProfilesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) _, err = Delete(tenantId, id, applicationType) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, err.Error()) @@ -220,7 +220,7 @@ func GetSettingProfilesFilteredWithPage(w http.ResponseWriter, r *http.Request) } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) settingProfiles := FindByContext(contextMap) sort.Slice(settingProfiles, func(i, j int) bool { @@ -258,7 +258,7 @@ func CreateSettingProfileHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = Create(tenantId, &settingProfiles, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -293,7 +293,7 @@ func CreateSettingProfilesPackageHandler(w http.ResponseWriter, r *http.Request) } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -340,7 +340,7 @@ func UpdateSettingProfilesHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = Update(tenantId, &settingProfiles, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -372,7 +372,7 @@ func UpdateSettingProfilesPackageHandler(w http.ResponseWriter, r *http.Request) return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity diff --git a/adminapi/setting/setting_rule_controller.go b/adminapi/setting/setting_rule_controller.go index 4820e3a..d15771b 100644 --- a/adminapi/setting/setting_rule_controller.go +++ b/adminapi/setting/setting_rule_controller.go @@ -50,7 +50,7 @@ func GetSettingRulesAllExport(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) all := GetAllSettingRules(tenantId) settingRules := []*logupload.SettingRule{} for _, entity := range all { @@ -82,7 +82,7 @@ func GetSettingRuleOneExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) settingRule, _ := GetOneSettingRule(tenantId, id) if settingRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -121,7 +121,7 @@ func DeleteOneSettingRulesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) _, err = DeleteSettingRule(tenantId, id, applicationType) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) @@ -170,7 +170,7 @@ func GetSettingRulesFilteredWithPage(w http.ResponseWriter, r *http.Request) { } } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) settingRules := FindByContextSettingRule(contextMap) sort.Slice(settingRules, func(i, j int) bool { @@ -207,7 +207,7 @@ func CreateSettingRuleHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = CreateSettingRule(tenantId, applicationType, &settingRules) if err != nil { xhttp.AdminError(w, err) @@ -239,7 +239,7 @@ func CreateSettingRulesPackageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -285,7 +285,7 @@ func UpdateSettingRulesHandler(w http.ResponseWriter, r *http.Request) { } } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = UpdateSettingRule(tenantId, applicationType, &settingRules) if err != nil { xhttp.AdminError(w, err) @@ -316,7 +316,7 @@ func UpdateSettingRulesPackageHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -384,7 +384,7 @@ func SettingTestPageHandler(w http.ResponseWriter, r *http.Request) { return } contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) result := make(map[string]interface{}) result["result"] = GetSettingRulesWithConfig(settingTypes, contextMap) diff --git a/adminapi/telemetry/telemetry_profile_controller.go b/adminapi/telemetry/telemetry_profile_controller.go index 1501b3c..1291254 100644 --- a/adminapi/telemetry/telemetry_profile_controller.go +++ b/adminapi/telemetry/telemetry_profile_controller.go @@ -28,8 +28,6 @@ import ( "github.com/rdkcentral/xconfwebconfig/dataapi/dcm/telemetry" - xcommon "github.com/rdkcentral/xconfadmin/common" - "github.com/rdkcentral/xconfadmin/shared" xlogupload "github.com/rdkcentral/xconfadmin/shared/logupload" @@ -94,7 +92,7 @@ func CreateTelemetryEntryFor(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) timestampedRule := CreateTelemetryProfile(tenantId, contextAttributeName, expectedValue, &telemetryProfile) response, err := util.JSONMarshal(timestampedRule) if err != nil { @@ -120,7 +118,7 @@ func DropTelemetryEntryFor(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) telemetryProfileList := DropTelemetryFor(tenantId, contextAttributeName, expectedValue) response, err := util.JSONMarshal(telemetryProfileList) if err != nil { @@ -144,7 +142,7 @@ func GetDescriptors(w http.ResponseWriter, r *http.Request) { } applicationType, _ := contextMap[xwcommon.APPLICATION_TYPE] - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) descriptors := GetAvailableDescriptors(tenantId, applicationType) response, err := util.JSONMarshal(descriptors) if err != nil { @@ -168,7 +166,7 @@ func GetTelemetryDescriptors(w http.ResponseWriter, r *http.Request) { } applicationType, _ := contextMap[xwcommon.APPLICATION_TYPE] - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) descriptors := GetAvailableProfileDescriptors(tenantId, applicationType) response, err := util.JSONMarshal(descriptors) if err != nil { @@ -213,7 +211,7 @@ func TempAddToPermanentRule(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) telemetryRule := xlogupload.GetOneTelemetryRule(tenantId, ruleId) //*TelemetryRule if telemetryRule == nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("no rule found for ruleId")) @@ -281,7 +279,7 @@ func BindToTelemetry(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) profile := xlogupload.GetOnePermanentTelemetryProfile(tenantId, telemetryId) //*PermanentTelemetryProfile if profile == nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("no rule found for ID "+telemetryId+" provided")) @@ -300,6 +298,11 @@ func BindToTelemetry(w http.ResponseWriter, r *http.Request) { } func TelemetryTestPageHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanRead(r, auth.TELEMETRY_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("Unable to extract body")) @@ -308,7 +311,6 @@ func TelemetryTestPageHandler(w http.ResponseWriter, r *http.Request) { body := xw.Body() contextMap := make(map[string]string) - var err error if body != "" { err = json.Unmarshal([]byte(body), &contextMap) if err != nil { @@ -323,14 +325,8 @@ func TelemetryTestPageHandler(w http.ResponseWriter, r *http.Request) { return } - applicationType, err := auth.CanRead(r, auth.TELEMETRY_ENTITY) - if err != nil { - xhttp.WriteAdminErrorResponse(w, err.(xcommon.XconfError).StatusCode, err.Error()) - return - } - contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) result := make(map[string]interface{}) result["context"] = contextMap diff --git a/adminapi/telemetry/telemetry_rule_handler.go b/adminapi/telemetry/telemetry_rule_handler.go index 79b7f91..6a7fcd5 100644 --- a/adminapi/telemetry/telemetry_rule_handler.go +++ b/adminapi/telemetry/telemetry_rule_handler.go @@ -46,7 +46,7 @@ func GetTelemetryRulesHandler(w http.ResponseWriter, r *http.Request) { } result := []*xwlogupload.TelemetryRule{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) ruleList := xwlogupload.GetTelemetryRuleListForAs(tenantId) for _, teleRule := range ruleList { if teleRule.ApplicationType != applicationType { @@ -83,7 +83,7 @@ func GetTelemetryRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) teleRule := xlogupload.GetOneTelemetryRule(tenantId, id) if teleRule == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -131,7 +131,7 @@ func DeleteTelmetryRuleByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := DeleteTelemetryRulebyId(tenantId, id, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -161,7 +161,7 @@ func CreateTelemetryRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := CreateTelemetryRule(tenantId, &newtmrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -198,7 +198,7 @@ func UpdateTelemetryRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) respEntity := UpdateTelemetryRule(tenantId, &newtmrule, applicationType) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -234,7 +234,7 @@ func PostTelemtryRuleEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity respEntity := CreateTelemetryRule(tenantId, &entity, applicationType) @@ -278,7 +278,7 @@ func PutTelemetryRuleEntitiesHandler(w http.ResponseWriter, r *http.Request) { } entitiesMap := map[string]xhttp.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity respEntity := UpdateTelemetryRule(tenantId, &entity, applicationType) @@ -325,7 +325,7 @@ func PostTelemetryRuleFilteredWithParamsHandler(w http.ResponseWriter, r *http.R } xutil.AddQueryParamsToContextMap(r, contextMap) contextMap[xwcommon.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) tmrules := TelemetryRuleFilterByContext(contextMap) sizeHeader := xhttp.CreateNumberOfItemsHttpHeaders(len(tmrules)) diff --git a/adminapi/telemetry/telemetry_v2_rule_handler.go b/adminapi/telemetry/telemetry_v2_rule_handler.go index 8ba7310..0da4688 100644 --- a/adminapi/telemetry/telemetry_v2_rule_handler.go +++ b/adminapi/telemetry/telemetry_v2_rule_handler.go @@ -53,7 +53,7 @@ func GetTelemetryTwoRulesAllExport(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) all := GetAll(tenantId) telemetryTwoRules := []*xwlogupload.TelemetryTwoRule{} for _, entity := range all { @@ -88,7 +88,7 @@ func GetTelemetryTwoRuleById(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) telemetryTwoRule := logupload.GetOneTelemetryTwoRule(tenantId, id) if telemetryTwoRule == nil { invalid := "Entity with id: " + id + " does not exist" @@ -138,7 +138,7 @@ func DeleteOneTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) _, err = Delete(tenantId, id) if err != nil { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) @@ -189,7 +189,7 @@ func GetTelemetryTwoRulesFilteredWithPage(w http.ResponseWriter, r *http.Request } } contextMap[core.APPLICATION_TYPE] = applicationType - contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r.Context(), r) + contextMap[xwcommon.TENANT_ID] = xhttp.GetTenantId(r) telemetryTwoRules := findByContext(contextMap) sort.SliceStable(telemetryTwoRules, func(i, j int) bool { @@ -205,6 +205,12 @@ func GetTelemetryTwoRulesFilteredWithPage(w http.ResponseWriter, r *http.Request } func CreateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.TELEMETRY_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + // r.Body is already drained in the middleware xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -213,19 +219,13 @@ func CreateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { } body := xw.Body() telemetry2Rule := xwlogupload.TelemetryTwoRule{} - err := json.Unmarshal([]byte(body), &telemetry2Rule) + err = json.Unmarshal([]byte(body), &telemetry2Rule) if err != nil { xhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) return } - applicationType, err := auth.CanWrite(r, auth.TELEMETRY_ENTITY) - if err != nil { - xhttp.AdminError(w, err) - return - } - - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = Create(tenantId, &telemetry2Rule, applicationType) if err != nil { xhttp.AdminError(w, err) @@ -239,6 +239,11 @@ func CreateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { } func CreateTelemetryTwoRulesPackageHandler(w http.ResponseWriter, r *http.Request) { + applicationType, err := auth.CanWrite(r, auth.TELEMETRY_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte("Unable to extract Body")) @@ -251,14 +256,8 @@ func CreateTelemetryTwoRulesPackageHandler(w http.ResponseWriter, r *http.Reques return } - applicationType, err := auth.CanWrite(r, auth.TELEMETRY_ENTITY) - if err != nil { - xhttp.AdminError(w, err) - return - } - entitiesMap := map[string]common.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity err := Create(tenantId, &entity, applicationType) @@ -301,7 +300,7 @@ func UpdateTelemetryTwoRuleHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = Update(tenantId, &telemetryTwoRule, writeApplication) if err != nil { xhttp.AdminError(w, err) @@ -334,7 +333,7 @@ func UpdateTelemetryTwoRulesPackageHandler(w http.ResponseWriter, r *http.Reques } entitiesMap := map[string]common.EntityMessage{} - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) for _, entity := range entities { entity := entity err := Update(tenantId, &entity, writeApplication) diff --git a/adminapi/xcrp/recooking_lockdown_settings_handler.go b/adminapi/xcrp/recooking_lockdown_settings_handler.go index e853536..f72c99c 100644 --- a/adminapi/xcrp/recooking_lockdown_settings_handler.go +++ b/adminapi/xcrp/recooking_lockdown_settings_handler.go @@ -53,7 +53,7 @@ func PostRecookingLockdownSettingsHandler(w http.ResponseWriter, r *http.Request dao.GetCacheManager().ForceSyncChanges() - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) var lockdownSettingFromDB *common.LockdownSettings lockdownSettingFromDB, err = lockdown.GetLockdownSettings(tenantId) if err != nil { diff --git a/http/auth.go b/http/auth.go index 0ba1f48..d0d6ddf 100644 --- a/http/auth.go +++ b/http/auth.go @@ -16,7 +16,6 @@ package http import ( - "context" "crypto/rsa" "encoding/base64" "errors" @@ -177,15 +176,12 @@ func GetAllowedPartnersFromContext(r *http.Request) []string { return allowedPartners.([]string) } -func GetTenantId(ctx context.Context, r *http.Request) string { - if ctx != nil { - authType := ctx.Value(CTX_KEY_AUTH_TYPE) - if authType != nil { - if authType == AUTH_TYPE_SAT_V2 { - return strings.ToUpper(GetTenantIdFromHeader(r)) - } - } +func GetTenantId(r *http.Request) string { + authType := r.Context().Value(CTX_KEY_AUTH_TYPE) + if authType == AUTH_TYPE_SAT_V2 { + return strings.ToUpper(GetTenantIdFromHeader(r)) } + return strings.ToUpper(db.GetDefaultTenantId()) } diff --git a/openspec/changes/sat-rbac-capabilities-v2/spec.md b/openspec/changes/sat-rbac-capabilities-v2/spec.md index bc9ea92..6e16ce5 100644 --- a/openspec/changes/sat-rbac-capabilities-v2/spec.md +++ b/openspec/changes/sat-rbac-capabilities-v2/spec.md @@ -213,6 +213,7 @@ Returned when: - Xerxes token validation fails - SAT token signature validation fails - SAT token is expired +- SAT token is missing required claims (such as allowedResources.allowedPartners, as enforced by the validator) Response body SHALL include an error code and message suitable for debugging. diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md index 9ea940a..9d3dc75 100644 --- a/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/design.md @@ -54,6 +54,8 @@ Capability authorization remains the first gate. Tenant enforcement is a second | `tenantId` not found in `allowedPartners` | `403 Forbidden` | | `tenantId` found in `allowedPartners` | Allow | +* If the token validator enforces allowedResources.allowedPartners as a required claim (per auth-contract.md SAT Token Validation Requirements), missing/empty values result in 401 Unauthorized during token validation and do not reach this phase. + ## Error Semantics - `401 Unauthorized` remains only for missing/invalid authentication. diff --git a/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md index ce5fd99..e64b748 100644 --- a/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md +++ b/openspec/changes/sat-rbac-v2-tenant-enforcement/spec.md @@ -11,12 +11,12 @@ This change updates openspec/specs/auth/auth-contract.md with the following norm - Authorization SHALL allow only when `allowedPartners` contains `tenantId`. - Authorization SHALL deny with `403 Forbidden` when: - `tenantId` is missing - - `allowedResources.allowedPartners` is missing - - `allowedResources.allowedPartners` is empty - `allowedPartners` does not contain `tenantId` - Legacy SAT behavior and login token/IDP behavior remain unchanged. - Capability strings remain unchanged. +Note: Missing or empty `allowedResources.allowedPartners` may be caught during SAT token validation (resulting in 401 Unauthorized), depending on validator behavior. If validation does not enforce this claim, the absence will be discovered during this authorization check and SHALL return 403 Forbidden. + ## Definitions ### Request Tenant @@ -93,7 +93,9 @@ For all SAT RBAC v2 requests, the system SHALL return `403 Forbidden` when any o |---|---|---|---|---| | Fail | Any | Any | Any | Existing deny behavior | | Pass | Missing | Present | N/A | `403 Forbidden` | -| Pass | Present | Missing | N/A | `403 Forbidden` | -| Pass | Present | Empty | N/A | `403 Forbidden` | +| Pass | Present | Missing | N/A | `403 Forbidden` * | +| Pass | Present | Empty | N/A | `403 Forbidden` * | | Pass | Present | Present | No | `403 Forbidden` | | Pass | Present | Present | Yes | Allow | + +* Note: If SAT token validation enforces allowedResources.allowedPartners as a required claim, missing/empty values result in 401 Unauthorized during token validation and do not reach this authorization check. diff --git a/openspec/specs/auth/auth-contract.md b/openspec/specs/auth/auth-contract.md index 771f2f8..16ba70c 100644 --- a/openspec/specs/auth/auth-contract.md +++ b/openspec/specs/auth/auth-contract.md @@ -24,6 +24,27 @@ This specification does not describe: The system SHALL validate supplied credentials and determine their validity deterministically. +### SAT Token Validation Requirements + +For SAT token authentication, specific claims may be required for a token +to be considered valid. + +Normative behavior: + +- The system SHALL validate SAT tokens for structure, signature, and + required claims. +- Required claims MAY include `allowedResources.allowedPartners`, +as enforced by the SAT token validation implementation. +- If required claims are missing or invalid, the token SHALL be rejected. +- Such failures SHALL result in `401 Unauthorized`. + +This validation occurs during authentication and is independent of +SAT RBAC v2 authorization semantics. + +Note: Missing or invalid `allowedResources.allowedPartners` MAY be treated +as an authentication failure during SAT token validation and result in +`401 Unauthorized`, depending on validator behavior. + ### Authentication Result On successful authentication, the system SHALL return an identity representation suitable for downstream use. @@ -113,13 +134,10 @@ Normative behavior for SAT RBAC v2 requests requiring tenant scope: the request `tenantId` value. - If `tenantId` is missing, authorization SHALL be denied with `403 Forbidden`. -- If `allowedResources.allowedPartners` is missing or empty, - authorization SHALL be denied with `403 Forbidden`. - If `allowedPartners` does not contain `tenantId`, authorization SHALL be denied with `403 Forbidden`. -SAT RBAC v2 tenant scope enforcement SHALL NOT modify SAT capability -strings and SHALL use request metadata plus SAT claims only. +SAT RBAC v2 tenant scope enforcement SHALL rely only on request metadata and SAT claims and SHALL NOT modify capability strings. ### Tenant Resolution By Auth Path @@ -130,8 +148,7 @@ Tenant resolution SHALL be path-specific in this phase: - Authorization SHALL enforce membership against SAT claim `allowedResources.allowedPartners`. - Legacy SAT path: - - Legacy SAT authorization semantics remain unchanged. - - Token validation SHALL NOT enforce tenant or partner claims. + - Legacy SAT authorization semantics remain unchanged, including any validation requirements for token claims such as allowedPartners. - Request processing SHALL continue to support multi-tenancy. - In this phase, request processing SHALL resolve `tenantId` to the default tenant. diff --git a/taggingapi/tag/tag_handler.go b/taggingapi/tag/tag_handler.go index 013595d..ac8c00f 100644 --- a/taggingapi/tag/tag_handler.go +++ b/taggingapi/tag/tag_handler.go @@ -35,7 +35,7 @@ func GetTagsByMemberHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tags, err := GetTagsByMember(tenantId, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) @@ -63,7 +63,7 @@ func GetTagsWithValuesByMemberHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tags, err := GetTagsWithValuesByMember(tenantId, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) diff --git a/taggingapi/tag/tag_member_handler.go b/taggingapi/tag/tag_member_handler.go index 194920d..5b3d5af 100644 --- a/taggingapi/tag/tag_member_handler.go +++ b/taggingapi/tag/tag_member_handler.go @@ -64,7 +64,7 @@ func GetTagMembersHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) query := r.URL.Query() isPaginatedRequest := query.Has("limit") || query.Has("cursor") @@ -126,7 +126,7 @@ func AddMembersToTagHandler(w http.ResponseWriter, r *http.Request) { } tagValue := getTagValueFromRequest(r) - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -194,7 +194,7 @@ func RemoveMembersFromTagHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) var members []string body, err := io.ReadAll(r.Body) @@ -258,7 +258,7 @@ func RemoveMemberFromTagHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) err = RemoveMemberWithXdas(tenantId, id, member) if err != nil { xhttp.WriteXconfErrorResponse(w, err) @@ -276,7 +276,7 @@ func GetAllTagsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) tagIds, err := GetAllTagIds(tenantId) if err != nil { xhttp.WriteXconfErrorResponse(w, err) @@ -306,7 +306,7 @@ func GetTagByIdHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) members, wasTruncated, err := GetTagById(tenantId, id) if err != nil { // Check if tag not found @@ -362,7 +362,7 @@ func DeleteTagHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xhttp.GetTenantId(r.Context(), r) + tenantId := xhttp.GetTenantId(r) populatedBuckets, err := getPopulatedBuckets(tenantId, id) if err != nil { xhttp.WriteXconfErrorResponse(w, err)