func (builder *builder) Cmp(i1, i2 frontend.Variable) frontend.Variable {

	bi1 := builder.ToBinary(i1, builder.cs.FieldBitLen())
	bi2 := builder.ToBinary(i2, builder.cs.FieldBitLen())

	var res frontend.Variable
	res = 0

	for i := builder.cs.FieldBitLen() - 1; i >= 0; i-- {
		iszeroi1 := builder.IsZero(bi1[i])
		iszeroi2 := builder.IsZero(bi2[i])

		i1i2 := builder.And(bi1[i], iszeroi2)
		i2i1 := builder.And(bi2[i], iszeroi1)

		n := builder.Select(i2i1, -1, 0)
		m := builder.Select(i1i2, 1, n)

		res = builder.Select(builder.IsZero(res), m, res)
	}
	return res
}


The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses.


func (builder *builder) AssertIsLessOrEqual(v frontend.Variable, bound frontend.Variable) {
	switch b := bound.(type) {
	case expr.Term:
		builder.mustBeLessOrEqVar(v, b)
	default:
		builder.mustBeLessOrEqCst(v, utils.FromInterface(b))
	}
}

The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result.


func (builder *builder) mustBeLessOrEqCst(a frontend.Variable, bound big.Int) {

	nbBits := builder.cs.FieldBitLen()

	// ensure the bound is positive, it's bit-len doesn't matter
	if bound.Sign() == -1 {
		panic("AssertIsLessOrEqual: bound must be positive")
	}
	if bound.BitLen() > nbBits {
		panic("AssertIsLessOrEqual: bound is too large, constraint will never be satisfied")
	}

	if ca, ok := builder.constantValue(a); ok {
		// a is constant, compare the big int values
		ba := builder.cs.ToBigInt(ca)
		if ba.Cmp(&bound) == 1 {
			panic(fmt.Sprintf("AssertIsLessOrEqual: %s > %s", ba.String(), bound.String()))
		}
	}

	// debug info
	debug := builder.newDebugInfo("mustBeLessOrEq", a, " <= ", bound)

	// note that at this stage, we didn't boolean-constraint these new variables yet
	// (as opposed to ToBinary)
	aBits := bits.ToBinary(builder, a, bits.WithNbDigits(nbBits), bits.WithUnconstrainedOutputs())

	// t trailing bits in the bound
	t := 0
	for i := 0; i < nbBits; i++ {
		if bound.Bit(i) == 0 {
			break
		}
		t++
	}

	p := make([]frontend.Variable, nbBits+1)
	// p[i] == 1 → a[j] == c[j] for all j ⩾ i
	p[nbBits] = 1

	for i := nbBits - 1; i >= t; i-- {
		if bound.Bit(i) == 0 {
			p[i] = p[i+1]
		} else {
			p[i] = builder.Mul(p[i+1], aBits[i])
		}
	}

	for i := nbBits - 1; i >= 0; i-- {

		if bound.Bit(i) == 0 {
			// (1 - p(i+1) - ai) * ai == 0
			l := builder.Sub(1, p[i+1], aBits[i]).(expr.Term)
			//l = builder.Sub(l, ).(term)

			builder.addPlonkConstraint(sparseR1C{
				xa: l.VID,
				xb: aBits[i].(expr.Term).VID,
				qM: builder.tOne,
			}, debug)
		} else {
			builder.AssertIsBoolean(aBits[i])
		}
	}

}


func (builder *builder) mustBeLessOrEqVar(a frontend.Variable, bound expr.Term) {

	debug := builder.newDebugInfo("mustBeLessOrEq", a, " <= ", bound)

	nbBits := builder.cs.FieldBitLen()

	aBits := bits.ToBinary(builder, a, bits.WithNbDigits(nbBits), bits.WithUnconstrainedOutputs())
	boundBits := builder.ToBinary(bound, nbBits)

	p := make([]frontend.Variable, nbBits+1)
	p[nbBits] = 1

	for i := nbBits - 1; i >= 0; i-- {

		// if bound[i] == 0
		// 		p[i] = p[i+1]
		//		t = p[i+1]
		// else
		// 		p[i] = p[i+1] * a[i]
		//		t = 0
		v := builder.Mul(p[i+1], aBits[i])
		p[i] = builder.Select(boundBits[i], v, p[i+1])

		t := builder.Select(boundBits[i], 0, p[i+1])

		// (1 - t - ai) * ai == 0
		l := builder.Sub(1, t, aBits[i]).(expr.Term)

		// note if bound[i] == 1, this constraint is (1 - ai) * ai == 0
		// → this is a boolean constraint
		// if bound[i] == 0, t must be 0 or 1, thus ai must be 0 or 1 too

		if ai, ok := builder.constantValue(aBits[i]); ok {
			// a is constant; ensure l == 0
			l.Coeff = builder.cs.Mul(l.Coeff, ai)
			builder.addPlonkConstraint(sparseR1C{
				xa: l.VID,
				qL: l.Coeff,
			}, debug)
		} else {
			// l * a[i] == 0
			builder.addPlonkConstraint(sparseR1C{
				xa: l.VID,
				xb: aBits[i].(expr.Term).VID,
				qM: l.Coeff,
			}, debug)
		}

	}

}


func (circuit *recursiveHint) Define(api frontend.API) error {
	// first hint produces wire w1
	w1, _ := api.Compiler().NewHint(make3, 1)

	// this linear expression is not recorded in a R1CS just yet
	linearExpression := api.Add(circuit.A, w1[0])

	// api.ToBinary calls another hint (bits.NBits) with linearExpression as input
	// however, when the solver will resolve bits[...] it will need to detect w1 as a dependency
	// in order to compute the correct linearExpression value
	bits := api.ToBinary(linearExpression, 10)

	a := api.FromBinary(bits...)

	api.AssertIsEqual(a, 45)

	return nil
}


func handleRequestBody(c *Client, r *Request) error {
	var bodyBytes []byte
	releaseBuffer(r.bodyBuf)
	r.bodyBuf = nil

	switch body := r.Body.(type) {
	case io.Reader:
		if c.setContentLength || r.setContentLength { // keep backward compatibility
			r.bodyBuf = acquireBuffer()
			if _, err := r.bodyBuf.ReadFrom(body); err != nil {
				return err
			}
			r.Body = nil
		} else {
			// Otherwise buffer less processing for `io.Reader`, sounds good.
			return nil
		}
	case []byte:
		bodyBytes = body
	case string:
		bodyBytes = []byte(body)
	default:
		contentType := r.Header.Get(hdrContentTypeKey)
		kind := kindOf(r.Body)
		var err error
		if IsJSONType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) {
			r.bodyBuf, err = jsonMarshal(c, r, r.Body)
		} else if IsXMLType(contentType) && (kind == reflect.Struct) {
			bodyBytes, err = c.XMLMarshal(r.Body)
		}
		if err != nil {
			return err
		}
	}

	if bodyBytes == nil && r.bodyBuf == nil {
		return errors.New("unsupported 'Body' type/value")
	}

	// []byte into Buffer
	if bodyBytes != nil && r.bodyBuf == nil {
		r.bodyBuf = acquireBuffer()
		_, _ = r.bodyBuf.Write(bodyBytes)
	}

	return nil
}

Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')

The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.


func (s *memoryStore) Verify(id, answer string, clear bool) bool {
	v := s.Get(id, clear)
	return v == answer
}

Insufficient Verification of Data Authenticity

The product does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data.


func (r *RoleBindingReflector) GetUserNamespacesFromRequest(req request.Request) ([]string, error) {
	var err error

	username, groups, _ := req.GetUserAndGroups()

	namespaces := sets.NewString()

	userOwnerKind := capsulev1beta2.UserOwner

	var userRoleBindings []interface{}

	if strings.HasPrefix(username, serviceaccount.ServiceAccountUsernamePrefix) {
		userOwnerKind = capsulev1beta2.ServiceAccountOwner

		_, username, err = serviceaccount.SplitUsername(username)
		if err != nil {
			return nil, errors.Wrap(err, "Unable to parse serviceAccount name")
		}
	}

	userRoleBindings, err = r.store.ByIndex(subjectIndex, fmt.Sprintf("%s-%s", userOwnerKind, username))
	if err != nil {
		return nil, errors.Wrap(err, "Unable to find rolebindings in index for user")
	}

	for _, rb := range userRoleBindings {
		rb := rb.(*rbacv1.RoleBinding)
		namespaces.Insert(rb.GetNamespace())
	}

	for _, group := range groups {
		groupRoleBindings, err := r.store.ByIndex(subjectIndex, fmt.Sprintf("%s-%s", capsulev1beta2.GroupOwner, group))
		if err != nil {
			return nil, errors.Wrap(err, "Unable to find rolebindings in index for groups")
		}

		for _, rb := range groupRoleBindings {
			rb := rb.(*rbacv1.RoleBinding)
			namespaces.Insert(rb.GetNamespace())
		}
	}

	return namespaces.List(), nil
}


func OwnerRoleBindingsIndexFunc(obj interface{}) (result []string, err error) {
	rb := obj.(*rbacv1.RoleBinding)

	for _, subject := range rb.Subjects {
		result = append(result, fmt.Sprintf("%s-%s", subject.Kind, subject.Name))
	}

	return result, nil
}


func (maap *MesheryApplicationPersister) GetMesheryApplications(search, order string, page, pageSize uint64, updatedAfter string) ([]byte, error) {
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	applications := []*MesheryApplication{}

	query := maap.DB.Where("updated_at > ?", updatedAfter).Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(meshery_applications.name) like ?)", like)
	}

	query.Table("meshery_applications").Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&applications)

	mesheryApplicationPage := &MesheryApplicationPage{
		Page:         page,
		PageSize:     pageSize,
		TotalCount:   int(count),
		Applications: applications,
	}

	return marshalMesheryApplicationPage(mesheryApplicationPage), nil
}

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')

The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.


func (mfp *MesheryFilterPersister) GetMesheryCatalogFilters(page, pageSize, search, order string) ([]byte, error) {
	var err error
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	var pg int
	if page != "" {
		pg, err = strconv.Atoi(page)

		if err != nil || pg < 0 {
			pg = 0
		}
	} else {
		pg = 0
	}

	// 0 page size is for all records
	var pgSize int
	if pageSize != "" {
		pgSize, err = strconv.Atoi(pageSize)

		if err != nil || pgSize < 0 {
			pgSize = 0
		}
	} else {
		pgSize = 0
	}

	filters := []MesheryFilter{}

	query := mfp.DB.Where("visibility = ?", Published).Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(meshery_filters.name) like ?)", like)
	}

	var count int64
	err = query.Model(&MesheryFilter{}).Count(&count).Error

	if err != nil {
		return nil, err
	}

	if pgSize != 0 {
		Paginate(uint(pg), uint(pgSize))(query).Find(&filters)
	} else {
		query.Find(&filters)
	}

	response := FiltersAPIResponse{
		Page:       uint(pg),
		PageSize:   uint(pgSize),
		TotalCount: uint(count),
		Filters:    filters,
	}

	marshalledResponse, _ := json.Marshal(response)
	return marshalledResponse, nil
}


func (mfp *MesheryFilterPersister) GetMesheryFilters(search, order string, page, pageSize uint64, visibility []string) ([]byte, error) {
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	filters := []*MesheryFilter{}

	var query *gorm.DB
	if len(visibility) == 0 {
		query = mfp.DB.Where("visibility in (?)", visibility)
	}
	query = query.Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(meshery_filters.name) like ?)", like)
	}

	query.Table("meshery_filters").Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&filters)

	mesheryFilterPage := &MesheryFilterPage{
		Page:       page,
		PageSize:   pageSize,
		TotalCount: int(count),
		Filters:    filters,
	}

	return marshalMesheryFilterPage(mesheryFilterPage), nil
}


func (mkcp *MesheryK8sContextPersister) GetMesheryK8sContexts(search, order string, page, pageSize uint64) ([]byte, error) {
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	contexts := []*K8sContext{}

	query := mkcp.DB.Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(name) like ?)", like)
	}

	query.Model(K8sContext{}).Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&contexts)

	mesheryK8sContextPage := MesheryK8sContextPage{
		Page:       page,
		PageSize:   pageSize,
		TotalCount: int(count),
		Contexts:   contexts,
	}

	resp, _ := json.Marshal(mesheryK8sContextPage)
	return resp, nil
}


func (mpp *MesheryPatternPersister) GetMesheryPatterns(search, order string, page, pageSize uint64, updatedAfter string, visibility []string) ([]byte, error) {
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	patterns := []*MesheryPattern{}
	var query *gorm.DB
	if len(visibility) == 0 {
		query = mpp.DB.Where("visibility in (?)", visibility)
	}
	query = query.Where("updated_at > ?", updatedAfter).Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(meshery_patterns.name) like ?)", like)
	}

	query.Table("meshery_patterns").Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&patterns)

	mesheryPatternPage := &MesheryPatternPage{
		Page:       page,
		PageSize:   pageSize,
		TotalCount: int(count),
		Patterns:   patterns,
	}

	return marshalMesheryPatternPage(mesheryPatternPage), nil
}


func (mpp *MesheryPatternPersister) GetMesheryCatalogPatterns(page, pageSize, search, order string) ([]byte, error) {
	var err error
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	var pg int
	if page != "" {
		pg, err = strconv.Atoi(page)

		if err != nil || pg < 0 {
			pg = 0
		}
	} else {
		pg = 0
	}

	// 0 page size is for all records
	var pgSize int
	if pageSize != "" {
		pgSize, err = strconv.Atoi(pageSize)

		if err != nil || pgSize < 0 {
			pgSize = 0
		}
	} else {
		pgSize = 0
	}

	patterns := []MesheryPattern{}

	query := mpp.DB.Where("visibility = ?", Published).Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(meshery_patterns.name) like ?)", like)
	}

	var count int64
	err = query.Model(&MesheryPattern{}).Count(&count).Error

	if err != nil {
		return nil, err
	}

	if pgSize != 0 {
		Paginate(uint(pg), uint(pgSize))(query).Find(&patterns)
	} else {
		query.Find(&patterns)
	}

	response := PatternsAPIResponse{
		Page:       uint(pg),
		PageSize:   uint(pgSize),
		TotalCount: uint(count),
		Patterns:   patterns,
	}

	marshalledResponse, _ := json.Marshal(response)
	return marshalledResponse, nil
}


func (prp *PatternResourcePersister) GetPatternResources(search, order, name, namespace, typ, oamType string, page, pageSize uint64) (*PatternResourcePage, error) {
	order = sanitizeOrderInput(order, []string{"created_at", "updated_at", "name"})

	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	resources := []*PatternResource{}

	query := prp.DB.Order(order).Where("deleted = false")

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(pattern_resources.name) like ?)", like)
	}
	if name != "" {
		query = query.Where("name = ?", name)
	}
	if namespace != "" {
		query = query.Where("namespace = ?", namespace)
	}
	if typ != "" {
		query = query.Where("type = ?", typ)
	}
	if oamType != "" {
		query = query.Where("oam_type = ?", oamType)
	}

	query.Model(&PatternResource{}).Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&resources)

	patternResourcePage := &PatternResourcePage{
		Page:       page,
		PageSize:   pageSize,
		TotalCount: int(count),
		Resources:  resources,
	}

	return patternResourcePage, nil
}


func (prp *PatternResourcePersister) Exists(name, namespace, typ, oamType string) bool {
	var result struct {
		Found bool
	}

	prp.DB.
		Raw(`
	SELECT
		EXISTS(SELECT 1 FROM pattern_resources WHERE name = ? AND namespace = ? AND type = ? AND oam_type = ? AND deleted = false) AS "found"`,
			name,
			namespace,
			typ,
			oamType,
		).
		Scan(&result)

	return result.Found
}


func (ppp *PerformanceProfilePersister) GetPerformanceProfiles(_, search, order string, page, pageSize uint64) ([]byte, error) {
	order = sanitizeOrderInput(order, []string{"updated_at", "created_at", "name", "last_run"})
	if order == "" {
		order = "updated_at desc"
	}

	count := int64(0)
	profiles := []*PerformanceProfile{}

	query := ppp.DB.
		Select(`
		id, name, load_generators,
		endpoints, qps, service_mesh,
		duration, request_headers, request_cookies,
		request_body, content_type, created_at,
		updated_at, (?) as last_run, (?) as total_results`,
			ppp.DB.Table("meshery_results").Select("DATETIME(MAX(meshery_results.test_start_time))").Where("performance_profile = performance_profiles.id"),
			ppp.DB.Table("meshery_results").Select("COUNT(meshery_results.name)").Where("performance_profile = performance_profiles.id"),
		).
		Order(order)

	if search != "" {
		like := "%" + strings.ToLower(search) + "%"
		query = query.Where("(lower(performance_profiles.name) like ?)", like)
	}

	query.Table("performance_profiles").Count(&count)

	Paginate(uint(page), uint(pageSize))(query).Find(&profiles)

	performanceProfilePage := &PerformanceProfilePage{
		Page:       page,
		PageSize:   pageSize,
		TotalCount: int(count),
		Profiles:   profiles,
	}

	return marshalPerformanceProfilePage(performanceProfilePage), nil
}


func sanitizeOrderInput(order string, validColumns []string) string {
	parsedOrderStr := strings.Split(order, " ")
	if len(parsedOrderStr) != 2 {
		return ""
	}

	inputCol := parsedOrderStr[0]
	typ := strings.ToLower(parsedOrderStr[1])
	for _, col := range validColumns {
		if col == inputCol {
			if typ == "desc" {
				return fmt.Sprintf("%s desc", col)
			}

			return fmt.Sprintf("%s asc", col)
		}
	}

	return ""
}


func initWithRegionMagic(regionMagic string) {
	if regionMagic == "" {
		log.Warn("no region magic setting, using default secret keys for checksum")
		return
	}

	log.Info("using magic secret keys for checksum with:", regionMagic)
	b := sha1.Sum([]byte(regionMagic))
	initTokenSecret(b[:8])
	initLocationSecret(b[:8])
}


func RandomString(length int, seed RandomSeed) string {
	runs := seed.Runes()
	result := ""
	for i := 0; i < length; i++ {
		rand.Seed(time.Now().UnixNano())
		randNumber := rand.Intn(len(runs))
		result += string(runs[randNumber])
	}
	return result
}

The product uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.


	return func(
		ctx context.Context,
		method string,
		req, reply interface{},
		cc *grpc.ClientConn,
		invoker grpc.UnaryInvoker,
		callOpts ...grpc.CallOption,
	) error {
		i := &InterceptorInfo{
			Method: method,
			Type:   UnaryClient,
		}
		if cfg.Filter != nil && !cfg.Filter(i) {
			return invoker(ctx, method, req, reply, cc, callOpts...)
		}

		name, attr := spanInfo(method, cc.Target())

		startOpts := append([]trace.SpanStartOption{
			trace.WithSpanKind(trace.SpanKindClient),
			trace.WithAttributes(attr...),
		},
			cfg.SpanStartOptions...,
		)

		ctx, span := tracer.Start(
			ctx,
			name,
			startOpts...,
		)
		defer span.End()

		ctx = inject(ctx, cfg.Propagators)

		if cfg.SentEvent {
			messageSent.Event(ctx, 1, req)
		}

		err := invoker(ctx, method, req, reply, cc, callOpts...)

		if cfg.ReceivedEvent {
			messageReceived.Event(ctx, 1, reply)
		}

		if err != nil {
			s, _ := status.FromError(err)
			span.SetStatus(codes.Error, s.Message())
			span.SetAttributes(statusCodeAttr(s.Code()))
		} else {
			span.SetAttributes(statusCodeAttr(grpc_codes.OK))
		}

		return err
	}

Allocation of Resources Without Limits or Throttling

The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.


func checkUnaryServerRecords(t *testing.T, reader metric.Reader) {
	rm := metricdata.ResourceMetrics{}
	err := reader.Collect(context.Background(), &rm)
	assert.NoError(t, err)
	require.Len(t, rm.ScopeMetrics, 1)

	// TODO: Remove these #4322
	address, ok := findScopeMetricAttribute(rm.ScopeMetrics[0], semconv.NetSockPeerAddrKey)
	assert.True(t, ok)
	port, ok := findScopeMetricAttribute(rm.ScopeMetrics[0], semconv.NetSockPeerPortKey)
	assert.True(t, ok)

	want := metricdata.ScopeMetrics{
		Scope: wantInstrumentationScope,
		Metrics: []metricdata.Metrics{
			{
				Name:        "rpc.server.duration",
				Description: "Measures the duration of inbound RPC.",
				Unit:        "ms",
				Data: metricdata.Histogram[float64]{
					Temporality: metricdata.CumulativeTemporality,
					DataPoints: []metricdata.HistogramDataPoint[float64]{
						{
							Attributes: attribute.NewSet(
								semconv.RPCMethod("EmptyCall"),
								semconv.RPCService("grpc.testing.TestService"),
								otelgrpc.RPCSystemGRPC,
								otelgrpc.GRPCStatusCodeKey.Int64(int64(codes.OK)),
								address,
								port,
							),
						},
						{
							Attributes: attribute.NewSet(
								semconv.RPCMethod("UnaryCall"),
								semconv.RPCService("grpc.testing.TestService"),
								otelgrpc.RPCSystemGRPC,
								otelgrpc.GRPCStatusCodeKey.Int64(int64(codes.OK)),
								address,
								port,
							),
						},
					},
				},
			},
		},
	}

	metricdatatest.AssertEqual(t, want, rm.ScopeMetrics[0], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())
}


func findScopeMetricAttribute(sm metricdata.ScopeMetrics, key attribute.Key) (attribute.KeyValue, bool) {
	for _, m := range sm.Metrics {
		// This only needs to cover data types used by the instrumentation.
		switch d := m.Data.(type) {
		case metricdata.Histogram[int64]:
			for _, dp := range d.DataPoints {
				if kv, ok := findAttribute(dp.Attributes.ToSlice(), key); ok {
					return kv, true
				}
			}
		case metricdata.Histogram[float64]:
			for _, dp := range d.DataPoints {
				if kv, ok := findAttribute(dp.Attributes.ToSlice(), key); ok {
					return kv, true
				}
			}
		default:
			panic(fmt.Sprintf("unexpected data type %T - name %s", d, m.Name))
		}
	}
	return attribute.KeyValue{}, false
}


func NewClient(url string) (*gitrekor.Client, error) {
	return gitrekor.New(url, rekor.WithUserAgent("gitsign"))
}

Improper Verification of Cryptographic Signature

The product does not verify, or incorrectly verifies, the cryptographic signature for data.


func rekorPubsFromClient(rekorClient *client.Rekor) (*cosign.TrustedTransparencyLogPubKeys, error) {
	publicKeys := cosign.NewTrustedTransparencyLogPubKeys()
	pubOK, err := rekorClient.Pubkey.GetPublicKey(nil)
	if err != nil {
		return nil, fmt.Errorf("unable to fetch rekor public key from rekor: %w", err)
	}
	if err := publicKeys.AddTransparencyLogPubKey([]byte(pubOK.Payload), tuf.Active); err != nil {
		return nil, fmt.Errorf("constructRekorPubKey: %w", err)
	}
	return &publicKeys, nil
}


func New(url string, opts ...rekor.Option) (*Client, error) {
	c, err := rekor.GetRekorClient(url, opts...)
	if err != nil {
		return nil, err
	}
	pubs, err := rekorPubsFromClient(c)
	if err != nil {
		return nil, err
	}
	return &Client{
		Rekor:      c,
		publicKeys: pubs,
	}, nil
}


func (t *handshakeTransport) readLoop() {
	first := true
	for {
		p, err := t.readOnePacket(first)
		first = false
		if err != nil {
			t.readError = err
			close(t.incoming)
			break
		}
		if p[0] == msgIgnore || p[0] == msgDebug {
			continue
		}
		t.incoming <- p
	}

	// Stop writers too.
	t.recordWriteError(t.readError)

	// Unblock the writer should it wait for this.
	close(t.startKex)

	// Don't close t.requestKex; it's also written to from writePacket.
}

Improper Validation of Integrity Check Value

The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.


func (t *transport) readPacket() (p []byte, err error) {
	for {
		p, err = t.reader.readPacket(t.bufReader)
		if err != nil {
			break
		}
		if len(p) == 0 || (p[0] != msgIgnore && p[0] != msgDebug) {
			break
		}
	}
	if debugTransport {
		t.printPacket(p, false)
	}

	return p, err
}


func (t *transport) writePacket(packet []byte) error {
	if debugTransport {
		t.printPacket(packet, true)
	}
	return t.writer.writePacket(t.bufWriter, t.rand, packet)
}


func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error {
	changeKeys := len(packet) > 0 && packet[0] == msgNewKeys

	err := s.packetCipher.writeCipherPacket(s.seqNum, w, rand, packet)
	if err != nil {
		return err
	}
	if err = w.Flush(); err != nil {
		return err
	}
	s.seqNum++
	if changeKeys {
		select {
		case cipher := <-s.pendingKeyChange:
			s.packetCipher = cipher
		default:
			panic("ssh: no key material for msgNewKeys")
		}
	}
	return err
}


func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) {
	packet, err := s.packetCipher.readCipherPacket(s.seqNum, r)
	s.seqNum++
	if err == nil && len(packet) == 0 {
		err = errors.New("ssh: zero length packet")
	}

	if len(packet) > 0 {
		switch packet[0] {
		case msgNewKeys:
			select {
			case cipher := <-s.pendingKeyChange:
				s.packetCipher = cipher
			default:
				return nil, errors.New("ssh: got bogus newkeys message")
			}

		case msgDisconnect:
			// Transform a disconnect message into an
			// error. Since this is lowest level at which
			// we interpret message types, doing it here
			// ensures that we don't have to handle it
			// elsewhere.
			var msg disconnectMsg
			if err := Unmarshal(packet, &msg); err != nil {
				return nil, err
			}
			return nil, &msg
		}
	}

	// The packet may point to an internal buffer, so copy the
	// packet out here.
	fresh := make([]byte, len(packet))
	copy(fresh, packet)

	return fresh, err
}


func (k *PublicKey) Decapsulate(priv *PrivateKey) ([]byte, error) {
	if priv == nil {
		return nil, fmt.Errorf("public key is empty")
	}

	var secret bytes.Buffer
	secret.Write(k.Bytes(false))

	sx, sy := priv.Curve.ScalarMult(k.X, k.Y, priv.D.Bytes())
	secret.Write([]byte{0x04})

	// Sometimes shared secret coordinates are less than 32 bytes; Big Endian
	l := len(priv.Curve.Params().P.Bytes())
	secret.Write(zeroPad(sx.Bytes(), l))
	secret.Write(zeroPad(sy.Bytes(), l))

	return kdf(secret.Bytes())
}


func CertHandler(c *gin.Context) {
	if strings.Contains(c.Request.UserAgent(), "Firefox") {
		c.Header("content-type", "application/x-x509-ca-cert")
		c.File("ca.cert.cer")
		return
	}
	noFirefoxTemplate.Execute(c.Writer, gin.H{
		"url": "http://" + c.Request.Host + c.Request.URL.String(),
	})
}

Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


func DeleteCertHandler(c *gin.Context) {
	DeleteCertificates(config.GetCertificatesDir())
}


func Init(ds model.DataStore) {
	once.Do(func() {
		log.Info("Setting Session Timeout", "value", conf.Server.SessionTimeout)
		secret, err := ds.Property(context.TODO()).DefaultGet(consts.JWTSecretKey, "not so secret")
		if err != nil {
			log.Error("No JWT secret found in DB. Setting a temp one, but please report this error", err)
		}
		Secret = []byte(secret)
		TokenAuth = jwtauth.New("HS256", Secret, nil)
	})
}

When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.


func New(ds model.DataStore, broker events.Broker) *Server {
	s := &Server{ds: ds, broker: broker}
	auth.Init(s.ds)
	initialSetup(ds)
	s.initRoutes()
	s.mountAuthenticationRoutes()
	s.mountRootRedirector()
	checkFfmpegInstallation()
	checkExternalCredentials()
	return s
}


const recordDefinition = (id, highByte) => {
	let structure = read().map(property => property.toString()) // ensure that all keys are strings and that the array is mutable
	let firstByte = id
	if (highByte !== undefined) {
		id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id)
		structure.highByte = highByte
	}
	let existingStructure = currentStructures[id]
	// If it is a shared structure, we need to restore any changes after reading.
	// Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
	// to the state prior to an incomplete read in order to properly resume.
	if (existingStructure && (existingStructure.isShared || sequentialMode)) {
		(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure
	}
	currentStructures[id] = structure
	structure.read = createStructureReader(structure, firstByte)
	return structure.read()
}

The product does not properly control the amount of recursion that takes place,  consuming excessive resources, such as allocated memory or the program stack.


function readKey() {
	let length = src[position++]
	if (length >= 0xa0 && length < 0xc0) {
		// fixstr, potentially use key cache
		length = length - 0xa0
		if (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)
			return srcString.slice(position - srcStringStart, (position += length) - srcStringStart)
		else if (!(srcStringEnd == 0 && srcEnd < 180))
			return readFixedString(length)
	} else { // not cacheable, go back and do a standard read
		position--
		return read().toString()
	}
	let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff
	let entry = keyCache[key]
	let checkPosition = position
	let end = position + length - 3
	let chunk
	let i = 0
	if (entry && entry.bytes == length) {
		while (checkPosition < end) {
			chunk = dataView.getUint32(checkPosition)
			if (chunk != entry[i++]) {
				checkPosition = 0x70000000
				break
			}
			checkPosition += 4
		}
		end += 3
		while (checkPosition < end) {
			chunk = src[checkPosition++]
			if (chunk != entry[i++]) {
				checkPosition = 0x70000000
				break
			}
		}
		if (checkPosition === end) {
			position = checkPosition
			return entry.string
		}
		end -= 3
		checkPosition = position
	}
	entry = []
	keyCache[key] = entry
	entry.bytes = length
	while (checkPosition < end) {
		chunk = dataView.getUint32(checkPosition)
		entry.push(chunk)
		checkPosition += 4
	}
	end += 3
	while (checkPosition < end) {
		chunk = src[checkPosition++]
		entry.push(chunk)
	}
	// for small blocks, avoiding the overhead of the extract call is helpful
	let string = length < 16 ? shortStringInJS(length) : longStringInJS(length)
	if (string != null)
		return entry.string = string
	return entry.string = readFixedString(length)
}


func SaveSettings(c *gin.Context) {
    var json struct {
        Server settings.Server `json:"server"`
        Nginx  settings.Nginx  `json:"nginx"`
        Openai settings.OpenAI `json:"openai"`
    }

    if !api.BindAndValid(c, &json) {
        return
    }

    settings.ServerSettings = json.Server
    settings.NginxSettings = json.Nginx
    settings.OpenAISettings = json.Openai

    settings.ReflectFrom()

    err := settings.Save()
    if err != nil {
        api.ErrHandler(c, err)
        return
    }

    GetSettings(c)
}

Improper Neutralization of Special Elements used in a Command ('Command Injection')

The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.


func GetSettings(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
        "server": settings.ServerSettings,
        "nginx":  settings.NginxSettings,
        "openai": settings.OpenAISettings,
    })
}


	return func(db *gorm.DB) *gorm.DB {
		sort := c.ctx.DefaultQuery("order", "desc")
		order := fmt.Sprintf("%s %s", DefaultQuery(c.ctx, "sort_by", c.itemKey), sort)
		return db.Order(order)
	}
}


	return func(db *gorm.DB) *gorm.DB {
		sort := c.DefaultQuery("order", "desc")

		order := fmt.Sprintf("`%s` %s", DefaultQuery(c, "sort_by", "id"), sort)
		db = db.Order(order)

		page := cast.ToInt(c.Query("page"))
		if page == 0 {
			page = 1
		}
		pageSize := settings.ServerSettings.PageSize
		reqPageSize := c.Query("page_size")
		if reqPageSize != "" {
			pageSize = cast.ToInt(reqPageSize)
		}
		offset := (page - 1) * pageSize

		return db.Offset(offset).Limit(pageSize)
	}
}


export const matcher = (rawStr: string, regexp: RegExp) => {
  const matchResult = rawStr.match(regexp);
  return matchResult;
};


    public function testComplexUse()
    {
        $this->assertResult(
'<ruby>
  <rbc>
    <rb>10</rb>
    <rb>31</rb>
    <rb>2002</rb>
  </rbc>
  <rtc>
    <rt>Month</rt>
    <rt>Day</rt>
    <rt>Year</rt>
  </rtc>
  <rtc>
    <rt rbspan="3">Expiration Date</rt>
  </rtc>
</ruby>'
        );

        /* not implemented
        function testBackwardsCompat()
        {
            $this->assertResult(
                '<ruby>A<rp>(</rp><rt>aaa</rt><rp>)</rp></ruby>',
                '<ruby><rb>A</rb><rp>(</rp><rt>aaa</rt><rp>)</rp></ruby>'
            );
        }
        */

    }


    public function setUp()
    {
        parent::setUp();
        $this->config->set('HTML.Doctype', 'XHTML 1.1');
    }


    public function testBasicUse()
    {
        $this->assertResult(
            '<ruby><rb>WWW</rb><rt>World Wide Web</rt></ruby>'
        );
    }


    public function testRPUse()
    {
        $this->assertResult(
            '<ruby><rb>WWW</rb><rp>(</rp><rt>World Wide Web</rt><rp>)</rp></ruby>'
        );
    }


    function verifyHtmlRender(text: string) {
        renderer.verify(x => x.setProperty(It.isAny(), 'innerHTML', text), Times.once());

        expect().nothing();
    }

Improper Handling of Additional Special Element

The product receives input from an upstream component, but it does not handle or incorrectly handles when an additional unexpected special element is provided.


    function verifyTextRender(text: string) {
        renderer.verify(x => x.setProperty(It.isAny(), 'textContent', text), Times.once());

        expect().nothing();
    }


    public ngOnChanges() {
        let html = '';

        let markdown = this.markdown;

        const hasExclamation = markdown.indexOf('!') === 0;

        if (hasExclamation) {
            markdown = markdown.substring(1);
        }

        if (!markdown) {
            html = markdown;
        } else if (this.optional && !hasExclamation) {
            html = markdown;
        } else if (this.markdown) {
            html = renderMarkdown(markdown, this.inline);
        }

        const hasHtml = html.indexOf('<') >= 0;

        if (hasHtml) {
            this.renderer.setProperty(this.element.nativeElement, 'innerHTML', html);
        } else {
            this.renderer.setProperty(this.element.nativeElement, 'textContent', html);
        }
    }


export function renderMarkdown(input: string | undefined | null, inline: boolean) {
    if (!input) {
        return '';
    }

    input = escapeHTML(input);

    if (inline) {
        return marked(input, { renderer: RENDERER_INLINE });
    } else {
        return marked(input, { renderer: RENDERER_DEFAULT });
    }
}


export function escapeHTML(html: string) {
    if (escapeTestNoEncode.test(html)) {
        return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
    }

    return html;
}


function renderInlineParagraph(text: string) {
    return text;
}


const getEscapeReplacement = (ch: string) => escapeReplacements[ch];


function renderLink(href: string, _: string, text: string) {
    if (href && href.startsWith('mailto')) {
        return text;
    } else {
        return `<a href="${href}" target="_blank", rel="noopener">${text} <i class="icon-external-link"></i></a>`;
    }
}


        const user = await firstValueFrom(users.getUser(id, null));

        return user.displayName;
    }


            return `<span class="marker-ref">${escapeHTML(marker)}</span>`;
        });


return `<span class="user-ref">${escapeHTML(placeholderValues.shift() || '')}</span>`;


export function getCellWidth(field: TableField, sizes: FieldSizes | undefined | null) {
    const size = sizes?.[field.name] || 0;

    if (size > 0) {
        return size;
    }

    switch (field) {
        case META_FIELDS.id:
            return 280;
        case META_FIELDS.created:
            return 150;
        case META_FIELDS.createdByAvatar:
            return 55;
        case META_FIELDS.createdByName:
            return 150;
        case META_FIELDS.lastModified:
            return 150;
        case META_FIELDS.lastModifiedByAvatar:
            return 55;
        case META_FIELDS.lastModifiedByName:
            return 150;
        case META_FIELDS.status:
            return 200;
        case META_FIELDS.statusNext:
            return 240;
        case META_FIELDS.statusColor:
            return 80;
        case META_FIELDS.version:
            return 80;
        default:
            return 200;
    }
}

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.


function _getPayloadURL (url: string, opts: LoadPayloadOptions = {}) {
  if (hasProtocol(url, true)) {
    throw new Error('Payload URL must not include hostname: ' + url)
  }
  const u = new URL(url, 'http://localhost')
  if (u.search) {
    throw new Error('Payload URL cannot contain search params: ' + url)
  }
  const hash = opts.hash || (opts.fresh ? Date.now() : '')
  return joinURL(useRuntimeConfig().app.baseURL, u.pathname, hash ? `_payload.${hash}.js` : '_payload.js')
}


        url: constructUpstreamRequestUrl('/api/v1/dependency-graph'),
        payload,
        options: upstreamRequestOptions,
      };

      const { response, attempt } = await reqQueue.push(request);
      if (!isSuccessStatusCode(response.statusCode)) {
        throw new Error(`${response.statusCode} ${response.statusMessage}`);
      } else {
        logger.info(
          { payload: payloadWithoutDepGraph, attempt },
          'dependency graph sent upstream successfully',
        );
      }
    } catch (error) {
      logger.error(
        { error, payload: payloadWithoutDepGraph },
        'could not send the dependency scan result upstream',
      );
    }
  }
}


        url: constructUpstreamRequestUrl('/api/v1/scan-results'),
        payload,
        options: upstreamRequestOptions,
      };

      const { response, attempt } = await reqQueue.push(request);
      if (!isSuccessStatusCode(response.statusCode)) {
        throw new Error(`${response.statusCode} ${response.statusMessage}`);
      } else {
        logger.info(
          { payload: payloadWithoutScanResults, attempt },
          'scan results sent upstream successfully',
        );
      }
    } catch (error) {
      logger.error(
        { error, payload: payloadWithoutScanResults },
        'could not send the scan results upstream',
      );
      return false;
    }
  }

  return true;
}


function constructUpstreamRequestUrl(
  requestPath: string,
  queryParams?: Record<string, string>,
): string {
  const requestUrl = new URL(upstreamUrl);
  requestUrl.pathname = path.join(requestUrl.pathname, requestPath);
  requestUrl.searchParams.set('version', upstreamRequestVersion);
  for (const key in queryParams) {
    requestUrl.searchParams.set(key, queryParams[key]);
  }
  return requestUrl.toString();
}


      url: constructUpstreamRequestUrl('/api/v1/runtime-results'),
      payload,
      options: upstreamRequestOptions,
    };

    const { response, attempt } = await reqQueue.push(request);

    if (!isSuccessStatusCode(response.statusCode)) {
      throw new Error(`${response.statusCode} ${response.statusMessage}`);
    }

    logger.info(
      {
        attempt,
        ...logContext,
      },
      'runtime data sent upstream successfully',
    );
  } catch (error) {
    logger.error(
      {
        error,
        ...logContext,
      },
      'could not send runtime data',
    );
  }
}


      url: constructUpstreamRequestUrl('api/v1/workload', queryParams),
      payload,
      options: upstreamRequestOptions,
    };

    const { response, attempt } = await reqQueue.push(request);
    // TODO: Remove this check, the upstream no longer returns 404 in such cases
    if (response.statusCode === 404) {
      logger.info(
        { payload },
        'attempted to delete a workload the Upstream service could not find',
      );
      return;
    }
    if (!isSuccessStatusCode(response.statusCode)) {
      throw new Error(`${response.statusCode} ${response.statusMessage}`);
    } else {
      logger.info(
        { workloadLocator: payload.workloadLocator, attempt },
        'workload deleted successfully',
      );
    }
  } catch (error) {
    logger.error(
      { error, payload },
      'could not send delete a workload from the upstream',
    );
  }
}


      url: constructUpstreamRequestUrl('/api/v1/workload'),
      payload,
      options: upstreamRequestOptions,
    };

    const { response, attempt } = await reqQueue.push(request);
    if (!isSuccessStatusCode(response.statusCode)) {
      throw new Error(`${response.statusCode} ${response.statusMessage}`);
    } else {
      logger.info(
        { workloadLocator: payload.workloadLocator, attempt },
        'workload metadata sent upstream successfully',
      );
    }
  } catch (error) {
    logger.error(
      { error, workloadLocator: payload.workloadLocator },
      'could not send workload metadata upstream',
    );
  }
}


      url: constructUpstreamRequestUrl('/api/v1/cluster'),
      payload,
      options: upstreamRequestOptions,
    };

    const { response, attempt } = await reqQueue.push(request);
    if (!isSuccessStatusCode(response.statusCode)) {
      throw new Error(`${response.statusCode} ${response.statusMessage}`);
    }

    logger.info(
      {
        userLocator: payload.userLocator,
        cluster: payload.cluster,
        agentId: payload.agentId,
        attempt,
      },
      'cluster metadata sent upstream successfully',
    );
  } catch (error) {
    logger.error(
      {
        error,
        userLocator: payload.userLocator,
        cluster: payload.cluster,
        agentId: payload.agentId,
      },
      'could not send cluster metadata',
    );
  }
}


export async function sendWorkloadEventsPolicy(
  payload: IWorkloadEventsPolicyPayload,
): Promise<void> {
  try {
    logger.info(
      {
        userLocator: payload.userLocator,
        cluster: payload.cluster,
        agentId: payload.agentId,
      },
      'attempting to send workload auto-import policy',
    );

    const { response, attempt } = await retryRequest(
      'post',
      constructUpstreamRequestUrl('/api/v1/policy'),
      payload,
      upstreamRequestOptions,
    );
    if (!isSuccessStatusCode(response.statusCode)) {
      throw new Error(`${response.statusCode} ${response.statusMessage}`);
    }

    logger.info(
      {
        userLocator: payload.userLocator,
        cluster: payload.cluster,
        agentId: payload.agentId,
        attempt,
      },
      'workload auto-import policy sent upstream successfully',
    );
  } catch (error) {
    logger.error(
      {
        error,
        userLocator: payload.userLocator,
        cluster: payload.cluster,
        agentId: payload.agentId,
      },
      'could not send workload auto-import policy',
    );
  }
}


async function deployKubernetesMonitor(
  imageOptions: IImageOptions,
  deployOptions: IDeployOptions,
): Promise<void> {
  if (!existsSync(helmPath)) {
    await downloadHelm();
  }

  await kubectl.applyK8sYaml('test/fixtures/proxying/tinyproxy-service.yaml');
  await kubectl.applyK8sYaml(
    'test/fixtures/proxying/tinyproxy-deployment.yaml',
  );
  await kubectl.waitForDeployment('forwarding-proxy', 'snyk-monitor');

  const imageNameAndTag = imageOptions.nameAndTag.split(':');
  const imageName = imageNameAndTag[0];
  const imageTag = imageNameAndTag[1];
  const imagePullPolicy = imageOptions.pullPolicy;

  await exec(
    `${helmPath} upgrade --install snyk-monitor ${helmChartPath} --namespace snyk-monitor ` +
      `--set image.repository=${imageName} ` +
      `--set image.tag=${imageTag} ` +
      `--set image.pullPolicy=${imagePullPolicy} ` +
      '--set integrationApi=https://api.dev.snyk.io/v2/kubernetes-upstream ' +
      `--set clusterName=${deployOptions.clusterName} ` +
      '--set https_proxy=http://forwarding-proxy:8080',
  );
  console.log(
    `Deployed ${imageOptions.nameAndTag} with pull policy ${imageOptions.pullPolicy}`,
  );
}


async function deployKubernetesMonitor(
  imageOptions: IImageOptions,
  deployOptions: IDeployOptions,
): Promise<void> {
  if (!existsSync(helmPath)) {
    await downloadHelm();
  }

  const imageNameAndTag = imageOptions.nameAndTag.split(':');
  const imageName = imageNameAndTag[0];
  const imageTag = imageNameAndTag[1];
  const imagePullPolicy = imageOptions.pullPolicy;

  await exec(
    `${helmPath} upgrade --install snyk-monitor ${helmChartPath} --namespace snyk-monitor ` +
      `--set image.repository=${imageName} ` +
      `--set image.tag=${imageTag} ` +
      `--set image.pullPolicy=${imagePullPolicy} ` +
      '--set integrationApi=https://api.dev.snyk.io/v2/kubernetes-upstream ' +
      `--set clusterName=${deployOptions.clusterName} ` +
      '--set nodeSelector."kubernetes\\.io/os"=linux ' +
      '--set pvc.enabled=true ' +
      '--set pvc.create=true ' +
      '--set log_level="INFO" ' +
      '--set rbac.serviceAccount.annotations."foo"="bar" ' +
      '--set volumes.projected.serviceAccountToken=true ' +
      '--set securityContext.fsGroup=65534 ' +
      '--set skopeo.compression.level=1 ' +
      '--set workers.count=5 ' +
      '--set sysdig.enabled=true ',
  );
  console.log(
    `Deployed ${imageOptions.nameAndTag} with pull policy ${imageOptions.pullPolicy}`,
  );
}


function createTestYamlDeployment(
  newYamlPath: string,
  imageNameAndTag: string,
  imagePullPolicy: string,
  clusterName: string,
): void {
  console.log('Creating YAML snyk-monitor deployment...');
  const originalDeploymentYaml = readFileSync(
    './snyk-monitor-deployment.yaml',
    'utf8',
  );
  const deployment = parse(originalDeploymentYaml);

  const container = deployment.spec.template.spec.containers.find(
    (container) => container.name === 'snyk-monitor',
  );
  container.image = imageNameAndTag;
  container.imagePullPolicy = imagePullPolicy;

  // Inject the baseUrl of kubernetes-upstream that snyk-monitor container use to send metadata
  const envVar = container.env.find(
    (env) => env.name === 'SNYK_INTEGRATION_API',
  );
  envVar.value = 'https://api.dev.snyk.io/v2/kubernetes-upstream';
  delete envVar.valueFrom;

  if (clusterName) {
    const clusterNameEnvVar = container.env.find(
      (env) => env.name === 'SNYK_CLUSTER_NAME',
    );
    clusterNameEnvVar.value = clusterName;
    delete clusterNameEnvVar.valueFrom;
  }

  writeFileSync(newYamlPath, stringify(deployment));
  console.log('Created YAML snyk-monitor deployment');
}


function getServiceAccountApiToken(): string {
  const serviceAccountApiToken = randomUUID();
  console.log(
    `Generated new service account API token ${serviceAccountApiToken}`,
  );
  return serviceAccountApiToken;
}


async function predeploy(
  integrationId: string,
  serviceAccountApiToken: string,
  namespace: string,
): Promise<void> {
  try {
    const secretName = 'snyk-monitor';
    console.log(`Creating namespace ${namespace} and secret ${secretName}`);

    try {
      await kubectl.createNamespace(namespace);
    } catch (error) {
      console.log(`Namespace ${namespace} already exist`);
    }
    const gcrDockercfg = process.env['PRIVATE_REGISTRIES_DOCKERCFG'] || '{}';
    await kubectl.createSecret(secretName, namespace, {
      'dockercfg.json': gcrDockercfg,
      integrationId,
      serviceAccountApiToken,
    });
    await createRegistriesConfigMap(namespace);
    console.log(`Namespace ${namespace} and secret ${secretName} created`);
  } catch (error) {
    console.log(
      'Could not create namespace and secret, they probably already exist',
    );
  }
}


      console.error(`nock pending mocks: ${nock.pendingMocks()}`);
      throw err;
    }
  });


            userLocator: expect.any(String),
            cluster: 'Default cluster',
            agentId: expect.any(String),
          },
          facts: [
            {
              type: 'loadedPackages',
              data: bodyNoToken.data,
            },
          ],
        });
      });

    await scrapeData();

    try {
      expect(nock.isDone()).toBeTruthy();
    } catch (err) {
      console.error(`nock pending mocks: ${nock.pendingMocks()}`);
      throw err;
    }
  });
});


  public run = async (): Promise<void> => {
    await globalResolver.doInit(this._platform);
    await this.phpDriveService.init();

    this.nodeRepository = await globalResolver.database.getRepository<DriveFile>(
      "drive_files",
      DriveFile,
    );

    let page: Pagination = { limitStr: "100" };
    const context: ExecutionContext = {
      user: {
        id: null,
        server_request: true,
      },
    };

    do {
      const companyListResult = await globalResolver.services.companies.getCompanies(page);
      page = companyListResult.nextPage as Pagination;

      for (const company of companyListResult.getEntities()) {
        await this.migrateCompany(company, {
          ...context,
          company: { id: company.id },
        });
      }

      console.log("Loop over companies...", page.page_token);
    } while (page.page_token);
  };

Improper Restriction of Excessive Authentication Attempts

The product does not implement sufficient measures to prevent multiple failed authentication attempts within a short time frame, making it more susceptible to brute force attacks.


export const createBubbleIcon = ({ className, path, target }) => {
  let bubbleClassName = `${className} woot-elements--${window.$chatwoot.position}`;
  const bubbleIcon = document.createElementNS(
    'http://www.w3.org/2000/svg',
    'svg'
  );
  bubbleIcon.setAttributeNS(null, 'id', 'woot-widget-bubble-icon');
  bubbleIcon.setAttributeNS(null, 'width', '24');
  bubbleIcon.setAttributeNS(null, 'height', '24');
  bubbleIcon.setAttributeNS(null, 'viewBox', '0 0 240 240');
  bubbleIcon.setAttributeNS(null, 'fill', 'none');
  bubbleIcon.setAttribute('xmlns', 'http://www.w3.org/2000/svg');

  const bubblePath = document.createElementNS(
    'http://www.w3.org/2000/svg',
    'path'
  );
  bubblePath.setAttributeNS(null, 'd', path);
  bubblePath.setAttributeNS(null, 'fill', '#FFFFFF');

  bubbleIcon.appendChild(bubblePath);
  target.appendChild(bubbleIcon);

  if (isExpandedView(window.$chatwoot.type)) {
    const textNode = document.createElement('div');
    textNode.id = 'woot-widget--expanded__text';
    textNode.innerText = '';
    target.appendChild(textNode);
    bubbleClassName += ' woot-widget--expanded';
  }

  target.className = bubbleClassName;
  target.title = 'Open chat window';
  return target;
};


export const setBubbleText = bubbleText => {
  if (isExpandedView(window.$chatwoot.type)) {
    const textNode = document.getElementById('woot-widget--expanded__text');
    textNode.innerText = bubbleText;
  }
};


export function defaultRenderTag(tag, params) {
  // This file is in lib but it's used as a helper
  let siteSettings = helperContext().siteSettings;

  params = params || {};
  const visibleName = escapeExpression(tag);
  tag = visibleName.toLowerCase();
  const classes = ["discourse-tag"];
  const tagName = params.tagName || "a";
  let path;
  if (tagName === "a" && !params.noHref) {
    if ((params.isPrivateMessage || params.pmOnly) && User.current()) {
      const username = params.tagsForUser
        ? params.tagsForUser
        : User.current().username;
      path = `/u/${username}/messages/tags/${tag}`;
    } else {
      path = `/tag/${tag}`;
    }
  }
  const href = path ? ` href='${getURL(path)}' ` : "";

  if (siteSettings.tag_style || params.style) {
    classes.push(params.style || siteSettings.tag_style);
  }
  if (params.size) {
    classes.push(params.size);
  }

  let val =
    "<" +
    tagName +
    href +
    " data-tag-name=" +
    tag +
    (params.description ? ' title="' + escape(params.description) + '" ' : "") +
    " class='" +
    classes.join(" ") +
    "'>" +
    visibleName +
    "</" +
    tagName +
    ">";

  if (params.count) {
    val += " x" + params.count + "";
  }

  return val;
}


  _saveDraft(channelId, draft) {
    const data = { chat_channel_id: channelId };
    if (draft) {
      data.data = JSON.stringify(draft);
    }

    ajax("/chat/drafts.json", { type: "POST", data, ignoreUnsent: false })
      .then(() => {
        this.markNetworkAsReliable();
      })
      .catch((error) => {
        // we ignore a draft which can't be saved because it's too big
        // and only deal with network error for now
        if (!error.jqXHR?.responseJSON?.errors?.length) {
          this.markNetworkAsUnreliable();
        }
      });
  }


  totalCount(count, pmCount) {
    return pmCount ? count + pmCount : count;
  },


      auth: auth.master(config),
      className: 'Object',
      restWhere: { value: { $gt: 2 } },
      restOptions: { limit: 2 },
    });
    const spy = spyOn(query, 'execute').and.callThrough();
    const classSpy = spyOn(RestQuery._UnsafeRestQuery.prototype, 'execute').and.callThrough();
    const results = [];
    await query.each(result => {
      expect(result.value).toBeGreaterThan(2);
      results.push(result);
    });
    expect(spy.calls.count()).toBe(0);
    expect(classSpy.calls.count()).toBe(4);
    expect(results.length).toBe(7);
  });

Always-Incorrect Control Flow Implementation

The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.


      auth: master(this.config),
      className: '_Role',
      restWhere,
    });
    await query.each(result => results.push(result));
  } else {
    await new Parse.Query(Parse.Role)
      .equalTo('users', this.user)
      .each(result => results.push(result.toJSON()), { useMasterKey: true });
  }
  return results;
};


      auth: master(config),
      className: '_Session',
      restWhere: { sessionToken },
      restOptions,
    });
    results = (await query.execute()).results;
  } else {
    results = (
      await new Parse.Query(Parse.Session)
        .limit(1)
        .include('user')
        .equalTo('sessionToken', sessionToken)
        .find({ useMasterKey: true })
    ).map(obj => obj.toJSON());
  }

  if (results.length !== 1 || !results[0]['user']) {
    throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token');
  }
  const now = new Date(),
    expiresAt = results[0].expiresAt ? new Date(results[0].expiresAt.iso) : undefined;
  if (expiresAt < now) {
    throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token is expired.');
  }
  const obj = results[0]['user'];
  delete obj.password;
  obj['className'] = '_User';
  obj['sessionToken'] = sessionToken;
  if (cacheController) {
    cacheController.user.put(sessionToken, obj);
  }
  const userObject = Parse.Object.fromJSON(obj);
  return new Auth({
    config,
    cacheController,
    isMaster: false,
    installationId,
    user: userObject,
  });
};


          auth: master(config),
          className: '_Installation',
          restWhere: updateWhere,
        });
        return restQuery.buildRestWhere().then(() => {
          const write = new RestWrite(
            config,
            master(config),
            '_Installation',
            restQuery.restWhere,
            restUpdate
          );
          write.runOptions.many = true;
          return write.execute();
        });
      };


_UnsafeRestQuery.prototype.redirectClassNameForKey = function () {
  if (!this.redirectKey) {
    return Promise.resolve();
  }

  // We need to change the class name based on the schema
  return this.config.database
    .redirectClassNameForKey(this.className, this.redirectKey)
    .then(newClassName => {
      this.className = newClassName;
      this.redirectClassName = newClassName;
    });
};


_UnsafeRestQuery.prototype.denyProtectedFields = async function () {
  if (this.auth.isMaster) {
    return;
  }
  const schemaController = await this.config.database.loadSchema();
  const protectedFields =
    this.config.database.addProtectedFields(
      schemaController,
      this.className,
      this.restWhere,
      this.findOptions.acl,
      this.auth,
      this.findOptions
    ) || [];
  for (const key of protectedFields) {
    if (this.restWhere[key]) {
      throw new Parse.Error(
        Parse.Error.OPERATION_FORBIDDEN,
        `This user is not allowed to query ${key} on class ${this.className}`
      );
    }
  }
};


_UnsafeRestQuery.prototype.handleIncludeAll = function () {
  if (!this.includeAll) {
    return;
  }
  return this.config.database
    .loadSchema()
    .then(schemaController => schemaController.getOneSchema(this.className))
    .then(schema => {
      const includeFields = [];
      const keyFields = [];
      for (const field in schema.fields) {
        if (
          (schema.fields[field].type && schema.fields[field].type === 'Pointer') ||
          (schema.fields[field].type && schema.fields[field].type === 'Array')
        ) {
          includeFields.push([field]);
          keyFields.push(field);
        }
      }
      // Add fields to include, keys, remove dups
      this.include = [...new Set([...this.include, ...includeFields])];
      // if this.keys not set, then all keys are already included
      if (this.keys) {
        this.keys = [...new Set([...this.keys, ...keyFields])];
      }
    });
};


_UnsafeRestQuery.prototype.handleInclude = function () {
  if (this.include.length == 0) {
    return;
  }

  var pathResponse = includePath(
    this.config,
    this.auth,
    this.response,
    this.include[0],
    this.restOptions
  );
  if (pathResponse.then) {
    return pathResponse.then(newResponse => {
      this.response = newResponse;
      this.include = this.include.slice(1);
      return this.handleInclude();
    });
  } else if (this.include.length > 0) {
    this.include = this.include.slice(1);
    return this.handleInclude();
  }

  return pathResponse;
};


_UnsafeRestQuery.prototype.runAfterFindTrigger = function () {
  if (!this.response) {
    return;
  }
  if (!this.runAfterFind) {
    return;
  }
  // Avoid doing any setup for triggers if there is no 'afterFind' trigger for this class.
  const hasAfterFindHook = triggers.triggerExists(
    this.className,
    triggers.Types.afterFind,
    this.config.applicationId
  );
  if (!hasAfterFindHook) {
    return Promise.resolve();
  }
  // Skip Aggregate and Distinct Queries
  if (this.findOptions.pipeline || this.findOptions.distinct) {
    return Promise.resolve();
  }

  const json = Object.assign({}, this.restOptions);
  json.where = this.restWhere;
  const parseQuery = new Parse.Query(this.className);
  parseQuery.withJSON(json);
  // Run afterFind trigger and set the new results
  return triggers
    .maybeRunAfterFindTrigger(
      triggers.Types.afterFind,
      this.auth,
      this.className,
      this.response.results,
      this.config,
      parseQuery,
      this.context
    )
    .then(results => {
      // Ensure we properly set the className back
      if (this.redirectClassName) {
        this.response.results = results.map(object => {
          if (object instanceof Parse.Object) {
            object = object.toJSON();
          }
          object.className = this.redirectClassName;
          return object;
        });
      } else {
        this.response.results = results;
      }
    });
};


