code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
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
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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 ""
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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])
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
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
} | 0 | Go | CWE-330 | Use of Insufficiently Random Values | The product uses insufficiently random numbers or values in a security context that depends on unpredictable numbers. | https://cwe.mitre.org/data/definitions/330.html | vulnerable |
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
} | 0 | Go | CWE-770 | 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. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
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())
} | 0 | Go | CWE-770 | 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. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
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
} | 0 | Go | CWE-770 | 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. | https://cwe.mitre.org/data/definitions/770.html | vulnerable |
func NewClient(url string) (*gitrekor.Client, error) {
return gitrekor.New(url, rekor.WithUserAgent("gitsign"))
} | 0 | Go | CWE-347 | Improper Verification of Cryptographic Signature | The product does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
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
} | 0 | Go | CWE-347 | Improper Verification of Cryptographic Signature | The product does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
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
} | 0 | Go | CWE-347 | Improper Verification of Cryptographic Signature | The product does not verify, or incorrectly verifies, the cryptographic signature for data. | https://cwe.mitre.org/data/definitions/347.html | vulnerable |
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.
} | 0 | Go | CWE-354 | 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. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
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
} | 0 | Go | CWE-354 | 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. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
func (t *transport) writePacket(packet []byte) error {
if debugTransport {
t.printPacket(packet, true)
}
return t.writer.writePacket(t.bufWriter, t.rand, packet)
} | 0 | Go | CWE-354 | 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. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
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
} | 0 | Go | CWE-354 | 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. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
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
} | 0 | Go | CWE-354 | 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. | https://cwe.mitre.org/data/definitions/354.html | vulnerable |
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())
} | 0 | Go | NVD-CWE-noinfo | null | null | null | vulnerable |
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(),
})
} | 0 | Go | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
func DeleteCertHandler(c *gin.Context) {
DeleteCertificates(config.GetCertificatesDir())
} | 0 | Go | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | vulnerable |
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)
})
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
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
} | 0 | Go | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | vulnerable |
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()
} | 0 | Go | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion that takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | vulnerable |
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)
} | 0 | Go | CWE-674 | Uncontrolled Recursion | The product does not properly control the amount of recursion that takes place, consuming excessive resources, such as allocated memory or the program stack. | https://cwe.mitre.org/data/definitions/674.html | vulnerable |
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)
} | 0 | Go | CWE-77 | 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. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
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)
} | 0 | Go | CWE-77 | 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. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
func GetSettings(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"server": settings.ServerSettings,
"nginx": settings.NginxSettings,
"openai": settings.OpenAISettings,
})
} | 0 | Go | CWE-77 | 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. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
func GetSettings(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"server": settings.ServerSettings,
"nginx": settings.NginxSettings,
"openai": settings.OpenAISettings,
})
} | 0 | Go | CWE-77 | 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. | https://cwe.mitre.org/data/definitions/77.html | vulnerable |
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)
}
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
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)
}
} | 0 | Go | CWE-89 | 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. | https://cwe.mitre.org/data/definitions/89.html | vulnerable |
export const matcher = (rawStr: string, regexp: RegExp) => {
const matchResult = rawStr.match(regexp);
return matchResult;
}; | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
export const matcher = (rawStr: string, regexp: RegExp) => {
const matchResult = rawStr.match(regexp);
return matchResult;
}; | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
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>'
);
}
*/
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
public function setUp()
{
parent::setUp();
$this->config->set('HTML.Doctype', 'XHTML 1.1');
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
public function testBasicUse()
{
$this->assertResult(
'<ruby><rb>WWW</rb><rt>World Wide Web</rt></ruby>'
);
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
public function testRPUse()
{
$this->assertResult(
'<ruby><rb>WWW</rb><rp>(</rp><rt>World Wide Web</rt><rp>)</rp></ruby>'
);
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
function verifyHtmlRender(text: string) {
renderer.verify(x => x.setProperty(It.isAny(), 'innerHTML', text), Times.once());
expect().nothing();
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
function verifyTextRender(text: string) {
renderer.verify(x => x.setProperty(It.isAny(), 'textContent', text), Times.once());
expect().nothing();
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
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);
}
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
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 });
}
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
export function escapeHTML(html: string) {
if (escapeTestNoEncode.test(html)) {
return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
}
return html;
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
function renderInlineParagraph(text: string) {
return text;
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
const getEscapeReplacement = (ch: string) => escapeReplacements[ch]; | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
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>`;
}
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
const user = await firstValueFrom(users.getUser(id, null));
return user.displayName;
} | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
return `<span class="marker-ref">${escapeHTML(marker)}</span>`;
}); | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
return `<span class="user-ref">${escapeHTML(placeholderValues.shift() || '')}</span>`; | 1 | TypeScript | CWE-167 | 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. | https://cwe.mitre.org/data/definitions/167.html | safe |
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;
}
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | 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. | https://cwe.mitre.org/data/definitions/352.html | safe |
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')
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
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',
);
}
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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;
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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();
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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}`,
);
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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}`,
);
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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');
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
function getServiceAccountApiToken(): string {
const serviceAccountApiToken = randomUUID();
console.log(
`Generated new service account API token ${serviceAccountApiToken}`,
);
return serviceAccountApiToken;
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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',
);
}
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
console.error(`nock pending mocks: ${nock.pendingMocks()}`);
throw err;
}
}); | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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;
}
});
}); | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
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);
}; | 1 | TypeScript | CWE-307 | 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. | https://cwe.mitre.org/data/definitions/307.html | safe |
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;
}; | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
export const setBubbleText = bubbleText => {
if (isExpandedView(window.$chatwoot.type)) {
const textNode = document.getElementById('woot-widget--expanded__text');
textNode.innerText = bubbleText;
}
}; | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
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 += " <span class='discourse-tag-count'>x" + params.count + "</span>";
}
return val;
} | 1 | TypeScript | CWE-79 | 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. | https://cwe.mitre.org/data/definitions/79.html | safe |
_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();
}
});
} | 1 | TypeScript | CWE-770 | 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. | https://cwe.mitre.org/data/definitions/770.html | safe |
totalCount(count, pmCount) {
return pmCount ? count + pmCount : count;
}, | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
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);
}); | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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;
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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,
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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}`
);
}
}
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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])];
}
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
}
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
}
}
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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;
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
}
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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,
});
}
}
);
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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
)
)
);
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_UnsafeRestQuery.prototype.replaceEquality = function () {
if (typeof this.restWhere !== 'object') {
return;
}
for (const key in this.restWhere) {
this.restWhere[key] = replaceEqualityConstraint(this.restWhere[key]);
}
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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));
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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
);
} | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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 };
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
}
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
_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();
});
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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);
}
} | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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();
}; | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
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);
});
} | 1 | TypeScript | CWE-670 | 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. | https://cwe.mitre.org/data/definitions/670.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.