mcanoglu/cwe-class-group huggingface dataset:
def taxable_ids(loc = which_location, org = which_organization, inner_method = which_ancestry_method)
      if SETTINGS[:locations_enabled] && loc.present?
        inner_ids_loc = if Location.ignore?(self.to_s)
                          self.unscoped.pluck("#{table_name}.id")
                        else
                          inner_select(loc, inner_method)
                        end
      end

// Vulnerability class: CWE-200
def perform_accept_invitation
    params.require(:id)
    params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {})

    invite = Invite.find_by(invite_key: params[:id])

    if invite.present?
      begin
        attrs = {
          username: params[:username],
          name: params[:name],
          password: params[:password],
          user_custom_fields: params[:user_custom_fields],
          ip_address: request.remote_ip,
          session: session
        }

        if invite.is_invite_link?
          params.require(:email)
          attrs[:email] = params[:email]
        else
          attrs[:email] = invite.email
          attrs[:email_token] = params[:email_token] if params[:email_token].present?
        end

        user = invite.redeem(**attrs)
      rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e
        return render json: failed_json.merge(message: e.message), status: 412
      end

      if user.blank?
        return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
      end

      log_on_user(user) if user.active?
      user.update_timezone_if_missing(params[:timezone])
      post_process_invite(user)
      create_topic_invite_notifications(invite, user)

      topic = invite.topics.first
      response = {}

      if user.present?
        if user.active?
          if user.guardian.can_see?(topic)
            response[:redirect_to] = path(topic.relative_url)
          else
            response[:redirect_to] = path("/")
          end
        else
          response[:message] = I18n.t('invite.confirm_email')
          if user.guardian.can_see?(topic)
            cookies[:destination_url] = path(topic.relative_url)
          end
        end
      end

      render json: success_json.merge(response)
    else
      render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404
    end
  end

// Vulnerability class: CWE-863
def email_verify_send

    raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]

    user = User.find_by(email: params[:email].downcase)
    if !user
      # result is always positive to avoid leaking of existing user accounts
      render json: { message: 'ok' }, status: :ok
      return
    end

    #if user.verified == true
    #  render json: { error: 'Already verified!' }, status: :unprocessable_entity
    #  return
    #end

    Token.create(action: 'Signup', user_id: user.id)

    result = User.signup_new_token(user)
    if result && result[:token]
      user = result[:user]
      NotificationFactory::Mailer.notification(
        template: 'signup',
        user:     user,
        objects:  result
      )

      # only if system is in develop mode, send token back to browser for browser tests
      if Setting.get('developer_mode') == true
        render json: { message: 'ok', token: result[:token].name }, status: :ok
        return
      end

      # token sent to user, send ok to browser
      render json: { message: 'ok' }, status: :ok
      return
    end

    # unable to generate token
    render json: { message: 'failed' }, status: :ok
  end

// Vulnerability class: CWE-863
def socket_for(mode)
      sync unless primaries.any? || (secondaries.any? && mode == :read)

      server = nil
      while primaries.any? || (secondaries.any? && mode == :read)
        if mode == :write || secondaries.empty?
          server = primaries.sample
        else
          server = secondaries.sample
        end

        if server
          socket = server.socket
          socket.connect unless socket.connection

          if socket.alive?
            break server
          else
            remove server
          end
        end
      end

// Vulnerability class: CWE-400
def password_policy(password)
    if Setting.get('password_min_size').to_i > password.length
      return ["Can\'t update password, it must be at least %s characters long!", Setting.get('password_min_size')]
    end
    if Setting.get('password_need_digit').to_i == 1 && password !~ /\d/
      return ["Can't update password, it must contain at least 1 digit!"]
    end
    if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )
      return ["Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!"]
    end

    true
  end

// Vulnerability class: CWE-863
it "updates the record matching selector with change" do
      session.should_receive(:with, :consistency => :strong).
        and_yield(session)

      session.should_receive(:execute).with do |update|
        update.flags.should eq []
        update.selector.should eq query.operation.selector
        update.update.should eq change
      end

      query.update change
    end

// Vulnerability class: CWE-400
it "should redeem the invite if invited by non staff but not approve" do
      SiteSetting.must_approve_users = true
      inviter = invite.invited_by
      user = invite_redeemer.redeem

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.invited_by).to eq(inviter)
      expect(inviter.notifications.count).to eq(1)
      expect(user.approved).to eq(false)
    end

// Vulnerability class: CWE-863
def query(query)
      if options[:consistency] == :eventual
        query.flags |= [:slave_ok] if query.respond_to? :flags
        mode = :read
      else
        mode = :write
      end

      reply = socket_for(mode).execute(query)

      reply.tap do |reply|
        if reply.flags.include?(:query_failure)
          raise Errors::QueryFailure.new(query, reply.documents.first)
        end
      end
    end

// Vulnerability class: CWE-20
it "should use the rest terminus when the 'puppet' URI scheme is used and a host name is present" do
    uri = "puppet://myhost/fakemod/my/file"

    # It appears that the mocking somehow interferes with the caching subsystem.
    # This mock somehow causes another terminus to get generated.
    term = @indirection.terminus(:rest)
    @indirection.stubs(:terminus).with(:rest).returns term
    term.expects(:find)
    @indirection.find(uri)
  end

// Vulnerability class: CWE-200
def query(query)
      if options[:consistency] == :eventual
        query.flags |= [:slave_ok] if query.respond_to? :flags
        mode = :read
      else
        mode = :write
      end

      reply = socket_for(mode).execute(query)

      reply.tap do |reply|
        if reply.flags.include?(:query_failure)
          raise Errors::QueryFailure.new(query, reply.documents.first)
        end
      end
    end

// Vulnerability class: CWE-400
def bulk_unread_topic_ids
    topic_query = TopicQuery.new(current_user)

    if inbox = params[:private_message_inbox]
      filter = private_message_filter(topic_query, inbox)
      topic_query.options[:limit] = false
      topics = topic_query.filter_private_messages_unread(current_user, filter)
    else
      topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics
      topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == "true"

      if params[:category_id]
        if params[:include_subcategories]
          topics = topics.where(<<~SQL, category_id: params[:category_id])
            category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR
            category_id = :category_id
          SQL
        else
          topics = topics.where('category_id = ?', params[:category_id])
        end
      end

      if params[:tag_name].present?
        topics = topics.joins(:tags).where("tags.name": params[:tag_name])
      end
    end

    topics.pluck(:id)
  end

// Vulnerability class: CWE-863
it "should redeem the invite if invited by staff" do
      SiteSetting.must_approve_users = true
      inviter = invite.invited_by
      inviter.admin = true
      user = invite_redeemer.redeem
      invite.reload

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.invited_by).to eq(inviter)
      expect(inviter.notifications.count).to eq(1)
      expect(user.approved).to eq(true)
    end

// Vulnerability class: CWE-863
func TestBuilder_BuildBootstrapLayeredRuntime(t *testing.T) {
	b := New("localhost:1111", "localhost:2222", filemgr.NewManager(), nil)
	staticCfg, err := b.BuildBootstrapLayeredRuntime()
	assert.NoError(t, err)
	testutil.AssertProtoJSONEqual(t, `
		{ "layers": [{
			"name": "static_layer_0",
			"staticLayer": {
				"overload": {
					"global_downstream_max_connections": 50000
				}
			}
		}] }
	`, staticCfg)
}

// Vulnerability class: CWE-200
func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
	added, err := cs.addVote(vote, peerID)
	if err != nil {
		// If the vote height is off, we'll just ignore it,
		// But if it's a conflicting sig, add it to the cs.evpool.
		// If it's otherwise invalid, punish peer.
		// nolint: gocritic
		if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
			if cs.privValidatorPubKey == nil {
				return false, errPubKeyIsNotSet
			}

			if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
				cs.Logger.Error(
					"Found conflicting vote from ourselves. Did you unsafe_reset a validator?",
					"height",
					vote.Height,
					"round",
					vote.Round,
					"type",
					vote.Type)
				return added, err
			}
			var timestamp time.Time
			if voteErr.VoteA.Height == cs.state.InitialHeight {
				timestamp = cs.state.LastBlockTime // genesis time
			} else {
				timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)
			}
			ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)
			evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)
			if evidenceErr != nil {
				cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr)
			}
			return added, err
		} else if err == types.ErrVoteNonDeterministicSignature {
			cs.Logger.Debug("Vote has non-deterministic signature", "err", err)
		} else {
			// Either
			// 1) bad peer OR
			// 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
			// 3) tmkms use with multiple validators connecting to a single tmkms instance
			// 		(https://github.com/tendermint/tendermint/issues/3839).
			cs.Logger.Info("Error attempting to add vote", "err", err)
			return added, ErrAddingVote
		}
	}
	return added, nil
}

// Vulnerability class: CWE-400
func remount(m *configs.Mount, rootfs string) error {
	var (
		dest = m.Destination
	)
	if !strings.HasPrefix(dest, rootfs) {
		dest = filepath.Join(rootfs, dest)
	}
	return unix.Mount(m.Source, dest, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), "")
}

// Vulnerability class: CWE-362
func (r *TokenRevocationHandler) RevokeToken(ctx context.Context, token string, tokenType fosite.TokenType, client fosite.Client) error {
	discoveryFuncs := []func() (request fosite.Requester, err error){
		func() (request fosite.Requester, err error) {
			// Refresh token
			signature := r.RefreshTokenStrategy.RefreshTokenSignature(token)
			return r.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil)
		},
		func() (request fosite.Requester, err error) {
			// Access token
			signature := r.AccessTokenStrategy.AccessTokenSignature(token)
			return r.TokenRevocationStorage.GetAccessTokenSession(ctx, signature, nil)
		},
	}

	// Token type hinting
	if tokenType == fosite.AccessToken {
		discoveryFuncs[0], discoveryFuncs[1] = discoveryFuncs[1], discoveryFuncs[0]
	}

	var ar fosite.Requester
	var err error
	if ar, err = discoveryFuncs[0](); err != nil {
		ar, err = discoveryFuncs[1]()
	}
	if err != nil {
		return err
	}

	if ar.GetClient().GetID() != client.GetID() {
		return errors.WithStack(fosite.ErrRevocationClientMismatch)
	}

	requestID := ar.GetID()
	r.TokenRevocationStorage.RevokeRefreshToken(ctx, requestID)
	r.TokenRevocationStorage.RevokeAccessToken(ctx, requestID)

	return nil
}

// Vulnerability class: CWE-755
func TestAddEvidenceFromConsensus(t *testing.T) {
	var height int64 = 10
	pool, val := defaultTestPool(height)
	ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, val, evidenceChainID)

	require.NoError(t, pool.AddEvidenceFromConsensus(ev))

	// evidence from consensus should not be added immediately but reside in the consensus buffer
	evList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes)
	require.Empty(t, evList)
	require.Zero(t, evSize)

	next := pool.EvidenceFront()
	require.Nil(t, next)

	// move to next height and update state and evidence pool
	state := pool.State()
	state.LastBlockHeight++
	pool.Update(state, []types.Evidence{})

	// should be able to retrieve evidence from pool
	evList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)
	require.Equal(t, []types.Evidence{ev}, evList)

	// shouldn't be able to submit the same evidence twice
	require.NoError(t, pool.AddEvidenceFromConsensus(ev))
	state = pool.State()
	state.LastBlockHeight++
	pool.Update(state, []types.Evidence{})
	evList2, _ := pool.PendingEvidence(defaultEvidenceMaxBytes)
	require.Equal(t, evList, evList2)
}

// Vulnerability class: CWE-400
func (svc Service) GetTeamScheduledQueries(ctx context.Context, teamID uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionRead); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
	if err != nil {
		return nil, err
	}

	return svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)
}

// Vulnerability class: CWE-863
func (evpool *Pool) Update(state sm.State, ev types.EvidenceList) {
	// sanity check
	if state.LastBlockHeight <= evpool.state.LastBlockHeight {
		panic(fmt.Sprintf(
			"Failed EvidencePool.Update new state height is less than or equal to previous state height: %d <= %d",
			state.LastBlockHeight,
			evpool.state.LastBlockHeight,
		))
	}
	evpool.logger.Info("Updating evidence pool", "last_block_height", state.LastBlockHeight,
		"last_block_time", state.LastBlockTime)

	evpool.logger.Info(
		"updating evidence pool",
		"last_block_height", state.LastBlockHeight,
		"last_block_time", state.LastBlockTime,
	)

	evpool.mtx.Lock()
	// flush awaiting evidence from consensus into pool
	evpool.flushConsensusBuffer()
	// update state
	evpool.state = state
	evpool.mtx.Unlock()

	// move committed evidence out from the pending pool and into the committed pool
	evpool.markEvidenceAsCommitted(ev)

	// prune pending evidence when it has expired. This also updates when the next evidence will expire
	if evpool.Size() > 0 && state.LastBlockHeight > evpool.pruningHeight &&
		state.LastBlockTime.After(evpool.pruningTime) {
		evpool.pruningHeight, evpool.pruningTime = evpool.removeExpiredPendingEvidence()
	}
}

// Vulnerability class: CWE-400
parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {
        // """Extract pushed bytes after opreturn. Returns list of bytes() objects,
        // one per push.
        let ops: PushDataOperation[];
    
        // Strict refusal of non-push opcodes; bad scripts throw OpreturnError."""
        try {
            ops = this.getScriptOperations(script);
        } catch(e) {
            //console.log(e);
            throw Error('Script error');
        }

        if(ops[0].opcode !== this.BITBOX.Script.opcodes.OP_RETURN)
            throw Error('No OP_RETURN');
        let chunks: (Buffer|null)[] = [];
        ops.slice(1).forEach(opitem => {
            if(opitem.opcode > this.BITBOX.Script.opcodes.OP_16)
                throw Error("Non-push opcode");
            if(opitem.opcode > this.BITBOX.Script.opcodes.OP_PUSHDATA4) {
                if(opitem.opcode === 80)
                    throw Error('Non-push opcode');
                if(!allow_op_number)
                    throw Error('OP_1NEGATE to OP_16 not allowed');
                if(opitem.opcode === this.BITBOX.Script.opcodes.OP_1NEGATE)
                    opitem.data = Buffer.from([0x81]);
                else // OP_1 - OP_16
                    opitem.data = Buffer.from([opitem.opcode - 80]);
            }
            if(opitem.opcode === this.BITBOX.Script.opcodes.OP_0 && !allow_op_0){
                throw Error('OP_0 not allowed');
            }
            chunks.push(opitem.data)
        });
        //console.log(chunks);
        return chunks
    }

// Vulnerability class: CWE-20
export function verify_multi_chunk_message(packets: any[]) {

    const messageBuilder = new MessageBuilder({});
    messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);

    messageBuilder.on("full_message_body", (fullMessageBody: Buffer) => {
        console.log("full_message_body received:");
        analyseExtensionObject(fullMessageBody, 0, 0);
    });
    messageBuilder.on("start_chunk", (info) => {
        console.log(" starting new chunk ", info.messageHeader);
    });

    messageBuilder.on("chunk", (messageChunk) => {
        console.log(messageHeaderToString(messageChunk));
    });

    let totalLength = 0;
    packets.forEach((packet) => {
        if (packet instanceof Array) {
            packet = Buffer.from(packet);
        }
        totalLength += packet.length;
        // console.log(sprintf(" adding packet size : %5d l=%d", packet.length, totalLength));
        messageBuilder.feed(packet);
    });
}

// Vulnerability class: CWE-400
export async function validateTransfer(
    connection: Connection,
    signature: TransactionSignature,
    { recipient, amount, splToken, reference, memo }: ValidateTransferFields,
    options?: { commitment?: Finality }
): Promise<TransactionResponse> {
    const response = await connection.getTransaction(signature, options);
    if (!response) throw new ValidateTransferError('not found');

    const message = response.transaction.message;
    const meta = response.meta;
    if (!meta) throw new ValidateTransferError('missing meta');
    if (meta.err) throw meta.err;

    const [preAmount, postAmount] = splToken
        ? await validateSPLTokenTransfer(message, meta, recipient, splToken)
        : await validateSystemTransfer(message, meta, recipient);

    if (postAmount.minus(preAmount).lt(amount)) throw new ValidateTransferError('amount not transferred');

    if (reference) {
        if (!Array.isArray(reference)) {
            reference = [reference];
        }

        for (const pubkey of reference) {
            if (!message.accountKeys.some((accountKey) => accountKey.equals(pubkey)))
                throw new ValidateTransferError('reference not found');
        }
    }

    // FIXME: add memo check

    return response;
}

// Vulnerability class: CWE-670
function simulateOpenSecureChannel(callback: SimpleCallback) {
           
            clientChannel.create("fake://foobar:123", (err?: Error) => {
                
                if (param.shouldFailAtClientConnection) {
                    if (!err) {
                        return callback(new Error(" Should have failed here !"));
                    }
                    callback();
                } else {
                    if (err) {
                        return callback(err);
                    }
                    setImmediate(() => callback());
                }
            });
        }

// Vulnerability class: CWE-400
constructor(options?: { signatureLength?: number }) {
        super();

        this.id = "";

        this._tick0 = 0;
        this._tick1 = 0;
        this._hasReceivedError = false;
        this.blocks = [];
        this.messageChunks = [];
        this._expectedChannelId = 0;

        options = options || {};

        this.signatureLength = options.signatureLength || 0;

        this.options = options;

        this._packetAssembler = new PacketAssembler({
            minimumSizeInBytes: 0,
            readMessageFunc: readRawMessageHeader
        });

        this._packetAssembler.on("message", (messageChunk) => this._feed_messageChunk(messageChunk));

        this._packetAssembler.on("newMessage", (info, data) => {
            if (doPerfMonitoring) {
                // record tick 0: when the first data is received
                this._tick0 = get_clock_tick();
            }
            /**
             *
             * notify the observers that a new message is being built
             * @event start_chunk
             * @param info
             * @param data
             */
            this.emit("start_chunk", info, data);
        });

        this._securityDefeated = false;
        this.totalBodySize = 0;
        this.totalMessageSize = 0;
        this.channelId = 0;
        this.offsetBodyStart = 0;
        this.sequenceHeader = null;
        this._init_new();
    }

// Vulnerability class: CWE-400
this._transport.on("message", (messageChunk: Buffer) => {
            /**
             * notify the observers that ClientSecureChannelLayer has received a message chunk
             * @event receive_chunk
             * @param message_chunk
             */
            this.emit("receive_chunk", messageChunk);
            this._on_receive_message_chunk(messageChunk);
        });

// Vulnerability class: CWE-400
privateKey: this.getPrivateKey() || undefined,
            securityMode: this.securityMode
        });
        this._requests = {};

        this.messageBuilder
            .on("message", (response: Response, msgType: string, requestId: number) => {
                this._on_message_received(response, msgType, requestId);
            })
            .on("start_chunk", () => {
                //
                if (doPerfMonitoring) {
                    this._tick2 = get_clock_tick();
                }
            })
            .on("error", (err, requestId) => {
                //
                let requestData = this._requests[requestId];

                if (doDebug) {
                    debugLog("request id = ", requestId, err);
                    debugLog(" message was ");
                    debugLog(requestData);
                }

                if (!requestData) {
                    requestData = this._requests[requestId + 1];
                    if (doTraceClientRequestContent) {
                        errorLog(" message was 2:", requestData ? requestData.request.toString() : "<null>");
                    }
                }
            });

        this.__in_normal_close_operation = false;

        this._timeout_request_count = 0;

        this._securityTokenTimeoutId = null;

        this.transportTimeout = options.transportTimeout || ClientSecureChannelLayer.defaultTransportTimeout;

        this.channelId = 0;

        this.connectionStrategy = coerceConnectionStrategy(options.connectionStrategy);
    }

// Vulnerability class: CWE-400
function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {
  // eslint-disable-next-line no-undef
  const wr = new WeakRef<CallIntoRenderer>(value);
  const mapKey = id[0] + '~' + id[1];
  rendererFunctionCache.set(mapKey, wr);
  finalizationRegistry.register(value, {
    id,
    webContents: wc,
    frameId
  } as FinalizerInfo);
  return value;
}

// Vulnerability class: CWE-668