_UnsafeRestQuery.prototype.execute = function (executeOptions) {
  return Promise.resolve()
    .then(() => {
      return this.buildRestWhere();
    })
    .then(() => {
      return this.denyProtectedFields();
    })
    .then(() => {
      return this.handleIncludeAll();
    })
    .then(() => {
      return this.handleExcludeKeys();
    })
    .then(() => {
      return this.runFind(executeOptions);
    })
    .then(() => {
      return this.runCount();
    })
    .then(() => {
      return this.handleInclude();
    })
    .then(() => {
      return this.runAfterFindTrigger();
    })
    .then(() => {
      return this.handleAuthAdapters();
    })
    .then(() => {
      return this.response;
    });
};


_UnsafeRestQuery.prototype.cleanResultAuthData = function (result) {
  delete result.password;
  if (result.authData) {
    Object.keys(result.authData).forEach(provider => {
      if (result.authData[provider] === null) {
        delete result.authData[provider];
      }
    });

    if (Object.keys(result.authData).length == 0) {
      delete result.authData;
    }
  }
};


_UnsafeRestQuery.prototype.runCount = function () {
  if (!this.doCount) {
    return;
  }
  this.findOptions.count = true;
  delete this.findOptions.skip;
  delete this.findOptions.limit;
  return this.config.database.find(this.className, this.restWhere, this.findOptions).then(c => {
    this.response.count = c;
  });
};


_UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
  var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
  if (!notInQueryObject) {
    return;
  }

  // The notInQuery value must have precisely two keys - where and className
  var notInQueryValue = notInQueryObject['$notInQuery'];
  if (!notInQueryValue.where || !notInQueryValue.className) {
    throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery');
  }

  const additionalOptions = {
    redirectClassNameForKey: notInQueryValue.redirectClassNameForKey,
  };

  if (this.restOptions.subqueryReadPreference) {
    additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
    additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
  } else if (this.restOptions.readPreference) {
    additionalOptions.readPreference = this.restOptions.readPreference;
  }

  const subquery = await RestQuery({
    method: RestQuery.Method.find,
    config: this.config,
    auth: this.auth,
    className: notInQueryValue.className,
    restWhere: notInQueryValue.where,
    restOptions: additionalOptions,
  });

  return subquery.execute().then(response => {
    transformNotInQuery(notInQueryObject, subquery.className, response.results);
    // Recurse to repeat
    return this.replaceNotInQuery();
  });
};


_UnsafeRestQuery.prototype.getUserAndRoleACL = function () {
  if (this.auth.isMaster) {
    return Promise.resolve();
  }

  this.findOptions.acl = ['*'];

  if (this.auth.user) {
    return this.auth.getUserRoles().then(roles => {
      this.findOptions.acl = this.findOptions.acl.concat(roles, [this.auth.user.id]);
      return;
    });
  } else {
    return Promise.resolve();
  }
};


_UnsafeRestQuery.prototype.replaceInQuery = async function () {
  var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
  if (!inQueryObject) {
    return;
  }

  // The inQuery value must have precisely two keys - where and className
  var inQueryValue = inQueryObject['$inQuery'];
  if (!inQueryValue.where || !inQueryValue.className) {
    throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery');
  }

  const additionalOptions = {
    redirectClassNameForKey: inQueryValue.redirectClassNameForKey,
  };

  if (this.restOptions.subqueryReadPreference) {
    additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
    additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
  } else if (this.restOptions.readPreference) {
    additionalOptions.readPreference = this.restOptions.readPreference;
  }

  const subquery = await RestQuery({
    method: RestQuery.Method.find,
    config: this.config,
    auth: this.auth,
    className: inQueryValue.className,
    restWhere: inQueryValue.where,
    restOptions: additionalOptions,
  });
  return subquery.execute().then(response => {
    transformInQuery(inQueryObject, subquery.className, response.results);
    // Recurse to repeat
    return this.replaceInQuery();
  });
};


_UnsafeRestQuery.prototype.buildRestWhere = function () {
  return Promise.resolve()
    .then(() => {
      return this.getUserAndRoleACL();
    })
    .then(() => {
      return this.redirectClassNameForKey();
    })
    .then(() => {
      return this.validateClientClassCreation();
    })
    .then(() => {
      return this.replaceSelect();
    })
    .then(() => {
      return this.replaceDontSelect();
    })
    .then(() => {
      return this.replaceInQuery();
    })
    .then(() => {
      return this.replaceNotInQuery();
    })
    .then(() => {
      return this.replaceEquality();
    });
};


_UnsafeRestQuery.prototype.each = function (callback) {
  const { config, auth, className, restWhere, restOptions, clientSDK } = this;
  // if the limit is set, use it
  restOptions.limit = restOptions.limit || 100;
  restOptions.order = 'objectId';
  let finished = false;

  return continueWhile(
    () => {
      return !finished;
    },
    async () => {
      // Safe here to use _UnsafeRestQuery because the security was already
      // checked during "await RestQuery()"
      const query = new _UnsafeRestQuery(
        config,
        auth,
        className,
        restWhere,
        restOptions,
        clientSDK,
        this.runAfterFind,
        this.context
      );
      const { results } = await query.execute();
      results.forEach(callback);
      finished = results.length < restOptions.limit;
      if (!finished) {
        restWhere.objectId = Object.assign({}, restWhere.objectId, {
          $gt: results[results.length - 1].objectId,
        });
      }
    }
  );
};


_UnsafeRestQuery.prototype.handleAuthAdapters = async function () {
  if (this.className !== '_User' || this.findOptions.explain) {
    return;
  }
  await Promise.all(
    this.response.results.map(result =>
      this.config.authDataManager.runAfterFind(
        { config: this.config, auth: this.auth },
        result.authData
      )
    )
  );
};


_UnsafeRestQuery.prototype.replaceEquality = function () {
  if (typeof this.restWhere !== 'object') {
    return;
  }
  for (const key in this.restWhere) {
    this.restWhere[key] = replaceEqualityConstraint(this.restWhere[key]);
  }
};


_UnsafeRestQuery.prototype.handleExcludeKeys = function () {
  if (!this.excludeKeys) {
    return;
  }
  if (this.keys) {
    this.keys = this.keys.filter(k => !this.excludeKeys.includes(k));
    return;
  }
  return this.config.database
    .loadSchema()
    .then(schemaController => schemaController.getOneSchema(this.className))
    .then(schema => {
      const fields = Object.keys(schema.fields);
      this.keys = fields.filter(k => !this.excludeKeys.includes(k));
    });
};


async function RestQuery({
  method,
  config,
  auth,
  className,
  restWhere = {},
  restOptions = {},
  clientSDK,
  runAfterFind = true,
  runBeforeFind = true,
  context,
}) {
  if (![RestQuery.Method.find, RestQuery.Method.get].includes(method)) {
    throw new Parse.Error(Parse.Error.INVALID_QUERY, 'bad query type');
  }
  enforceRoleSecurity(method, className, auth);
  const result = runBeforeFind
    ? await triggers.maybeRunQueryTrigger(
      triggers.Types.beforeFind,
      className,
      restWhere,
      restOptions,
      config,
      auth,
      context,
      method === RestQuery.Method.get
    )
    : Promise.resolve({ restWhere, restOptions });

  return new _UnsafeRestQuery(
    config,
    auth,
    className,
    result.restWhere || restWhere,
    result.restOptions || restOptions,
    clientSDK,
    runAfterFind,
    context
  );
}


_UnsafeRestQuery.prototype.replaceSelect = async function () {
  var selectObject = findObjectWithKey(this.restWhere, '$select');
  if (!selectObject) {
    return;
  }

  // The select value must have precisely two keys - query and key
  var selectValue = selectObject['$select'];
  // iOS SDK don't send where if not set, let it pass
  if (
    !selectValue.query ||
    !selectValue.key ||
    typeof selectValue.query !== 'object' ||
    !selectValue.query.className ||
    Object.keys(selectValue).length !== 2
  ) {
    throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select');
  }

  const additionalOptions = {
    redirectClassNameForKey: selectValue.query.redirectClassNameForKey,
  };

  if (this.restOptions.subqueryReadPreference) {
    additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
    additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
  } else if (this.restOptions.readPreference) {
    additionalOptions.readPreference = this.restOptions.readPreference;
  }

  const subquery = await RestQuery({
    method: RestQuery.Method.find,
    config: this.config,
    auth: this.auth,
    className: selectValue.query.className,
    restWhere: selectValue.query.where,
    restOptions: additionalOptions,
  });

  return subquery.execute().then(response => {
    transformSelect(selectObject, selectValue.key, response.results);
    // Keep replacing $select clauses
    return this.replaceSelect();
  });
};


_UnsafeRestQuery.prototype.runFind = function (options = {}) {
  if (this.findOptions.limit === 0) {
    this.response = { results: [] };
    return Promise.resolve();
  }
  const findOptions = Object.assign({}, this.findOptions);
  if (this.keys) {
    findOptions.keys = this.keys.map(key => {
      return key.split('.')[0];
    });
  }
  if (options.op) {
    findOptions.op = options.op;
  }
  return this.config.database
    .find(this.className, this.restWhere, findOptions, this.auth)
    .then(results => {
      if (this.className === '_User' && !findOptions.explain) {
        for (var result of results) {
          this.cleanResultAuthData(result);
        }
      }

      this.config.filesController.expandFilesInObject(this.config, results);

      if (this.redirectClassName) {
        for (var r of results) {
          r.className = this.redirectClassName;
        }
      }
      this.response = { results: results };
    });
};


_UnsafeRestQuery.prototype.validateClientClassCreation = function () {
  if (
    this.config.allowClientClassCreation === false &&
    !this.auth.isMaster &&
    SchemaController.systemClasses.indexOf(this.className) === -1
  ) {
    return this.config.database
      .loadSchema()
      .then(schemaController => schemaController.hasClass(this.className))
      .then(hasClass => {
        if (hasClass !== true) {
          throw new Parse.Error(
            Parse.Error.OPERATION_FORBIDDEN,
            'This user is not allowed to access ' + 'non-existent class: ' + this.className
          );
        }
      });
  } else {
    return Promise.resolve();
  }
};


_UnsafeRestQuery.prototype.replaceDontSelect = async function () {
  var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
  if (!dontSelectObject) {
    return;
  }

  // The dontSelect value must have precisely two keys - query and key
  var dontSelectValue = dontSelectObject['$dontSelect'];
  if (
    !dontSelectValue.query ||
    !dontSelectValue.key ||
    typeof dontSelectValue.query !== 'object' ||
    !dontSelectValue.query.className ||
    Object.keys(dontSelectValue).length !== 2
  ) {
    throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect');
  }
  const additionalOptions = {
    redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey,
  };

  if (this.restOptions.subqueryReadPreference) {
    additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
    additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
  } else if (this.restOptions.readPreference) {
    additionalOptions.readPreference = this.restOptions.readPreference;
  }

  const subquery = await RestQuery({
    method: RestQuery.Method.find,
    config: this.config,
    auth: this.auth,
    className: dontSelectValue.query.className,
    restWhere: dontSelectValue.query.where,
    restOptions: additionalOptions,
  });

  return subquery.execute().then(response => {
    transformDontSelect(dontSelectObject, dontSelectValue.key, response.results);
    // Keep replacing $dontSelect clauses
    return this.replaceDontSelect();
  });
};


function enforceRoleSecurity(method, className, auth) {
  if (className === '_Installation' && !auth.isMaster && !auth.isMaintenance) {
    if (method === 'delete' || method === 'find') {
      const error = `Clients aren't allowed to perform the ${method} operation on the installation collection.`;
      throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
    }
  }

  //all volatileClasses are masterKey only
  if (
    classesWithMasterOnlyAccess.indexOf(className) >= 0 &&
    !auth.isMaster &&
    !auth.isMaintenance
  ) {
    const error = `Clients aren't allowed to perform the ${method} operation on the ${className} collection.`;
    throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
  }

  // readOnly masterKey is not allowed
  if (auth.isReadOnly && (method === 'delete' || method === 'create' || method === 'update')) {
    const error = `read-only masterKey isn't allowed to perform the ${method} operation.`;
    throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
  }
}


const find = async (config, auth, className, restWhere, restOptions, clientSDK, context) => {
  const query = await RestQuery({
    method: RestQuery.Method.find,
    config,
    auth,
    className,
    restWhere,
    restOptions,
    clientSDK,
    context,
  });
  return query.execute();
};


function update(config, auth, className, restWhere, restObject, clientSDK, context) {
  enforceRoleSecurity('update', className, auth);

  return Promise.resolve()
    .then(async () => {
      const hasTriggers = checkTriggers(className, config, ['beforeSave', 'afterSave']);
      const hasLiveQuery = checkLiveQuery(className, config);
      if (hasTriggers || hasLiveQuery) {
        // Do not use find, as it runs the before finds
        const query = await RestQuery({
          method: RestQuery.Method.get,
          config,
          auth,
          className,
          restWhere,
          runAfterFind: false,
          runBeforeFind: false,
          context,
        });
        return query.execute({
          op: 'update',
        });
      }
      return Promise.resolve({});
    })
    .then(({ results }) => {
      var originalRestObject;
      if (results && results.length) {
        originalRestObject = results[0];
      }
      return new RestWrite(
        config,
        auth,
        className,
        restWhere,
        restObject,
        originalRestObject,
        clientSDK,
        context,
        'update'
      ).execute();
    })
    .catch(error => {
      handleSessionMissingError(error, className, auth);
    });
}


const get = async (config, auth, className, objectId, restOptions, clientSDK, context) => {
  var restWhere = { objectId };
  const query = await RestQuery({
    method: RestQuery.Method.get,
    config,
    auth,
    className,
    restWhere,
    restOptions,
    clientSDK,
    context,
  });
  return query.execute();
};


module.exports = async (ctx) => {
    const { subdomain } = ctx.params;
    if (!isValidHost(subdomain)) {
        throw Error('Invalid subdomain');
    }
    const shopUrl = `https://${subdomain}.booth.pm`;

    let shopName;
    const items = [];
    for (let page = 1; page <= maxPages; page++) {
        const pageUrl = `${shopUrl}/items?page=${page}`;
        // eslint-disable-next-line no-await-in-loop
        const response = await got({
            method: 'get',
            url: pageUrl,
        });

        const data = response.data;

        const $ = cheerio.load(data);
        shopName = $('div.shop-name > span').text();
        const pageItems = $('li.item');

        if (pageItems.length === 0) {
            break;
        }

        for (let i = 0; i < pageItems.length; ++i) {
            const pageItem = pageItems[i];

            // extract item name
            const itemName = $('h2.item-name > a', pageItem).text();

            // extract item url
            const itemUrl = shopUrl + $('h2.item-name > a', pageItem).attr('href');

            // extract item preview url
            const itemPreviewUrl = $('div.swap-image > img', pageItem).attr('src');

            items.push({
                title: itemName,
                description: `<img src='${itemPreviewUrl}'/>`,
                link: itemUrl,
            });
        }
    }

    ctx.state.data = {
        title: shopName,
        link: shopUrl,
        description: shopName,
        allowEmpty: true,
        item: items,
    };
};

The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.


module.exports = async (ctx) => {
    const { column } = ctx.params;
    if (!isValidHost(column)) {
        throw Error('Invalid column');
    }
    const link = `http://${column}.blog.caixin.com`;
    const feed_url = `${link}/feed`;
    const feed = await parser.parseURL(feed_url);

    const title = `财新博客 - ${/[^»]*$/.exec(feed.title)[0]}`;

    const items = await Promise.all(
        feed.items.slice(0, 10).map(async (item, index) => {
            const link = item.link;
            const single = {
                title: item.title,
                pubDate: item.pubDate,
                link,
                author: item['dc:creator'],
            };
            const other = await ctx.cache.tryGet(link, () => load(link, index === 0));
            return Promise.resolve(Object.assign({}, single, other));
        })
    );

    ctx.state.data = {
        title,
        link,
        description: items[0].feed_description,
        item: items,
    };
};


const domainValidation = (domain, ctx) => {
    if (!config.feature.allow_user_supply_unsafe_domain && !allowDomain.includes(domain)) {
        ctx.throw(403, `This RSS is disabled unless 'ALLOW_USER_SUPPLY_UNSAFE_DOMAIN' is set to 'true'.`);
    }
};


module.exports = async (ctx) => {
    const pub = ctx.params.pub;
    const jrn = ctx.params.jrn;
    const host = `https://${pub}.scitation.org`;
    const jrnlUrl = `${host}/toc/${jrn}/current?size=all`;
    if (!isValidHost(pub)) {
        throw Error('Invalid pub');
    }

    // use Puppeteer due to the obstacle by cloudflare challenge
    const browser = await require('@/utils/puppeteer')();

    const { jrnlName, list } = await ctx.cache.tryGet(
        jrnlUrl,
        async () => {
            const response = await puppeteerGet(jrnlUrl, browser);
            const $ = cheerio.load(response);
            const jrnlName = $('.header-journal-title').text();
            const list = $('.card')
                .toArray()
                .map((item) => {
                    $(item).find('.access-text').remove();
                    const title = $(item).find('.hlFld-Title').text();
                    const authors = $(item).find('.entryAuthor.all').text();
                    const img = $(item).find('img').attr('src');
                    const link = $(item).find('.ref.nowrap').attr('href');
                    const doi = link.replace('/doi/full/', '');
                    const description = renderDesc(title, authors, doi, img);
                    return {
                        title,
                        link,
                        doi,
                        description,
                    };
                });
            return {
                jrnlName,
                list,
            };
        },
        config.cache.routeExpire,
        false
    );

    browser.close();

    ctx.state.data = {
        title: jrnlName,
        link: jrnlUrl,
        item: list,
        allowEmpty: true,
    };
};


module.exports = async (ctx) => {
    const type = ctx.params.type ?? 'www';
    if (!isValidHost(type)) {
        throw Error('Invalid type');
    }

    const base_url = `https://${type}.solidot.org`;
    const response = await got({
        method: 'get',
        url: base_url,
    });
    const data = response.data; // content is html format
    const $ = cheerio.load(data);

    // get urls
    const a = $('div.block_m').find('div.bg_htit > h2 > a');
    const urls = [];
    for (let i = 0; i < a.length; ++i) {
        urls.push($(a[i]).attr('href'));
    }

    // get articles
    const msg_list = await Promise.all(urls.map((u) => ctx.cache.tryGet(u, () => get_article(u))));

    // feed the data
    ctx.state.data = {
        title: '奇客的资讯，重要的东西',
        link: base_url,
        item: msg_list,
    };
};


        appendTo: () => document.body,
        onCreate(instance) {


        onCreate(instance) {
            const content = instance.props.content + $("#narrow-hotkey-tooltip-template").html();
            instance.setContent(parse_html(content));
        },


        onCreate(instance) {
            instance.setContent(
                parse_html(render_narrow_tooltip({content: instance.props.content})),
            );
        },


function renderFile(
  filename: string,
  data: DataObj,
  config?: PartialConfig,
  cb?: CallbackFn,
): Promise<string> | void {
  /*
  Here we have some function overloading.
  Essentially, the first 2 arguments to renderFile should always be the filename and data
  Express will call renderFile with (filename, data, cb)
  We also want to make (filename, data, options, cb) available
  */

  let renderConfig: EtaConfigWithFilename;
  let callback: CallbackFn | undefined;
  data = data || {};

  // First, assign our callback function to `callback`
  // We can leave it undefined if neither parameter is a function;
  // Callbacks are optional
  if (typeof cb === "function") {
    // The 4th argument is the callback
    callback = cb;
  } else if (typeof config === "function") {
    // The 3rd arg is the callback
    callback = config;
  }

  // If there is a config object passed in explicitly, use it
  if (typeof config === "object") {
    renderConfig = getConfig(
      (config as PartialConfig) || {},
    ) as EtaConfigWithFilename;
  } else {
    // Otherwise, get the default config
    renderConfig = getConfig({}) as EtaConfigWithFilename;
  }

  // Set the filename option on the template
  // This will first try to resolve the file path (see getPath for details)
  renderConfig.filename = getPath(filename, renderConfig);

  return tryHandleCache(data, renderConfig, callback);
}


function renderFile(
  filename: string,
  data: DataObj,
  config?: PartialConfig,
  cb?: CallbackFn
): Promise<string> | void {
  /*
  Here we have some function overloading.
  Essentially, the first 2 arguments to renderFile should always be the filename and data
  Express will call renderFile with (filename, data, cb)
  We also want to make (filename, data, options, cb) available
  */

  let renderConfig: EtaConfigWithFilename;
  let callback: CallbackFn | undefined;
  data = data || {};

  // First, assign our callback function to `callback`
  // We can leave it undefined if neither parameter is a function;
  // Callbacks are optional
  if (typeof cb === "function") {
    // The 4th argument is the callback
    callback = cb;
  } else if (typeof config === "function") {
    // The 3rd arg is the callback
    callback = config;
  }

  // If there is a config object passed in explicitly, use it
  if (typeof config === "object") {
    renderConfig = getConfig((config as PartialConfig) || {}) as EtaConfigWithFilename;
  } else {
    // Otherwise, get the default config
    renderConfig = getConfig({}) as EtaConfigWithFilename;
  }

  // Set the filename option on the template
  // This will first try to resolve the file path (see getPath for details)
  renderConfig.filename = getPath(filename, renderConfig);

  return tryHandleCache(data, renderConfig, callback);
}


function getElementFromTemplate(template: UpdateFunctionWithMethods<unknown>): HTMLElement {
    const element = document.createElement("div");
    template(document.body, element);

    return element;
}


    default: jest.requireActual("escape-string-regexp"),
}));


export function highlightFilterElements(
    content: string | number | undefined,
    search: string | number | undefined
): UpdateFunctionWithMethods<unknown> {
    const text_content = content?.toString();
    if (
        text_content === "" ||
        text_content === undefined ||
        search === "" ||
        search === undefined
    ) {
        return html`${text_content}`;
    }

    const classifier = Classifier(search.toString());
    const templates = classifier.classify(text_content).map((highlighted_text) => {
        if (!HighlightedText.isHighlight(highlighted_text)) {
            return html`${highlighted_text.content}`;
        }
        return html`<span class="highlight">${highlighted_text.content}</span>`;
    });
    return html`${templates}`;
}


    function getHTMLStringFromTemplate(template) {
        const element = document.createElement("div");
        template({}, element);

        return element.innerHTML;
    }


function TuleapHighlightFilter() {
    function getHTMLStringFromTemplate(template) {
        const element = document.createElement("div");
        template({}, element);

        return element.innerHTML;
    }

    return function (text, search) {
        if (text === null) {
            return null;
        }
        return getHTMLStringFromTemplate(highlightFilterElements(text, search));
    };
}


export async function downloadKubectl(version: string): Promise<string> {
    let cachedToolpath = toolCache.find(kubectlToolName, version);
    let kubectlDownloadPath = '';
    const arch = getKubectlArch();
    if (!cachedToolpath) {
        try {
            kubectlDownloadPath = await toolCache.downloadTool(getkubectlDownloadURL(version, arch));
        } catch (exception) {
            if (exception instanceof toolCache.HTTPError && exception.httpStatusCode === 404) {
                throw new Error(util.format("Kubectl '%s' for '%s' arch not found.", version, arch));
            } else {
                throw new Error('DownloadKubectlFailed');
            }
        }

        cachedToolpath = await toolCache.cacheFile(kubectlDownloadPath, kubectlToolName + getExecutableExtension(), kubectlToolName, version);
    }

    const kubectlPath = path.join(cachedToolpath, kubectlToolName + getExecutableExtension());
    fs.chmodSync(kubectlPath, '775');
    return kubectlPath;
}

