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 (*BridgeViewStub) FindBridgeStopped(al *types.ERC20EventBridgeStopped, blockNumber, logIndex uint64, txHash string) error { return nil }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (*BridgeViewStub) FindBridgeResumed(al *types.ERC20EventBridgeResumed, blockNumber, logIndex uint64, txHash string) error { return nil }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (*BridgeViewStub) FindAssetLimitsUpdated(w *types.ERC20AssetLimitsUpdated, blockNumber, logIndex uint64, ethAssetAddress string, txHash string) error { return nil }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (o *OnChainVerifier) filterSignerAdded( ctx context.Context, filterer *multisig.MultisigControlFilterer, event *types.SignerEvent, ) error { iter, err := filterer.FilterSignerAdded( &bind.FilterOpts{ Start: event.BlockNumber, End: &event.BlockNumber, Context: ctx, }, ) if err != nil { o.log.Error("Couldn't start filtering on signer added event", logging.Error(err)) return err } defer iter.Close() for iter.Next() { if o.log.GetLevel() <= logging.DebugLevel { o.log.Debug("found signer added event on chain", logging.String("new-signer", iter.Event.NewSigner.Hex()), ) } nonce, _ := big.NewInt(0).SetString(event.Nonce, 10) if iter.Event.Raw.BlockNumber == event.BlockNumber && uint64(iter.Event.Raw.Index) == event.LogIndex && iter.Event.NewSigner.Hex() == event.Address && nonce.Cmp(iter.Event.Nonce) == 0 && iter.Event.Raw.TxHash.Hex() == event.TxHash { // now we know the event is OK, // just need to check for confirmations return o.ethConfirmations.Check(event.BlockNumber) } } return ErrNoSignerEventFound }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (o *OnChainVerifier) CheckThresholdSetEvent( event *types.SignerThresholdSetEvent, ) error { o.mu.RLock() defer o.mu.RUnlock() if o.log.GetLevel() <= logging.DebugLevel { o.log.Debug("checking threshold set event on chain", logging.String("contract-address", o.multiSigAddress.Hex()), logging.String("event", event.String()), ) } filterer, err := multisig.NewMultisigControlFilterer( o.multiSigAddress, o.ethClient, ) if err != nil { o.log.Error("could not instantiate multisig control filterer", logging.Error(err)) return err } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() iter, err := filterer.FilterThresholdSet( &bind.FilterOpts{ Start: event.BlockNumber, End: &event.BlockNumber, Context: ctx, }, ) if err != nil { o.log.Error("Couldn't start filtering on signer added event", logging.Error(err)) return err } defer iter.Close() for iter.Next() { if o.log.GetLevel() <= logging.DebugLevel { o.log.Debug("found threshold set event on chain", logging.Uint16("new-threshold", iter.Event.NewThreshold), ) } nonce, _ := big.NewInt(0).SetString(event.Nonce, 10) if iter.Event.Raw.BlockNumber == event.BlockNumber && uint64(iter.Event.Raw.Index) == event.LogIndex && iter.Event.NewThreshold == uint16(event.Threshold) && nonce.Cmp(iter.Event.Nonce) == 0 && iter.Event.Raw.TxHash.Hex() == event.TxHash { // now we know the event is OK, // just need to check for confirmations return o.ethConfirmations.Check(event.BlockNumber) } } return ErrNoThresholdSetEventFound }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func (o *OnChainVerifier) filterSignerRemoved( ctx context.Context, filterer *multisig.MultisigControlFilterer, event *types.SignerEvent, ) error { iter, err := filterer.FilterSignerRemoved( &bind.FilterOpts{ Start: event.BlockNumber, End: &event.BlockNumber, Context: ctx, }, ) if err != nil { o.log.Error("Couldn't start filtering on signer removed event", logging.Error(err)) return err } defer iter.Close() for iter.Next() { if o.log.GetLevel() <= logging.DebugLevel { o.log.Debug("found signer removed event on chain", logging.String("old-signer", iter.Event.OldSigner.Hex()), ) } nonce, _ := big.NewInt(0).SetString(event.Nonce, 10) if iter.Event.Raw.BlockNumber == event.BlockNumber && uint64(iter.Event.Raw.Index) == event.LogIndex && iter.Event.OldSigner.Hex() == event.Address && nonce.Cmp(iter.Event.Nonce) == 0 && iter.Event.Raw.TxHash.Hex() == event.TxHash { // now we know the event is OK, // just need to check for confirmations return o.ethConfirmations.Check(event.BlockNumber) } } return ErrNoSignerEventFound }
1
Go
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
func ValidateAllAuthorizationModels(ctx context.Context, db storage.OpenFGADatastore) ([]validationResult, error) { validationResults := make([]validationResult, 0) continuationTokenStores := "" for { // fetch a page of stores stores, tokenStores, err := db.ListStores(ctx, storage.PaginationOptions{ PageSize: 100, From: continuationTokenStores, }) if err != nil { return nil, fmt.Errorf("error reading stores: %w", err) } // validate each store for _, store := range stores { latestModelID, err := db.FindLatestAuthorizationModelID(ctx, store.Id) if err != nil { fmt.Printf("no models in store %s \n", store.Id) } continuationTokenModels := "" for { // fetch a page of models for that store models, tokenModels, err := db.ReadAuthorizationModels(ctx, store.Id, storage.PaginationOptions{ PageSize: 100, From: continuationTokenModels, }) if err != nil { return nil, fmt.Errorf("error reading authorization models: %w", err) } // validate each model for _, model := range models { _, err := typesystem.NewAndValidate(context.Background(), model) validationResult := validationResult{ StoreID: store.Id, ModelID: model.Id, IsLatestModel: model.Id == latestModelID, } if err != nil { validationResult.Error = err.Error() } validationResults = append(validationResults, validationResult) } continuationTokenModels = string(tokenModels) if continuationTokenModels == "" { break } } } // next page of stores continuationTokenStores = string(tokenStores) if continuationTokenStores == "" { break } } return validationResults, nil }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (q *ExpandQuery) Execute(ctx context.Context, req *openfgapb.ExpandRequest) (*openfgapb.ExpandResponse, error) { store := req.GetStoreId() modelID := req.GetAuthorizationModelId() tupleKey := req.GetTupleKey() object := tupleKey.GetObject() relation := tupleKey.GetRelation() if object == "" || relation == "" { return nil, serverErrors.InvalidExpandInput } tk := tupleUtils.NewTupleKey(object, relation, "") model, err := q.datastore.ReadAuthorizationModel(ctx, store, modelID) if err != nil { if errors.Is(err, storage.ErrNotFound) { return nil, serverErrors.AuthorizationModelNotFound(modelID) } return nil, serverErrors.HandleError("", err) } if !typesystem.IsSchemaVersionSupported(model.GetSchemaVersion()) { return nil, serverErrors.ValidationError(typesystem.ErrInvalidSchemaVersion) } typesys, err := typesystem.NewAndValidate(ctx, model) if err != nil { return nil, serverErrors.ValidationError(typesystem.ErrInvalidModel) } if err = validation.ValidateObject(typesys, tk); err != nil { return nil, serverErrors.ValidationError(err) } err = validation.ValidateRelation(typesys, tk) if err != nil { return nil, serverErrors.ValidationError(err) } objectType := tupleUtils.GetType(object) rel, err := typesys.GetRelation(objectType, relation) if err != nil { if errors.Is(err, typesystem.ErrObjectTypeUndefined) { return nil, serverErrors.TypeNotFound(objectType) } if errors.Is(err, typesystem.ErrRelationUndefined) { return nil, serverErrors.RelationNotFound(relation, objectType, tk) } return nil, serverErrors.HandleError("", err) } userset := rel.GetRewrite() root, err := q.resolveUserset(ctx, store, userset, tk, typesys) if err != nil { return nil, err } return &openfgapb.ExpandResponse{ Tree: &openfgapb.UsersetTree{ Root: root, }, }, nil }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (w *WriteAuthorizationModelCommand) Execute(ctx context.Context, req *openfgapb.WriteAuthorizationModelRequest) (*openfgapb.WriteAuthorizationModelResponse, error) { // Until this is solved: https://github.com/envoyproxy/protoc-gen-validate/issues/74 if len(req.GetTypeDefinitions()) > w.backend.MaxTypesPerAuthorizationModel() { return nil, serverErrors.ExceededEntityLimit("type definitions in an authorization model", w.backend.MaxTypesPerAuthorizationModel()) } // Fill in the schema version for old requests, which don't contain it, while we migrate to the new schema version. if req.SchemaVersion == "" { req.SchemaVersion = typesystem.SchemaVersion1_1 } model := &openfgapb.AuthorizationModel{ Id: ulid.Make().String(), SchemaVersion: req.GetSchemaVersion(), TypeDefinitions: req.GetTypeDefinitions(), } _, err := typesystem.NewAndValidate(ctx, model) if err != nil { return nil, serverErrors.InvalidAuthorizationModelInput(err) } err = w.backend.WriteAuthorizationModel(ctx, req.GetStoreId(), model) if err != nil { return nil, serverErrors.NewInternalError("Error writing authorization model configuration", err) } return &openfgapb.WriteAuthorizationModelResponse{ AuthorizationModelId: model.Id, }, nil }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (s *Server) StreamedListObjects(req *openfgapb.StreamedListObjectsRequest, srv openfgapb.OpenFGAService_StreamedListObjectsServer) error { ctx := srv.Context() ctx, span := tracer.Start(ctx, "StreamedListObjects", trace.WithAttributes( attribute.String("object_type", req.GetType()), attribute.String("relation", req.GetRelation()), attribute.String("user", req.GetUser()), )) defer span.End() storeID := req.GetStoreId() modelID, err := s.resolveAuthorizationModelID(ctx, storeID, req.GetAuthorizationModelId()) if err != nil { return err } model, err := s.datastore.ReadAuthorizationModel(ctx, storeID, modelID) if err != nil { if errors.Is(err, storage.ErrNotFound) { return serverErrors.AuthorizationModelNotFound(req.GetAuthorizationModelId()) } return serverErrors.HandleError("", err) } typesys, err := typesystem.NewAndValidate(ctx, model) if err != nil { return serverErrors.ValidationError(typesystem.ErrInvalidModel) } ctx = typesystem.ContextWithTypesystem(ctx, typesys) q := &commands.ListObjectsQuery{ Datastore: s.datastore, Logger: s.logger, ListObjectsDeadline: s.config.ListObjectsDeadline, ListObjectsMaxResults: s.config.ListObjectsMaxResults, ResolveNodeLimit: s.config.ResolveNodeLimit, } req.AuthorizationModelId = modelID return q.ExecuteStreamed(ctx, req, srv) }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (s *Server) ListObjects(ctx context.Context, req *openfgapb.ListObjectsRequest) (*openfgapb.ListObjectsResponse, error) { storeID := req.GetStoreId() targetObjectType := req.GetType() ctx, span := tracer.Start(ctx, "ListObjects", trace.WithAttributes( attribute.String("object_type", targetObjectType), attribute.String("relation", req.GetRelation()), attribute.String("user", req.GetUser()), )) defer span.End() modelID := req.GetAuthorizationModelId() modelID, err := s.resolveAuthorizationModelID(ctx, storeID, modelID) if err != nil { return nil, err } model, err := s.datastore.ReadAuthorizationModel(ctx, storeID, modelID) if err != nil { if errors.Is(err, storage.ErrNotFound) { return nil, serverErrors.AuthorizationModelNotFound(modelID) } return nil, err } typesys, err := typesystem.NewAndValidate(ctx, model) if err != nil { return nil, serverErrors.ValidationError(typesystem.ErrInvalidModel) } ctx = typesystem.ContextWithTypesystem(ctx, typesys) q := &commands.ListObjectsQuery{ Datastore: s.datastore, Logger: s.logger, ListObjectsDeadline: s.config.ListObjectsDeadline, ListObjectsMaxResults: s.config.ListObjectsMaxResults, ResolveNodeLimit: s.config.ResolveNodeLimit, } return q.Execute(ctx, &openfgapb.ListObjectsRequest{ StoreId: storeID, ContextualTuples: req.GetContextualTuples(), AuthorizationModelId: modelID, Type: targetObjectType, Relation: req.Relation, User: req.User, }) }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func TestCheckDoesNotThrowBecauseDirectTupleWasFound(t *testing.T) { ctx := context.Background() storeID := ulid.Make().String() modelID := ulid.Make().String() typedefs := parser.MustParse(` type user type repo relations define reader: [user] as self `) tk := tuple.NewTupleKey("repo:openfga", "reader", "user:anne") tuple := &openfgapb.Tuple{Key: tk} mockController := gomock.NewController(t) defer mockController.Finish() mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController) mockDatastore.EXPECT(). ReadAuthorizationModel(gomock.Any(), storeID, modelID). AnyTimes(). Return(&openfgapb.AuthorizationModel{ SchemaVersion: typesystem.SchemaVersion1_1, TypeDefinitions: typedefs, }, nil) // it could happen that one of the following two mocks won't be necessary because the goroutine will be short-circuited mockDatastore.EXPECT(). ReadUserTuple(gomock.Any(), storeID, gomock.Any()). AnyTimes(). Return(tuple, nil) mockDatastore.EXPECT(). ReadUsersetTuples(gomock.Any(), storeID, gomock.Any()). AnyTimes(). DoAndReturn( func(_ context.Context, _ string, _ storage.ReadUsersetTuplesFilter) (storage.TupleIterator, error) { time.Sleep(50 * time.Millisecond) return nil, errors.New("some error") }) s := New(&Dependencies{ Datastore: mockDatastore, Logger: logger.NewNoopLogger(), Transport: gateway.NewNoopTransport(), }, &Config{ ResolveNodeLimit: test.DefaultResolveNodeLimit, }) checkResponse, err := s.Check(ctx, &openfgapb.CheckRequest{ StoreId: storeID, TupleKey: tk, AuthorizationModelId: modelID, }) require.NoError(t, err) require.Equal(t, true, checkResponse.Allowed) }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func BenchmarkListObjectsNoRaceCondition(b *testing.B) { ctx := context.Background() logger := logger.NewNoopLogger() transport := gateway.NewNoopTransport() store := ulid.Make().String() modelID := ulid.Make().String() mockController := gomock.NewController(b) defer mockController.Finish() typedefs := parser.MustParse(` type user type repo relations define allowed: [user] as self define viewer: [user] as self and allowed `) mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController) mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgapb.AuthorizationModel{ SchemaVersion: typesystem.SchemaVersion1_1, TypeDefinitions: typedefs, }, nil) mockDatastore.EXPECT().ListObjectsByType(gomock.Any(), store, "repo").AnyTimes().Return(nil, errors.New("error reading from storage")) s := New(&Dependencies{ Datastore: mockDatastore, Transport: transport, Logger: logger, }, &Config{ ResolveNodeLimit: test.DefaultResolveNodeLimit, ListObjectsDeadline: 5 * time.Second, ListObjectsMaxResults: 1000, }) b.ResetTimer() for i := 0; i < b.N; i++ { _, err := s.ListObjects(ctx, &openfgapb.ListObjectsRequest{ StoreId: store, AuthorizationModelId: modelID, Type: "repo", Relation: "viewer", User: "user:bob", }) require.ErrorIs(b, err, serverErrors.NewInternalError("", errors.New("error reading from storage"))) err = s.StreamedListObjects(&openfgapb.StreamedListObjectsRequest{ StoreId: store, AuthorizationModelId: modelID, Type: "repo", Relation: "viewer", User: "user:bob", }, NewMockStreamServer()) require.ErrorIs(b, err, serverErrors.NewInternalError("", errors.New("error reading from storage"))) } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func TestListObjects_Unoptimized_UnhappyPaths(t *testing.T) { ctx := context.Background() logger := logger.NewNoopLogger() transport := gateway.NewNoopTransport() store := ulid.Make().String() modelID := ulid.Make().String() mockController := gomock.NewController(t) defer mockController.Finish() mockDatastore := mockstorage.NewMockOpenFGADatastore(mockController) mockDatastore.EXPECT().ReadAuthorizationModel(gomock.Any(), store, modelID).AnyTimes().Return(&openfgapb.AuthorizationModel{ SchemaVersion: typesystem.SchemaVersion1_1, TypeDefinitions: parser.MustParse(` type user type repo relations define allowed: [user] as self define viewer: [user] as self and allowed `), }, nil) mockDatastore.EXPECT().ListObjectsByType(gomock.Any(), store, "repo").AnyTimes().Return(nil, errors.New("error reading from storage")) s := New(&Dependencies{ Datastore: mockDatastore, Transport: transport, Logger: logger, }, &Config{ ResolveNodeLimit: test.DefaultResolveNodeLimit, ListObjectsDeadline: 5 * time.Second, ListObjectsMaxResults: 1000, }) t.Run("error_listing_objects_from_storage_in_non-streaming_version", func(t *testing.T) { res, err := s.ListObjects(ctx, &openfgapb.ListObjectsRequest{ StoreId: store, AuthorizationModelId: modelID, Type: "repo", Relation: "viewer", User: "user:bob", }) require.Nil(t, res) require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage"))) }) t.Run("error_listing_objects_from_storage_in_streaming_version", func(t *testing.T) { err := s.StreamedListObjects(&openfgapb.StreamedListObjectsRequest{ StoreId: store, AuthorizationModelId: modelID, Type: "repo", Relation: "viewer", User: "user:bob", }, NewMockStreamServer()) require.ErrorIs(t, err, serverErrors.NewInternalError("", errors.New("error reading from storage"))) }) }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func BenchmarkListObjectsWithConcurrentChecks(b *testing.B, ds storage.OpenFGADatastore) { ctx := context.Background() store := ulid.Make().String() typedefs := parser.MustParse(` type user type document relations define allowed: [user] as self define viewer: [user] as self and allowed `) model := &openfgapb.AuthorizationModel{ Id: ulid.Make().String(), SchemaVersion: typesystem.SchemaVersion1_1, TypeDefinitions: typedefs, } err := ds.WriteAuthorizationModel(ctx, store, model) require.NoError(b, err) n := 0 for i := 0; i < 100; i++ { var tuples []*openfgapb.TupleKey for j := 0; j < ds.MaxTuplesPerWrite()/2; j++ { obj := fmt.Sprintf("document:%s", strconv.Itoa(n)) user := fmt.Sprintf("user:%s", strconv.Itoa(n)) tuples = append( tuples, tuple.NewTupleKey(obj, "viewer", user), tuple.NewTupleKey(obj, "allowed", user), ) n += 1 } err = ds.Write(ctx, store, nil, tuples) require.NoError(b, err) } listObjectsQuery := commands.ListObjectsQuery{ Datastore: ds, Logger: logger.NewNoopLogger(), ResolveNodeLimit: DefaultResolveNodeLimit, } var r *openfgapb.ListObjectsResponse ctx = typesystem.ContextWithTypesystem(ctx, typesystem.New(model)) b.ResetTimer() for i := 0; i < b.N; i++ { r, _ = listObjectsQuery.Execute(ctx, &openfgapb.ListObjectsRequest{ StoreId: store, AuthorizationModelId: model.Id, Type: "document", Relation: "viewer", User: "user:999", }) } listObjectsResponse = r }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func BenchmarkListObjectsWithReverseExpand(b *testing.B, ds storage.OpenFGADatastore) { ctx := context.Background() store := ulid.Make().String() model := &openfgapb.AuthorizationModel{ Id: ulid.Make().String(), SchemaVersion: typesystem.SchemaVersion1_1, TypeDefinitions: []*openfgapb.TypeDefinition{ { Type: "user", }, { Type: "document", Relations: map[string]*openfgapb.Userset{ "viewer": typesystem.This(), }, Metadata: &openfgapb.Metadata{ Relations: map[string]*openfgapb.RelationMetadata{ "viewer": { DirectlyRelatedUserTypes: []*openfgapb.RelationReference{ typesystem.DirectRelationReference("user", ""), }, }, }, }, }, }, } err := ds.WriteAuthorizationModel(ctx, store, model) require.NoError(b, err) n := 0 for i := 0; i < 100; i++ { var tuples []*openfgapb.TupleKey for j := 0; j < ds.MaxTuplesPerWrite(); j++ { obj := fmt.Sprintf("document:%s", strconv.Itoa(n)) user := fmt.Sprintf("user:%s", strconv.Itoa(n)) tuples = append(tuples, tuple.NewTupleKey(obj, "viewer", user)) n += 1 } err = ds.Write(ctx, store, nil, tuples) require.NoError(b, err) } listObjectsQuery := commands.ListObjectsQuery{ Datastore: ds, Logger: logger.NewNoopLogger(), ResolveNodeLimit: DefaultResolveNodeLimit, } var r *openfgapb.ListObjectsResponse ctx = typesystem.ContextWithTypesystem(ctx, typesystem.New(model)) b.ResetTimer() for i := 0; i < b.N; i++ { r, _ = listObjectsQuery.Execute(ctx, &openfgapb.ListObjectsRequest{ StoreId: store, AuthorizationModelId: model.Id, Type: "document", Relation: "viewer", User: "user:999", }) } listObjectsResponse = r }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func New(model *openfgapb.AuthorizationModel) *TypeSystem { tds := make(map[string]*openfgapb.TypeDefinition, len(model.GetTypeDefinitions())) relations := make(map[string]map[string]*openfgapb.Relation, len(model.GetTypeDefinitions())) for _, td := range model.GetTypeDefinitions() { typeName := td.GetType() tds[typeName] = td tdRelations := make(map[string]*openfgapb.Relation, len(td.GetRelations())) for relation, rewrite := range td.GetRelations() { r := &openfgapb.Relation{ Name: relation, Rewrite: rewrite, TypeInfo: &openfgapb.RelationTypeInfo{}, } if metadata, ok := td.GetMetadata().GetRelations()[relation]; ok { r.TypeInfo.DirectlyRelatedUserTypes = metadata.GetDirectlyRelatedUserTypes() } tdRelations[relation] = r } relations[typeName] = tdRelations } return &TypeSystem{ modelID: model.GetId(), schemaVersion: model.GetSchemaVersion(), typeDefinitions: tds, relations: relations, } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func TestSuccessfulRewriteValidations(t *testing.T) { var tests = []struct { name string model *openfgapb.AuthorizationModel }{ { name: "empty_relations", model: &openfgapb.AuthorizationModel{ SchemaVersion: SchemaVersion1_1, TypeDefinitions: []*openfgapb.TypeDefinition{ { Type: "repo", }, }, }, }, { name: "zero_length_relations_is_valid", model: &openfgapb.AuthorizationModel{ SchemaVersion: SchemaVersion1_1, TypeDefinitions: []*openfgapb.TypeDefinition{ { Type: "repo", Relations: map[string]*openfgapb.Userset{}, }, }, }, }, { name: "self_referencing_type_restriction_with_entrypoint", model: &openfgapb.AuthorizationModel{ TypeDefinitions: parser.MustParse(` type user type document relations define editor: [user] as self define viewer: [document#viewer] as self or editor `), SchemaVersion: SchemaVersion1_1, }, }, { name: "intersection_may_contain_repeated_relations", model: &openfgapb.AuthorizationModel{ TypeDefinitions: parser.MustParse(` type user type document relations define editor: [user] as self define viewer as editor and editor `), SchemaVersion: SchemaVersion1_1, }, }, { name: "exclusion_may_contain_repeated_relations", model: &openfgapb.AuthorizationModel{ TypeDefinitions: parser.MustParse(` type user type document relations define editor: [user] as self define viewer as editor but not editor `), SchemaVersion: SchemaVersion1_1, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { _, err := NewAndValidate(context.Background(), test.model) require.NoError(t, err) }) } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (c *LocalChecker) checkComputedUserset(parentctx context.Context, req *ResolveCheckRequest, rewrite *openfgav1.Userset_ComputedUserset) CheckHandlerFunc { return func(ctx context.Context) (*ResolveCheckResponse, error) { ctx, span := tracer.Start(ctx, "checkComputedUserset") defer span.End() rewrittenTupleKey := tuple.NewTupleKey( req.TupleKey.GetObject(), rewrite.ComputedUserset.GetRelation(), req.TupleKey.GetUser(), ) if _, visited := req.VisitedPaths[tuple.TupleKeyToString(rewrittenTupleKey)]; visited { return nil, ErrCycleDetected } return c.dispatch( ctx, &ResolveCheckRequest{ StoreID: req.GetStoreID(), AuthorizationModelID: req.GetAuthorizationModelID(), TupleKey: rewrittenTupleKey, ResolutionMetadata: &ResolutionMetadata{ Depth: req.GetResolutionMetadata().Depth - 1, DatastoreQueryCount: req.GetResolutionMetadata().DatastoreQueryCount, }, VisitedPaths: maps.Clone(req.VisitedPaths), })(ctx) } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (c *LocalChecker) ResolveCheck( ctx context.Context, req *ResolveCheckRequest, ) (*ResolveCheckResponse, error) { ctx, span := tracer.Start(ctx, "ResolveCheck") defer span.End() span.SetAttributes(attribute.String("tuple_key", req.GetTupleKey().String())) if req.GetResolutionMetadata().Depth == 0 { return nil, ErrResolutionDepthExceeded } typesys, ok := typesystem.TypesystemFromContext(ctx) if !ok { panic("typesystem missing in context") } object := req.GetTupleKey().GetObject() relation := req.GetTupleKey().GetRelation() objectType, _ := tuple.SplitObject(object) rel, err := typesys.GetRelation(objectType, relation) if err != nil { return nil, fmt.Errorf("relation '%s' undefined for object type '%s'", relation, objectType) } if req.VisitedPaths != nil { if _, visited := req.VisitedPaths[tuple.TupleKeyToString(req.GetTupleKey())]; visited { return nil, ErrCycleDetected } req.VisitedPaths[tuple.TupleKeyToString(req.GetTupleKey())] = struct{}{} } else { req.VisitedPaths = map[string]struct{}{ tuple.TupleKeyToString(req.GetTupleKey()): {}, } } resp, err := union(ctx, c.concurrencyLimit, c.checkRewrite(ctx, req, rel.GetRewrite())) if err != nil { return nil, err } return resp, nil }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (q *ListObjectsQuery) Execute( ctx context.Context, req *openfgav1.ListObjectsRequest, ) (*ListObjectsResponse, error) { resultsChan := make(chan ListObjectsResult, 1) maxResults := q.listObjectsMaxResults if maxResults > 0 { resultsChan = make(chan ListObjectsResult, maxResults) } timeoutCtx := ctx if q.listObjectsDeadline != 0 { var cancel context.CancelFunc timeoutCtx, cancel = context.WithTimeout(ctx, q.listObjectsDeadline) defer cancel() } resolutionMetadata := reverseexpand.NewResolutionMetadata() err := q.evaluate(timeoutCtx, req, resultsChan, maxResults, resolutionMetadata) if err != nil { return nil, err } objects := make([]string, 0) for { select { case <-timeoutCtx.Done(): q.logger.WarnWithContext( ctx, fmt.Sprintf("list objects timeout after %s", q.listObjectsDeadline.String()), ) return &ListObjectsResponse{ Objects: objects, ResolutionMetadata: *resolutionMetadata, }, nil case result, channelOpen := <-resultsChan: if result.Err != nil { if errors.Is(result.Err, serverErrors.AuthorizationModelResolutionTooComplex) { return nil, result.Err } return nil, serverErrors.HandleError("", result.Err) } if !channelOpen { return &ListObjectsResponse{ Objects: objects, ResolutionMetadata: *resolutionMetadata, }, nil } objects = append(objects, result.ObjectID) } } }
1
Go
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
func (g *GatewayRoute) GetRoute() *http.ServeMux { gatewayMux := http.NewServeMux() gatewayMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/ping" { w.WriteHeader(http.StatusOK) if _, err := w.Write([]byte("pong from gateway service")); err != nil { logger.Error("Failed to `pong` in resposne to `ping`", zap.Any("error", err)) } return } proxy := g.management.GetProxy(r.URL.Path) if proxy == nil { w.WriteHeader(http.StatusNotFound) return } // to fix https://github.com/IceWhaleTech/CasaOS/security/advisories/GHSA-32h8-rgcj-2g3c#event-102885 // API V1 and V2 both read ip from request header. So the fix is effective for v1 and v2. rewriteRequestSourceIP(r) proxy.ServeHTTP(w, r) }) return gatewayMux }
1
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
safe
func rewriteRequestSourceIP(r *http.Request) { // we may receive two kinds of requests. a request from reverse proxy. a request from client. // in reverse proxy, X-Forwarded-For will like // `X-Forwarded-For:[192.168.6.102]`(normal) // `X-Forwarded-For:[::1, 192.168.6.102]`(hacked) Note: the ::1 is inject by attacker. // `X-Forwarded-For:[::1]`(normal or hacked) local request. But it from browser have JWT. So we can and need to verify it // `X-Forwarded-For:[::1,::1]`(normal or hacked) attacker can build the request to bypass the verification. // But in the case. the remoteAddress should be the real ip. So we can use remoteAddress to verify it. ipList := strings.Split(r.Header.Get("X-Forwarded-For"), ",") r.Header.Del("X-Forwarded-For") r.Header.Del("X-Real-IP") // Note: the X-Forwarded-For depend the correct config from reverse proxy. // otherwise the X-Forwarded-For may be empty. remoteIP := r.RemoteAddr[:strings.LastIndex(r.RemoteAddr, ":")] if len(ipList) > 0 && (remoteIP == "127.0.0.1" || remoteIP == "::1") { // to process the request from reverse proxy // in reverse proxy, X-Forwarded-For will container multiple IPs. // if the request is from reverse proxy, the r.RemoteAddr will be 127.0.0.1. // So we need get ip from X-Forwarded-For r.Header.Add("X-Forwarded-For", ipList[len(ipList)-1]) } // to process the request from client. // the gateway will add the X-Forwarded-For to request header. // So we didn't need to add it. }
1
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
safe
func (s *connectionsStruct) MountSmaba(username, host, directory, port, mountPoint, password string) error { err := unix.Mount( fmt.Sprintf("//%s/%s", host, directory), mountPoint, "cifs", unix.MS_NOATIME|unix.MS_NODEV|unix.MS_NOSUID, fmt.Sprintf("username=%s,password=%s", username, password), ) return err //str := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;MountCIFS " + username + " " + host + " " + directory + " " + port + " " + mountPoint + " " + password) //return str }
1
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
safe
Skipper: func(c echo.Context) bool { return c.RealIP() == "::1" || c.RealIP() == "127.0.0.1" // return true }, ParseTokenFunc: func(token string, c echo.Context) (interface{}, error) { // claims, code := jwt.Validate(token) // TODO - needs JWT validation // if code != common_err.SUCCESS { // return nil, echo.ErrUnauthorized // } valid, claims, err := jwt.Validate(token, func() (*ecdsa.PublicKey, error) { return external.GetPublicKey(config.CommonInfo.RuntimePath) }) if err != nil || !valid { return nil, echo.ErrUnauthorized } c.Request().Header.Set("user_id", strconv.Itoa(claims.ID)) return claims, nil }, TokenLookupFuncs: []echo_middleware.ValuesExtractor{ func(c echo.Context) ([]string, error) { return []string{c.Request().Header.Get(echo.HeaderAuthorization)}, nil }, }, }))
1
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
safe
func (r *Reader) readBytes(op string) []byte { size := int(r.ReadLong()) if size < 0 { fnName := "Read" + strings.ToTitle(op) r.ReportError(fnName, "invalid "+op+" length") return nil } if size == 0 { return []byte{} } if max := r.cfg.getMaxByteSliceSize(); max > 0 && size > max { fnName := "Read" + strings.ToTitle(op) r.ReportError(fnName, "size is greater than `Config.MaxByteSliceSize`") return nil } // The bytes are entirely in the buffer and of a reasonable size. // Use the byte slab. if r.head+size <= r.tail && size <= 1024 { if cap(r.slab) < size { r.slab = make([]byte, 1024) } dst := r.slab[:size] r.slab = r.slab[size:] copy(dst, r.buf[r.head:r.head+size]) r.head += size return dst } buf := make([]byte, size) r.Read(buf) return buf }
1
Go
CWE-400
Uncontrolled Resource Consumption
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.
https://cwe.mitre.org/data/definitions/400.html
safe
func TestReader_ReadStringLargerThanMaxByteSliceSize(t *testing.T) { data := []byte{ 246, 255, 255, 255, 255, 10, 255, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, } r := avro.NewReader(bytes.NewReader(data), 4) _ = r.ReadString() assert.Error(t, r.Error) }
1
Go
CWE-400
Uncontrolled Resource Consumption
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.
https://cwe.mitre.org/data/definitions/400.html
safe
func TestReader_ReadBytesLargerThanMaxByteSliceSize(t *testing.T) { data := []byte{ 246, 255, 255, 255, 255, 10, 255, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, } r := avro.NewReader(bytes.NewReader(data), 4) _ = r.ReadBytes() assert.Error(t, r.Error) }
1
Go
CWE-400
Uncontrolled Resource Consumption
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.
https://cwe.mitre.org/data/definitions/400.html
safe
func (u *MysqlService) ChangeAccess(info dto.ChangeDBInfo) error { if cmd.CheckIllegal(info.Value) { return buserr.New(constant.ErrCmdIllegal) } var ( mysql model.DatabaseMysql err error ) if info.ID != 0 { mysql, err = mysqlRepo.Get(commonRepo.WithByID(info.ID)) if err != nil { return err } if info.Value == mysql.Permission { return nil } } app, err := appInstallRepo.LoadBaseInfo("mysql", "") if err != nil { return err } if info.ID == 0 { mysql.Name = "*" mysql.Username = "root" mysql.Permission = "%" mysql.Password = app.Password } if info.Value != mysql.Permission { var userlist []string if strings.Contains(mysql.Permission, ",") { userlist = strings.Split(mysql.Permission, ",") } else { userlist = append(userlist, mysql.Permission) } for _, user := range userlist { if len(user) != 0 { if strings.HasPrefix(app.Version, "5.6") { if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop user '%s'@'%s'", mysql.Username, user)); err != nil { return err } } else { if err := excuteSql(app.ContainerName, app.Password, fmt.Sprintf("drop user if exists '%s'@'%s'", mysql.Username, user)); err != nil { return err } } } } if info.ID == 0 { return nil } } if err := u.createUser(app.ContainerName, app.Password, app.Version, dto.MysqlDBCreate{ Username: mysql.Username, Name: mysql.Name, Permission: info.Value, Password: mysql.Password, }); err != nil { return err } if err := excuteSql(app.ContainerName, app.Password, "flush privileges"); err != nil { return err } if info.ID == 0 { return nil } _ = mysqlRepo.Update(mysql.ID, map[string]interface{}{"permission": info.Value}) return nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*model.DatabaseMysql, error) { if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format, req.Permission) { return nil, buserr.New(constant.ErrCmdIllegal) } if req.Username == "root" { return nil, errors.New("Cannot set root as user name") } app, err := appInstallRepo.LoadBaseInfo("mysql", "") if err != nil { return nil, err } mysql, _ := mysqlRepo.Get(commonRepo.WithByName(req.Name)) if mysql.ID != 0 { return nil, constant.ErrRecordExist } if err := copier.Copy(&mysql, &req); err != nil { return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) } createSql := fmt.Sprintf("create database `%s` default character set %s collate %s", req.Name, req.Format, formatMap[req.Format]) if err := excSQL(app.ContainerName, app.Password, createSql); err != nil { if strings.Contains(err.Error(), "ERROR 1007") { return nil, buserr.New(constant.ErrDatabaseIsExist) } return nil, err } if err := u.createUser(app.ContainerName, app.Password, app.Version, req); err != nil { return nil, err } global.LOG.Infof("create database %s successful!", req.Name) mysql.MysqlName = app.Name if err := mysqlRepo.Create(ctx, &mysql); err != nil { return nil, err } return &mysql, nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (u *SSHService) GenerateSSH(req dto.GenerateSSH) error { if cmd.CheckIllegal(req.EncryptionMode, req.Password) { return buserr.New(constant.ErrCmdIllegal) } currentUser, err := user.Current() if err != nil { return fmt.Errorf("load current user failed, err: %v", err) } secretFile := fmt.Sprintf("%s/.ssh/id_item_%s", currentUser.HomeDir, req.EncryptionMode) secretPubFile := fmt.Sprintf("%s/.ssh/id_item_%s.pub", currentUser.HomeDir, req.EncryptionMode) authFile := currentUser.HomeDir + "/.ssh/authorized_keys" command := fmt.Sprintf("ssh-keygen -t %s -f %s/.ssh/id_item_%s | echo y", req.EncryptionMode, currentUser.HomeDir, req.EncryptionMode) if len(req.Password) != 0 { command = fmt.Sprintf("ssh-keygen -t %s -P %s -f %s/.ssh/id_item_%s | echo y", req.EncryptionMode, req.Password, currentUser.HomeDir, req.EncryptionMode) } stdout, err := cmd.Exec(command) if err != nil { return fmt.Errorf("generate failed, err: %v, message: %s", err, stdout) } defer func() { _ = os.Remove(secretFile) }() defer func() { _ = os.Remove(secretPubFile) }() if _, err := os.Stat(authFile); err != nil { _, _ = os.Create(authFile) } stdout1, err := cmd.Execf("cat %s >> %s/.ssh/authorized_keys", secretPubFile, currentUser.HomeDir) if err != nil { return fmt.Errorf("generate failed, err: %v, message: %s", err, stdout1) } fileOp := files.NewFileOp() if err := fileOp.Rename(secretFile, fmt.Sprintf("%s/.ssh/id_%s", currentUser.HomeDir, req.EncryptionMode)); err != nil { return err } if err := fileOp.Rename(secretPubFile, fmt.Sprintf("%s/.ssh/id_%s.pub", currentUser.HomeDir, req.EncryptionMode)); err != nil { return err } return nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (f *Firewall) RichRules(rule FireInfo, operation string) error { if cmd.CheckIllegal(operation, rule.Address, rule.Protocol, rule.Port, rule.Strategy) { return buserr.New(constant.ErrCmdIllegal) } ruleStr := "" if strings.Contains(rule.Address, "-") { std, err := cmd.Execf("firewall-cmd --permanent --new-ipset=%s --type=hash:ip", rule.Address) if err != nil { return fmt.Errorf("add new ipset failed, err: %s", std) } std2, err := cmd.Execf("firewall-cmd --permanent --ipset=%s --add-entry=%s", rule.Address, rule.Address) if err != nil { return fmt.Errorf("add entry to ipset failed, err: %s", std2) } if err := f.Reload(); err != nil { return err } ruleStr = fmt.Sprintf("rule source ipset=%s %s", rule.Address, rule.Strategy) } else { ruleStr = "rule family=ipv4 " if len(rule.Address) != 0 { ruleStr += fmt.Sprintf("source address=%s ", rule.Address) } if len(rule.Port) != 0 { ruleStr += fmt.Sprintf("port port=%s ", rule.Port) } if len(rule.Protocol) != 0 { ruleStr += fmt.Sprintf("protocol=%s ", rule.Protocol) } ruleStr += rule.Strategy } stdout, err := cmd.Execf("firewall-cmd --zone=public --%s-rich-rule '%s' --permanent", operation, ruleStr) if err != nil { return fmt.Errorf("%s rich rules failed, err: %s", operation, stdout) } return nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (f *Firewall) Port(port FireInfo, operation string) error { if cmd.CheckIllegal(operation, port.Protocol, port.Port) { return buserr.New(constant.ErrCmdIllegal) } stdout, err := cmd.Execf("firewall-cmd --zone=public --%s-port=%s/%s --permanent", operation, port.Port, port.Protocol) if err != nil { return fmt.Errorf("%s port failed, err: %s", operation, stdout) } return nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func (f *Ufw) RichRules(rule FireInfo, operation string) error { switch rule.Strategy { case "accept": rule.Strategy = "allow" case "drop": rule.Strategy = "deny" default: return fmt.Errorf("unsupport strategy %s", rule.Strategy) } if cmd.CheckIllegal(operation, rule.Protocol, rule.Address, rule.Port) { return buserr.New(constant.ErrCmdIllegal) } ruleStr := fmt.Sprintf("%s %s ", f.CmdStr, rule.Strategy) if operation == "remove" { ruleStr = fmt.Sprintf("%s delete %s ", f.CmdStr, rule.Strategy) } if len(rule.Protocol) != 0 { ruleStr += fmt.Sprintf("proto %s ", rule.Protocol) } if strings.Contains(rule.Address, "-") { ruleStr += fmt.Sprintf("from %s to %s ", strings.Split(rule.Address, "-")[0], strings.Split(rule.Address, "-")[1]) } else { ruleStr += fmt.Sprintf("from %s ", rule.Address) } if len(rule.Port) != 0 { ruleStr += fmt.Sprintf("to any port %s ", rule.Port) } stdout, err := cmd.Exec(ruleStr) if err != nil { return fmt.Errorf("%s rich rules failed, err: %s", operation, stdout) } return nil }
1
Go
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
safe
func GetSchemaVersion(version string) string { minorVersion := GetMinorVersion(version) return minorVersion + ".0" }
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 GetSchemaVersion(version string) string { minorVersion := GetMinorVersion(version) return minorVersion + ".0" }
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 GetSchemaVersion(version string) string { minorVersion := GetMinorVersion(version) return minorVersion + ".0" }
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 GetSchemaVersion(version string) string { minorVersion := GetMinorVersion(version) return minorVersion + ".0" }
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
static void cmd_sdbk(Sdb *db, const char *input) { char *out = (input[0] == ' ') ? sdb_querys (db, NULL, 0, input + 1) : sdb_querys (db, NULL, 0, "*"); if (out) { r_cons_println (out); free (out); } else { R_LOG_ERROR ("Usage: ask [query]"); } }
0
Go
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static void cmd_anal_ucall_ref(RCore *core, ut64 addr) { RAnalFunction * fcn = r_anal_get_function_at (core->anal, addr); if (fcn) { r_cons_printf (" ; %s", fcn->name); } else { r_cons_printf (" ; 0x%" PFMT64x, addr); } }
0
Go
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
static void axfm(RCore *core) { RVecAnalRef *refs = r_anal_xrefs_get_from (core->anal, UT64_MAX); if (refs && !RVecAnalRef_empty (refs)) { RVecAnalRef_sort (refs, compare_ref); ut64 last_addr = UT64_MAX; RAnalRef *ref; R_VEC_FOREACH (refs, ref) { const bool is_first = ref->addr != last_addr; const char *name; if (is_first) { name = axtm_name (core, ref->addr); r_cons_printf ("0x%"PFMT64x": %s\n", ref->addr, name? name: "?"); } name = axtm_name (core, ref->at); r_cons_printf (" 0x%"PFMT64x": %s\n", ref->at, name? name: "?"); last_addr = ref->addr; } } RVecAnalRef_free (refs); }
0
Go
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
vulnerable
func (cr *collectionRepo) AddCollection(ctx context.Context, collection *entity.Collection) (err error) { id, err := cr.uniqueIDRepo.GenUniqueIDStr(ctx, collection.TableName()) if err == nil { collection.ID = id _, err = cr.data.DB.Insert(collection) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } } return nil }
0
Go
CWE-362
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.
https://cwe.mitre.org/data/definitions/362.html
vulnerable
func (uc *UserController) RetrievePassWord(ctx *gin.Context) { req := &schema.UserRetrievePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } captchaPass := uc.actionService.ActionRecordVerifyCaptcha(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP(), req.CaptchaID, req.CaptchaCode) if !captchaPass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "captcha_code", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.CaptchaVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) return } _, _ = uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) code, err := uc.userService.RetrievePassWord(ctx, req) handler.HandleResponse(ctx, err, code) }
0
Go
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
func (sc *SiteInfoController) UpdateGeneral(ctx *gin.Context) { req := schema.SiteGeneralReq{} if handler.BindAndCheck(ctx, &req) { return } err := sc.siteInfoService.SaveSiteGeneral(ctx, req) handler.HandleResponse(ctx, err, nil) }
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 (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) { if len(req.Username) > 0 { if checker.IsInvalidUsername(req.Username) { errField := &validator.FormErrorField{ ErrorField: "username", ErrorMsg: reason.UsernameInvalid, } errFields = append(errFields, errField) return errFields, errors.BadRequest(reason.UsernameInvalid) } } req.BioHTML = converter.Markdown2HTML(req.Bio) return nil, nil }
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 (uc *UserController) RetrievePassWord(ctx *gin.Context) { req := &schema.UserRetrievePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } captchaPass := uc.actionService.ActionRecordVerifyCaptcha(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP(), req.CaptchaID, req.CaptchaCode) if !captchaPass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "captcha_code", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.CaptchaVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) return } _, _ = uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) _, err := uc.userService.RetrievePassWord(ctx, req) handler.HandleResponse(ctx, err, nil) }
0
Go
CWE-203
Observable Discrepancy
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
https://cwe.mitre.org/data/definitions/203.html
vulnerable
func (us *UserService) RetrievePassWord(ctx context.Context, req *schema.UserRetrievePassWordRequest) (string, error) { userInfo, has, err := us.userRepo.GetByEmail(ctx, req.Email) if err != nil { return "", err } if !has { return "", errors.BadRequest(reason.UserNotFound) } // send email data := &schema.EmailCodeContent{ Email: req.Email, UserID: userInfo.ID, } code := uuid.NewString() verifyEmailURL := fmt.Sprintf("%s/users/password-reset?code=%s", us.getSiteUrl(ctx), code) title, body, err := us.emailService.PassResetTemplate(ctx, verifyEmailURL) if err != nil { return "", err } go us.emailService.SendAndSaveCode(ctx, req.Email, title, body, code, data.ToJSONString()) return code, nil }
0
Go
CWE-203
Observable Discrepancy
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
https://cwe.mitre.org/data/definitions/203.html
vulnerable
func (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.OriginalText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
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 (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.OriginalText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
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 (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.OriginalText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
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 Markdown2HTML(source string) string { mdConverter := goldmark.New( goldmark.WithExtensions(&DangerousHTMLFilterExtension{}, extension.GFM), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( goldmarkHTML.WithHardWraps(), ), ) var buf bytes.Buffer if err := mdConverter.Convert([]byte(source), &buf); err != nil { log.Error(err) return source } return buf.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 Markdown2HTML(source string) string { mdConverter := goldmark.New( goldmark.WithExtensions(&DangerousHTMLFilterExtension{}, extension.GFM), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( goldmarkHTML.WithHardWraps(), ), ) var buf bytes.Buffer if err := mdConverter.Convert([]byte(source), &buf); err != nil { log.Error(err) return source } return buf.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 (uc *UserController) UseRePassWord(ctx *gin.Context) { req := &schema.UserRePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } req.Content = uc.emailService.VerifyUrlExpired(ctx, req.Code) if len(req.Content) == 0 { handler.HandleResponse(ctx, errors.Forbidden(reason.EmailVerifyURLExpired), &schema.ForbiddenResp{Type: schema.ForbiddenReasonTypeURLExpired}) return } resp, err := uc.userService.UseRePassword(ctx, req) uc.actionService.ActionRecordDel(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) handler.HandleResponse(ctx, err, resp) }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (uc *UserController) UserModifyPassWord(ctx *gin.Context) { req := &schema.UserModifyPassWordRequest{} if handler.BindAndCheck(ctx, req) { return } req.UserID = middleware.GetLoginUserIDFromContext(ctx) oldPassVerification, err := uc.userService.UserModifyPassWordVerification(ctx, req) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !oldPassVerification { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "old_pass", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.OldPasswordVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.OldPasswordVerificationFailed), errFields) return } if req.OldPass == req.Pass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.NewPasswordSameAsPreviousSetting), }) handler.HandleResponse(ctx, errors.BadRequest(reason.NewPasswordSameAsPreviousSetting), errFields) return } err = uc.userService.UserModifyPassword(ctx, req) handler.HandleResponse(ctx, err, nil) }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string) { key := constant.UserTokenMappingCacheKey + userID resp, _ := ar.data.Cache.GetString(ctx, key) mapping := make(map[string]bool, 0) if len(resp) > 0 { _ = json.Unmarshal([]byte(resp), &mapping) log.Debugf("find %d user tokens by user id %s", len(mapping), userID) } for token := range mapping { if err := ar.RemoveUserCacheInfo(ctx, token); err != nil { log.Error(err) } else { log.Debugf("del user %s token success") } } if err := ar.RemoveUserStatus(ctx, userID); err != nil { log.Error(err) } if err := ar.data.Cache.Del(ctx, key); err != nil { log.Error(err) } }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (u *UserModifyPassWordRequest) Check() (errFields []*validator.FormErrorField, err error) { // TODO i18n err = checker.CheckPassword(8, 32, 0, u.Pass) if err != nil { errField := &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), } errFields = append(errFields, errField) return errFields, err } return nil, nil }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (as *AuthService) RemoveUserTokens(ctx context.Context, userID string) { as.authRepo.RemoveUserTokens(ctx, userID) }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserAdminService) UpdateUserPassword(ctx context.Context, req *schema.UpdateUserPasswordReq) (err error) { // Users cannot modify their password if req.UserID == req.LoginUserID { return errors.BadRequest(reason.AdminCannotUpdateTheirPassword) } userInfo, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) if err != nil { return err } if !exist { return errors.BadRequest(reason.UserNotFound) } hashPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { return err } err = us.userRepo.UpdateUserPassword(ctx, userInfo.ID, string(hashPwd)) if err != nil { return err } // logout this user us.authService.RemoveUserTokens(ctx, req.UserID) return }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserAdminService) UpdateUserRole(ctx context.Context, req *schema.UpdateUserRoleReq) (err error) { // Users cannot modify their roles if req.UserID == req.LoginUserID { return errors.BadRequest(reason.UserCannotUpdateYourRole) } err = us.userRoleRelService.SaveUserRole(ctx, req.UserID, req.RoleID) if err != nil { return err } us.authService.RemoveUserTokens(ctx, req.UserID) return }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserService) UserModifyPassword(ctx context.Context, request *schema.UserModifyPassWordRequest) error { enpass, err := us.encryptPassword(ctx, request.Pass) if err != nil { return err } userInfo, has, err := us.userRepo.GetByUserID(ctx, request.UserID) if err != nil { return err } if !has { return fmt.Errorf("user does not exist") } isPass := us.verifyPassword(ctx, request.OldPass, userInfo.Pass) if !isPass { return fmt.Errorf("the old password verification failed") } err = us.userRepo.UpdatePass(ctx, userInfo.ID, enpass) if err != nil { return err } return nil }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserService) UserModifyPassWordVerification(ctx context.Context, request *schema.UserModifyPassWordRequest) (bool, error) { userInfo, has, err := us.userRepo.GetByUserID(ctx, request.UserID) if err != nil { return false, err } if !has { return false, fmt.Errorf("user does not exist") } isPass := us.verifyPassword(ctx, request.OldPass, userInfo.Pass) if !isPass { return false, nil } return true, nil }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserService) UseRePassword(ctx context.Context, req *schema.UserRePassWordRequest) (resp *schema.GetUserResp, err error) { data := &schema.EmailCodeContent{} err = data.FromJSONString(req.Content) if err != nil { return nil, errors.BadRequest(reason.EmailVerifyURLExpired) } userInfo, exist, err := us.userRepo.GetByEmail(ctx, data.Email) if err != nil { return nil, err } if !exist { return nil, errors.BadRequest(reason.UserNotFound) } enpass, err := us.encryptPassword(ctx, req.Pass) if err != nil { return nil, err } err = us.userRepo.UpdatePass(ctx, userInfo.ID, enpass) if err != nil { return nil, err } resp = &schema.GetUserResp{} return resp, nil }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (us *UserService) verifyPassword(ctx context.Context, LoginPass, UserPass string) bool { err := bcrypt.CompareHashAndPassword([]byte(UserPass), []byte(LoginPass)) return err == nil }
0
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
func (m *MyValidator) Check(value interface{}) (errFields []*FormErrorField, err error) { err = m.Validate.Struct(value) if err != nil { var valErrors validator.ValidationErrors if !errors.As(err, &valErrors) { log.Error(err) return nil, errors.New("validate check exception") } for _, fieldError := range valErrors { errField := &FormErrorField{ ErrorField: fieldError.Field(), ErrorMsg: fieldError.Translate(m.Tran), } // get original tag name from value for set err field key. structNamespace := fieldError.StructNamespace() _, fieldName, found := strings.Cut(structNamespace, ".") if found { originalTag := getObjectTagByFieldName(value, fieldName) if len(originalTag) > 0 { errField.ErrorField = originalTag } } errFields = append(errFields, errField) } if len(errFields) > 0 { errMsg := "" if len(errFields) == 1 { errMsg = errFields[0].ErrorMsg } return errFields, myErrors.BadRequest(reason.RequestFormatError).WithMsg(errMsg) } } if v, ok := value.(Checker); ok { errFields, err = v.Check() if err == nil { return nil, nil } for _, errField := range errFields { errField.ErrorMsg = translator.Tr(m.Lang, errField.ErrorMsg) } return errFields, err } return nil, nil }
0
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
vulnerable
func (u *UserRePassWordRequest) Check() (errFields []*validator.FormErrorField, err error) { // TODO i18n err = checker.CheckPassword(8, 32, 0, u.Pass) if err != nil { errField := &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), } errFields = append(errFields, errField) return errFields, err } return nil, nil }
0
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
vulnerable
func (u *UserModifyPasswordReq) Check() (errFields []*validator.FormErrorField, err error) { // TODO i18n err = checker.CheckPassword(8, 32, 0, u.Pass) if err != nil { errField := &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), } errFields = append(errFields, errField) return errFields, err } return nil, nil }
0
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
vulnerable
func (u *UserRegisterReq) Check() (errFields []*validator.FormErrorField, err error) { // TODO i18n err = checker.CheckPassword(8, 32, 0, u.Pass) if err != nil { errField := &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), } errFields = append(errFields, errField) return errFields, err } return nil, nil }
0
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
vulnerable
func (vc *VoteController) VoteDown(ctx *gin.Context) { req := &schema.VoteReq{} if handler.BindAndCheck(ctx, req) { return } req.ObjectID = uid.DeShortID(req.ObjectID) req.UserID = middleware.GetLoginUserIDFromContext(ctx) can, needRank, err := vc.rankService.CheckVotePermission(ctx, req.UserID, req.ObjectID, false) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !can { lang := handler.GetLang(ctx) msg := translator.TrWithData(lang, reason.NoEnoughRankToOperate, &schema.PermissionTrTplData{Rank: needRank}) handler.HandleResponse(ctx, errors.Forbidden(reason.NoEnoughRankToOperate).WithMsg(msg), nil) return } dto := &schema.VoteDTO{} _ = copier.Copy(dto, req) resp, err := vc.VoteService.VoteDown(ctx, dto) if err != nil { handler.HandleResponse(ctx, err, schema.ErrTypeToast) } else { handler.HandleResponse(ctx, err, resp) } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vc *VoteController) VoteUp(ctx *gin.Context) { req := &schema.VoteReq{} if handler.BindAndCheck(ctx, req) { return } req.ObjectID = uid.DeShortID(req.ObjectID) req.UserID = middleware.GetLoginUserIDFromContext(ctx) can, needRank, err := vc.rankService.CheckVotePermission(ctx, req.UserID, req.ObjectID, true) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !can { lang := handler.GetLang(ctx) msg := translator.TrWithData(lang, reason.NoEnoughRankToOperate, &schema.PermissionTrTplData{Rank: needRank}) handler.HandleResponse(ctx, errors.Forbidden(reason.NoEnoughRankToOperate).WithMsg(msg), nil) return } dto := &schema.VoteDTO{} _ = copier.Copy(dto, req) resp, err := vc.VoteService.VoteUp(ctx, dto) if err != nil { handler.HandleResponse(ctx, err, schema.ErrTypeToast) } else { handler.HandleResponse(ctx, err, resp) } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *AnswerActivityRepo) DeleteQuestion(ctx context.Context, questionID string) (err error) { questionInfo := &entity.Question{} exist, err := ar.data.DB.Context(ctx).Where("id = ?", questionID).Get(questionInfo) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if !exist { return nil } // get all this object activity activityList := make([]*entity.Activity, 0) session := ar.data.DB.Context(ctx).Where("has_rank = 1") session.Where("cancelled = ?", entity.ActivityAvailable) err = session.Find(&activityList, &entity.Activity{ObjectID: questionID}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if len(activityList) == 0 { return nil } log.Infof("questionInfo %s deleted will rollback activity %d", questionID, len(activityList)) _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) for _, act := range activityList { log.Infof("user %s rollback rank %d", act.UserID, -act.Rank) _, e := ar.userRankRepo.TriggerUserRank( ctx, session, act.UserID, -act.Rank, act.ActivityType) if e != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() } if _, e := session.Where("id = ?", act.ID).Cols("cancelled", "cancelled_at"). Update(&entity.Activity{Cancelled: entity.ActivityCancelled, CancelledAt: time.Now()}); e != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() } } return nil, nil }) if err != nil { return err } // get all answers answerList := make([]*entity.Answer, 0) err = ar.data.DB.Context(ctx).Find(&answerList, &entity.Answer{QuestionID: questionID}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } for _, answerInfo := range answerList { err = ar.DeleteAnswer(ctx, answerInfo.ID) if err != nil { log.Error(err) } } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func NewQuestionActivityRepo( data *data.Data, activityRepo activity_common.ActivityRepo, userRankRepo rank.UserRankRepo, ) activity.QuestionActivityRepo { return &AnswerActivityRepo{ data: data, activityRepo: activityRepo, userRankRepo: userRankRepo, } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *AnswerActivityRepo) DeleteAnswer(ctx context.Context, answerID string) (err error) { answerInfo := &entity.Answer{} exist, err := ar.data.DB.Context(ctx).Where("id = ?", answerID).Get(answerInfo) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if !exist { return nil } // get all this object activity activityList := make([]*entity.Activity, 0) session := ar.data.DB.Context(ctx).Where("has_rank = 1") session.Where("cancelled = ?", entity.ActivityAvailable) err = session.Find(&activityList, &entity.Activity{ObjectID: answerID}) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if len(activityList) == 0 { return nil } log.Infof("answerInfo %s deleted will rollback activity %d", answerID, len(activityList)) _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) for _, act := range activityList { log.Infof("user %s rollback rank %d", act.UserID, -act.Rank) _, e := ar.userRankRepo.TriggerUserRank( ctx, session, act.UserID, -act.Rank, act.ActivityType) if e != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() } if _, e := session.Where("id = ?", act.ID).Cols("cancelled", "cancelled_at"). Update(&entity.Activity{Cancelled: entity.ActivityCancelled, CancelledAt: time.Now()}); e != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(e).WithStack() } } return nil, nil }) if err != nil { return err } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *FollowRepo) FollowCancel(ctx context.Context, objectID, userID string) error { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) var ( existsActivity entity.Activity has bool ) result = nil has, err = session.Where(builder.Eq{"activity_type": activityType}). And(builder.Eq{"user_id": userID}). And(builder.Eq{"object_id": objectID}). Get(&existsActivity) if err != nil || !has { return } if has && existsActivity.Cancelled == entity.ActivityCancelled { return } if _, err = session.Where("id = ?", existsActivity.ID). Cols("cancelled"). Update(&entity.Activity{ Cancelled: entity.ActivityCancelled, CancelledAt: time.Now(), }); err != nil { return } err = ar.updateFollows(ctx, session, objectID, -1) return }) return err }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *FollowRepo) Follow(ctx context.Context, objectID, userID string) error { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) var ( existsActivity entity.Activity has bool ) result = nil has, err = session.Where(builder.Eq{"activity_type": activityType}). And(builder.Eq{"user_id": userID}). And(builder.Eq{"object_id": objectID}). Get(&existsActivity) if err != nil { return } if has && existsActivity.Cancelled == entity.ActivityAvailable { return } if has { _, err = session.Where(builder.Eq{"id": existsActivity.ID}). Cols(`cancelled`). Update(&entity.Activity{ Cancelled: entity.ActivityAvailable, }) } else { // update existing activity with new user id and u object id _, err = session.Insert(&entity.Activity{ UserID: userID, ObjectID: objectID, OriginalObjectID: objectID, ActivityType: activityType, Cancelled: entity.ActivityAvailable, Rank: 0, HasRank: 0, }) } if err != nil { log.Error(err) return } // start update followers when everything is fine err = ar.updateFollows(ctx, session, objectID, 1) if err != nil { log.Error(err) } return }) return err }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *UserActiveActivityRepo) UserActive(ctx context.Context, userID string) (err error) { cfg, err := ar.configService.GetConfigByKey(ctx, UserActivated) if err != nil { return err } activityType := cfg.ID deltaRank := cfg.GetIntValue() addActivity := &entity.Activity{ UserID: userID, ObjectID: "0", OriginalObjectID: "0", ActivityType: activityType, Rank: deltaRank, HasRank: 1, } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) _, exists, err := ar.activityRepo.GetActivity(ctx, session, "0", addActivity.UserID, activityType) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if exists { return nil, nil } _, err = ar.userRankRepo.TriggerUserRank(ctx, session, addActivity.UserID, addActivity.Rank, activityType) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } _, err = session.Insert(addActivity) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return nil, nil }) return err }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) ListUserVotes(ctx context.Context, userID string, page int, pageSize int, activityTypes []int) (voteList []entity.Activity, total int64, err error) { session := vr.data.DB.Context(ctx) cond := builder. And( builder.Eq{"user_id": userID}, builder.Eq{"cancelled": 0}, builder.In("activity_type", activityTypes), ) session.Where(cond).Desc("updated_at") total, err = pager.Help(page, pageSize, &voteList, &entity.Activity{}, session) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) VoteDownCancel(ctx context.Context, objectID string, userID, objectUserID string) (resp *schema.VoteResp, err error) { var objectType string resp = &schema.VoteResp{} objectType, err = obj.GetObjectTypeStrByObjectID(objectID) if err != nil { err = errors.BadRequest(reason.ObjectNotFound) return } actions, ok := LimitDownActions[objectType] if !ok { err = errors.BadRequest(reason.DisallowVote) return } return vr.voteCancel(ctx, objectID, userID, objectUserID, actions) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func NewVoteRepo( data *data.Data, uniqueIDRepo unique.UniqueIDRepo, configService *config.ConfigService, activityRepo activity_common.ActivityRepo, userRankRepo rank.UserRankRepo, voteCommon activity_common.VoteRepo, notificationQueueService notice_queue.NotificationQueueService, ) service.VoteRepo { return &VoteRepo{ data: data, uniqueIDRepo: uniqueIDRepo, configService: configService, activityRepo: activityRepo, userRankRepo: userRankRepo, voteCommon: voteCommon, notificationQueueService: notificationQueueService, } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) updateVotes(ctx context.Context, session *xorm.Session, objectID string, votes int) (err error) { var ( objectType string e error ) objectType, err = obj.GetObjectTypeStrByObjectID(objectID) switch objectType { case "question": _, err = session.Where("id = ?", objectID).Incr("vote_count", votes).Update(&entity.Question{}) case "answer": _, err = session.Where("id = ?", objectID).Incr("vote_count", votes).Update(&entity.Answer{}) case "comment": _, err = session.Where("id = ?", objectID).Incr("vote_count", votes).Update(&entity.Comment{}) default: e = errors.BadRequest(reason.DisallowVote) } if e != nil { err = e } else if err != nil { err = errors.BadRequest(reason.DatabaseError).WithError(err).WithStack() } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) sendNotification(ctx context.Context, activityUserID, objectUserID, objectID string) { objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return } msg := &schema.NotificationMsg{ ReceiverUserID: activityUserID, TriggerUserID: objectUserID, Type: schema.NotificationTypeAchievement, ObjectID: objectID, ObjectType: objectType, } vr.notificationQueueService.Send(ctx, msg) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) VoteUp(ctx context.Context, objectID string, userID, objectUserID string) (resp *schema.VoteResp, err error) { resp = &schema.VoteResp{} objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { err = errors.BadRequest(reason.ObjectNotFound) return } actions, ok := LimitUpActions[objectType] if !ok { err = errors.BadRequest(reason.DisallowVote) return } _, _ = vr.VoteDownCancel(ctx, objectID, userID, objectUserID) return vr.vote(ctx, objectID, userID, objectUserID, actions) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) VoteDown(ctx context.Context, objectID string, userID, objectUserID string) (resp *schema.VoteResp, err error) { resp = &schema.VoteResp{} objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { err = errors.BadRequest(reason.ObjectNotFound) return } actions, ok := LimitDownActions[objectType] if !ok { err = errors.BadRequest(reason.DisallowVote) return } _, _ = vr.VoteUpCancel(ctx, objectID, userID, objectUserID) return vr.vote(ctx, objectID, userID, objectUserID, actions) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) VoteUpCancel(ctx context.Context, objectID string, userID, objectUserID string) (resp *schema.VoteResp, err error) { var objectType string resp = &schema.VoteResp{} objectType, err = obj.GetObjectTypeStrByObjectID(objectID) if err != nil { err = errors.BadRequest(reason.ObjectNotFound) return } actions, ok := LimitUpActions[objectType] if !ok { err = errors.BadRequest(reason.DisallowVote) return } return vr.voteCancel(ctx, objectID, userID, objectUserID, actions) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) GetVoteResultByObjectId(ctx context.Context, objectID string) (resp *schema.VoteResp, err error) { resp = &schema.VoteResp{} for _, action := range []string{"vote_up", "vote_down"} { var ( activity entity.Activity votes int64 activityType int ) activityType, _, _, _ = vr.activityRepo.GetActivityTypeByObjID(ctx, objectID, action) votes, err = vr.data.DB.Context(ctx).Where(builder.Eq{"object_id": objectID}). And(builder.Eq{"activity_type": activityType}). And(builder.Eq{"cancelled": 0}). Count(&activity) if err != nil { return } if action == "vote_up" { resp.UpVotes = int(votes) } else { resp.DownVotes = int(votes) } } resp.Votes = resp.UpVotes - resp.DownVotes return resp, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vr *VoteRepo) CheckRank(ctx context.Context, objectID, objectUserID, userID string, action string) (activityUserID string, activityType, rank, hasRank int, err error) { activityType, rank, hasRank, err = vr.activityRepo.GetActivityTypeByObjID(ctx, objectID, action) if err != nil { return } activityUserID = userID if strings.Contains(action, "voted") { activityUserID = objectUserID } return activityUserID, activityType, rank, hasRank, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *ActivityRepo) GetActivityTypeByObjID(ctx context.Context, objectID string, action string) ( activityType, rank, hasRank int, err error) { objectKey, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return } confKey := fmt.Sprintf("%s.%s", objectKey, action) cfg, err := ar.configService.GetConfigByKey(ctx, confKey) if err != nil { return } activityType, rank = cfg.ID, cfg.GetIntValue() hasRank = 0 if rank != 0 { hasRank = 1 } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *ActivityRepo) GetActivityTypeByObjKey(ctx context.Context, objectKey, action string) (activityType int, err error) { configKey := fmt.Sprintf("%s.%s", objectKey, action) cfg, err := ar.configService.GetConfigByKey(ctx, configKey) if err != nil { return 0, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return cfg.ID, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *FollowRepo) IsFollowed(ctx context.Context, userID, objectID string) (followed bool, err error) { objectKey, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return false, err } activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectKey, "follow") if err != nil { return false, err } at := &entity.Activity{} has, err := ar.data.DB.Context(ctx).Where("user_id = ? AND object_id = ? AND activity_type = ?", userID, objectID, activityType).Get(at) if err != nil { return false, err } if !has { return false, nil } if at.Cancelled == entity.ActivityCancelled { return false, nil } else { return true, nil } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *FollowRepo) GetFollowUserIDs(ctx context.Context, objectID string) (userIDs []string, err error) { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return nil, err } activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectTypeStr, "follow") if err != nil { log.Errorf("can't get activity type by object key: %s", objectTypeStr) return nil, err } userIDs = make([]string, 0) session := ar.data.DB.Context(ctx).Select("user_id") session.Table(entity.Activity{}.TableName()) session.Where("object_id = ?", objectID) session.Where("activity_type = ?", activityType) session.Where("cancelled = 0") err = session.Find(&userIDs) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return userIDs, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ar *FollowRepo) GetFollowIDs(ctx context.Context, userID, objectKey string) (followIDs []string, err error) { followIDs = make([]string, 0) activityType, err := ar.activityRepo.GetActivityTypeByObjKey(ctx, objectKey, "follow") if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } session := ar.data.DB.Context(ctx).Select("object_id") session.Table(entity.Activity{}.TableName()) session.Where("user_id = ? AND activity_type = ?", userID, activityType) session.Where("cancelled = 0") err = session.Find(&followIDs) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return followIDs, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ur *UserRankRepo) TriggerUserRank(ctx context.Context, session *xorm.Session, userID string, deltaRank int, activityType int, ) (isReachStandard bool, err error) { // IMPORTANT: If user center enabled the rank agent, then we should not change user rank. if plugin.RankAgentEnabled() { return false, nil } if deltaRank == 0 { return false, nil } if deltaRank < 0 { // if user rank is lower than 1 after this action, then user rank will be set to 1 only. var isReachMin bool isReachMin, err = ur.checkUserMinRank(ctx, session, userID, deltaRank) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if isReachMin { _, err = session.Where(builder.Eq{"id": userID}).Update(&entity.User{Rank: 1}) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return true, nil } } else { isReachStandard, err = ur.checkUserTodayRank(ctx, session, userID, activityType) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if isReachStandard { return isReachStandard, nil } } _, err = session.Where(builder.Eq{"id": userID}).Incr("`rank`", deltaRank).Update(&entity.User{}) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return false, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (ur *userRepo) GetByUsernames(ctx context.Context, usernames []string) ([]*entity.User, error) { list := make([]*entity.User, 0) err := ur.data.DB.Where("status =?", entity.UserStatusAvailable).In("username", usernames).Find(&list) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return list, err } tryToDecorateUserListFromUserCenter(ctx, ur.data, list) return list, nil }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func NewAnswerActivityService( answerActivityRepo AnswerActivityRepo, questionActivityRepo QuestionActivityRepo) *AnswerActivityService { return &AnswerActivityService{ answerActivityRepo: answerActivityRepo, questionActivityRepo: questionActivityRepo, } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (as *AnswerActivityService) DeleteQuestion(ctx context.Context, questionID string, createdAt time.Time, voteCount int) (err error) { if voteCount >= 3 { log.Infof("There is no need to roll back the reputation by answering likes above the target value. %s %d", questionID, voteCount) return nil } if createdAt.Before(time.Now().AddDate(0, 0, -60)) { log.Infof("There is no need to roll back the reputation by answer's existence time meets the target. %s %s", questionID, createdAt.String()) return nil } return as.questionActivityRepo.DeleteQuestion(ctx, questionID) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (as *AnswerActivityService) DeleteAnswer(ctx context.Context, answerID string, createdAt time.Time, voteCount int) (err error) { if voteCount >= 3 { log.Infof("There is no need to roll back the reputation by answering likes above the target value. %s %d", answerID, voteCount) return nil } if createdAt.Before(time.Now().AddDate(0, 0, -60)) { log.Infof("There is no need to roll back the reputation by answer's existence time meets the target. %s %s", answerID, createdAt.String()) return nil } return as.answerActivityRepo.DeleteAnswer(ctx, answerID) }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vs *VoteService) GetObjectUserID(ctx context.Context, objectID string) (userID string, err error) { var objectKey string objectKey, err = obj.GetObjectTypeStrByObjectID(objectID) if err != nil { err = nil return } switch objectKey { case "question": object, has, e := vs.questionRepo.GetQuestion(ctx, objectID) if e != nil || !has { err = errors.BadRequest(reason.QuestionNotFound).WithError(e).WithStack() return } userID = object.UserID case "answer": object, has, e := vs.answerRepo.GetAnswer(ctx, objectID) if e != nil || !has { err = errors.BadRequest(reason.AnswerNotFound).WithError(e).WithStack() return } userID = object.UserID case "comment": object, has, e := vs.commentCommonRepo.GetComment(ctx, objectID) if e != nil || !has { err = errors.BadRequest(reason.CommentNotFound).WithError(e).WithStack() return } userID = object.UserID default: err = errors.BadRequest(reason.DisallowVote).WithError(err).WithStack() return } return }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vs *VoteService) VoteDown(ctx context.Context, dto *schema.VoteDTO) (voteResp *schema.VoteResp, err error) { voteResp = &schema.VoteResp{} var objectUserID string objectUserID, err = vs.GetObjectUserID(ctx, dto.ObjectID) if err != nil { return } // check user is voting self or not if objectUserID == dto.UserID { err = errors.BadRequest(reason.DisallowVoteYourSelf) return } if dto.IsCancel { return vs.voteRepo.VoteDownCancel(ctx, dto.ObjectID, dto.UserID, objectUserID) } else { return vs.voteRepo.VoteDown(ctx, dto.ObjectID, dto.UserID, objectUserID) } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (vs *VoteService) VoteUp(ctx context.Context, dto *schema.VoteDTO) (voteResp *schema.VoteResp, err error) { voteResp = &schema.VoteResp{} var objectUserID string objectUserID, err = vs.GetObjectUserID(ctx, dto.ObjectID) if err != nil { return } // check user is voting self or not if objectUserID == dto.UserID { err = errors.BadRequest(reason.DisallowVoteYourSelf) return } if dto.IsCancel { return vs.voteRepo.VoteUpCancel(ctx, dto.ObjectID, dto.UserID, objectUserID) } else { return vs.voteRepo.VoteUp(ctx, dto.ObjectID, dto.UserID, objectUserID) } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func NewVoteService( VoteRepo VoteRepo, uniqueIDRepo unique.UniqueIDRepo, configService *config.ConfigService, questionRepo questioncommon.QuestionRepo, answerRepo answercommon.AnswerRepo, commentCommonRepo comment_common.CommentCommonRepo, objectService *object_info.ObjService, ) *VoteService { return &VoteService{ voteRepo: VoteRepo, UniqueIDRepo: uniqueIDRepo, configService: configService, questionRepo: questionRepo, answerRepo: answerRepo, commentCommonRepo: commentCommonRepo, objectService: objectService, } }
0
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
vulnerable
func (am *AuthUserMiddleware) AdminAuth() gin.HandlerFunc { return func(ctx *gin.Context) { token := ExtractToken(ctx) if len(token) == 0 { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) ctx.Abort() return } userInfo, err := am.authService.GetAdminUserCacheInfo(ctx, token) if err != nil { handler.HandleResponse(ctx, errors.Forbidden(reason.UnauthorizedError), nil) ctx.Abort() return } if userInfo != nil { if userInfo.UserStatus == entity.UserStatusDeleted { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) ctx.Abort() return } ctx.Set(ctxUUIDKey, userInfo) } ctx.Next() } }
0
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable