diff --git a/adminapi/auth/permission_service.go b/adminapi/auth/permission_service.go index 162c70b..4640118 100644 --- a/adminapi/auth/permission_service.go +++ b/adminapi/auth/permission_service.go @@ -90,6 +90,69 @@ 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{ + // 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}, + {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 +203,7 @@ func getEntityPermission(entityType string) *EntityPermission { return &CommonPermissions } if entityType == TOOL_ENTITY { - return &CommonPermissions + return &ToolPermissions } if entityType == CHANGE_ENTITY { return &ChangePermissions @@ -187,167 +250,267 @@ 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" + + // metrics has no readwrite capability; only xconf:metrics:readonly is valid + if domain == DOMAIN_METRICS { + return util.Contains(capabilities, readCap) } - // 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, readCap) || util.Contains(capabilities, writeCap) +} + +func hasSATv2WriteCapability(capabilities []string, domain SATv2Domain) bool { + // metrics has no write capability + if domain == DOMAIN_METRICS { + return false } - return false + + writeCap := "xconf:" + string(domain) + ":readwrite" + return util.Contains(capabilities, writeCap) } -func HasWritePermissionForTool(r *http.Request) bool { - if !(owcommon.SatOn) { - return true +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") } - // 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 - } + allowedPartners := xhttp.GetAllowedPartnersFromContext(r) + if len(allowedPartners) == 0 { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "SAT token is missing allowed partners") } - return false + if !util.CaseInsensitiveContains(allowedPartners, tenantId) { + return xwcommon.NewRemoteErrorAS(http.StatusForbidden, "SAT token is not allowed for tenant "+tenantId) + } + + return 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 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") + } - 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 !hasSATv2ReadCapability(capabilities, domain) { + requiredCap := "xconf:" + string(domain) + ":readonly" + 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 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 !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) + 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 paths are not under xconfAdminService; check registry before stripping prefix + for _, m := range satV2RouteMappings { + if strings.HasPrefix(path, m.Prefix) { + return m.Domain, true } } - if applicationType == "" { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission") - } else { - return "", xwcommon.NewRemoteErrorAS(http.StatusForbidden, "No read permission for ApplicationType "+applicationType) + // 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(adminPath, m.Prefix) { + return m.Domain, true + } + } + + return "", false } var GetPermissionsFunc = getPermissions @@ -467,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") @@ -477,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/auth/permission_service_test.go b/adminapi/auth/permission_service_test.go new file mode 100644 index 0000000..90976a4 --- /dev/null +++ b/adminapi/auth/permission_service_test.go @@ -0,0 +1,677 @@ +/** + * 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) + } +} + +// 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/canary/canary_settings_handler.go b/adminapi/canary/canary_settings_handler.go index ad5afe7..724d929 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) 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) 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..dce7931 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) + changes := FindByContextForChanges(tenantId, searchContext) sort.Slice(changes, func(i, j int) bool { return changes[j].Updated < changes[i].Updated }) @@ -88,13 +89,20 @@ func ApproveChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) headerMap := createHeadersMap(tenantId, applicationType) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, nil) } 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) + approvedChange, err := GetApprovedAll(tenantId, applicationType) if err != nil { xwhttp.WriteXconfResponse(w, http.StatusBadRequest, []byte(err.Error())) return @@ -113,7 +121,7 @@ func RevertChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) approveId, found := mux.Vars(r)[xcommon.APPROVE_ID] if !found || approveId == "" { @@ -137,7 +145,7 @@ func CancelChangeHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) changeId, found := mux.Vars(r)[xcommon.CHANGE_ID] if !found || changeId == "" { @@ -216,8 +224,8 @@ func GetGroupedChangesHandler(w http.ResponseWriter, r *http.Request) { xhttp.AdminError(w, err) return } - - tenantId := xwhttp.GetTenantId(r, "") + + tenantId := xhttp.GetTenantId(r) changeList := xchange.GetChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[i].Updated < changeList[j].Updated @@ -264,7 +272,7 @@ func GetGroupedApprovedChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) changeList := xchange.GetApprovedChangeList(tenantId) sort.Slice(changeList, func(i, j int) bool { return changeList[j].Updated < changeList[i].Updated @@ -308,7 +316,13 @@ func ApprovedChangesGeneratePage(list []*xwchange.ApprovedChange, page int, page } func GetChangedEntityIdsHandler(w http.ResponseWriter, r *http.Request) { - entityIds := GetChangedEntityIds() + _, err := auth.CanRead(r, auth.CHANGE_ENTITY) + if err != nil { + xhttp.AdminError(w, err) + return + } + tenantId := xhttp.GetTenantId(r) + entityIds := GetChangedEntityIds(tenantId) response, err := util.JSONMarshal(entityIds) if err != nil { log.Error(fmt.Sprintf("json.Marshal entityIds error: %v", err)) @@ -323,7 +337,7 @@ func ApproveChangesHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) xw, ok := w.(*xwhttp.XResponseWriter) if !ok { @@ -432,7 +446,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) + changeList := FindByContextForChanges(tenantId, searchContext) headerMap := createHeadersWithEntitySize(len(changeList), len(approvedChangeList)) xwhttp.WriteXconfResponseWithHeaders(w, headerMap, http.StatusOK, response) } @@ -479,7 +494,8 @@ func GetChangesFilteredHandler(w http.ResponseWriter, r *http.Request) { } searchContext[xwcommon.APPLICATION_TYPE] = applicationType - changeList := FindByContextForChanges(searchContext) + 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 a2f1409..a3c77bf 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" @@ -42,16 +41,11 @@ import ( log "github.com/sirupsen/logrus" ) -func GetApprovedAll(r *http.Request) ([]*xwchange.ApprovedChange, error) { - tenantId := xwhttp.GetTenantId(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) } } @@ -87,7 +81,7 @@ func beforeSavingChange(r *http.Request, change *xwchange.Change) error { return err } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) return validateAllChanges(tenantId, change) } @@ -164,7 +158,7 @@ func CreateApprovedChange(r *http.Request, change *xwchange.Change) (*xwchange.A return nil, err } - tenantId := db.GetDefaultTenantId() + tenantId := xhttp.GetTenantId(r) approvedChange := xwchange.ApprovedChange(*change) xchange.SetOneApprovedChange(tenantId, &approvedChange) jsonBytes, _ := json.Marshal(change) @@ -176,7 +170,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) approvedChange := xchange.GetOneApprovedChange(tenantId, approvedId) if approvedChange == nil { return xwcommon.NewRemoteErrorAS(http.StatusNotFound, "ApprovedChange with "+approvedId+" id does not exist") @@ -193,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 := db.GetDefaultTenantId() + 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 := db.GetDefaultTenantId() + 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 @@ -213,7 +207,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) canceledChange, err := Delete(tenantId, changeId) if err != nil { return err @@ -257,9 +251,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 +290,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) change := xchange.GetOneChange(tenantId, id) if change == nil { return nil, xwcommon.NewRemoteErrorAS(http.StatusNotFound, "Change with "+id+" id does not exist") @@ -340,7 +333,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) changesToApprove, err := GetChangesByEntityIds(tenantId, changeIds) if err != nil { return nil, err @@ -380,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 := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) userName := auth.GetUserNameOrUnknown(r) change.ApprovedUser = userName approvedChange, err := CreateApprovedChange(r, change) @@ -393,7 +386,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) for _, entityId := range entityIdsToByCancelChanges { changes := GetChangesByEntityId(tenantId, entityId) for _, changeByEntityId := range changes { @@ -417,7 +410,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) changesToRevert := []*xwchange.ApprovedChange{} for _, changeId := range *changeIds { approvedChange := xchange.GetOneApprovedChange(tenantId, changeId) @@ -440,8 +433,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 +471,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) 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..d8cedd3 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") } @@ -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) } @@ -397,7 +395,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 +416,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..1429b75 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) 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) 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) 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) 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) 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) 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..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 536f85f..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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 bd2c079..e50147d 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 caf6c24..db740d4 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) 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) 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) 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) 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) 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) 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..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 := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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) 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..73db5f0 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) 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) + 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) + 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) + 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) + 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) + 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) + 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) 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) allFormulas := GetDcmFormulaAll(tenantId) dsList := []*logupload.DeviceSettings{} diff --git a/adminapi/dcm/logrepo_settings_handler.go b/adminapi/dcm/logrepo_settings_handler.go index c00a173..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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,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) + 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) + 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) 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) 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) 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) 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..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 580ad8b..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 62c436b..c7c8e20 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) + // 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 := xwhttp.GetTenantId(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 7500b1b..23cf988 100644 --- a/adminapi/lockdown/lockdown_settings_handler.go +++ b/adminapi/lockdown/lockdown_settings_handler.go @@ -29,12 +29,12 @@ import ( ) func PutLockdownSettingsHandler(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 } - xw, ok := w.(*xhttp.XResponseWriter) + xw, ok := w.(*xwhttp.XResponseWriter) if !ok { xhttp.WriteAdminErrorResponse(w, http.StatusBadRequest, "responsewriter cast error") return @@ -47,7 +47,7 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) respEntity := SetLockdownSetting(tenantId, &lockdownSettings) if respEntity.Error != nil { xhttp.WriteAdminErrorResponse(w, respEntity.Status, respEntity.Error.Error()) @@ -57,8 +57,11 @@ func PutLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { } func GetLockdownSettingsHandler(w http.ResponseWriter, r *http.Request) { - // No permission check needed - tenantId := xwhttp.GetTenantId(r, "") + if _, err := auth.CanRead(r, auth.TOOL_ENTITY); err != nil { + xhttp.AdminError(w, err) + return + } + 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 7ca1682..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 f362591..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(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) 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) 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) 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) 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..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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 37765f2..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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 0e3989e..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] = xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 09f16d7..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 3b6b94a..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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 2c23dda..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 := xwhttp.GetTenantId(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 70a34c0..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 82d31bc..c22fd4b 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) 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..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 := xwhttp.GetTenantId(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 3273972..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 := xwhttp.GetTenantId(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 4573f9f..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) entitiesMap := map[string]xhttp.EntityMessage{} for _, entity := range entities { entity := entity @@ -125,7 +125,11 @@ func PutModelEntitiesHandler(w http.ResponseWriter, r *http.Request) { } func ObsoleteGetModelPageHandler(w http.ResponseWriter, r *http.Request) { - tenantId := xwhttp.GetTenantId(r, "") + if _, err := auth.CanRead(r, auth.COMMON_ENTITY); err != nil { + xhttp.AdminError(w, err) + return + } + 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 @@ -179,7 +183,7 @@ func PostModelFilteredHandler(w http.ResponseWriter, r *http.Request) { } // Get all entries and sort them - tenantId := xwhttp.GetTenantId(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 @@ -224,7 +228,7 @@ func GetModelByIdHandler(w http.ResponseWriter, r *http.Request) { return } id = strings.ToUpper(id) - tenantId := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) model := shared.GetOneModel(tenantId, id) if model == nil { errorStr := fmt.Sprintf("%v not found", id) @@ -261,7 +265,7 @@ func GetModelHandler(w http.ResponseWriter, r *http.Request) { return } - tenantId := xwhttp.GetTenantId(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 d1a2e02..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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] = xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 cedd893..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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(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 := xwhttp.GetTenantId(r, "") + tenantId := xhttp.GetTenantId(r) fwRule, err := GetOnePercentageBeanFromDB(tenantId, id) if err != nil { xhttp.WriteAdminErrorResponse(w, http.StatusNotFound, "\"