Incorrect Permission Assignment for Critical Resource

The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.


		fastify.addHook('onRequest', async (request, reply) => {
			// %71ueueとかでリクエストされたら困るため
			const url = decodeURI(request.url);
			if (url === bullBoardPath || url.startsWith(bullBoardPath + '/')) {
				const token = request.cookies.token;
				if (token == null) {
					reply.code(401);
					throw new Error('login required');
				}
				const user = await this.usersRepository.findOneBy({ token });
				if (user == null) {
					reply.code(403);
					throw new Error('no such user');
				}
				const isAdministrator = await this.roleService.isAdministrator(user);
				if (!isAdministrator) {
					reply.code(403);
					throw new Error('access denied');
				}
			}
		});


		super(meta, paramDef, async (ps, me) => {
			const user = await this.usersRepository.findOneBy({ id: ps.userId });

			if (user == null) {
				throw new Error('user not found');
			}

			if (user.avatarId == null) return;

			await this.usersRepository.update(user.id, {
				avatar: null,
				avatarId: null,
				avatarUrl: null,
				avatarBlurhash: null,
			});

			this.moderationLogService.log(me, 'unsetUserAvatar', {
				userId: user.id,
				userUsername: user.username,
				userHost: user.host,
				fileId: user.avatarId,
			});
		});

The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.


	public connectChannel(id: string, params: any, channel: string, pong = false) {
		const channelService = this.channelsService.getChannelService(channel);

		if (channelService.requireCredential && this.user == null) {
			return;
		}

		if (this.token && ((channelService.kind && !this.token.permission.some(p => p === channelService.kind))
			|| (!channelService.kind && channelService.requireCredential))) {
			return;
		}

		// 共有可能チャンネルに接続しようとしていて、かつそのチャンネルに既に接続していたら無意味なので無視
		if (channelService.shouldShare && this.channels.some(c => c.chName === channel)) {
			return;
		}

		const ch: Channel = channelService.create(id, this);
		this.channels.push(ch);
		ch.init(params ?? {});

		if (pong) {
			this.sendMessageToWs('connected', {
				id: id,
			});
		}
	}

The product does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.


create: (id: string, connection: Connection) => Channel;


		session: randomUUID(),
		permission: permissions,
	}, user);

	return (res.body as misskey.entities.MiauthGenTokenResponse).token;
};


export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: boolean): string;
export function format(sql: string, values: unknown[], timeZone?: string, dialect?: string): string;

The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.


export function escapeId(val: string, forbidQualified?: boolean): string;
export function escape(val: Escapable | Escapable[], timeZone?: string, dialect?: string, format?: boolean): string;


	getTokenFromRequest: (req) => {
		if (req.headers['x-csrf-token']) {
			return req.headers['x-csrf-token'];
		} else if (req.body && req.body.csrf_token) {
			return req.body.csrf_token;
		} else if (req.query) {
			return req.query._csrf;
		}
	},

The product does not properly verify that the source of data or communication is valid.


			Origin: nconf.get('url'),
			Cookie: cookie,
		},
		query: {
			_csrf: csrf_token,
		},
	});

	socket.on('connect', () => {
		callback(null, socket);
	});

	socket.on('error', (err) => {
		callback(err);
	});
};


function getFirstHeader(req: http.IncomingMessage, headerName: string): string | undefined {
  const val = req.headers[headerName]
  return Array.isArray(val) ? val[0] : val
}


export function ensureOrigin(req: express.Request, _?: express.Response, next?: express.NextFunction): void {
  if (!authenticateOrigin(req)) {
    throw new HttpError("Forbidden", HttpCode.Forbidden)
  }
  if (next) {
    next()
  }
}


export function authenticateOrigin(req: express.Request): boolean {
  // A missing origin probably means the source is non-browser.  Not sure we
  // have a use case for this but let it through.
  const originRaw = getFirstHeader(req, "origin")
  if (!originRaw) {
    return true
  }

  let origin: string
  try {
    origin = new URL(originRaw).host.trim().toLowerCase()
  } catch (error) {
    return false // Malformed URL.
  }

  // Honor Forwarded if present.
  const forwardedRaw = getFirstHeader(req, "forwarded")
  if (forwardedRaw) {
    const parts = forwardedRaw.split(/[;,]/)
    for (let i = 0; i < parts.length; ++i) {
      const [key, value] = splitOnFirstEquals(parts[i])
      if (key.trim().toLowerCase() === "host" && value) {
        return origin === value.trim().toLowerCase()
      }
    }
  }

  // Honor X-Forwarded-Host if present.
  const xHost = getFirstHeader(req, "x-forwarded-host")
  if (xHost) {
    return origin === xHost.trim().toLowerCase()
  }

  // A missing host likely means the reverse proxy has not been configured to
  // forward the host which means we cannot perform the check.  Emit a warning
  // so an admin can fix the issue.
  const host = getFirstHeader(req, "host")
  if (!host) {
    logger.warn(`no host headers found; blocking request to ${req.originalUrl}`)
    return false
  }

  return origin === host.trim().toLowerCase()
}


export const wsErrorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
  logger.error(`${err.message} ${err.stack}`)
  let statusCode = 500
  if (errorHasStatusCode(err)) {
    statusCode = err.statusCode
  } else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {
    statusCode = HttpCode.NotFound
  }
  ;(req as WebsocketRequest).ws.end(`HTTP/1.1 ${statusCode} ${err.message}\r\n\r\n`)
}


export function splitOnFirstEquals(str: string): [string, string | undefined] {
  const split = str.split(/=(.+)?/, 2)
  return [split[0], split[1]]
}


    return new Promise<Websocket>((resolve, reject) => {
      ws.on("error", (err) => reject(err))
      ws.on("open", () => resolve(ws))
    })


    cwd: path.join(fixtures, 'merge'),
    commit: '82442c2405804d7aa44e7bedbc0b93bb17707626 || touch ci ||',
  });

  expect(latestInfo.error).toBeInstanceOf(Error);
});


    return { error: new Error('Not a valid commit hash') };
  }

  if (!isGit(thisPath)) {
    return {};
  }

  try {
    const { stdout } = execa.commandSync(`git --no-pager show ${thisCommit} --summary`, { cwd });

    const info = stdout
      .split('\n')
      .filter((entry) => entry.length !== 0);
    const mergeIndex = info[1]?.indexOf('Merge') === -1 ? 0 : 1;

    const hash = (new RegExp(regex).exec(info[0]) || [])[1];
    const shortHash = hash.slice(0, 7);

    const getInfo = (index: number): string | undefined => {
      const [, extractedInfo] = (new RegExp(regex).exec(info[index]) || []);

      return extractedInfo;
    };

    const author = (getInfo(1 + mergeIndex)?.match(/([^<]+)/) || [])[1]?.trim();
    const [, email] = getInfo(1 + mergeIndex)?.match(/<([^>]+)>/) || [];
    const date = getInfo(2 + mergeIndex);
    const message = stdout.split('\n\n')[1].trim();

    return {
      hash,
      shortHash,
      commit: hash,
      shortCommit: shortHash,
      author,
      email,
      date,
      message,
    };
  } catch (error) {
    return { error };
  }
};


function inspectFallback(val) {
  const domains = Object.keys(val);
  if (domains.length === 0) {
    return "[Object: null prototype] {}";
  }
  let result = "[Object: null prototype] {\n";
  Object.keys(val).forEach((domain, i) => {
    result += formatDomain(domain, val[domain]);
    if (i < domains.length - 1) {
      result += ",";
    }
    result += "\n";
  });
  result += "}";
  return result;
}

Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')

The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.


  removeAllCookies(cb) {
    this.idx = Object.create(null);
    return cb(null);
  }


function formatPath(pathName, pathValue) {
  const indent = "    ";
  let result = `${indent}'${pathName}': [Object: null prototype] {\n`;
  Object.keys(pathValue).forEach((cookieName, i, cookieNames) => {
    const cookie = pathValue[cookieName];
    result += `      ${cookieName}: ${cookie.inspect()}`;
    if (i < cookieNames.length - 1) {
      result += ",";
    }
    result += "\n";
  });
  result += `${indent}}`;
  return result;
}


  putCookie(cookie, cb) {
    if (!this.idx[cookie.domain]) {
      this.idx[cookie.domain] = Object.create(null);
    }
    if (!this.idx[cookie.domain][cookie.path]) {
      this.idx[cookie.domain][cookie.path] = Object.create(null);
    }
    this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
    cb(null);
  }


  constructor() {
    super();
    this.synchronous = true;
    this.idx = Object.create(null);
    const customInspectSymbol = getCustomInspectSymbol();
    if (customInspectSymbol) {
      this[customInspectSymbol] = this.inspect;
    }
  }


function formatDomain(domainName, domainValue) {
  const indent = "  ";
  let result = `${indent}'${domainName}': [Object: null prototype] {\n`;
  Object.keys(domainValue).forEach((path, i, paths) => {
    result += formatPath(path, domainValue[path]);
    if (i < paths.length - 1) {
      result += ",";
    }
    result += "\n";
  });
  result += `${indent}}`;
  return result;
}


      ? element.boundElementIds.map((id) => ({ type: "arrow", id }))
      : element.boundElements ?? [],
    updated: element.updated ?? getUpdatedTimestamp(),
    link: element.link ? normalizeLink(element.link) : null,
    locked: element.locked ?? false,
  };


export const isLocalLink = (link: string | null) => {
  return !!(link?.includes(location.origin) || link?.startsWith("/"));
};


export const normalizeLink = (link: string) => {
  return sanitizeUrl(link);
};


export async function git(path: string): Promise<BlameResult> {
  const blamedLines: { [line: string]: BlamedLine } = {};
  const pathToGit: string = await which('git');

  if (!existsSync(path)) {
    throw new Error(`File ${path} does not exist`);
  }

  const result = execa.sync(pathToGit, ['blame', '-w', path]);
  result.stdout.split('\n').forEach(line => {
    if (line !== '') {
      const blamedLine = convertStringToObject(line);
      if (blamedLine.line) {
        blamedLines[blamedLine.line] = blamedLine;
      }
    }
  });
  return {
    [path]: blamedLines
  };
}

Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')

The product constructs a string for a command to be executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string.


  measure() {
    graphqlSync({ schema, source });
  },

The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.


        name @stream(label: "streamLabel", initialCount: 1, extraArg: true)
      }
    `).toDeepEqual([
      {
        message:
          'Fields "name" conflict because they have differing stream directives. Use different aliases on the fields to fetch both if this was intentional.',
        locations: [
          { line: 3, column: 9 },
          { line: 4, column: 9 },
        ],
      },
    ]);
  });


function sameArguments(
  node1: FieldNode | DirectiveNode,
  node2: FieldNode | DirectiveNode,
): boolean {
  const args1 = node1.arguments;
  const args2 = node2.arguments;

  if (args1 === undefined || args1.length === 0) {
    return args2 === undefined || args2.length === 0;
  }
  if (args2 === undefined || args2.length === 0) {
    return false;
  }

  if (args1.length !== args2.length) {
    return false;
  }

  const values2 = new Map(args2.map(({ name, value }) => [name.value, value]));
  return args1.every((arg1) => {
    const value1 = arg1.value;
    const value2 = values2.get(arg1.name.value);
    if (value2 === undefined) {
      return false;
    }

    return stringifyValue(value1) === stringifyValue(value2);
  });
}